context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// <copyright file="MatrixTests.Arithmetic.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// 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.
// </copyright>
using System;
using MathNet.Numerics.Distributions;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Complex32;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex32
{
using Numerics;
/// <summary>
/// Abstract class with the common set of matrix tests
/// </summary>
public abstract partial class MatrixTests
{
/// <summary>
/// Can multiply with a complex number.
/// </summary>
/// <param name="real">Complex32 real part value.</param>
[TestCase(0)]
[TestCase(1)]
[TestCase(2.2f)]
public void CanMultiplyWithComplex(float real)
{
var value = new Complex32(real, 1.0f);
var matrix = TestMatrices["Singular3x3"];
var clone = matrix.Clone();
clone = clone.Multiply(value);
for (var i = 0; i < matrix.RowCount; i++)
{
for (var j = 0; j < matrix.ColumnCount; j++)
{
Assert.AreEqual(matrix[i, j] * value, clone[i, j]);
}
}
}
/// <summary>
/// Can multiply with a vector.
/// </summary>
[Test]
public void CanMultiplyWithVector()
{
var matrix = TestMatrices["Singular3x3"];
var x = new DenseVector(new[] { new Complex32(1, 1), new Complex32(2, 1), new Complex32(3, 1) });
var y = matrix * x;
Assert.AreEqual(matrix.RowCount, y.Count);
for (var i = 0; i < matrix.RowCount; i++)
{
var ar = matrix.Row(i);
var dot = ar * x;
Assert.AreEqual(dot, y[i]);
}
}
/// <summary>
/// Can multiply with a vector into a result.
/// </summary>
[Test]
public void CanMultiplyWithVectorIntoResult()
{
var matrix = TestMatrices["Singular3x3"];
var x = new DenseVector(new[] { new Complex32(1, 1), new Complex32(2, 1), new Complex32(3, 1) });
var y = new DenseVector(3);
matrix.Multiply(x, y);
for (var i = 0; i < matrix.RowCount; i++)
{
var ar = matrix.Row(i);
var dot = ar * x;
Assert.AreEqual(dot, y[i]);
}
}
/// <summary>
/// Can multiply with a vector into result when updating input argument.
/// </summary>
[Test]
public void CanMultiplyWithVectorIntoResultWhenUpdatingInputArgument()
{
var matrix = TestMatrices["Singular3x3"];
var x = new DenseVector(new[] { new Complex32(1, 1), new Complex32(2, 1), new Complex32(3, 1) });
var y = x;
matrix.Multiply(x, x);
Assert.AreSame(y, x);
y = new DenseVector(new[] { new Complex32(1, 1), new Complex32(2, 1), new Complex32(3, 1) });
for (var i = 0; i < matrix.RowCount; i++)
{
var ar = matrix.Row(i);
var dot = ar * y;
Assert.AreEqual(dot, x[i]);
}
}
/// <summary>
/// Multiply with a vector into too large result throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void MultiplyWithVectorIntoLargerResultThrowsArgumentException()
{
var matrix = TestMatrices["Singular3x3"];
var x = new DenseVector(new[] { new Complex32(1, 1), new Complex32(2, 1), new Complex32(3, 1) });
Vector<Complex32> y = new DenseVector(4);
Assert.That(() => matrix.Multiply(x, y), Throws.ArgumentException);
}
/// <summary>
/// Can left multiply with a complex.
/// </summary>
/// <param name="real">Complex32 real value.</param>
[TestCase(0)]
[TestCase(1)]
[TestCase(2.2f)]
public void CanOperatorLeftMultiplyWithComplex(float real)
{
var value = new Complex32(real, 1.0f);
var matrix = TestMatrices["Singular3x3"];
var clone = value * matrix;
for (var i = 0; i < matrix.RowCount; i++)
{
for (var j = 0; j < matrix.ColumnCount; j++)
{
Assert.AreEqual(value * matrix[i, j], clone[i, j]);
}
}
}
/// <summary>
/// Can right multiply with a Complex.
/// </summary>
/// <param name="real">Complex32 real value.</param>
[TestCase(0)]
[TestCase(1)]
[TestCase(2.2f)]
public void CanOperatorRightMultiplyWithComplex(float real)
{
var value = new Complex32(real, 1.0f);
var matrix = TestMatrices["Singular3x3"];
var clone = matrix * value;
for (var i = 0; i < matrix.RowCount; i++)
{
for (var j = 0; j < matrix.ColumnCount; j++)
{
Assert.AreEqual(matrix[i, j] * value, clone[i, j]);
}
}
}
/// <summary>
/// Can multiply with a Complex into result.
/// </summary>
/// <param name="real">Complex32 real value.</param>
[TestCase(0)]
[TestCase(1)]
[TestCase(2.2f)]
public void CanMultiplyWithComplexIntoResult(float real)
{
var value = new Complex32(real, 1.0f);
var matrix = TestMatrices["Singular3x3"];
var result = matrix.Clone();
matrix.Multiply(value, result);
for (var i = 0; i < matrix.RowCount; i++)
{
for (var j = 0; j < matrix.ColumnCount; j++)
{
Assert.AreEqual(matrix[i, j] * value, result[i, j]);
}
}
}
/// <summary>
/// Multiply with a scalar when result has more rows throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void MultiplyWithScalarWhenResultHasMoreRowsThrowsArgumentException()
{
var matrix = TestMatrices["Singular3x3"];
var result = CreateMatrix(matrix.RowCount + 1, matrix.ColumnCount);
Assert.That(() => matrix.Multiply(2.3f, result), Throws.ArgumentException);
}
/// <summary>
/// Multiply with a scalar when result has more columns throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void MultiplyWithScalarWhenResultHasMoreColumnsThrowsArgumentException()
{
var matrix = TestMatrices["Singular3x3"];
var result = CreateMatrix(matrix.RowCount, matrix.ColumnCount + 1);
Assert.That(() => matrix.Multiply(2.3f, result), Throws.ArgumentException);
}
/// <summary>
/// Can add a matrix.
/// </summary>
/// <param name="mtxA">Matrix A name.</param>
/// <param name="mtxB">Matrix B name.</param>
[TestCase("Singular3x3", "Square3x3")]
[TestCase("Singular4x4", "Square4x4")]
public void CanAddMatrix(string mtxA, string mtxB)
{
var matrixA = TestMatrices[mtxA];
var matrixB = TestMatrices[mtxB];
var matrix = matrixA.Clone();
matrix = matrix.Add(matrixB);
for (var i = 0; i < matrix.RowCount; i++)
{
for (var j = 0; j < matrix.ColumnCount; j++)
{
Assert.AreEqual(matrix[i, j], matrixA[i, j] + matrixB[i, j]);
}
}
}
/// <summary>
/// Can add a matrix.
/// </summary>
/// <param name="mtx">Matrix name.</param>
[TestCase("Square3x3")]
[TestCase("Tall3x2")]
public void CanAddMatrixToSelf(string mtx)
{
var matrix = TestMatrices[mtx].Clone();
var result = matrix.Add(matrix);
for (var i = 0; i < matrix.RowCount; i++)
{
for (var j = 0; j < matrix.ColumnCount; j++)
{
Assert.AreEqual(result[i, j], 2*matrix[i, j]);
}
}
}
/// <summary>
/// Can subtract a matrix.
/// </summary>
/// <param name="mtx">Matrix name.</param>
[TestCase("Square3x3")]
[TestCase("Tall3x2")]
public void CanSubtractMatrixFromSelf(string mtx)
{
var matrix = TestMatrices[mtx].Clone();
var result = matrix.Subtract(matrix);
for (var i = 0; i < matrix.RowCount; i++)
{
for (var j = 0; j < matrix.ColumnCount; j++)
{
Assert.AreEqual(result[i, j], Complex32.Zero);
}
}
}
/// <summary>
/// Adding a matrix with fewer columns throws <c>ArgumentOutOfRangeException</c>.
/// </summary>
[Test]
public void AddMatrixWithFewerColumnsThrowsArgumentOutOfRangeException()
{
var matrix = TestMatrices["Singular3x3"];
var other = TestMatrices["Tall3x2"];
Assert.That(() => matrix.Add(other), Throws.TypeOf<ArgumentOutOfRangeException>());
}
/// <summary>
/// Adding a matrix with fewer rows throws <c>ArgumentOutOfRangeException</c>.
/// </summary>
[Test]
public void AddMatrixWithFewerRowsThrowsArgumentOutOfRangeException()
{
var matrix = TestMatrices["Singular3x3"];
var other = TestMatrices["Wide2x3"];
Assert.That(() => matrix.Add(other), Throws.TypeOf<ArgumentOutOfRangeException>());
}
/// <summary>
/// Add matrices using "+" operator.
/// </summary>
/// <param name="mtxA">Matrix A name.</param>
/// <param name="mtxB">Matrix B name.</param>
[TestCase("Singular3x3", "Square3x3")]
[TestCase("Singular4x4", "Square4x4")]
public void CanAddUsingOperator(string mtxA, string mtxB)
{
var matrixA = TestMatrices[mtxA];
var matrixB = TestMatrices[mtxB];
var result = matrixA + matrixB;
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(result[i, j], matrixA[i, j] + matrixB[i, j]);
}
}
}
/// <summary>
/// Add operator when right side has fewer columns throws <c>ArgumentOutOfRangeException</c>.
/// </summary>
[Test]
public void AddOperatorWhenRightSideHasFewerColumnsThrowsArgumentOutOfRangeException()
{
var matrix = TestMatrices["Singular3x3"];
var other = TestMatrices["Tall3x2"];
Assert.Throws<ArgumentOutOfRangeException>(() => { var result = matrix + other; });
}
/// <summary>
/// Add operator when right side has fewer rows throws <c>ArgumentOutOfRangeException</c>.
/// </summary>
[Test]
public void AddOperatorWhenRightSideHasFewerRowsThrowsArgumentOutOfRangeException()
{
var matrix = TestMatrices["Singular3x3"];
var other = TestMatrices["Wide2x3"];
Assert.Throws<ArgumentOutOfRangeException>(() => { var result = matrix + other; });
}
/// <summary>
/// Can subtract a matrix.
/// </summary>
/// <param name="mtxA">Matrix A name.</param>
/// <param name="mtxB">Matrix B name.</param>
[TestCase("Singular3x3", "Square3x3")]
[TestCase("Singular4x4", "Square4x4")]
public void CanSubtractMatrix(string mtxA, string mtxB)
{
var matrixA = TestMatrices[mtxA];
var matrixB = TestMatrices[mtxB];
var matrix = matrixA.Clone();
matrix = matrix.Subtract(matrixB);
for (var i = 0; i < matrix.RowCount; i++)
{
for (var j = 0; j < matrix.ColumnCount; j++)
{
Assert.AreEqual(matrix[i, j], matrixA[i, j] - matrixB[i, j]);
}
}
}
/// <summary>
/// Subtract a matrix when right side has fewer columns throws <c>ArgumentOutOfRangeException</c>.
/// </summary>
[Test]
public void SubtractMatrixWithFewerColumnsThrowsArgumentOutOfRangeException()
{
var matrix = TestMatrices["Singular3x3"];
var other = TestMatrices["Tall3x2"];
Assert.That(() => matrix.Subtract(other), Throws.TypeOf<ArgumentOutOfRangeException>());
}
/// <summary>
/// Subtract a matrix when right side has fewer rows throws <c>ArgumentOutOfRangeException</c>.
/// </summary>
[Test]
public void SubtractMatrixWithFewerRowsThrowsArgumentOutOfRangeException()
{
var matrix = TestMatrices["Singular3x3"];
var other = TestMatrices["Wide2x3"];
Assert.That(() => matrix.Subtract(other), Throws.TypeOf<ArgumentOutOfRangeException>());
}
/// <summary>
/// Can subtract a matrix using "-" operator.
/// </summary>
/// <param name="mtxA">Matrix A name.</param>
/// <param name="mtxB">Matrix B name.</param>
[TestCase("Singular3x3", "Square3x3")]
[TestCase("Singular4x4", "Square4x4")]
public void CanSubtractUsingOperator(string mtxA, string mtxB)
{
var matrixA = TestMatrices[mtxA];
var matrixB = TestMatrices[mtxB];
var result = matrixA - matrixB;
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(result[i, j], matrixA[i, j] - matrixB[i, j]);
}
}
}
/// <summary>
/// Subtract operator when right side has fewer columns throws <c>ArgumentOutOfRangeException</c>
/// </summary>
[Test]
public void SubtractOperatorWhenRightSideHasFewerColumnsThrowsArgumentOutOfRangeException()
{
var matrix = TestMatrices["Singular3x3"];
var other = TestMatrices["Tall3x2"];
Assert.Throws<ArgumentOutOfRangeException>(() => { var result = matrix - other; });
}
/// <summary>
/// Subtract operator when right side has fewer rows <c>ArgumentOutOfRangeException</c>
/// </summary>
[Test]
public void SubtractOperatorWhenRightSideHasFewerRowsThrowsArgumentOutOfRangeException()
{
var matrix = TestMatrices["Singular3x3"];
var other = TestMatrices["Wide2x3"];
Assert.Throws<ArgumentOutOfRangeException>(() => { var result = matrix - other; });
}
/// <summary>
/// Can multiply a matrix with matrix.
/// </summary>
/// <param name="nameA">Matrix A name.</param>
/// <param name="nameB">Matrix B name.</param>
[TestCase("Singular3x3", "Square3x3")]
[TestCase("Singular4x4", "Square4x4")]
[TestCase("Wide2x3", "Square3x3")]
[TestCase("Wide2x3", "Tall3x2")]
[TestCase("Tall3x2", "Wide2x3")]
public void CanMultiplyMatrixWithMatrix(string nameA, string nameB)
{
var matrixA = TestMatrices[nameA];
var matrixB = TestMatrices[nameB];
var matrixC = matrixA * matrixB;
Assert.AreEqual(matrixC.RowCount, matrixA.RowCount);
Assert.AreEqual(matrixC.ColumnCount, matrixB.ColumnCount);
for (var i = 0; i < matrixC.RowCount; i++)
{
for (var j = 0; j < matrixC.ColumnCount; j++)
{
AssertHelpers.AlmostEqual(matrixA.Row(i) * matrixB.Column(j), matrixC[i, j], 5);
}
}
}
/// <summary>
/// Can transpose and multiply a matrix with matrix.
/// </summary>
/// <param name="nameA">Matrix name.</param>
[TestCase("Singular3x3")]
[TestCase("Singular4x4")]
[TestCase("Wide2x3")]
[TestCase("Tall3x2")]
public void CanTransposeAndMultiplyMatrixWithMatrix(string nameA)
{
var matrixA = TestMatrices[nameA];
var matrixB = TestMatrices[nameA];
var matrixC = matrixA.TransposeAndMultiply(matrixB);
Assert.AreEqual(matrixC.RowCount, matrixA.RowCount);
Assert.AreEqual(matrixC.ColumnCount, matrixB.RowCount);
for (var i = 0; i < matrixC.RowCount; i++)
{
for (var j = 0; j < matrixC.ColumnCount; j++)
{
AssertHelpers.AlmostEqual(matrixA.Row(i) * matrixB.Row(j), matrixC[i, j], 5);
}
}
}
/// <summary>
/// Can transpose and multiply a matrix with differing dimensions.
/// </summary>
[Test]
public void CanTransposeAndMultiplyWithDifferingDimensions()
{
var matrixA = TestMatrices["Tall3x2"];
var matrixB = CreateMatrix(5, 2);
var count = 1;
for (var row = 0; row < matrixB.RowCount; row++)
{
for (var col = 0; col < matrixB.ColumnCount; col++)
{
if (row == col)
{
matrixB[row, col] = count++;
}
}
}
var matrixC = matrixA.TransposeAndMultiply(matrixB);
Assert.AreEqual(matrixC.RowCount, matrixA.RowCount);
Assert.AreEqual(matrixC.ColumnCount, matrixB.RowCount);
for (var i = 0; i < matrixC.RowCount; i++)
{
for (var j = 0; j < matrixC.ColumnCount; j++)
{
AssertHelpers.AlmostEqual(matrixA.Row(i) * matrixB.Row(j), matrixC[i, j], 5);
}
}
}
/// <summary>
/// Transpose and multiply a matrix with matrix of incompatible size throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void TransposeAndMultiplyMatrixMatrixWithIncompatibleSizesThrowsArgumentException()
{
var matrix = TestMatrices["Singular3x3"];
var other = TestMatrices["Tall3x2"];
Assert.That(() => matrix.TransposeAndMultiply(other), Throws.ArgumentException);
}
/// <summary>
/// Can transpose and multiply a matrix with matrix into a result matrix.
/// </summary>
/// <param name="nameA">Matrix name.</param>
[TestCase("Singular3x3")]
[TestCase("Singular4x4")]
[TestCase("Wide2x3")]
[TestCase("Tall3x2")]
public void CanTransposeAndMultiplyMatrixWithMatrixIntoResult(string nameA)
{
var matrixA = TestMatrices[nameA];
var matrixB = TestMatrices[nameA];
var matrixC = CreateMatrix(matrixA.RowCount, matrixB.RowCount);
matrixA.TransposeAndMultiply(matrixB, matrixC);
Assert.AreEqual(matrixC.RowCount, matrixA.RowCount);
Assert.AreEqual(matrixC.ColumnCount, matrixB.RowCount);
for (var i = 0; i < matrixC.RowCount; i++)
{
for (var j = 0; j < matrixC.ColumnCount; j++)
{
AssertHelpers.AlmostEqual(matrixA.Row(i) * matrixB.Row(j), matrixC[i, j], 5);
}
}
}
/// <summary>
/// Multiply a matrix with incompatible size matrix throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void MultiplyMatrixMatrixWithIncompatibleSizesThrowsArgumentException()
{
var matrix = TestMatrices["Singular3x3"];
var other = TestMatrices["Wide2x3"];
Assert.Throws<ArgumentException>(() => { var result = matrix * other; });
}
/// <summary>
/// Can multiply a matrix with matrix into a result matrix.
/// </summary>
/// <param name="nameA">Matrix A name.</param>
/// <param name="nameB">Matrix B name.</param>
[TestCase("Singular3x3", "Square3x3")]
[TestCase("Singular4x4", "Square4x4")]
[TestCase("Wide2x3", "Square3x3")]
[TestCase("Wide2x3", "Tall3x2")]
[TestCase("Tall3x2", "Wide2x3")]
public virtual void CanMultiplyMatrixWithMatrixIntoResult(string nameA, string nameB)
{
var matrixA = TestMatrices[nameA];
var matrixB = TestMatrices[nameB];
var matrixC = CreateMatrix(matrixA.RowCount, matrixB.ColumnCount);
matrixA.Multiply(matrixB, matrixC);
Assert.AreEqual(matrixC.RowCount, matrixA.RowCount);
Assert.AreEqual(matrixC.ColumnCount, matrixB.ColumnCount);
for (var i = 0; i < matrixC.RowCount; i++)
{
for (var j = 0; j < matrixC.ColumnCount; j++)
{
AssertHelpers.AlmostEqual(matrixA.Row(i) * matrixB.Column(j), matrixC[i, j], 5);
}
}
}
/// <summary>
/// Can multiply transposed matrix with a vector.
/// </summary>
[Test]
public void CanTransposeThisAndMultiplyWithVector()
{
var matrix = TestMatrices["Singular3x3"];
var x = new DenseVector(new[] { new Complex32(1, 1), new Complex32(2, 1), new Complex32(3, 1) });
var y = matrix.TransposeThisAndMultiply(x);
Assert.AreEqual(matrix.ColumnCount, y.Count);
for (var j = 0; j < matrix.ColumnCount; j++)
{
var ar = matrix.Column(j);
var dot = ar * x;
AssertHelpers.AlmostEqual(dot, y[j], 5);
}
}
/// <summary>
/// Can multiply transposed matrix with a vector into a result.
/// </summary>
[Test]
public void CanTransposeThisAndMultiplyWithVectorIntoResult()
{
var matrix = TestMatrices["Singular3x3"];
var x = new DenseVector(new[] { new Complex32(1, 1), new Complex32(2, 1), new Complex32(3, 1) });
var y = new DenseVector(3);
matrix.TransposeThisAndMultiply(x, y);
for (var j = 0; j < matrix.ColumnCount; j++)
{
var ar = matrix.Column(j);
var dot = ar * x;
AssertHelpers.AlmostEqual(dot, y[j], 5);
}
}
/// <summary>
/// Can multiply transposed matrix with a vector into result when updating input argument.
/// </summary>
[Test]
public void CanTransposeThisAndMultiplyWithVectorIntoResultWhenUpdatingInputArgument()
{
var matrix = TestMatrices["Singular3x3"];
var x = new DenseVector(new[] { new Complex32(1, 1), new Complex32(2, 1), new Complex32(3, 1) });
var y = x;
matrix.TransposeThisAndMultiply(x, x);
Assert.AreSame(y, x);
y = new DenseVector(new[] { new Complex32(1, 1), new Complex32(2, 1), new Complex32(3, 1) });
for (var j = 0; j < matrix.ColumnCount; j++)
{
var ar = matrix.Column(j);
var dot = ar * y;
AssertHelpers.AlmostEqual(dot, x[j], 5);
}
}
/// <summary>
/// Multiply transposed matrix with a vector into too large result throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void TransposeThisAndMultiplyWithVectorIntoLargerResultThrowsArgumentException()
{
var matrix = TestMatrices["Singular3x3"];
var x = new DenseVector(new[] { new Complex32(1, 1), new Complex32(2, 1), new Complex32(3, 1) });
Vector<Complex32> y = new DenseVector(4);
Assert.That(() => matrix.TransposeThisAndMultiply(x, y), Throws.ArgumentException);
}
/// <summary>
/// Can multiply transposed matrix with another matrix.
/// </summary>
/// <param name="nameA">Matrix name.</param>
[TestCase("Singular3x3")]
[TestCase("Singular4x4")]
[TestCase("Wide2x3")]
[TestCase("Tall3x2")]
public void CanTransposeThisAndMultiplyMatrixWithMatrix(string nameA)
{
var matrixA = TestMatrices[nameA];
var matrixB = TestMatrices[nameA];
var matrixC = matrixA.TransposeThisAndMultiply(matrixB);
Assert.AreEqual(matrixC.RowCount, matrixA.ColumnCount);
Assert.AreEqual(matrixC.ColumnCount, matrixB.ColumnCount);
for (var i = 0; i < matrixC.RowCount; i++)
{
for (var j = 0; j < matrixC.ColumnCount; j++)
{
AssertHelpers.AlmostEqual(matrixA.Column(i) * matrixB.Column(j), matrixC[i, j], 5);
}
}
}
/// <summary>
/// Multiply the transpose of matrix with another matrix of incompatible size throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void TransposeThisAndMultiplyMatrixMatrixWithIncompatibleSizesThrowsArgumentException()
{
var matrix = TestMatrices["Wide2x3"];
var other = TestMatrices["Singular3x3"];
Assert.That(() => matrix.TransposeThisAndMultiply(other), Throws.ArgumentException);
}
/// <summary>
/// Multiply transpose of this matrix with another matrix into a result matrix.
/// </summary>
/// <param name="nameA">Matrix name.</param>
[TestCase("Singular3x3")]
[TestCase("Singular4x4")]
[TestCase("Wide2x3")]
[TestCase("Tall3x2")]
public void CanTransposeThisAndMultiplyMatrixWithMatrixIntoResult(string nameA)
{
var matrixA = TestMatrices[nameA];
var matrixB = TestMatrices[nameA];
var matrixC = CreateMatrix(matrixA.ColumnCount, matrixB.ColumnCount);
matrixA.TransposeThisAndMultiply(matrixB, matrixC);
Assert.AreEqual(matrixC.RowCount, matrixA.ColumnCount);
Assert.AreEqual(matrixC.ColumnCount, matrixB.ColumnCount);
for (var i = 0; i < matrixC.RowCount; i++)
{
for (var j = 0; j < matrixC.ColumnCount; j++)
{
AssertHelpers.AlmostEqual(matrixA.Column(i) * matrixB.Column(j), matrixC[i, j], 5);
}
}
}
/// <summary>
/// Can negate a matrix.
/// </summary>
/// <param name="name">Matrix name.</param>
[TestCase("Singular3x3")]
[TestCase("Singular4x4")]
[TestCase("Wide2x3")]
[TestCase("Wide2x3")]
[TestCase("Tall3x2")]
public void CanNegate(string name)
{
var matrix = TestMatrices[name];
var copy = matrix.Clone();
copy = copy.Negate();
for (var i = 0; i < matrix.RowCount; i++)
{
for (var j = 0; j < matrix.ColumnCount; j++)
{
Assert.AreEqual(-matrix[i, j], copy[i, j]);
}
}
}
/// <summary>
/// Can negate a matrix into a result matrix.
/// </summary>
/// <param name="name">Matrix name.</param>
[TestCase("Singular3x3")]
[TestCase("Singular4x4")]
[TestCase("Wide2x3")]
[TestCase("Wide2x3")]
[TestCase("Tall3x2")]
public void CanNegateIntoResult(string name)
{
var matrix = TestMatrices[name];
var copy = matrix.Clone();
matrix.Negate(copy);
for (var i = 0; i < matrix.RowCount; i++)
{
for (var j = 0; j < matrix.ColumnCount; j++)
{
Assert.AreEqual(-matrix[i, j], copy[i, j]);
}
}
}
/// <summary>
/// Negate into a result matrix with more rows throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void NegateIntoResultWithMoreRowsThrowsArgumentException()
{
var matrix = TestMatrices["Singular3x3"];
var target = CreateMatrix(matrix.RowCount + 1, matrix.ColumnCount);
Assert.That(() => matrix.Negate(target), Throws.ArgumentException);
}
/// <summary>
/// Negate into a result matrix with more rows throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void NegateIntoResultWithMoreColumnsThrowsArgumentException()
{
var matrix = TestMatrices["Singular3x3"];
var target = CreateMatrix(matrix.RowCount + 1, matrix.ColumnCount);
Assert.That(() => matrix.Negate(target), Throws.ArgumentException);
}
/// <summary>
/// Can calculate Kronecker product.
/// </summary>
[Test]
public void CanKroneckerProduct()
{
var matrixA = TestMatrices["Wide2x3"];
var matrixB = TestMatrices["Square3x3"];
var result = CreateMatrix(matrixA.RowCount * matrixB.RowCount, matrixA.ColumnCount * matrixB.ColumnCount);
matrixA.KroneckerProduct(matrixB, result);
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
for (var ii = 0; ii < matrixB.RowCount; ii++)
{
for (var jj = 0; jj < matrixB.ColumnCount; jj++)
{
Assert.AreEqual(result[(i * matrixB.RowCount) + ii, (j * matrixB.ColumnCount) + jj], matrixA[i, j] * matrixB[ii, jj]);
}
}
}
}
}
/// <summary>
/// Can calculate Kronecker product into a result matrix.
/// </summary>
[Test]
public void CanKroneckerProductIntoResult()
{
var matrixA = TestMatrices["Wide2x3"];
var matrixB = TestMatrices["Square3x3"];
var result = matrixA.KroneckerProduct(matrixB);
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
for (var ii = 0; ii < matrixB.RowCount; ii++)
{
for (var jj = 0; jj < matrixB.ColumnCount; jj++)
{
Assert.AreEqual(result[(i * matrixB.RowCount) + ii, (j * matrixB.ColumnCount) + jj], matrixA[i, j] * matrixB[ii, jj]);
}
}
}
}
}
/// <summary>
/// Can normalize columns of a matrix.
/// </summary>
/// <param name="p">The norm under which to normalize the columns under.</param>
[TestCase(1)]
[TestCase(2)]
public void CanNormalizeColumns(int p)
{
var matrix = TestMatrices["Square4x4"];
var result = matrix.NormalizeColumns(p);
for (var j = 0; j < result.ColumnCount; j++)
{
var col = result.Column(j);
AssertHelpers.AlmostEqual(1d, col.Norm(p), 5);
}
}
/// <summary>
/// Normalize columns with wrong parameter throws <c>ArgumentOutOfRangeException</c>.
/// </summary>
[Test]
public void NormalizeColumnsWithWrongParameterThrowsArgumentOutOfRangeException()
{
Assert.That(() => TestMatrices["Square4x4"].NormalizeColumns(-4), Throws.TypeOf<ArgumentOutOfRangeException>());
}
/// <summary>
/// Can normalize rows of a matrix.
/// </summary>
/// <param name="p">The norm under which to normalize the rows under.</param>
[TestCase(1)]
[TestCase(2)]
public void CanNormalizeRows(int p)
{
var matrix = TestMatrices["Square4x4"].NormalizeRows(p);
for (var i = 0; i < matrix.RowCount; i++)
{
var row = matrix.Row(i);
AssertHelpers.AlmostEqual(1d, row.Norm(p), 5);
}
}
/// <summary>
/// Normalize rows with wrong parameter throws <c>ArgumentOutOfRangeException</c>.
/// </summary>
[Test]
public void NormalizeRowsWithWrongParameterThrowsArgumentOutOfRangeException()
{
Assert.That(() => TestMatrices["Square4x4"].NormalizeRows(-4), Throws.TypeOf<ArgumentOutOfRangeException>());
}
/// <summary>
/// Can pointwise multiply matrices into a result matrix.
/// </summary>
[Test]
public void CanPointwiseMultiplyIntoResult()
{
foreach (var data in TestMatrices.Values)
{
var other = data.Clone();
var result = data.Clone();
data.PointwiseMultiply(other, result);
for (var i = 0; i < data.RowCount; i++)
{
for (var j = 0; j < data.ColumnCount; j++)
{
Assert.AreEqual(data[i, j] * other[i, j], result[i, j]);
}
}
result = data.PointwiseMultiply(other);
for (var i = 0; i < data.RowCount; i++)
{
for (var j = 0; j < data.ColumnCount; j++)
{
Assert.AreEqual(data[i, j] * other[i, j], result[i, j]);
}
}
}
}
/// <summary>
/// Pointwise multiply matrices with invalid dimensions into a result throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void PointwiseMultiplyWithInvalidDimensionsIntoResultThrowsArgumentException()
{
var matrix = TestMatrices["Wide2x3"];
var other = CreateMatrix(matrix.RowCount + 1, matrix.ColumnCount);
var result = matrix.Clone();
Assert.That(() => matrix.PointwiseMultiply(other, result), Throws.ArgumentException);
}
/// <summary>
/// Pointwise multiply matrices with invalid result dimensions throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void PointwiseMultiplyWithInvalidResultDimensionsThrowsArgumentException()
{
var matrix = TestMatrices["Wide2x3"];
var other = matrix.Clone();
var result = CreateMatrix(matrix.RowCount + 1, matrix.ColumnCount);
Assert.That(() => matrix.PointwiseMultiply(other, result), Throws.ArgumentException);
}
/// <summary>
/// Can pointwise divide matrices into a result matrix.
/// </summary>
[Test]
public virtual void CanPointwiseDivideIntoResult()
{
var data = TestMatrices["Singular3x3"];
var other = data.Clone();
var result = data.Clone();
data.PointwiseDivide(other, result);
for (var i = 0; i < data.RowCount; i++)
{
for (var j = 0; j < data.ColumnCount; j++)
{
Assert.AreEqual(data[i, j] / other[i, j], result[i, j]);
}
}
result = data.PointwiseDivide(other);
for (var i = 0; i < data.RowCount; i++)
{
for (var j = 0; j < data.ColumnCount; j++)
{
Assert.AreEqual(data[i, j] / other[i, j], result[i, j]);
}
}
}
/// <summary>
/// Pointwise divide matrices with invalid dimensions into a result throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void PointwiseDivideWithInvalidDimensionsIntoResultThrowsArgumentException()
{
var matrix = TestMatrices["Wide2x3"];
var other = CreateMatrix(matrix.RowCount + 1, matrix.ColumnCount);
var result = matrix.Clone();
Assert.That(() => matrix.PointwiseDivide(other, result), Throws.ArgumentException);
}
/// <summary>
/// Pointwise divide matrices with invalid result dimensions throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void PointwiseDivideWithInvalidResultDimensionsThrowsArgumentException()
{
var matrix = TestMatrices["Wide2x3"];
var other = matrix.Clone();
var result = CreateMatrix(matrix.RowCount + 1, matrix.ColumnCount);
Assert.That(() => matrix.PointwiseDivide(other, result), Throws.ArgumentException);
}
/// <summary>
/// Create random matrix with non-positive number of rows throw <c>ArgumentException</c>.
/// </summary>
/// <param name="numberOfRows">Number of rows.</param>
[TestCase(0)]
[TestCase(-2)]
public void RandomWithNonPositiveNumberOfRowsThrowsArgumentException(int numberOfRows)
{
Assert.That(() => DenseMatrix.CreateRandom(numberOfRows, 4, new ContinuousUniform()), Throws.TypeOf<ArgumentOutOfRangeException>());
}
/// <summary>
/// Can trace.
/// </summary>
[Test]
public void CanTrace()
{
var matrix = TestMatrices["Square3x3"];
var trace = matrix.Trace();
Assert.AreEqual(new Complex32(6.6f, 3), trace);
}
/// <summary>
/// Trace of non-square matrix throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void TraceOfNonSquareMatrixThrowsArgumentException()
{
var matrix = TestMatrices["Wide2x3"];
Assert.That(() => matrix.Trace(), Throws.ArgumentException);
}
}
}
| |
// 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.IO;
using System.Linq;
using Xunit;
namespace System.CommandLine.Tests
{
public class HelpTextGeneratorTests
{
[Fact]
public void Help_Empty()
{
var expectedHelp = @"
usage: tool
";
var actualHelp = GetHelp(syntax => { });
AssertMatch(expectedHelp, actualHelp);
}
[Fact]
public void Help_Command_Overview()
{
var expectedHelp = @"
usage: tool <command> [<args>]
pull Gets commits from another repo
commit Adds commits to the current repo
push Transfers commits to another repo
";
var actualHelp = GetHelp(string.Empty, syntax =>
{
var command = string.Empty;
syntax.DefineCommand("pull", ref command, "Gets commits from another repo");
syntax.DefineCommand("commit", ref command, "Adds commits to the current repo");
syntax.DefineCommand("push", ref command, "Transfers commits to another repo");
});
AssertMatch(expectedHelp, actualHelp);
}
[Fact]
public void Help_Command_Details()
{
var expectedHelp = @"
usage: tool commit [-o <arg>]
-o <arg> Some option
";
var actualHelp = GetHelp("commit", syntax =>
{
var o = string.Empty;
syntax.DefineCommand("pull");
syntax.DefineCommand("commit");
syntax.DefineOption("o", ref o, "Some option");
syntax.DefineCommand("push");
});
AssertMatch(expectedHelp, actualHelp);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Help_Option(bool includeHidden)
{
var expectedHelp = @"
usage: tool [-s] [--keyword] [-f] [-o <arg>] [--option <arg>]
[--optional [arg]]
-s Single character flag
--keyword Keyword flag
-f, --flag A flag with with short and long name
-o <arg> Single character option with value
--option <arg> Keyword option with value
--optional [arg] Keyword option with optional value
";
var actualHelp = GetHelp(syntax =>
{
var s = false;
var keyword = false;
var flag = false;
var o = string.Empty;
var option = string.Empty;
syntax.DefineOption("s", ref s, "Single character flag");
syntax.DefineOption("keyword", ref keyword, "Keyword flag");
syntax.DefineOption("f|flag", ref flag, "A flag with with short and long name");
syntax.DefineOption("o", ref o, "Single character option with value");
syntax.DefineOption("option", ref option, "Keyword option with value");
syntax.DefineOption("optional", ref option, false, "Keyword option with optional value");
if (includeHidden)
{
var h = syntax.DefineParameter("h", string.Empty);
h.IsHidden = true;
}
});
AssertMatch(expectedHelp, actualHelp);
}
[Fact]
public void Help_Option_List()
{
var expectedHelp = @"
usage: tool [-r <arg>...] [--color <arg>...]
-r <arg>... The references
--color, -c <arg>... The colors to use
";
var actualHelp = GetHelp(syntax =>
{
var r = (IReadOnlyList<string>)null;
var c = (IReadOnlyList<string>)null;
syntax.DefineOptionList("r", ref r, "The references");
syntax.DefineOptionList("color|c", ref c, "The colors to use");
});
AssertMatch(expectedHelp, actualHelp);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Help_Parameter(bool includeHidden)
{
var expectedHelp = @"
usage: tool <p1> <p2>
<p1> Parameter One
<p2> Parameter Two
";
var actualHelp = GetHelp(syntax =>
{
if (includeHidden)
{
var h = syntax.DefineOption("h", string.Empty);
h.IsHidden = true;
}
var p1 = string.Empty;
var p2 = false;
syntax.DefineParameter("p1", ref p1, "Parameter One");
syntax.DefineParameter("p2", ref p2, "Parameter Two");
});
AssertMatch(expectedHelp, actualHelp);
}
[Fact]
public void Help_Parameter_List()
{
var expectedHelp = @"
usage: tool <first> <second>...
<first> The first
<second>... The second
";
var actualHelp = GetHelp(syntax =>
{
var r = string.Empty;
var c = (IReadOnlyList<string>)null;
syntax.DefineParameter("first", ref r, "The first");
syntax.DefineParameterList("second", ref c, "The second");
});
AssertMatch(expectedHelp, actualHelp);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Help_OptionAndParameter(bool includeHidden)
{
var expectedHelp = @"
usage: tool [-o] [-x <arg>] [--] <p1> <p2>
-o Option #1
-x, --option2 <arg> Option #2
<p1> Parameter One
<p2> Parameter Two
";
var actualHelp = GetHelp(syntax =>
{
var o1 = false;
var o2 = string.Empty;
var p1 = string.Empty;
var p2 = false;
syntax.DefineOption("o", ref o1, "Option #1");
syntax.DefineOption("x|option2", ref o2, "Option #2");
if (includeHidden)
{
var h = syntax.DefineOption("h", string.Empty);
h.IsHidden = true;
}
syntax.DefineParameter("p1", ref p1, "Parameter One");
syntax.DefineParameter("p2", ref p2, "Parameter Two");
if (includeHidden)
{
var h = syntax.DefineParameter("h", string.Empty);
h.IsHidden = true;
}
});
AssertMatch(expectedHelp, actualHelp);
}
[Fact]
public void Help_Wrapping_Usage()
{
var expectedHelp = @"
usage: tool [-a] [-b] [-c] [-d] [-e] [-f] [-g] [-h]
[-i] [-j] [-k] [-l] [-m] [-n] [-o] [-p]
[-q]
-a a
-b b
-c c
-d d
-e e
-f f
-g g
-h h
-i i
-j j
-k k
-l l
-m m
-n n
-o o
-p p
-q q
";
var actualHelp = GetHelp(55, syntax =>
{
var f = false;
for (var c = 'a'; c <= 'q'; c++)
{
var cText = c.ToString();
syntax.DefineOption(cText, ref f, cText);
}
});
AssertMatch(expectedHelp, actualHelp);
}
[Fact]
public void Help_Wrapping_Usage_LongToken_First()
{
var expectedHelp = @"
usage: tool [--Lorem_ipsum_dolor_sit_amet_consectetur_adipiscing_elit_sed_do_eiusmod_tempor]
[-a] [-b] [-c] [-d]
--Lorem_ipsum_dolor_sit_amet_consectetur_adipiscing_elit_sed_do_eiusmod_tempor Lorem ipsum flag
-a a
-b b
-c c
-d d
";
var actualHelp = GetHelp(55, syntax =>
{
var f = false;
syntax.DefineOption("Lorem_ipsum_dolor_sit_amet_consectetur_adipiscing_elit_sed_do_eiusmod_tempor", ref f, "Lorem ipsum flag");
for (var c = 'a'; c <= 'd'; c++)
{
var cText = c.ToString();
syntax.DefineOption(cText, ref f, cText);
}
});
AssertMatch(expectedHelp, actualHelp);
}
[Fact]
public void Help_Wrapping_Usage_LongToken_Second()
{
var expectedHelp = @"
usage: tool [-a]
[--Lorem_ipsum_dolor_sit_amet_consectetur_adipiscing_elit_sed_do_eiusmod_tempor]
[-b] [-c] [-d]
-a a
--Lorem_ipsum_dolor_sit_amet_consectetur_adipiscing_elit_sed_do_eiusmod_tempor Lorem ipsum flag
-b b
-c c
-d d
";
var actualHelp = GetHelp(55, syntax =>
{
var f = false;
for (var c = 'a'; c <= 'd'; c++)
{
var cText = c.ToString();
syntax.DefineOption(cText, ref f, cText);
if (c == 'a')
syntax.DefineOption("Lorem_ipsum_dolor_sit_amet_consectetur_adipiscing_elit_sed_do_eiusmod_tempor", ref f, "Lorem ipsum flag");
}
});
AssertMatch(expectedHelp, actualHelp);
}
[Fact]
public void Help_Wrapping_Text()
{
var expectedHelp = @"
usage: tool [-s <arg>] [-f]
-s <arg> Lorem ipsum dolor sit amet, consectetur
adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.
-f Lorem ipsum dolor sit amet.
";
var actualHelp = GetHelp(55, syntax =>
{
var s = string.Empty;
var f = false;
syntax.DefineOption("s", ref s, "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.");
syntax.DefineOption("f", ref f, "Lorem ipsum dolor sit amet.");
});
AssertMatch(expectedHelp, actualHelp);
}
[Fact]
public void Help_Wrapping_Text_LongToken_First()
{
var expectedHelp = @"
usage: tool [-s <arg>] [-f]
-s <arg> Lorem_ipsum_dolor_sit_amet_consectetur_adipiscing_elit_sed_do_eiusmod_tempor
incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.
-f Lorem ipsum dolor sit amet.
";
var actualHelp = GetHelp(55, syntax =>
{
var s = string.Empty;
var f = false;
syntax.DefineOption("s", ref s, "Lorem_ipsum_dolor_sit_amet_consectetur_adipiscing_elit_sed_do_eiusmod_tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.");
syntax.DefineOption("f", ref f, "Lorem ipsum dolor sit amet.");
});
AssertMatch(expectedHelp, actualHelp);
}
[Fact]
public void Help_Wrapping_Text_LongToken_Second()
{
var expectedHelp = @"
usage: tool [-s <arg>] [-f]
-s <arg> Lorem
ipsum_dolor_sit_amet_consectetur_adipiscing_elit_sed_do_eiusmod_tempor
incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.
-f Lorem ipsum dolor sit amet.
";
var actualHelp = GetHelp(55, syntax =>
{
var s = string.Empty;
var f = false;
syntax.DefineOption("s", ref s, "Lorem ipsum_dolor_sit_amet_consectetur_adipiscing_elit_sed_do_eiusmod_tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.");
syntax.DefineOption("f", ref f, "Lorem ipsum dolor sit amet.");
});
AssertMatch(expectedHelp, actualHelp);
}
private static void AssertMatch(string expectedText, string actualText)
{
var expectedLines = SplitLines(expectedText);
RemoveLeadingBlankLines(expectedLines);
RemoveTrailingBlankLines(expectedLines);
UnindentLines(expectedLines);
var actualLines = SplitLines(actualText);
RemoveLeadingBlankLines(actualLines);
RemoveTrailingBlankLines(actualLines);
Assert.Equal(expectedLines.Count, actualLines.Count);
for (var i = 0; i < expectedLines.Count; i++)
Assert.Equal(expectedLines[i], actualLines[i]);
}
private static List<string> SplitLines(string expectedHelp)
{
var lines = new List<string>();
// Get lines
using (var stringReader = new StringReader(expectedHelp))
{
string line;
while ((line = stringReader.ReadLine()) != null)
lines.Add(line);
}
return lines;
}
private static void RemoveLeadingBlankLines(List<string> lines)
{
while (lines.Count > 0 && lines.First().Trim().Length == 0)
lines.RemoveAt(0);
}
private static void RemoveTrailingBlankLines(List<string> lines)
{
while (lines.Count > 0 && lines.Last().Trim().Length == 0)
lines.RemoveAt(lines.Count - 1);
}
private static void UnindentLines(List<string> lines)
{
var minIndent = lines.Where(l => l.Length > 0)
.Min(l => l.Length - l.TrimStart().Length);
for (var i = 0; i < lines.Count; i++)
{
if (lines[i].Length >= minIndent)
lines[i] = lines[i].Substring(minIndent);
}
}
private static string GetHelp(Action<ArgumentSyntax> defineAction)
{
return CreateSyntax(defineAction).GetHelpText();
}
private static string GetHelp(string commandLine, Action<ArgumentSyntax> defineAction)
{
return CreateSyntax(commandLine, defineAction).GetHelpText();
}
private static string GetHelp(int maxWidth, Action<ArgumentSyntax> defineAction)
{
return CreateSyntax(defineAction).GetHelpText(maxWidth);
}
private static ArgumentSyntax CreateSyntax(Action<ArgumentSyntax> defineAction)
{
return CreateSyntax(new string[0], defineAction);
}
private static ArgumentSyntax CreateSyntax(string commandLine, Action<ArgumentSyntax> defineAction)
{
var args = Splitter.Split(commandLine);
return CreateSyntax(args, defineAction);
}
private static ArgumentSyntax CreateSyntax(IEnumerable<string> arguments, Action<ArgumentSyntax> defineAction)
{
var syntax = new ArgumentSyntax(arguments);
syntax.ApplicationName = "tool";
defineAction(syntax);
return syntax;
}
}
}
| |
//#define InferenceWeb
using System;
using System.Collections.Generic;
using System.Threading;
using System.Web;
using NHibernate;
using NHibernate.Cfg;
using SchemaExport = NHibernate.Tool.hbm2ddl.SchemaExport;
using SchemaUpdate = NHibernate.Tool.hbm2ddl.SchemaUpdate;
//using Inference.Exceptions;
// TODO: Create an "ISessionStorage" interface with properties Session and Transaction (get and set)
// Then implement it for ThreadContext, HttpContext, CallContext, etc.
// Make NHibernateHelper select a SessionStorage and use it...
// Cf. Sample - Wiki_AndrewMayorovAspNet.zip
/* In Web.config
<httpModules>
<add name="NHibernateHelper_ThreadAndHttpContext"
type="NHibernateInAction.CaveatEmptor.Persistence.HttpRequestModule, NHibernateInAction.CaveatEmptor" />
* Or, in our case:
<add name="NHibernateHelper_ThreadAndHttpContext"
type="Alexandria.Persistence.HttpRequestModule, Alexandria" />
</httpModules>
*/
/* HttpRequestModule.cs
public class HttpRequestModule : IHttpModule
{
public String ModuleName
{
get { return "NHibernateHelper_ThreadAndHttpContext"; }
}
public void Init(HttpApplication application)
{
application.BeginRequest += new EventHandler(this.Application_BeginRequest);
application.EndRequest += new EventHandler(this.Application_EndRequest);
application.Error += new EventHandler(this.Application_Error);
}
private void Application_BeginRequest(object source, EventArgs e)
{
// Note: This is useless (because the session will be eventually created when needed)
// And it may be a waste of ressources because it might not be used at all
NHibernateHelper_ThreadAndHttpContext.GetSession();
}
private void Application_EndRequest(object source, EventArgs e)
{
NHibernateHelper_ThreadAndHttpContext.CloseSession();
}
private void Application_Error(object sender, EventArgs e)
{
// TODO: Useful to add?
// Most of the time, it should be possible to catch the error and rollback
NHibernateHelper_ThreadAndHttpContext.RollbackAndCloseSession();
}
public void Dispose() {}
}*/
namespace Inference.Persistence
{
interface IContextCache<T>
{
T Get();
void Store(T obj);
void Remove();
}
class ThreadCache<T> : IContextCache<T> where T : class
{
private readonly Dictionary<string, T> threadDictionary = new Dictionary<string, T>();
public ThreadCache()
{
}
public T Get()
{
T obj = null; // ISession session = null;
Thread threadCurrent = Thread.CurrentThread;
if (threadCurrent.Name == null)
{
threadCurrent.Name = Guid.NewGuid().ToString();
}
else if (threadDictionary.ContainsKey(threadCurrent.Name))
{
/*
object threadSession = _threadSessions[threadCurrent.Name];
if (threadSession != null)
{
session = (ISession)threadSession;
}
*/
obj = threadDictionary[threadCurrent.Name];
}
return obj; // session;
}
public void Store(T obj)
{
Thread threadCurrent = Thread.CurrentThread;
if (threadCurrent.Name == null)
{
threadCurrent.Name = Guid.NewGuid().ToString();
}
if (threadDictionary.ContainsKey(threadCurrent.Name))
{
threadDictionary[threadCurrent.Name] = obj;
}
else
{
threadDictionary.Add(threadCurrent.Name, obj);
}
}
public void Remove()
{
Thread threadCurrent = Thread.CurrentThread;
if (threadCurrent.Name != null && threadDictionary.ContainsKey(threadCurrent.Name))
{
threadDictionary.Remove(threadCurrent.Name);
}
}
}
#if InferenceWeb
class HttpContextCache<T> : IContextCache<T> where T : class
{
private readonly string key;
public HttpContextCache(string key)
{
this.key = key;
}
public T Get()
{
if (HttpContext.Current.Items.Contains(key))
{
return (T)HttpContext.Current.Items[key];
}
return null;
}
public void Store(T obj)
{
if (HttpContext.Current.Items.Contains(key))
{
HttpContext.Current.Items[key] = obj;
}
else
{
HttpContext.Current.Items.Add(key, obj);
}
}
public void Remove()
{
if (HttpContext.Current.Items.Contains(key))
{
HttpContext.Current.Items.Remove(key);
}
}
}
#endif
static class ContextCacheFactory
{
public static IContextCache<T> CreateContextCache<T>(string key) where T : class
{
#if InferenceWeb
if (HttpContext.Current != null)
{
return new HttpContextCache<T>(key);
}
#endif
return new ThreadCache<T>();
}
}
/// <summary>
/// Provides "Thread Context" and HttpContext to manage sessions.
/// </summary>
public static class NHibernateHelper_ThreadAndHttpContext
{
#region private static variables
private static readonly Configuration _configuration;
private static readonly ISessionFactory _sessionFactory;
#if OLD_20100219
private static Hashtable _threadSessions = new Hashtable();
private static readonly bool isHttpContextAvailable = (HttpContext.Current != null);
#endif
private const string _httpContextSessionKey = "NHibernate.ISession";
private const string _httpContextTransactionKey = "NHibernate.ITransaction";
private static readonly IContextCache<ISession> _sessionCache = ContextCacheFactory.CreateContextCache<ISession>(_httpContextSessionKey);
private static readonly IContextCache<ITransaction> _transactionCache = ContextCacheFactory.CreateContextCache<ITransaction>(_httpContextTransactionKey);
#endregion
#region constructors
/*
private NHibernateHelper_ThreadAndHttpContext()
{
}
*/
static NHibernateHelper_ThreadAndHttpContext()
{
try
{
/*
var cfg = new Configuration();
cfg.Configure();
cfg.AddAssembly(typeof (Product).Assembly);
const bool script = false;
const bool export = true;
const bool justDrop = false;
//const bool format = false;
//new SchemaExport(cfg).Execute(false, true, false, false);
new SchemaExport(cfg).Execute(script, export, justDrop);
*/
_configuration = new Configuration();
_configuration.Configure();
_configuration.AddAssembly(typeof(Inference.Domain.Clause).Assembly);
_sessionFactory = _configuration.BuildSessionFactory();
}
catch (Exception ex)
{
throw new Exception(System.Reflection.MethodInfo.GetCurrentMethod().Name + " error: ", ex);
}
}
#endregion
# region private static methods
/// <summary>
/// gets the current session
/// </summary>
private static ISession GetCurrentSession()
{
#if OLD_20100219
ISession session = null;
if (!isHttpContextAvailable)
{
session = GetCurrentThreadSession();
}
else
{
session = GetCurrentHttpContextSession();
}
return session;
#else
return _sessionCache.Get();
#endif
}
/// <summary>
/// sets the current session
/// </summary>
private static void StoreCurrentSession(ISession session)
{
#if OLD_20100219
if (!isHttpContextAvailable)
{
StoreCurrentThreadSession(session);
}
else
{
StoreCurrentHttpContextSession(session);
}
#else
_sessionCache.Store(session);
#endif
}
/// <summary>
/// sets the current session
/// </summary>
private static void RemoveCurrentSession()
{
#if OLD_20100219
if (!isHttpContextAvailable)
{
RemoveCurrentThreadSession();
}
else
{
RemoveCurrentHttpContextSession();
}
#else
_sessionCache.Remove();
#endif
}
private static ITransaction GetCurrentTransaction()
{
return _transactionCache.Get();
}
private static void StoreCurrentTransaction(ITransaction transaction)
{
_transactionCache.Store(transaction);
if (transaction != null && GetCurrentTransaction() == null)
{
throw new Exception("NHibernateHelper_ThreadAndHttpContext.StoreCurrentTransaction() failed.");
}
}
private static void RemoveCurrentTransaction()
{
_transactionCache.Remove();
}
# endregion
#if OLD_20100219
#region private static methods - HttpContext related
/// <summary>
/// gets the session for the current thread
/// </summary>
private static ISession GetCurrentHttpContextSession()
{
if (HttpContext.Current.Items.Contains(_httpContextSessionKey))
{
return (ISession)HttpContext.Current.Items[_httpContextSessionKey];
}
return null;
}
private static void StoreCurrentHttpContextSession(ISession session)
{
if (HttpContext.Current.Items.Contains(_httpContextSessionKey))
{
HttpContext.Current.Items[_httpContextSessionKey] = session;
}
else
{
HttpContext.Current.Items.Add(_httpContextSessionKey, session);
}
}
/// <summary>
/// remove the session for the currennt HttpContext
/// </summary>
private static void RemoveCurrentHttpContextSession()
{
if (HttpContext.Current.Items.Contains(_httpContextSessionKey))
{
HttpContext.Current.Items.Remove(_httpContextSessionKey);
}
}
#endregion
#region private static methods - ThreadContext related
/// <summary>
/// gets the session for the current thread
/// </summary>
private static ISession GetCurrentThreadSession()
{
ISession session = null;
Thread threadCurrent = Thread.CurrentThread;
if (threadCurrent.Name == null)
{
threadCurrent.Name = Guid.NewGuid().ToString();
}
else
{
object threadSession = _threadSessions[threadCurrent.Name];
if (threadSession != null)
{
session = (ISession)threadSession;
}
}
return session;
}
private static void StoreCurrentThreadSession(ISession session)
{
if (_threadSessions.Contains(Thread.CurrentThread.Name))
{
_threadSessions[Thread.CurrentThread.Name] = session;
}
else
{
_threadSessions.Add(Thread.CurrentThread.Name, session);
}
}
private static void RemoveCurrentThreadSession()
{
if (_threadSessions.Contains(Thread.CurrentThread.Name))
{
_threadSessions.Remove(Thread.CurrentThread.Name);
}
}
#endregion
#endif
#region public static methods
/// <summary>
/// gets a session (creates new one if none available)
/// </summary>
/// <returns>a session</returns>
public static ISession GetSession()
{
// ThAW 2011/07/23 : Test
//return _sessionFactory.OpenSession();
ISession session = GetCurrentSession();
if (session == null)
{
session = _sessionFactory.OpenSession();
}
if (!session.IsConnected)
{
session.Reconnect();
}
StoreCurrentSession(session);
return session;
}
/// <summary>
/// closes the current session
/// </summary>
public static void CloseSession()
{
ISession session = GetCurrentSession();
if (session == null)
{
return;
}
if (!session.IsConnected)
{
session.Reconnect();
}
session.Flush();
session.Close();
RemoveCurrentSession();
}
/// <summary>
/// disconnects the current session (if not in active transaction)
/// </summary>
public static void DisconnectSession()
{
ISession session = GetCurrentSession();
if (session == null)
{
return;
}
if (!session.IsConnected)
{
return;
}
if (session.Transaction == null || session.Transaction.WasCommitted || session.Transaction.WasRolledBack)
{
session.Disconnect();
}
}
/// <summary>Start a new database transaction.</summary>
public static void BeginTransaction()
{
ITransaction tx = GetCurrentTransaction(); // (ITransaction)CallContext.GetData(nameTransaction);
try
{
if (tx == null)
{
#if ENABLE_LOGGING
log.Debug("Starting new database transaction in this context.");
#endif
tx = GetSession().BeginTransaction();
StoreCurrentTransaction(tx); // CallContext.SetData(nameTransaction, tx);
}
}
catch (HibernateException /* ex */ )
{
throw; // new InfrastructureException(ex);
}
}
/// <summary>Commit the database transaction.</summary>
public static void CommitTransaction()
{
ITransaction tx = GetCurrentTransaction(); //(ITransaction)CallContext.GetData(nameTransaction);
try
{
if (tx != null && !tx.WasCommitted && !tx.WasRolledBack)
{
#if ENABLE_LOGGING
log.Debug("Committing database transaction of this context.");
#endif
tx.Commit();
}
RemoveCurrentTransaction(); // CallContext.SetData(nameTransaction, null);
}
catch (HibernateException /* ex */ )
{
RollbackTransaction();
throw; // new InfrastructureException(ex);
}
}
/// <summary>Roll back the database transaction.</summary>
public static void RollbackTransaction()
{
ITransaction tx = GetCurrentTransaction(); //(ITransaction)CallContext.GetData(nameTransaction);
try
{
RemoveCurrentTransaction(); // CallContext.SetData(nameTransaction, null);
if (tx != null && !tx.WasCommitted && !tx.WasRolledBack)
{
#if ENABLE_LOGGING
log.Debug("Trying to rollback database transaction of this context.");
#endif
tx.Rollback();
}
}
catch (HibernateException /* ex */ )
{
throw; // new InfrastructureException(ex);
}
finally
{
CloseSession();
}
}
public static SchemaExport GetSchemaExportObject()
{
return new SchemaExport(_configuration);
}
public static SchemaUpdate GetSchemaUpdateObject()
{
return new SchemaUpdate(_configuration);
}
#endregion
/*
#region public static properties
public static Configuration Configuration // ThAW
{
get
{
return _configuration;
}
}
#endregion
*/
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Azure.Devices.Client
{
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
#if !WINDOWS_UWP && !PCL
using System.Transactions;
#endif
static class TaskHelpers
{
public static readonly Task CompletedTask = Task.FromResult(default(VoidTaskResult));
/// <summary>
/// Create a Task based on Begin/End IAsyncResult pattern.
/// </summary>
/// <param name="begin"></param>
/// <param name="end"></param>
/// <param name="state">
/// This parameter helps reduce allocations by passing state to the Funcs. e.g.:
/// await TaskHelpers.CreateTask(
/// (c, s) => ((Transaction)s).BeginCommit(c, s),
/// (a) => ((Transaction)a.AsyncState).EndCommit(a),
/// transaction);
/// </param>
public static Task CreateTask(Func<AsyncCallback, object, IAsyncResult> begin, Action<IAsyncResult> end, object state = null)
{
Task retval;
try
{
retval = Task.Factory.FromAsync(begin, end, state);
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
var completionSource = new TaskCompletionSource<object>(state);
completionSource.SetException(ex);
retval = completionSource.Task;
}
return retval;
}
public static Task<T> CreateTask<T>(Func<AsyncCallback, object, IAsyncResult> begin, Func<IAsyncResult, T> end, object state = null)
{
Task<T> retval;
try
{
retval = Task<T>.Factory.FromAsync(begin, end, state);
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
var completionSource = new TaskCompletionSource<T>(state);
completionSource.SetException(ex);
retval = completionSource.Task;
}
return retval;
}
#if !WINDOWS_UWP && !PCL
/// <summary>
/// Create a Task based on Begin/End IAsyncResult pattern.
/// </summary>
/// <param name="transaction">The transaction (optional) to use. If not null a TransactionScope will be used when calling the begin Func.</param>
/// <param name="begin"></param>
/// <param name="end"></param>
/// <param name="state">
/// This parameter helps reduce allocations by passing state to the Funcs. e.g.:
/// await TaskHelpers.CreateTask(
/// (c, s) => ((Transaction)s).BeginCommit(c, s),
/// (a) => ((Transaction)a.AsyncState).EndCommit(a),
/// transaction);
/// </param>
public static Task CreateTransactionalTask(Transaction transaction, Func<AsyncCallback, object, IAsyncResult> begin, Action<IAsyncResult> end, object state = null)
{
Task retval;
TransactionScope scope = null;
try
{
scope = Fx.CreateTransactionScope(transaction);
retval = Task.Factory.FromAsync(begin, end, state);
Fx.CompleteTransactionScope(ref scope);
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
if (scope != null)
{
scope.Dispose();
}
var completionSource = new TaskCompletionSource<object>(state);
completionSource.SetException(ex);
retval = completionSource.Task;
}
return retval;
}
public static Task<TResult> CreateTransactionalTask<TResult>(Transaction transaction, Func<AsyncCallback, object, IAsyncResult> begin, Func<IAsyncResult, TResult> end)
{
Task<TResult> retval;
TransactionScope scope = null;
try
{
scope = Fx.CreateTransactionScope(transaction);
retval = Task.Factory.FromAsync(begin, end, null);
Fx.CompleteTransactionScope(ref scope);
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
if (scope != null)
{
scope.Dispose();
}
var completionSource = new TaskCompletionSource<TResult>();
completionSource.SetException(ex);
retval = completionSource.Task;
}
return retval;
}
#endif
public static Task ExecuteAndGetCompletedTask(Action action)
{
TaskCompletionSource<object> completedTcs = new TaskCompletionSource<object>();
try
{
action();
completedTcs.SetResult(null);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completedTcs.SetException(e);
}
return completedTcs.Task;
}
public static Task<TResult> ExecuteAndGetCompletedTask<TResult>(Func<TResult> function)
{
TaskCompletionSource<TResult> completedTcs = new TaskCompletionSource<TResult>();
try
{
completedTcs.SetResult(function());
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completedTcs.SetException(e);
}
return completedTcs.Task;
}
public static void Fork(this Task thisTask)
{
Fork(thisTask, "TaskExtensions.Fork");
}
public static void Fork(this Task thisTask, string tracingInfo)
{
Fx.Assert(thisTask != null, "task is required!");
thisTask.ContinueWith(t => Fx.Exception.TraceHandled(t.Exception, tracingInfo), TaskContinuationOptions.OnlyOnFaulted);
}
public static IAsyncResult ToAsyncResult(this Task task, AsyncCallback callback, object state)
{
if (task.AsyncState == state)
{
if (callback != null)
{
task.ContinueWith(
t => callback(task),
TaskContinuationOptions.ExecuteSynchronously);
}
return task;
}
var tcs = new TaskCompletionSource<object>(state);
task.ContinueWith(
_ =>
{
if (task.IsFaulted)
{
tcs.TrySetException(task.Exception.InnerExceptions);
}
else if (task.IsCanceled)
{
tcs.TrySetCanceled();
}
else
{
tcs.TrySetResult(null);
}
if (callback != null)
{
callback(tcs.Task);
}
},
TaskContinuationOptions.ExecuteSynchronously);
return tcs.Task;
}
public static IAsyncResult ToAsyncResult<TResult>(this Task<TResult> task, AsyncCallback callback, object state)
{
if (task.AsyncState == state)
{
if (callback != null)
{
task.ContinueWith(
t => callback(task),
TaskContinuationOptions.ExecuteSynchronously);
}
return task;
}
var tcs = new TaskCompletionSource<TResult>(state);
task.ContinueWith(
_ =>
{
if (task.IsFaulted)
{
tcs.TrySetException(task.Exception.InnerExceptions);
}
else if (task.IsCanceled)
{
tcs.TrySetCanceled();
}
else
{
tcs.TrySetResult(task.Result);
}
if (callback != null)
{
callback(tcs.Task);
}
},
TaskContinuationOptions.ExecuteSynchronously);
return tcs.Task;
}
public static void EndAsyncResult(IAsyncResult asyncResult)
{
Task task = asyncResult as Task;
if (task == null)
{
throw Fx.Exception.AsError(new ArgumentException(CommonResources.InvalidAsyncResult));
}
try
{
task.Wait();
}
catch (AggregateException ae)
{
ExceptionDispatcher.Throw(ae.GetBaseException());
}
}
public static TResult EndAsyncResult<TResult>(IAsyncResult asyncResult)
{
Task<TResult> task = asyncResult as Task<TResult>;
if (task == null)
{
throw Fx.Exception.AsError(new ArgumentException(CommonResources.InvalidAsyncResult));
}
try
{
return task.Result;
}
catch (AggregateException ae)
{
ExceptionDispatcher.Throw(ae.GetBaseException());
// Dummy Code
throw ae.GetBaseException();
}
}
internal static void MarshalTaskResults<TResult>(Task source, TaskCompletionSource<TResult> proxy)
{
Fx.Assert(source != null, "source Task is required!");
Fx.Assert(proxy != null, "proxy TaskCompletionSource is required!");
switch (source.Status)
{
case TaskStatus.Faulted:
var exception = source.Exception.GetBaseException();
proxy.TrySetException(exception);
break;
case TaskStatus.Canceled:
proxy.TrySetCanceled();
break;
case TaskStatus.RanToCompletion:
Task<TResult> castedSource = source as Task<TResult>;
proxy.TrySetResult(
castedSource == null ? default(TResult) : // source is a Task
castedSource.Result); // source is a Task<TResult>
break;
}
}
public static Task WithTimeoutNoException(this Task task, TimeSpan timeout)
{
return WithTimeoutNoException(task, timeout, CancellationToken.None);
}
public static async Task WithTimeoutNoException(this Task task, TimeSpan timeout, CancellationToken token)
{
if (timeout == TimeSpan.MaxValue)
{
timeout = Timeout.InfiniteTimeSpan;
}
if (task.IsCompleted || (timeout == Timeout.InfiniteTimeSpan && token == CancellationToken.None))
{
await task;
return;
}
using (var cts = CancellationTokenSource.CreateLinkedTokenSource(token))
{
if (task == await Task.WhenAny(task, Task.Delay(timeout, cts.Token)))
{
cts.Cancel();
await task;
}
}
}
public static Task WithTimeout(this Task task, TimeSpan timeout, Func<string> errorMessage)
{
return WithTimeout(task, timeout, errorMessage, CancellationToken.None);
}
public static async Task WithTimeout(this Task task, TimeSpan timeout, Func<string> errorMessage, CancellationToken token)
{
if (timeout == TimeSpan.MaxValue)
{
timeout = Timeout.InfiniteTimeSpan;
}
if (task.IsCompleted || (timeout == Timeout.InfiniteTimeSpan && token == CancellationToken.None))
{
await task;
return;
}
using (var cts = CancellationTokenSource.CreateLinkedTokenSource(token))
{
if (task == await Task.WhenAny(task, Task.Delay(timeout, cts.Token)))
{
cts.Cancel();
await task;
return;
}
}
throw new TimeoutException(errorMessage());
}
public static Task<T> WithTimeout<T>(this Task<T> task, TimeSpan timeout, Func<string> errorMessage)
{
return WithTimeout(task, timeout, errorMessage, CancellationToken.None);
}
public static async Task<T> WithTimeout<T>(this Task<T> task, TimeSpan timeout, Func<string> errorMessage, CancellationToken token)
{
if (timeout == TimeSpan.MaxValue)
{
timeout = Timeout.InfiniteTimeSpan;
}
if (task.IsCompleted || (timeout == Timeout.InfiniteTimeSpan && token == CancellationToken.None))
{
return await task;
}
using (var cts = CancellationTokenSource.CreateLinkedTokenSource(token))
{
if (task == await Task.WhenAny(task, Task.Delay(timeout, cts.Token)))
{
cts.Cancel();
return await task;
}
}
throw new TimeoutException(errorMessage());
}
[StructLayout(LayoutKind.Sequential, Size = 1)]
internal struct VoidTaskResult
{
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: MemoryMappedFile
**
** Purpose: Managed MemoryMappedFiles.
**
** Date: February 7, 2007
**
===========================================================*/
using System;
using System.Diagnostics;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.AccessControl;
using System.Security.Permissions;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
namespace System.IO.MemoryMappedFiles {
public class MemoryMappedFile : IDisposable {
private SafeMemoryMappedFileHandle _handle;
private bool _leaveOpen;
private FileStream _fileStream;
internal const int DefaultSize = 0;
// Private constructors to be used by the factory methods.
[System.Security.SecurityCritical]
private MemoryMappedFile(SafeMemoryMappedFileHandle handle) {
Debug.Assert(handle != null && !handle.IsClosed && !handle.IsInvalid, "handle is null, closed, or invalid");
_handle = handle;
_leaveOpen = true; // No FileStream to dispose of in this case.
}
[System.Security.SecurityCritical]
private MemoryMappedFile(SafeMemoryMappedFileHandle handle, FileStream fileStream, bool leaveOpen) {
Debug.Assert(handle != null && !handle.IsClosed && !handle.IsInvalid, "handle is null, closed, or invalid");
Debug.Assert(fileStream != null, "fileStream is null");
_handle = handle;
_fileStream = fileStream;
_leaveOpen = leaveOpen;
}
// Factory Method Group #1: Opens an existing named memory mapped file. The native OpenFileMapping call
// will check the desiredAccessRights against the ACL on the memory mapped file. Note that a memory
// mapped file created without an ACL will use a default ACL taken from the primary or impersonation token
// of the creator. On my machine, I always get ReadWrite access to it so I never have to use anything but
// the first override of this method. Note: having ReadWrite access to the object does not mean that we
// have ReadWrite access to the pages mapping the file. The OS will check against the access on the pages
// when a view is created.
public static MemoryMappedFile OpenExisting(string mapName) {
return OpenExisting(mapName, MemoryMappedFileRights.ReadWrite, HandleInheritability.None);
}
public static MemoryMappedFile OpenExisting(string mapName, MemoryMappedFileRights desiredAccessRights) {
return OpenExisting(mapName, desiredAccessRights, HandleInheritability.None);
}
[System.Security.SecurityCritical]
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public static MemoryMappedFile OpenExisting(string mapName, MemoryMappedFileRights desiredAccessRights,
HandleInheritability inheritability) {
if (mapName == null) {
throw new ArgumentNullException("mapName", SR.GetString(SR.ArgumentNull_MapName));
}
if (mapName.Length == 0) {
throw new ArgumentException(SR.GetString(SR.Argument_MapNameEmptyString));
}
if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) {
throw new ArgumentOutOfRangeException("inheritability");
}
if (((int)desiredAccessRights & ~((int)(MemoryMappedFileRights.FullControl | MemoryMappedFileRights.AccessSystemSecurity))) != 0) {
throw new ArgumentOutOfRangeException("desiredAccessRights");
}
SafeMemoryMappedFileHandle handle = OpenCore(mapName, inheritability, (int)desiredAccessRights, false);
return new MemoryMappedFile(handle);
}
// Factory Method Group #2: Creates a new memory mapped file where the content is taken from an existing
// file on disk. This file must be opened by a FileStream before given to us. Specifying DefaultSize to
// the capacity will make the capacity of the memory mapped file match the size of the file. Specifying
// a value larger than the size of the file will enlarge the new file to this size. Note that in such a
// case, the capacity (and there for the size of the file) will be rounded up to a multiple of the system
// page size. One can use FileStream.SetLength to bring the length back to a desirable size. By default,
// the MemoryMappedFile will close the FileStream object when it is disposed. This behavior can be
// changed by the leaveOpen boolean argument.
public static MemoryMappedFile CreateFromFile(String path) {
return CreateFromFile(path, FileMode.Open, null, DefaultSize, MemoryMappedFileAccess.ReadWrite);
}
public static MemoryMappedFile CreateFromFile(String path, FileMode mode) {
return CreateFromFile(path, mode, null, DefaultSize, MemoryMappedFileAccess.ReadWrite);
}
public static MemoryMappedFile CreateFromFile(String path, FileMode mode, String mapName) {
return CreateFromFile(path, mode, mapName, DefaultSize, MemoryMappedFileAccess.ReadWrite);
}
public static MemoryMappedFile CreateFromFile(String path, FileMode mode, String mapName, Int64 capacity) {
return CreateFromFile(path, mode, mapName, capacity, MemoryMappedFileAccess.ReadWrite);
}
[System.Security.SecurityCritical]
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public static MemoryMappedFile CreateFromFile(String path, FileMode mode, String mapName, Int64 capacity,
MemoryMappedFileAccess access) {
if (path == null) {
throw new ArgumentNullException("path");
}
if (mapName != null && mapName.Length == 0) {
throw new ArgumentException(SR.GetString(SR.Argument_MapNameEmptyString));
}
if (capacity < 0) {
throw new ArgumentOutOfRangeException("capacity", SR.GetString(SR.ArgumentOutOfRange_PositiveOrDefaultCapacityRequired));
}
if (access < MemoryMappedFileAccess.ReadWrite ||
access > MemoryMappedFileAccess.ReadWriteExecute) {
throw new ArgumentOutOfRangeException("access");
}
if (mode == FileMode.Append) {
throw new ArgumentException(SR.GetString(SR.Argument_NewMMFAppendModeNotAllowed), "mode");
}
if (access == MemoryMappedFileAccess.Write) {
throw new ArgumentException(SR.GetString(SR.Argument_NewMMFWriteAccessNotAllowed), "access");
}
bool existed = File.Exists(path);
FileStream fileStream = new FileStream(path, mode, GetFileStreamFileSystemRights(access), FileShare.None, 0x1000, FileOptions.None);
if (capacity == 0 && fileStream.Length == 0) {
CleanupFile(fileStream, existed, path);
throw new ArgumentException(SR.GetString(SR.Argument_EmptyFile));
}
if (access == MemoryMappedFileAccess.Read && capacity > fileStream.Length) {
CleanupFile(fileStream, existed, path);
throw new ArgumentException(SR.GetString(SR.Argument_ReadAccessWithLargeCapacity));
}
if (capacity == DefaultSize) {
capacity = fileStream.Length;
}
// one can always create a small view if they do not want to map an entire file
if (fileStream.Length > capacity) {
CleanupFile(fileStream, existed, path);
throw new ArgumentOutOfRangeException("capacity", SR.GetString(SR.ArgumentOutOfRange_CapacityGEFileSizeRequired));
}
SafeMemoryMappedFileHandle handle = null;
try {
handle = CreateCore(fileStream.SafeFileHandle, mapName, HandleInheritability.None, null,
access, MemoryMappedFileOptions.None, capacity);
}
catch {
CleanupFile(fileStream, existed, path);
throw;
}
Debug.Assert(handle != null && !handle.IsInvalid);
return new MemoryMappedFile(handle, fileStream, false);
}
[System.Security.SecurityCritical]
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public static MemoryMappedFile CreateFromFile(FileStream fileStream, String mapName, Int64 capacity,
MemoryMappedFileAccess access, MemoryMappedFileSecurity memoryMappedFileSecurity,
HandleInheritability inheritability, bool leaveOpen) {
if (fileStream == null) {
throw new ArgumentNullException("fileStream", SR.GetString(SR.ArgumentNull_FileStream));
}
if (mapName != null && mapName.Length == 0) {
throw new ArgumentException(SR.GetString(SR.Argument_MapNameEmptyString));
}
if (capacity < 0) {
throw new ArgumentOutOfRangeException("capacity", SR.GetString(SR.ArgumentOutOfRange_PositiveOrDefaultCapacityRequired));
}
if (capacity == 0 && fileStream.Length == 0) {
throw new ArgumentException(SR.GetString(SR.Argument_EmptyFile));
}
if (access < MemoryMappedFileAccess.ReadWrite ||
access > MemoryMappedFileAccess.ReadWriteExecute) {
throw new ArgumentOutOfRangeException("access");
}
if (access == MemoryMappedFileAccess.Write) {
throw new ArgumentException(SR.GetString(SR.Argument_NewMMFWriteAccessNotAllowed), "access");
}
if (access == MemoryMappedFileAccess.Read && capacity > fileStream.Length) {
throw new ArgumentException(SR.GetString(SR.Argument_ReadAccessWithLargeCapacity));
}
if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) {
throw new ArgumentOutOfRangeException("inheritability");
}
// flush any bytes written to the FileStream buffer so that we can see them in our MemoryMappedFile
fileStream.Flush();
if (capacity == DefaultSize) {
capacity = fileStream.Length;
}
// one can always create a small view if they do not want to map an entire file
if (fileStream.Length > capacity) {
throw new ArgumentOutOfRangeException("capacity", SR.GetString(SR.ArgumentOutOfRange_CapacityGEFileSizeRequired));
}
SafeMemoryMappedFileHandle handle = CreateCore(fileStream.SafeFileHandle, mapName, inheritability, memoryMappedFileSecurity,
access, MemoryMappedFileOptions.None, capacity);
return new MemoryMappedFile(handle, fileStream, leaveOpen);
}
// Factory Method Group #3: Creates a new empty memory mapped file. Such memory mapped files are ideal
// for IPC, when mapName != null.
public static MemoryMappedFile CreateNew(String mapName, Int64 capacity) {
return CreateNew(mapName, capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, null,
HandleInheritability.None);
}
public static MemoryMappedFile CreateNew(String mapName, Int64 capacity, MemoryMappedFileAccess access) {
return CreateNew(mapName, capacity, access, MemoryMappedFileOptions.None, null,
HandleInheritability.None);
}
[System.Security.SecurityCritical]
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public static MemoryMappedFile CreateNew(String mapName, Int64 capacity, MemoryMappedFileAccess access,
MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity,
HandleInheritability inheritability) {
if (mapName != null && mapName.Length == 0) {
throw new ArgumentException(SR.GetString(SR.Argument_MapNameEmptyString));
}
if (capacity <= 0) {
throw new ArgumentOutOfRangeException("capacity", SR.GetString(SR.ArgumentOutOfRange_NeedPositiveNumber));
}
if (IntPtr.Size == 4 && capacity > UInt32.MaxValue) {
throw new ArgumentOutOfRangeException("capacity", SR.GetString(SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed));
}
if (access < MemoryMappedFileAccess.ReadWrite ||
access > MemoryMappedFileAccess.ReadWriteExecute) {
throw new ArgumentOutOfRangeException("access");
}
if (access == MemoryMappedFileAccess.Write) {
throw new ArgumentException(SR.GetString(SR.Argument_NewMMFWriteAccessNotAllowed), "access");
}
if (((int)options & ~((int)(MemoryMappedFileOptions.DelayAllocatePages ))) != 0) {
throw new ArgumentOutOfRangeException("options");
}
if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) {
throw new ArgumentOutOfRangeException("inheritability");
}
SafeMemoryMappedFileHandle handle = CreateCore(new SafeFileHandle(new IntPtr(-1), true), mapName, inheritability,
memoryMappedFileSecurity, access, options, capacity);
return new MemoryMappedFile(handle);
}
// Factory Method Group #4: Creates a new empty memory mapped file or opens an existing
// memory mapped file if one exists with the same name. The capacity, options, and
// memoryMappedFileSecurity arguments will be ignored in the case of the later.
// This is ideal for P2P style IPC.
public static MemoryMappedFile CreateOrOpen(String mapName, Int64 capacity) {
return CreateOrOpen(mapName, capacity, MemoryMappedFileAccess.ReadWrite,
MemoryMappedFileOptions.None, null, HandleInheritability.None);
}
public static MemoryMappedFile CreateOrOpen(String mapName, Int64 capacity,
MemoryMappedFileAccess access) {
return CreateOrOpen(mapName, capacity, access, MemoryMappedFileOptions.None, null, HandleInheritability.None);
}
[System.Security.SecurityCritical]
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public static MemoryMappedFile CreateOrOpen(String mapName, Int64 capacity,
MemoryMappedFileAccess access, MemoryMappedFileOptions options,
MemoryMappedFileSecurity memoryMappedFileSecurity,
HandleInheritability inheritability) {
if (mapName == null) {
throw new ArgumentNullException("mapName", SR.GetString(SR.ArgumentNull_MapName));
}
if (mapName.Length == 0) {
throw new ArgumentException(SR.GetString(SR.Argument_MapNameEmptyString));
}
if (capacity <= 0) {
throw new ArgumentOutOfRangeException("capacity", SR.GetString(SR.ArgumentOutOfRange_NeedPositiveNumber));
}
if (IntPtr.Size == 4 && capacity > UInt32.MaxValue) {
throw new ArgumentOutOfRangeException("capacity", SR.GetString(SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed));
}
if (access < MemoryMappedFileAccess.ReadWrite ||
access > MemoryMappedFileAccess.ReadWriteExecute) {
throw new ArgumentOutOfRangeException("access");
}
if (((int)options & ~((int)(MemoryMappedFileOptions.DelayAllocatePages))) != 0) {
throw new ArgumentOutOfRangeException("options");
}
if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) {
throw new ArgumentOutOfRangeException("inheritability");
}
SafeMemoryMappedFileHandle handle;
// special case for write access; create will never succeed
if (access == MemoryMappedFileAccess.Write) {
handle = OpenCore(mapName, inheritability, GetFileMapAccess(access), true);
}
else {
handle = CreateOrOpenCore(new SafeFileHandle(new IntPtr(-1), true), mapName, inheritability,
memoryMappedFileSecurity, access, options, capacity);
}
return new MemoryMappedFile(handle);
}
// Used by the 2 Create factory method groups. A -1 fileHandle specifies that the
// memory mapped file should not be associated with an exsiting file on disk (ie start
// out empty).
[System.Security.SecurityCritical]
private static SafeMemoryMappedFileHandle CreateCore(SafeFileHandle fileHandle, String mapName,
HandleInheritability inheritability,
MemoryMappedFileSecurity memoryMappedFileSecurity,
MemoryMappedFileAccess access, MemoryMappedFileOptions options,
Int64 capacity) {
SafeMemoryMappedFileHandle handle = null;
Object pinningHandle;
UnsafeNativeMethods.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability, memoryMappedFileSecurity, out pinningHandle);
// split the long into two ints
Int32 capacityLow = (Int32)(capacity & 0x00000000FFFFFFFFL);
Int32 capacityHigh = (Int32)(capacity >> 32);
try {
handle = UnsafeNativeMethods.CreateFileMapping(fileHandle, secAttrs, GetPageAccess(access) | (int)options,
capacityHigh, capacityLow, mapName);
Int32 errorCode = Marshal.GetLastWin32Error();
if (!handle.IsInvalid && errorCode == UnsafeNativeMethods.ERROR_ALREADY_EXISTS) {
handle.Dispose();
__Error.WinIOError(errorCode, String.Empty);
}
else if (handle.IsInvalid) {
__Error.WinIOError(errorCode, String.Empty);
}
}
finally {
if (pinningHandle != null) {
GCHandle pinHandle = (GCHandle)pinningHandle;
pinHandle.Free();
}
}
return handle;
}
// Used by the OpenExisting factory method group and by CreateOrOpen if access is write.
// We'll throw an ArgumentException if the file mapping object didn't exist and the
// caller used CreateOrOpen since Create isn't valid with Write access
[System.Security.SecurityCritical]
private static SafeMemoryMappedFileHandle OpenCore(String mapName, HandleInheritability inheritability,
int desiredAccessRights, bool createOrOpen) {
SafeMemoryMappedFileHandle handle = UnsafeNativeMethods.OpenFileMapping(desiredAccessRights,
(inheritability & HandleInheritability.Inheritable) != 0, mapName);
Int32 lastError = Marshal.GetLastWin32Error();
if (handle.IsInvalid) {
if (createOrOpen && (lastError == UnsafeNativeMethods.ERROR_FILE_NOT_FOUND)) {
throw new ArgumentException(SR.GetString(SR.Argument_NewMMFWriteAccessNotAllowed), "access");
}
else {
__Error.WinIOError(lastError, String.Empty);
}
}
return handle;
}
// Used by the CreateOrOpen factory method groups. A -1 fileHandle specifies that the
// memory mapped file should not be associated with an existing file on disk (ie start
// out empty).
//
// Try to open the file if it exists -- this requires a bit more work. Loop until we can
// either create or open a memory mapped file up to a timeout. CreateFileMapping may fail
// if the file exists and we have non-null security attributes, in which case we need to
// use OpenFileMapping. But, there exists a race condition because the memory mapped file
// may have closed inbetween the two calls -- hence the loop.
//
// This uses similar retry/timeout logic as in performance counter. It increases the wait
// time each pass through the loop and times out in approximately 1.4 minutes. If after
// retrying, a MMF handle still hasn't been opened, throw an InvalidOperationException.
//
[System.Security.SecurityCritical]
private static SafeMemoryMappedFileHandle CreateOrOpenCore(SafeFileHandle fileHandle, String mapName,
HandleInheritability inheritability,
MemoryMappedFileSecurity memoryMappedFileSecurity,
MemoryMappedFileAccess access, MemoryMappedFileOptions options,
Int64 capacity) {
Debug.Assert(access != MemoryMappedFileAccess.Write, "Callers requesting write access shouldn't try to create a mmf");
SafeMemoryMappedFileHandle handle = null;
Object pinningHandle;
UnsafeNativeMethods.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability, memoryMappedFileSecurity, out pinningHandle);
// split the long into two ints
Int32 capacityLow = (Int32)(capacity & 0x00000000FFFFFFFFL);
Int32 capacityHigh = (Int32)(capacity >> 32);
try {
int waitRetries = 14; //((2^13)-1)*10ms == approximately 1.4mins
int waitSleep = 0;
// keep looping until we've exhausted retries or break as soon we we get valid handle
while (waitRetries > 0) {
// try to create
handle = UnsafeNativeMethods.CreateFileMapping(fileHandle, secAttrs,
GetPageAccess(access) | (int)options, capacityHigh, capacityLow, mapName);
Int32 createErrorCode = Marshal.GetLastWin32Error();
if (!handle.IsInvalid) {
break;
}
else {
if (createErrorCode != UnsafeNativeMethods.ERROR_ACCESS_DENIED) {
__Error.WinIOError(createErrorCode, String.Empty);
}
// the mapname exists but our ACL is preventing us from opening it with CreateFileMapping.
// Let's try to open it with OpenFileMapping.
handle.SetHandleAsInvalid();
}
// try to open
handle = UnsafeNativeMethods.OpenFileMapping(GetFileMapAccess(access), (inheritability &
HandleInheritability.Inheritable) != 0, mapName);
Int32 openErrorCode = Marshal.GetLastWin32Error();
// valid handle
if (!handle.IsInvalid) {
break;
}
// didn't get valid handle; have to retry
else {
if (openErrorCode != UnsafeNativeMethods.ERROR_FILE_NOT_FOUND) {
__Error.WinIOError(openErrorCode, String.Empty);
}
// increase wait time
--waitRetries;
if (waitSleep == 0) {
waitSleep = 10;
}
else {
System.Threading.Thread.Sleep(waitSleep);
waitSleep *= 2;
}
}
}
// finished retrying but couldn't create or open
if (handle == null || handle.IsInvalid) {
throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_CantCreateFileMapping));
}
}
finally {
if (pinningHandle != null) {
GCHandle pinHandle = (GCHandle)pinningHandle;
pinHandle.Free();
}
}
return handle;
}
// Creates a new view in the form of a stream.
public MemoryMappedViewStream CreateViewStream() {
return CreateViewStream(0, DefaultSize, MemoryMappedFileAccess.ReadWrite);
}
public MemoryMappedViewStream CreateViewStream(Int64 offset, Int64 size) {
return CreateViewStream(offset, size, MemoryMappedFileAccess.ReadWrite);
}
[System.Security.SecurityCritical]
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public MemoryMappedViewStream CreateViewStream(Int64 offset, Int64 size, MemoryMappedFileAccess access) {
if (offset < 0) {
throw new ArgumentOutOfRangeException("offset", SR.GetString(SR.ArgumentOutOfRange_NeedNonNegNum));
}
if (size < 0) {
throw new ArgumentOutOfRangeException("size", SR.GetString(SR.ArgumentOutOfRange_PositiveOrDefaultSizeRequired));
}
if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) {
throw new ArgumentOutOfRangeException("access");
}
if (IntPtr.Size == 4 && size > UInt32.MaxValue) {
throw new ArgumentOutOfRangeException("size", SR.GetString(SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed));
}
MemoryMappedView view = MemoryMappedView.CreateView(_handle, access, offset, size);
return new MemoryMappedViewStream(view);
}
// Creates a new view in the form of an accessor. Accessors are for random access.
public MemoryMappedViewAccessor CreateViewAccessor() {
return CreateViewAccessor(0, DefaultSize, MemoryMappedFileAccess.ReadWrite);
}
public MemoryMappedViewAccessor CreateViewAccessor(Int64 offset, Int64 size) {
return CreateViewAccessor(offset, size, MemoryMappedFileAccess.ReadWrite);
}
[System.Security.SecurityCritical]
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public MemoryMappedViewAccessor CreateViewAccessor(Int64 offset, Int64 size, MemoryMappedFileAccess access) {
if (offset < 0) {
throw new ArgumentOutOfRangeException("offset", SR.GetString(SR.ArgumentOutOfRange_NeedNonNegNum));
}
if (size < 0) {
throw new ArgumentOutOfRangeException("size", SR.GetString(SR.ArgumentOutOfRange_PositiveOrDefaultSizeRequired));
}
if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) {
throw new ArgumentOutOfRangeException("access");
}
if (IntPtr.Size == 4 && size > UInt32.MaxValue) {
throw new ArgumentOutOfRangeException("size", SR.GetString(SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed));
}
MemoryMappedView view = MemoryMappedView.CreateView(_handle, access, offset, size);
return new MemoryMappedViewAccessor(view);
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
[SecuritySafeCritical]
protected virtual void Dispose(bool disposing) {
try {
if (_handle != null && !_handle.IsClosed) {
_handle.Dispose();
}
}
finally {
if (_fileStream != null && _leaveOpen == false) {
_fileStream.Dispose();
}
}
}
public SafeMemoryMappedFileHandle SafeMemoryMappedFileHandle {
[SecurityCritical]
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
get {
return _handle;
}
}
[System.Security.SecurityCritical]
public MemoryMappedFileSecurity GetAccessControl() {
if (_handle.IsClosed) {
__Error.FileNotOpen();
}
return new MemoryMappedFileSecurity(_handle, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
[System.Security.SecurityCritical]
public void SetAccessControl(MemoryMappedFileSecurity memoryMappedFileSecurity) {
if (memoryMappedFileSecurity == null) {
throw new ArgumentNullException("memoryMappedFileSecurity");
}
if (_handle.IsClosed) {
__Error.FileNotOpen();
}
memoryMappedFileSecurity.PersistHandle(_handle);
}
// We don't need to expose this now that we have created views that can start at any address.
[System.Security.SecurityCritical]
internal static Int32 GetSystemPageAllocationGranularity() {
UnsafeNativeMethods.SYSTEM_INFO info = new UnsafeNativeMethods.SYSTEM_INFO();
UnsafeNativeMethods.GetSystemInfo(ref info);
return info.dwAllocationGranularity;
}
// This converts a MemoryMappedFileAccess to it's corresponding native PAGE_XXX value to be used by the
// factory methods that construct a new memory mapped file object. MemoryMappedFileAccess.Write is not
// valid here since there is no corresponding PAGE_XXX value.
internal static Int32 GetPageAccess(MemoryMappedFileAccess access) {
if (access == MemoryMappedFileAccess.Read) {
return UnsafeNativeMethods.PAGE_READONLY;
}
else if (access == MemoryMappedFileAccess.ReadWrite) {
return UnsafeNativeMethods.PAGE_READWRITE;
}
else if (access == MemoryMappedFileAccess.CopyOnWrite) {
return UnsafeNativeMethods.PAGE_WRITECOPY;
}
else if (access == MemoryMappedFileAccess.ReadExecute) {
return UnsafeNativeMethods.PAGE_EXECUTE_READ;
}
else if (access == MemoryMappedFileAccess.ReadWriteExecute) {
return UnsafeNativeMethods.PAGE_EXECUTE_READWRITE;
}
// If we reached here, access was invalid.
throw new ArgumentOutOfRangeException("access");
}
// This converts a MemoryMappedFileAccess to its corresponding native FILE_MAP_XXX value to be used when
// creating new views.
internal static Int32 GetFileMapAccess(MemoryMappedFileAccess access) {
if (access == MemoryMappedFileAccess.Read) {
return UnsafeNativeMethods.FILE_MAP_READ;
}
else if (access == MemoryMappedFileAccess.Write) {
return UnsafeNativeMethods.FILE_MAP_WRITE;
}
else if (access == MemoryMappedFileAccess.ReadWrite) {
return UnsafeNativeMethods.FILE_MAP_READ | UnsafeNativeMethods.FILE_MAP_WRITE;
}
else if (access == MemoryMappedFileAccess.CopyOnWrite) {
return UnsafeNativeMethods.FILE_MAP_COPY;
}
else if (access == MemoryMappedFileAccess.ReadExecute) {
return UnsafeNativeMethods.FILE_MAP_EXECUTE | UnsafeNativeMethods.FILE_MAP_READ;
}
else if (access == MemoryMappedFileAccess.ReadWriteExecute) {
return UnsafeNativeMethods.FILE_MAP_EXECUTE | UnsafeNativeMethods.FILE_MAP_READ |
UnsafeNativeMethods.FILE_MAP_WRITE;
}
// If we reached here, access was invalid.
throw new ArgumentOutOfRangeException("access");
}
// This converts a MemoryMappedFileAccess to a FileSystemRights for use by FileStream
private static FileSystemRights GetFileStreamFileSystemRights(MemoryMappedFileAccess access) {
switch (access) {
case MemoryMappedFileAccess.Read:
case MemoryMappedFileAccess.CopyOnWrite:
return FileSystemRights.ReadData;
case MemoryMappedFileAccess.ReadWrite:
return FileSystemRights.ReadData | FileSystemRights.WriteData;
case MemoryMappedFileAccess.Write:
return FileSystemRights.WriteData;
case MemoryMappedFileAccess.ReadExecute:
return FileSystemRights.ReadData | FileSystemRights.ExecuteFile;
case MemoryMappedFileAccess.ReadWriteExecute:
return FileSystemRights.ReadData | FileSystemRights.WriteData | FileSystemRights.ExecuteFile;
default:
// If we reached here, access was invalid.
throw new ArgumentOutOfRangeException("access");
}
}
// This converts a MemoryMappedFileAccess to a FileAccess. MemoryMappedViewStream and
// MemoryMappedViewAccessor subclass UnmanagedMemoryStream and UnmanagedMemoryAccessor, which both use
// FileAccess to determine whether they are writable and/or readable.
internal static FileAccess GetFileAccess(MemoryMappedFileAccess access) {
if (access == MemoryMappedFileAccess.Read) {
return FileAccess.Read;
}
if (access == MemoryMappedFileAccess.Write) {
return FileAccess.Write;
}
else if (access == MemoryMappedFileAccess.ReadWrite) {
return FileAccess.ReadWrite;
}
else if (access == MemoryMappedFileAccess.CopyOnWrite) {
return FileAccess.ReadWrite;
}
else if (access == MemoryMappedFileAccess.ReadExecute) {
return FileAccess.Read;
}
else if (access == MemoryMappedFileAccess.ReadWriteExecute) {
return FileAccess.ReadWrite;
}
// If we reached here, access was invalid.
throw new ArgumentOutOfRangeException("access");
}
// Helper method used to extract the native binary security descriptor from the MemoryMappedFileSecurity
// type. If pinningHandle is not null, caller must free it AFTER the call to CreateFile has returned.
[System.Security.SecurityCritical]
private unsafe static UnsafeNativeMethods.SECURITY_ATTRIBUTES GetSecAttrs(HandleInheritability inheritability,
MemoryMappedFileSecurity memoryMappedFileSecurity, out Object pinningHandle) {
pinningHandle = null;
UnsafeNativeMethods.SECURITY_ATTRIBUTES secAttrs = null;
if ((inheritability & HandleInheritability.Inheritable) != 0 ||
memoryMappedFileSecurity != null) {
secAttrs = new UnsafeNativeMethods.SECURITY_ATTRIBUTES();
secAttrs.nLength = (Int32)Marshal.SizeOf(secAttrs);
if ((inheritability & HandleInheritability.Inheritable) != 0) {
secAttrs.bInheritHandle = 1;
}
// For ACLs, get the security descriptor from the MemoryMappedFileSecurity.
if (memoryMappedFileSecurity != null) {
byte[] sd = memoryMappedFileSecurity.GetSecurityDescriptorBinaryForm();
pinningHandle = GCHandle.Alloc(sd, GCHandleType.Pinned);
fixed (byte* pSecDescriptor = sd)
secAttrs.pSecurityDescriptor = pSecDescriptor;
}
}
return secAttrs;
}
// clean up: close file handle and delete files we created
private static void CleanupFile(FileStream fileStream, bool existed, String path) {
fileStream.Close();
if (!existed) {
File.Delete(path);
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Effects;
using osu.Framework.Graphics.Primitives;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Input.Events;
using osu.Framework.Utils;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Types;
using osu.Game.Skinning;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Screens.Edit.Compose.Components.Timeline
{
public class TimelineHitObjectBlueprint : SelectionBlueprint<HitObject>
{
private const float circle_size = 38;
private Container repeatsContainer;
public Action<DragEvent> OnDragHandled;
[UsedImplicitly]
private readonly Bindable<double> startTime;
private Bindable<int> indexInCurrentComboBindable;
private Bindable<int> comboIndexBindable;
private Bindable<int> comboIndexWithOffsetsBindable;
private Bindable<Color4> displayColourBindable;
private readonly ExtendableCircle circle;
private readonly Border border;
private readonly Container colouredComponents;
private readonly OsuSpriteText comboIndexText;
[Resolved]
private ISkinSource skin { get; set; }
public TimelineHitObjectBlueprint(HitObject item)
: base(item)
{
Anchor = Anchor.CentreLeft;
Origin = Anchor.CentreLeft;
startTime = item.StartTimeBindable.GetBoundCopy();
startTime.BindValueChanged(time => X = (float)time.NewValue, true);
RelativePositionAxes = Axes.X;
RelativeSizeAxes = Axes.X;
Height = circle_size;
AddRangeInternal(new Drawable[]
{
circle = new ExtendableCircle
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
},
border = new Border
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
},
colouredComponents = new Container
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
comboIndexText = new OsuSpriteText
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.Centre,
Y = -1,
Font = OsuFont.Default.With(size: circle_size * 0.5f, weight: FontWeight.Regular),
},
}
},
});
if (item is IHasDuration)
{
colouredComponents.Add(new DragArea(item)
{
OnDragHandled = e => OnDragHandled?.Invoke(e)
});
}
}
protected override void LoadComplete()
{
base.LoadComplete();
switch (Item)
{
case IHasDisplayColour displayColour:
displayColourBindable = displayColour.DisplayColour.GetBoundCopy();
displayColourBindable.BindValueChanged(_ => updateColour(), true);
break;
case IHasComboInformation comboInfo:
indexInCurrentComboBindable = comboInfo.IndexInCurrentComboBindable.GetBoundCopy();
indexInCurrentComboBindable.BindValueChanged(_ => updateComboIndex(), true);
comboIndexBindable = comboInfo.ComboIndexBindable.GetBoundCopy();
comboIndexWithOffsetsBindable = comboInfo.ComboIndexWithOffsetsBindable.GetBoundCopy();
comboIndexBindable.BindValueChanged(_ => updateColour());
comboIndexWithOffsetsBindable.BindValueChanged(_ => updateColour(), true);
skin.SourceChanged += updateColour;
break;
}
}
protected override void OnSelected()
{
// base logic hides selected blueprints when not selected, but timeline doesn't do that.
updateColour();
}
protected override void OnDeselected()
{
// base logic hides selected blueprints when not selected, but timeline doesn't do that.
updateColour();
}
private void updateComboIndex() => comboIndexText.Text = (indexInCurrentComboBindable.Value + 1).ToString();
private void updateColour()
{
Color4 colour;
switch (Item)
{
case IHasDisplayColour displayColour:
colour = displayColour.DisplayColour.Value;
break;
case IHasComboInformation combo:
colour = combo.GetComboColour(skin);
break;
default:
return;
}
if (IsSelected)
{
border.Show();
colour = colour.Lighten(0.3f);
}
else
{
border.Hide();
}
if (Item is IHasDuration duration && duration.Duration > 0)
circle.Colour = ColourInfo.GradientHorizontal(colour, colour.Lighten(0.4f));
else
circle.Colour = colour;
var col = circle.Colour.TopLeft.Linear;
colouredComponents.Colour = OsuColour.ForegroundTextColourFor(col);
}
protected override void Update()
{
base.Update();
// no bindable so we perform this every update
float duration = (float)(Item.GetEndTime() - Item.StartTime);
if (Width != duration)
{
Width = duration;
// kind of haphazard but yeah, no bindables.
if (Item is IHasRepeats repeats)
updateRepeats(repeats);
}
}
private void updateRepeats(IHasRepeats repeats)
{
repeatsContainer?.Expire();
colouredComponents.Add(repeatsContainer = new Container
{
RelativeSizeAxes = Axes.Both,
});
for (int i = 0; i < repeats.RepeatCount; i++)
{
repeatsContainer.Add(new Circle
{
Size = new Vector2(circle_size / 3),
Alpha = 0.2f,
Anchor = Anchor.CentreLeft,
Origin = Anchor.Centre,
RelativePositionAxes = Axes.X,
X = (float)(i + 1) / (repeats.RepeatCount + 1),
});
}
}
protected override bool ShouldBeConsideredForInput(Drawable child) => true;
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) =>
circle.ReceivePositionalInputAt(screenSpacePos);
public override Quad SelectionQuad => circle.ScreenSpaceDrawQuad;
public override Vector2 ScreenSpaceSelectionPoint => ScreenSpaceDrawQuad.TopLeft;
public class DragArea : Circle
{
private readonly HitObject hitObject;
[Resolved]
private Timeline timeline { get; set; }
public Action<DragEvent> OnDragHandled;
public override bool HandlePositionalInput => hitObject != null;
public DragArea(HitObject hitObject)
{
this.hitObject = hitObject;
CornerRadius = circle_size / 2;
Masking = true;
Size = new Vector2(circle_size, 1);
Anchor = Anchor.CentreRight;
Origin = Anchor.Centre;
RelativePositionAxes = Axes.X;
RelativeSizeAxes = Axes.Y;
InternalChildren = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
}
};
}
protected override void LoadComplete()
{
base.LoadComplete();
updateState();
FinishTransforms();
}
protected override bool OnHover(HoverEvent e)
{
updateState();
return base.OnHover(e);
}
protected override void OnHoverLost(HoverLostEvent e)
{
updateState();
base.OnHoverLost(e);
}
private bool hasMouseDown;
protected override bool OnMouseDown(MouseDownEvent e)
{
hasMouseDown = true;
updateState();
return true;
}
protected override void OnMouseUp(MouseUpEvent e)
{
hasMouseDown = false;
updateState();
base.OnMouseUp(e);
}
private void updateState()
{
if (hasMouseDown)
{
this.ScaleTo(0.7f, 200, Easing.OutQuint);
}
else if (IsHovered)
{
this.ScaleTo(0.8f, 200, Easing.OutQuint);
}
else
{
this.ScaleTo(0.6f, 200, Easing.OutQuint);
}
this.FadeTo(IsHovered || hasMouseDown ? 0.8f : 0.2f, 200, Easing.OutQuint);
}
[Resolved]
private EditorBeatmap beatmap { get; set; }
[Resolved]
private IBeatSnapProvider beatSnapProvider { get; set; }
[Resolved(CanBeNull = true)]
private IEditorChangeHandler changeHandler { get; set; }
protected override bool OnDragStart(DragStartEvent e)
{
changeHandler?.BeginChange();
return true;
}
protected override void OnDrag(DragEvent e)
{
base.OnDrag(e);
OnDragHandled?.Invoke(e);
if (timeline.SnapScreenSpacePositionToValidTime(e.ScreenSpaceMousePosition).Time is double time)
{
switch (hitObject)
{
case IHasRepeats repeatHitObject:
// find the number of repeats which can fit in the requested time.
var lengthOfOneRepeat = repeatHitObject.Duration / (repeatHitObject.RepeatCount + 1);
var proposedCount = Math.Max(0, (int)Math.Round((time - hitObject.StartTime) / lengthOfOneRepeat) - 1);
if (proposedCount == repeatHitObject.RepeatCount)
return;
repeatHitObject.RepeatCount = proposedCount;
beatmap.Update(hitObject);
break;
case IHasDuration endTimeHitObject:
var snappedTime = Math.Max(hitObject.StartTime, beatSnapProvider.SnapTime(time));
if (endTimeHitObject.EndTime == snappedTime || Precision.AlmostEquals(snappedTime, hitObject.StartTime, beatmap.GetBeatLengthAtTime(snappedTime)))
return;
endTimeHitObject.Duration = snappedTime - hitObject.StartTime;
beatmap.Update(hitObject);
break;
}
}
}
protected override void OnDragEnd(DragEndEvent e)
{
base.OnDragEnd(e);
OnDragHandled?.Invoke(null);
changeHandler?.EndChange();
}
}
public class Border : ExtendableCircle
{
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
Content.Child.Alpha = 0;
Content.Child.AlwaysPresent = true;
Content.BorderColour = colours.Yellow;
Content.EdgeEffect = new EdgeEffectParameters();
}
}
/// <summary>
/// A circle with externalised end caps so it can take up the full width of a relative width area.
/// </summary>
public class ExtendableCircle : CompositeDrawable
{
protected readonly Circle Content;
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => Content.ReceivePositionalInputAt(screenSpacePos);
public override Quad ScreenSpaceDrawQuad => Content.ScreenSpaceDrawQuad;
public ExtendableCircle()
{
Padding = new MarginPadding { Horizontal = -circle_size / 2f };
InternalChild = Content = new Circle
{
BorderColour = OsuColour.Gray(0.75f),
BorderThickness = 4,
Masking = true,
RelativeSizeAxes = Axes.Both,
EdgeEffect = new EdgeEffectParameters
{
Type = EdgeEffectType.Shadow,
Radius = 5,
Colour = Color4.Black.Opacity(0.4f)
}
};
}
}
}
}
| |
// 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.Runtime;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Diagnostics;
using Internal.Runtime.Augments;
using Internal.Runtime.CompilerServices;
namespace System
{
// WARNING: Bartok hard-codes offsets to the delegate fields, so it's notion of where fields are may
// differ from the runtime's notion. Bartok honors sequential and explicit layout directives, so I've
// ordered the fields in such a way as to match the runtime's layout and then just tacked on this
// sequential layout directive so that Bartok matches it.
[StructLayout(LayoutKind.Sequential)]
[DebuggerDisplay("Target method(s) = {GetTargetMethodsDescriptionForDebugger()}")]
public abstract partial class Delegate : ICloneable
{
// This ctor exists solely to prevent C# from generating a protected .ctor that violates the surface area. I really want this to be a
// "protected-and-internal" rather than "internal" but C# has no keyword for the former.
internal Delegate()
{
// ! Do NOT put any code here. Delegate constructers are not guaranteed to be executed.
}
// New Delegate Implementation
internal protected object m_firstParameter;
internal protected object m_helperObject;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2111:PointersShouldNotBeVisible")]
internal protected IntPtr m_extraFunctionPointerOrData;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2111:PointersShouldNotBeVisible")]
internal protected IntPtr m_functionPointer;
[ThreadStatic]
protected static string s_DefaultValueString;
// WARNING: These constants are also declared in System.Private.TypeLoader\Internal\Runtime\TypeLoader\CallConverterThunk.cs
// Do not change their values without updating the values in the calling convention converter component
protected const int MulticastThunk = 0;
protected const int ClosedStaticThunk = 1;
protected const int OpenStaticThunk = 2;
protected const int ClosedInstanceThunkOverGenericMethod = 3; // This may not exist
protected const int DelegateInvokeThunk = 4;
protected const int OpenInstanceThunk = 5; // This may not exist
protected const int ReversePinvokeThunk = 6; // This may not exist
protected const int ObjectArrayThunk = 7; // This may not exist
//
// If the thunk does not exist, the function will return IntPtr.Zero.
protected virtual IntPtr GetThunk(int whichThunk)
{
#if DEBUG
// The GetThunk function should be overriden on all delegate types, except for universal
// canonical delegates which use calling convention converter thunks to marshal arguments
// for the delegate call. If we execute this version of GetThunk, we can at least assert
// that the current delegate type is a generic type.
Debug.Assert(this.EETypePtr.IsGeneric);
#endif
return TypeLoaderExports.GetDelegateThunk(this, whichThunk);
}
//
// If there is a default value string, the overridden function should set the
// s_DefaultValueString field and return true.
protected virtual bool LoadDefaultValueString() { return false; }
/// <summary>
/// Used by various parts of the runtime as a replacement for Delegate.Method
///
/// The Interop layer uses this to distinguish between different methods on a
/// single type, and to get the function pointer for delegates to static functions
///
/// The reflection apis use this api to figure out what MethodInfo is related
/// to a delegate.
///
/// </summary>
/// <param name="typeOfFirstParameterIfInstanceDelegate">
/// This value indicates which type an delegate's function pointer is associated with
/// This value is ONLY set for delegates where the function pointer points at an instance method
/// </param>
/// <param name="isOpenResolver">
/// This value indicates if the returned pointer is an open resolver structure.
/// </param>
/// <returns></returns>
unsafe internal IntPtr GetFunctionPointer(out RuntimeTypeHandle typeOfFirstParameterIfInstanceDelegate, out bool isOpenResolver)
{
typeOfFirstParameterIfInstanceDelegate = default(RuntimeTypeHandle);
isOpenResolver = false;
if (GetThunk(MulticastThunk) == m_functionPointer)
{
return IntPtr.Zero;
}
else if (m_extraFunctionPointerOrData != IntPtr.Zero)
{
if (GetThunk(OpenInstanceThunk) == m_functionPointer)
{
typeOfFirstParameterIfInstanceDelegate = ((OpenMethodResolver*)m_extraFunctionPointerOrData)->DeclaringType;
isOpenResolver = true;
}
return m_extraFunctionPointerOrData;
}
else
{
if (m_firstParameter != null)
typeOfFirstParameterIfInstanceDelegate = new RuntimeTypeHandle(m_firstParameter.EETypePtr);
// TODO! Implementation issue for generic invokes here ... we need another IntPtr for uniqueness.
return m_functionPointer;
}
}
// @todo: Not an api but some NativeThreadPool code still depends on it.
internal IntPtr GetNativeFunctionPointer()
{
// CORERT-TODO: PInvoke delegate marshalling
#if !CORERT
if (GetThunk(ReversePinvokeThunk) != m_functionPointer)
{
throw new InvalidOperationException("GetNativeFunctionPointer may only be used on a reverse pinvoke delegate");
}
#endif
return m_extraFunctionPointerOrData;
}
// This function is known to the IL Transformer.
protected void InitializeClosedInstance(object firstParameter, IntPtr functionPointer)
{
if (firstParameter == null)
throw new ArgumentException(SR.Arg_DlgtNullInst);
m_functionPointer = functionPointer;
m_firstParameter = firstParameter;
}
// This function is known to the IL Transformer.
protected void InitializeClosedInstanceSlow(object firstParameter, IntPtr functionPointer)
{
// This method is like InitializeClosedInstance, but it handles ALL cases. In particular, it handles generic method with fun function pointers.
if (firstParameter == null)
throw new ArgumentException(SR.Arg_DlgtNullInst);
if (!FunctionPointerOps.IsGenericMethodPointer(functionPointer))
{
m_functionPointer = functionPointer;
m_firstParameter = firstParameter;
}
else
{
m_firstParameter = this;
m_functionPointer = GetThunk(ClosedInstanceThunkOverGenericMethod);
m_extraFunctionPointerOrData = functionPointer;
m_helperObject = firstParameter;
}
}
// This function is known to the IL Transformer.
protected void InitializeClosedInstanceWithGVMResolution(object firstParameter, RuntimeMethodHandle tokenOfGenericVirtualMethod)
{
if (firstParameter == null)
throw new ArgumentException(SR.Arg_DlgtNullInst);
IntPtr functionResolution = TypeLoaderExports.GVMLookupForSlot(firstParameter, tokenOfGenericVirtualMethod);
if (functionResolution == IntPtr.Zero)
{
// TODO! What to do when GVM resolution fails. Should never happen
throw new InvalidOperationException();
}
if (!FunctionPointerOps.IsGenericMethodPointer(functionResolution))
{
m_functionPointer = functionResolution;
m_firstParameter = firstParameter;
}
else
{
m_firstParameter = this;
m_functionPointer = GetThunk(ClosedInstanceThunkOverGenericMethod);
m_extraFunctionPointerOrData = functionResolution;
m_helperObject = firstParameter;
}
return;
}
// This is used to implement MethodInfo.CreateDelegate() in a desktop-compatible way. Yes, the desktop really
// let you use that api to invoke an instance method with a null 'this'.
private void InitializeClosedInstanceWithoutNullCheck(object firstParameter, IntPtr functionPointer)
{
if (!FunctionPointerOps.IsGenericMethodPointer(functionPointer))
{
m_functionPointer = functionPointer;
m_firstParameter = firstParameter;
}
else
{
m_firstParameter = this;
m_functionPointer = GetThunk(ClosedInstanceThunkOverGenericMethod);
m_extraFunctionPointerOrData = functionPointer;
m_helperObject = firstParameter;
}
}
// This function is known to the IL Transformer.
protected void InitializeClosedStaticThunk(object firstParameter, IntPtr functionPointer, IntPtr functionPointerThunk)
{
m_extraFunctionPointerOrData = functionPointer;
m_helperObject = firstParameter;
m_functionPointer = functionPointerThunk;
m_firstParameter = this;
}
// This function is known to the IL Transformer.
protected void InitializeOpenStaticThunk(IntPtr functionPointer, IntPtr functionPointerThunk)
{
// This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself.
m_firstParameter = this;
m_functionPointer = functionPointerThunk;
m_extraFunctionPointerOrData = functionPointer;
}
// This function is known to the IL Transformer.
protected void InitializeOpenInstanceThunk(IntPtr functionPointer, IntPtr functionPointerThunk)
{
// This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself.
m_firstParameter = this;
m_functionPointer = functionPointerThunk;
OpenMethodResolver instanceMethodResolver = new OpenMethodResolver(default(RuntimeTypeHandle), functionPointer, 0);
m_extraFunctionPointerOrData = instanceMethodResolver.ToIntPtr();
}
protected void InitializeOpenInstanceThunkDynamic(IntPtr functionPointer, IntPtr functionPointerThunk)
{
// This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself.
m_firstParameter = this;
m_functionPointer = functionPointerThunk;
m_extraFunctionPointerOrData = functionPointer;
}
internal void SetClosedStaticFirstParameter(object firstParameter)
{
// Closed static delegates place a value in m_helperObject that they pass to the target method.
Debug.Assert(m_functionPointer == GetThunk(ClosedStaticThunk));
m_helperObject = firstParameter;
}
// This function is only ever called by the open instance method thunk, and in that case,
// m_extraFunctionPointerOrData always points to an OpenMethodResolver
[MethodImpl(MethodImplOptions.NoInlining)]
protected IntPtr GetActualTargetFunctionPointer(object thisObject)
{
return OpenMethodResolver.ResolveMethod(m_extraFunctionPointerOrData, thisObject);
}
public override int GetHashCode()
{
return GetType().GetHashCode();
}
private bool IsDynamicDelegate()
{
if (this.GetThunk(MulticastThunk) == IntPtr.Zero)
{
return true;
}
return false;
}
public object DynamicInvoke(params object[] args)
{
if (IsDynamicDelegate())
{
// DynamicDelegate case
return ((Func<object[], object>)m_helperObject)(args);
}
else
{
IntPtr invokeThunk = this.GetThunk(DelegateInvokeThunk);
return System.InvokeUtils.CallDynamicInvokeMethod(this.m_firstParameter, this.m_functionPointer, this, invokeThunk, IntPtr.Zero, this, args);
}
}
public unsafe static Delegate Combine(Delegate a, Delegate b)
{
if (a == null)
return b;
if (b == null)
return a;
return a.CombineImpl(b);
}
public static Delegate Remove(Delegate source, Delegate value)
{
if (source == null)
return null;
if (value == null)
return source;
if (!InternalEqualTypes(source, value))
throw new ArgumentException("The types of 'source' and 'value' should match.");
return source.RemoveImpl(value);
}
public static Delegate RemoveAll(Delegate source, Delegate value)
{
Delegate newDelegate = null;
do
{
newDelegate = source;
source = Remove(source, value);
}
while (newDelegate != source);
return newDelegate;
}
// Used to support the C# compiler in implementing the "+" operator for delegates
public static Delegate Combine(params Delegate[] delegates)
{
if ((delegates == null) || (delegates.Length == 0))
return null;
Delegate d = delegates[0];
for (int i = 1; i < delegates.Length; i++)
{
d = Combine(d, delegates[i]);
}
return d;
}
private MulticastDelegate NewMulticastDelegate(Delegate[] invocationList, int invocationCount, bool thisIsMultiCastAlready)
{
// First, allocate a new multicast delegate just like this one, i.e. same type as the this object
MulticastDelegate result = (MulticastDelegate)RuntimeImports.RhNewObject(this.EETypePtr);
// Performance optimization - if this already points to a true multicast delegate,
// copy _methodPtr and _methodPtrAux fields rather than calling into the EE to get them
if (thisIsMultiCastAlready)
{
result.m_functionPointer = this.m_functionPointer;
}
else
{
result.m_functionPointer = GetThunk(MulticastThunk);
}
result.m_firstParameter = result;
result.m_helperObject = invocationList;
result.m_extraFunctionPointerOrData = (IntPtr)invocationCount;
return result;
}
internal MulticastDelegate NewMulticastDelegate(Delegate[] invocationList, int invocationCount)
{
return NewMulticastDelegate(invocationList, invocationCount, false);
}
private bool TrySetSlot(Delegate[] a, int index, Delegate o)
{
if (a[index] == null && System.Threading.Interlocked.CompareExchange<Delegate>(ref a[index], o, null) == null)
return true;
// The slot may be already set because we have added and removed the same method before.
// Optimize this case, because it's cheaper than copying the array.
if (a[index] != null)
{
MulticastDelegate d = (MulticastDelegate)o;
MulticastDelegate dd = (MulticastDelegate)a[index];
if (Object.ReferenceEquals(dd.m_firstParameter, d.m_firstParameter) &&
Object.ReferenceEquals(dd.m_helperObject, d.m_helperObject) &&
dd.m_extraFunctionPointerOrData == d.m_extraFunctionPointerOrData &&
dd.m_functionPointer == d.m_functionPointer)
{
return true;
}
}
return false;
}
// This method will combine this delegate with the passed delegate
// to form a new delegate.
internal Delegate CombineImpl(Delegate follow)
{
if ((Object)follow == null) // cast to object for a more efficient test
return this;
// Verify that the types are the same...
if (!InternalEqualTypes(this, follow))
throw new ArgumentException();
if (IsDynamicDelegate() && follow.IsDynamicDelegate())
{
throw new InvalidOperationException();
}
MulticastDelegate dFollow = (MulticastDelegate)follow;
Delegate[] resultList;
int followCount = 1;
Delegate[] followList = dFollow.m_helperObject as Delegate[];
if (followList != null)
followCount = (int)dFollow.m_extraFunctionPointerOrData;
int resultCount;
Delegate[] invocationList = m_helperObject as Delegate[];
if (invocationList == null)
{
resultCount = 1 + followCount;
resultList = new Delegate[resultCount];
resultList[0] = this;
if (followList == null)
{
resultList[1] = dFollow;
}
else
{
for (int i = 0; i < followCount; i++)
resultList[1 + i] = followList[i];
}
return NewMulticastDelegate(resultList, resultCount);
}
else
{
int invocationCount = (int)m_extraFunctionPointerOrData;
resultCount = invocationCount + followCount;
resultList = null;
if (resultCount <= invocationList.Length)
{
resultList = invocationList;
if (followList == null)
{
if (!TrySetSlot(resultList, invocationCount, dFollow))
resultList = null;
}
else
{
for (int i = 0; i < followCount; i++)
{
if (!TrySetSlot(resultList, invocationCount + i, followList[i]))
{
resultList = null;
break;
}
}
}
}
if (resultList == null)
{
int allocCount = invocationList.Length;
while (allocCount < resultCount)
allocCount *= 2;
resultList = new Delegate[allocCount];
for (int i = 0; i < invocationCount; i++)
resultList[i] = invocationList[i];
if (followList == null)
{
resultList[invocationCount] = dFollow;
}
else
{
for (int i = 0; i < followCount; i++)
resultList[invocationCount + i] = followList[i];
}
}
return NewMulticastDelegate(resultList, resultCount, true);
}
}
private Delegate[] DeleteFromInvocationList(Delegate[] invocationList, int invocationCount, int deleteIndex, int deleteCount)
{
Delegate[] thisInvocationList = m_helperObject as Delegate[];
int allocCount = thisInvocationList.Length;
while (allocCount / 2 >= invocationCount - deleteCount)
allocCount /= 2;
Delegate[] newInvocationList = new Delegate[allocCount];
for (int i = 0; i < deleteIndex; i++)
newInvocationList[i] = invocationList[i];
for (int i = deleteIndex + deleteCount; i < invocationCount; i++)
newInvocationList[i - deleteCount] = invocationList[i];
return newInvocationList;
}
private bool EqualInvocationLists(Delegate[] a, Delegate[] b, int start, int count)
{
for (int i = 0; i < count; i++)
{
if (!(a[start + i].Equals(b[i])))
return false;
}
return true;
}
// This method currently looks backward on the invocation list
// for an element that has Delegate based equality with value. (Doesn't
// look at the invocation list.) If this is found we remove it from
// this list and return a new delegate. If its not found a copy of the
// current list is returned.
internal Delegate RemoveImpl(Delegate value)
{
// There is a special case were we are removing using a delegate as
// the value we need to check for this case
//
MulticastDelegate v = value as MulticastDelegate;
if (v == null)
return this;
if (v.m_helperObject as Delegate[] == null)
{
Delegate[] invocationList = m_helperObject as Delegate[];
if (invocationList == null)
{
// they are both not real Multicast
if (this.Equals(value))
return null;
}
else
{
int invocationCount = (int)m_extraFunctionPointerOrData;
for (int i = invocationCount; --i >= 0;)
{
if (value.Equals(invocationList[i]))
{
if (invocationCount == 2)
{
// Special case - only one value left, either at the beginning or the end
return invocationList[1 - i];
}
else
{
Delegate[] list = DeleteFromInvocationList(invocationList, invocationCount, i, 1);
return NewMulticastDelegate(list, invocationCount - 1, true);
}
}
}
}
}
else
{
Delegate[] invocationList = m_helperObject as Delegate[];
if (invocationList != null)
{
int invocationCount = (int)m_extraFunctionPointerOrData;
int vInvocationCount = (int)v.m_extraFunctionPointerOrData;
for (int i = invocationCount - vInvocationCount; i >= 0; i--)
{
if (EqualInvocationLists(invocationList, v.m_helperObject as Delegate[], i, vInvocationCount))
{
if (invocationCount - vInvocationCount == 0)
{
// Special case - no values left
return null;
}
else if (invocationCount - vInvocationCount == 1)
{
// Special case - only one value left, either at the beginning or the end
return invocationList[i != 0 ? 0 : invocationCount - 1];
}
else
{
Delegate[] list = DeleteFromInvocationList(invocationList, invocationCount, i, vInvocationCount);
return NewMulticastDelegate(list, invocationCount - vInvocationCount, true);
}
}
}
}
}
return this;
}
public virtual Delegate[] GetInvocationList()
{
Delegate[] del;
Delegate[] invocationList = m_helperObject as Delegate[];
if (invocationList == null)
{
del = new Delegate[1];
del[0] = this;
}
else
{
// Create an array of delegate copies and each
// element into the array
int invocationCount = (int)m_extraFunctionPointerOrData;
del = new Delegate[invocationCount];
for (int i = 0; i < invocationCount; i++)
del[i] = invocationList[i];
}
return del;
}
public MethodInfo Method
{
get
{
return GetMethodImpl();
}
}
protected virtual MethodInfo GetMethodImpl()
{
return RuntimeAugments.Callbacks.GetDelegateMethod(this);
}
public override bool Equals(Object obj)
{
// It is expected that all real uses of the Equals method will hit the MulticastDelegate.Equals logic instead of this
// therefore, instead of duplicating the desktop behavior where direct calls to this Equals function do not behave
// correctly, we'll just throw here.
throw new PlatformNotSupportedException();
}
public static bool operator ==(Delegate d1, Delegate d2)
{
if ((Object)d1 == null)
return (Object)d2 == null;
return d1.Equals(d2);
}
public static bool operator !=(Delegate d1, Delegate d2)
{
if ((Object)d1 == null)
return (Object)d2 != null;
return !d1.Equals(d2);
}
public Object Target
{
get
{
// Multi-cast delegates return the Target of the last delegate in the list
if (m_functionPointer == GetThunk(MulticastThunk))
{
Delegate[] invocationList = (Delegate[])m_helperObject;
int invocationCount = (int)m_extraFunctionPointerOrData;
return invocationList[invocationCount - 1].Target;
}
// Closed static delegates place a value in m_helperObject that they pass to the target method.
if (m_functionPointer == GetThunk(ClosedStaticThunk) ||
m_functionPointer == GetThunk(ClosedInstanceThunkOverGenericMethod) ||
m_functionPointer == GetThunk(ObjectArrayThunk))
return m_helperObject;
// Other non-closed thunks can be identified as the m_firstParameter field points at this.
if (Object.ReferenceEquals(m_firstParameter, this))
{
return null;
}
// Closed instance delegates place a value in m_firstParameter, and we've ruled out all other types of delegates
return m_firstParameter;
}
}
public virtual object Clone()
{
return MemberwiseClone();
}
internal bool IsOpenStatic
{
get
{
return GetThunk(OpenStaticThunk) == m_functionPointer;
}
}
internal static bool InternalEqualTypes(object a, object b)
{
return a.EETypePtr == b.EETypePtr;
}
// Returns a new delegate of the specified type whose implementation is provied by the
// provided delegate.
internal static Delegate CreateObjectArrayDelegate(Type t, Func<object[], object> handler)
{
EETypePtr delegateEEType;
if (!t.TryGetEEType(out delegateEEType))
{
throw new InvalidOperationException();
}
if (!delegateEEType.IsDefType || delegateEEType.IsGenericTypeDefinition)
{
throw new InvalidOperationException();
}
Delegate del = (Delegate)(RuntimeImports.RhNewObject(delegateEEType));
IntPtr objArrayThunk = del.GetThunk(Delegate.ObjectArrayThunk);
if (objArrayThunk == IntPtr.Zero)
{
throw new InvalidOperationException();
}
del.m_helperObject = handler;
del.m_functionPointer = objArrayThunk;
del.m_firstParameter = del;
return del;
}
//
// Internal (and quite unsafe) helper to create delegates of an arbitrary type. This is used to support Reflection invoke.
//
// Note that delegates constructed the normal way do not come through here. The IL transformer generates the equivalent of
// this code customized for each delegate type.
//
internal static Delegate CreateDelegate(EETypePtr delegateEEType, IntPtr ldftnResult, Object thisObject, bool isStatic, bool isOpen)
{
Delegate del = (Delegate)(RuntimeImports.RhNewObject(delegateEEType));
// What? No constructor call? That's right, and it's not an oversight. All "construction" work happens in
// the Initialize() methods. This helper has a hard dependency on this invariant.
if (isStatic)
{
if (isOpen)
{
IntPtr thunk = del.GetThunk(Delegate.OpenStaticThunk);
del.InitializeOpenStaticThunk(ldftnResult, thunk);
}
else
{
IntPtr thunk = del.GetThunk(Delegate.ClosedStaticThunk);
del.InitializeClosedStaticThunk(thisObject, ldftnResult, thunk);
}
}
else
{
if (isOpen)
{
IntPtr thunk = del.GetThunk(Delegate.OpenInstanceThunk);
del.InitializeOpenInstanceThunkDynamic(ldftnResult, thunk);
}
else
{
del.InitializeClosedInstanceWithoutNullCheck(thisObject, ldftnResult);
}
}
return del;
}
private string GetTargetMethodsDescriptionForDebugger()
{
if (m_functionPointer == GetThunk(MulticastThunk))
{
// Multi-cast delegates return the Target of the last delegate in the list
Delegate[] invocationList = (Delegate[])m_helperObject;
int invocationCount = (int)m_extraFunctionPointerOrData;
StringBuilder builder = new StringBuilder();
for (int c = 0; c < invocationCount; c++)
{
if (c != 0)
builder.Append(", ");
builder.Append(invocationList[c].GetTargetMethodsDescriptionForDebugger());
}
return builder.ToString();
}
else
{
RuntimeTypeHandle typeOfFirstParameterIfInstanceDelegate;
bool isOpenThunk;
IntPtr functionPointer = GetFunctionPointer(out typeOfFirstParameterIfInstanceDelegate, out isOpenThunk);
if (!FunctionPointerOps.IsGenericMethodPointer(functionPointer))
{
return DebuggerFunctionPointerFormattingHook(functionPointer, typeOfFirstParameterIfInstanceDelegate);
}
else
{
unsafe
{
GenericMethodDescriptor* pointerDef = FunctionPointerOps.ConvertToGenericDescriptor(functionPointer);
return DebuggerFunctionPointerFormattingHook(pointerDef->InstantiationArgument, typeOfFirstParameterIfInstanceDelegate);
}
}
}
}
private static string DebuggerFunctionPointerFormattingHook(IntPtr functionPointer, RuntimeTypeHandle typeOfFirstParameterIfInstanceDelegate)
{
// This method will be hooked by the debugger and the debugger will cause it to return a description for the function pointer
throw new NotSupportedException();
}
}
}
| |
using System;
using System.Collections.Generic;
using MongoDB.Configuration;
using MongoDB.Serialization;
using NUnit.Framework;
namespace MongoDB.UnitTests.Serialization
{
[TestFixture]
public class SerializationFactoryTests : SerializationTestBase
{
[Test]
public void GetBsonReaderSettingsDefaults()
{
var factory = new SerializationFactory();
var readerSettings = factory.GetBsonReaderSettings(typeof(int));
Assert.AreEqual(readerSettings.ReadLocalTime,true);
Assert.IsNotNull(readerSettings.Builder);
}
[Test]
public void ReadLocalTimeCanBeChangedByConfig()
{
var factory = new SerializationFactory(new MongoConfiguration {ReadLocalTime = false});
var readerSettings = factory.GetBsonReaderSettings(typeof(int));
Assert.AreEqual(readerSettings.ReadLocalTime, false);
}
public class ProtectedConstructor
{
protected ProtectedConstructor(){}
}
[Test]
public void CanCreateObjectFromProtectedConstructor()
{
var obj = Deserialize<ProtectedConstructor>(EmptyDocumentBson);
Assert.IsNotNull(obj);
}
public class PrivateConstructor
{
private PrivateConstructor() { }
}
[Test]
[ExpectedException(typeof(MissingMethodException))]
public void CanNotCreateObjectFromPrivateConstructor()
{
var obj = Deserialize<PrivateConstructor>(EmptyDocumentBson);
Assert.IsNotNull(obj);
}
public class SetProtectedPropertys
{
protected double Property { get; set; }
public double GetProperty() {return Property; }
}
[Test]
public void CanSetProtectedProperty()
{
var bson = Serialize(new Document("Property", 4));
var prop = Deserialize<SetProtectedPropertys>(bson);
Assert.IsNotNull(prop);
Assert.AreEqual(4, prop.GetProperty());
}
public class SetPrivatePropertys
{
private double Property { get; set; }
public double GetProperty() { return Property; }
}
[Test]
public void CanNotSetPrivatePropertys()
{
var bson = Serialize(new Document("Property", 4));
var prop = Deserialize<SetPrivatePropertys>(bson);
Assert.IsNotNull(prop);
Assert.AreEqual(0, prop.GetProperty());
}
public class NullableProperty
{
public double? Value { get; set; }
}
[Test]
public void CanSetNullOnNullablPropertys()
{
var bson = Serialize(new Document("Value", null));
var obj = Deserialize<NullableProperty>(bson);
Assert.IsNotNull(obj);
Assert.IsNull(obj.Value);
}
[Test]
public void CanSetValueOnNullablPropertys()
{
var bson = Serialize(new Document("Value", 10));
var obj = Deserialize<NullableProperty>(bson);
Assert.IsNotNull(obj);
Assert.AreEqual(10,obj.Value);
}
public class GenericDictionary
{
public Dictionary<string, int> Property { get; set; }
}
[Test]
public void CanSerializeGenericDictionary()
{
var expectedBson = Serialize<Document>(new Document("Property", new Document() { { "key1", 10 }, { "key2", 20 } }));
var obj = new GenericDictionary { Property = new Dictionary<string, int> { { "key1", 10 }, { "key2", 20 } } };
var bson = Serialize<GenericDictionary>(obj);
Assert.AreEqual(expectedBson, bson);
}
[Test]
public void CanDeserializeGenericDictionary()
{
var bson = Serialize<Document>(new Document("Property", new Document() { { "key1", 10 }, { "key2", 20 } }));
var prop = Deserialize<GenericDictionary>(bson);
Assert.IsNotNull(prop);
Assert.IsNotNull(prop.Property);
Assert.AreEqual(2,prop.Property.Count);
Assert.Contains(new KeyValuePair<string, int>("key1", 10), prop.Property);
Assert.Contains(new KeyValuePair<string, int>("key2", 20), prop.Property);
}
public class GenericStringDictionaryWithComplexType
{
public Dictionary<string, GenericDictionaryComplexType> Dict { get; set; }
}
public class GenericDictionaryComplexType
{
public string Name { get; set; }
}
[Test]
public void CanSerializeStringGenericDictionaryWithComplexType()
{
var expectedBson = Serialize<Document>(new Document("Dict", new Document { { "key1", new Document("Name", "a") }, { "key2", new Document("Name", "b") } }));
var obj = new GenericStringDictionaryWithComplexType { Dict = new Dictionary<string, GenericDictionaryComplexType> { { "key1", new GenericDictionaryComplexType { Name = "a" } }, { "key2", new GenericDictionaryComplexType { Name = "b" } } } };
var bson = Serialize<GenericStringDictionaryWithComplexType>(obj);
Assert.AreEqual(expectedBson, bson);
}
[Test]
public void CanDeserializeStringGenericDictionaryWithComplexType()
{
var bson = Serialize<Document>(new Document("Dict", new Document { { "key1", new Document("Name", "a") }, { "key2", new Document("Name", "b") } }));
var prop = Deserialize<GenericStringDictionaryWithComplexType>(bson);
Assert.IsNotNull(prop);
Assert.IsNotNull(prop.Dict);
Assert.AreEqual(2, prop.Dict.Count);
Assert.IsTrue(prop.Dict["key1"].Name == "a");
Assert.IsTrue(prop.Dict["key2"].Name == "b");
}
public class GenericIntDictionaryWithComplexType
{
public Dictionary<int, GenericDictionaryComplexType> Dict { get; set; }
}
[Test]
public void CanSerializeIntGenericDictionaryWithComplexType()
{
var expectedBson = Serialize<Document>(new Document("Dict", new Document { { "1", new Document("Name", "a") }, { "2", new Document("Name", "b") } }));
var obj = new GenericIntDictionaryWithComplexType { Dict = new Dictionary<int, GenericDictionaryComplexType> { { 1, new GenericDictionaryComplexType { Name = "a" } }, { 2, new GenericDictionaryComplexType { Name = "b" } } } };
var bson = Serialize<GenericIntDictionaryWithComplexType>(obj);
Assert.AreEqual(expectedBson, bson);
}
[Test]
public void CanDeserializeIntGenericDictionaryWithComplexType()
{
var bson = Serialize<Document>(new Document("Dict", new Document { { "1", new Document("Name", "a") }, { "2", new Document("Name", "b") } }));
var prop = Deserialize<GenericIntDictionaryWithComplexType>(bson);
Assert.IsNotNull(prop);
Assert.IsNotNull(prop.Dict);
Assert.AreEqual(2, prop.Dict.Count);
Assert.IsTrue(prop.Dict[1].Name == "a");
Assert.IsTrue(prop.Dict[2].Name == "b");
}
public class SortedListDictionary
{
public SortedList<string, int> Property { get; set; }
}
[Test]
public void CanSerializeSortedListDictionary()
{
var expectedBson = Serialize<Document>(new Document("Property", new Document { { "key1", 10 }, { "key2", 20 } }));
var obj = new SortedListDictionary { Property = new SortedList<string, int> { { "key1", 10 }, { "key2", 20 } } };
var bson = Serialize<SortedListDictionary>(obj);
Assert.AreEqual(expectedBson, bson);
}
[Test]
public void CanDeserializeSortedListDictionary()
{
var bson = Serialize<Document>(new Document("Property", new Document { { "key1", 10 }, { "key2", 20 } }));
var prop = Deserialize<SortedListDictionary>(bson);
Assert.IsNotNull(prop);
Assert.IsNotNull(prop.Property);
Assert.AreEqual(2, prop.Property.Count);
Assert.Contains(new KeyValuePair<string, int>("key1", 10), prop.Property);
Assert.Contains(new KeyValuePair<string, int>("key2", 20), prop.Property);
}
public class HashSetHelper
{
public HashSet<string> Property { get; set; }
}
[Test]
public void CanSerializeAndDeserializeHashSet()
{
var obj = new HashSetHelper {Property = new HashSet<string> {"test1", "test2"}};
var bson = Serialize<HashSetHelper>(obj);
var prop = Deserialize<HashSetHelper>(bson);
Assert.IsNotNull(prop);
Assert.IsNotNull(prop.Property);
Assert.AreEqual(2, prop.Property.Count);
Assert.IsTrue(prop.Property.Contains("test1"));
Assert.IsTrue(prop.Property.Contains("test2"));
}
public class EnumHelper
{
public enum Test
{
A=1,
B=2
}
public List<Test> Tests { get; set; }
}
[Test]
public void CanSerializerAndDesializeEnumLists()
{
var helper = new EnumHelper {Tests = new List<EnumHelper.Test> {EnumHelper.Test.A}};
var bson = Serialize<EnumHelper>(helper);
var deserialize = Deserialize<EnumHelper>(bson);
Assert.IsNotNull(deserialize);
Assert.IsNotNull(deserialize.Tests);
Assert.Contains(EnumHelper.Test.A, deserialize.Tests);
}
public class ByteArrayHelper
{
public byte[] Property { get; set; }
}
[Test]
public void CanWriteByteArrayPropertyFromBinary()
{
var bson = Serialize(new Document("Property", new Binary(new byte[] {1, 2, 3, 4})));
var helper = Deserialize<ByteArrayHelper>(bson);
Assert.IsNotNull(helper);
Assert.AreEqual(4, helper.Property.Length);
Assert.AreEqual(1, helper.Property[0]);
Assert.AreEqual(2, helper.Property[1]);
Assert.AreEqual(3, helper.Property[2]);
Assert.AreEqual(4, helper.Property[3]);
}
public class EmbeddedDocumentHelper
{
public Document Document { get; set; }
}
[Test]
public void CanReadEmbeddedDocument()
{
var bson = Serialize(new Document("Document", new Document("Embedded",new Document("value", 10))));
var helper = Deserialize<EmbeddedDocumentHelper>(bson);
Assert.IsNotNull(helper);
Assert.IsNotNull(helper.Document);
Assert.AreEqual(1, helper.Document.Count);
var embedded = helper.Document["Embedded"] as Document;
Assert.IsNotNull(embedded);
Assert.AreEqual(1, embedded.Count);
Assert.AreEqual(10, embedded["value"]);
}
public class DictionaryWithEnumAsKeyHelper
{
public Dictionary<DateTimeKind, int> Dict { get; set; }
}
[Test]
public void SerializesAnEnumAsIntWhenItsUsedAsDictionaryKey()
{
var obj = new DictionaryWithEnumAsKeyHelper { Dict = new Dictionary<DateTimeKind, int> { { DateTimeKind.Utc, 9 } } };
var bson = Serialize<DictionaryWithEnumAsKeyHelper>(obj);
var doc = Deserialize<Document>(bson);
Assert.IsNotNull(doc);
var dict = doc["Dict"] as Document;
Assert.IsNotNull(dict);
Assert.AreEqual(1, dict.Count);
Assert.AreEqual(9, dict[Convert.ToString((int)DateTimeKind.Utc)]);
}
[Test]
public void CanDeserializeADictionaryWithEnumAsKey()
{
var bson = Serialize<Document>(new Document("Dict", new Document(( (int)DateTimeKind.Utc ).ToString(), 9)));
var prop = Deserialize<DictionaryWithEnumAsKeyHelper>(bson);
Assert.IsNotNull(prop);
Assert.IsNotNull(prop.Dict);
Assert.AreEqual(1,prop.Dict.Count);
Assert.AreEqual(9,prop.Dict[DateTimeKind.Utc]);
}
public class NullDictionaryPropertyHelper
{
public Dictionary<string, string> Dict { get; set; }
}
[Test]
public void CanDeserializeAndNullDictionaryProperty()
{
var bson = Serialize<Document>(new Document("Dict", null));
var prop = Deserialize<NullDictionaryPropertyHelper>(bson);
Assert.IsNotNull(prop);
Assert.IsNull(prop.Dict);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Xunit;
namespace System.IO.MemoryMappedFiles.Tests
{
/// <summary>
/// Tests for MemoryMappedViewStream.
/// </summary>
public class MemoryMappedViewStreamTests : MemoryMappedFilesTestBase
{
/// <summary>
/// Test to validate the offset, size, and access parameters to MemoryMappedFile.CreateViewAccessor.
/// </summary>
[Fact]
public void InvalidArguments()
{
int mapLength = s_pageSize.Value;
foreach (MemoryMappedFile mmf in CreateSampleMaps(mapLength))
{
using (mmf)
{
// Offset
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => mmf.CreateViewStream(-1, mapLength));
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => mmf.CreateViewStream(-1, mapLength, MemoryMappedFileAccess.ReadWrite));
// Size
AssertExtensions.Throws<ArgumentOutOfRangeException>("size", () => mmf.CreateViewStream(0, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("size", () => mmf.CreateViewStream(0, -1, MemoryMappedFileAccess.ReadWrite));
if (IntPtr.Size == 4)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("size", () => mmf.CreateViewStream(0, 1 + (long)uint.MaxValue));
AssertExtensions.Throws<ArgumentOutOfRangeException>("size", () => mmf.CreateViewStream(0, 1 + (long)uint.MaxValue, MemoryMappedFileAccess.ReadWrite));
}
else
{
Assert.Throws<IOException>(() => mmf.CreateViewStream(0, long.MaxValue));
Assert.Throws<IOException>(() => mmf.CreateViewStream(0, long.MaxValue, MemoryMappedFileAccess.ReadWrite));
}
// Offset + Size
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewStream(0, mapLength + 1));
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewStream(0, mapLength + 1, MemoryMappedFileAccess.ReadWrite));
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewStream(mapLength, 1));
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewStream(mapLength, 1, MemoryMappedFileAccess.ReadWrite));
// Access
AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => mmf.CreateViewStream(0, mapLength, (MemoryMappedFileAccess)(-1)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => mmf.CreateViewStream(0, mapLength, (MemoryMappedFileAccess)(42)));
}
}
}
[Theory]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.CopyOnWrite)]
public void ValidAccessLevelCombinations(MemoryMappedFileAccess mapAccess, MemoryMappedFileAccess viewAccess)
{
const int Capacity = 4096;
AssertExtensions.ThrowsIf<UnauthorizedAccessException>(PlatformDetection.IsWinRT &&
(mapAccess == MemoryMappedFileAccess.ReadExecute ||
mapAccess == MemoryMappedFileAccess.ReadWriteExecute ||
viewAccess == MemoryMappedFileAccess.ReadExecute ||
viewAccess == MemoryMappedFileAccess.ReadWriteExecute), () =>
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, Capacity, mapAccess))
using (MemoryMappedViewStream s = mmf.CreateViewStream(0, Capacity, viewAccess))
{
ValidateMemoryMappedViewStream(s, Capacity, viewAccess);
}
});
}
[Theory]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWriteExecute)]
public void InvalidAccessLevelsCombinations(MemoryMappedFileAccess mapAccess, MemoryMappedFileAccess viewAccess)
{
const int Capacity = 4096;
AssertExtensions.ThrowsIf<UnauthorizedAccessException>(PlatformDetection.IsWinRT &&
(mapAccess == MemoryMappedFileAccess.ReadExecute ||
mapAccess == MemoryMappedFileAccess.ReadWriteExecute), () =>
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, Capacity, mapAccess))
{
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewStream(0, Capacity, viewAccess));
}
});
}
/// <summary>
/// Test to verify that setting the length of the stream is unsupported.
/// </summary>
[Fact]
public void SettingLengthNotSupported()
{
foreach (MemoryMappedFile mmf in CreateSampleMaps())
{
using (mmf)
using (MemoryMappedViewStream s = mmf.CreateViewStream())
{
Assert.Throws<NotSupportedException>(() => s.SetLength(4096));
}
}
}
/// <summary>
/// Test to verify the accessor's PointerOffset.
/// </summary>
[Fact]
public void PointerOffsetMatchesViewStart()
{
const int MapLength = 4096;
foreach (MemoryMappedFile mmf in CreateSampleMaps(MapLength))
{
using (mmf)
{
using (MemoryMappedViewStream s = mmf.CreateViewStream())
{
Assert.Equal(0, s.PointerOffset);
}
using (MemoryMappedViewStream s = mmf.CreateViewStream(0, MapLength))
{
Assert.Equal(0, s.PointerOffset);
}
using (MemoryMappedViewStream s = mmf.CreateViewStream(1, MapLength - 1))
{
Assert.Equal(1, s.PointerOffset);
}
using (MemoryMappedViewStream s = mmf.CreateViewStream(MapLength - 1, 1))
{
Assert.Equal(MapLength - 1, s.PointerOffset);
}
// On Unix creating a view of size zero will result in an offset and capacity
// of 0 due to mmap behavior, whereas on Windows it's possible to create a
// zero-size view anywhere in the created file mapping.
using (MemoryMappedViewStream s = mmf.CreateViewStream(MapLength, 0))
{
Assert.Equal(
RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? MapLength : 0,
s.PointerOffset);
}
}
}
}
/// <summary>
/// Test all of the Read/Write accessor methods against a variety of maps and accessors.
/// </summary>
[Theory]
[InlineData(0, 8192)]
[InlineData(8100, 92)]
[InlineData(0, 20)]
[InlineData(1, 8191)]
[InlineData(17, 8175)]
[InlineData(17, 20)]
public void AllReadWriteMethods(long offset, long size)
{
foreach (MemoryMappedFile mmf in CreateSampleMaps(8192))
{
using (mmf)
using (MemoryMappedViewStream s = mmf.CreateViewStream(offset, size))
{
AssertWritesReads(s);
}
}
}
/// <summary>Performs many reads and writes of against the stream.</summary>
private static void AssertWritesReads(MemoryMappedViewStream s)
{
// Write and read at the beginning
s.Position = 0;
s.WriteByte(42);
s.Position = 0;
Assert.Equal(42, s.ReadByte());
// Write and read at the end
byte[] data = new byte[] { 1, 2, 3 };
s.Position = s.Length - data.Length;
s.Write(data, 0, data.Length);
s.Position = s.Length - data.Length;
Array.Clear(data, 0, data.Length);
Assert.Equal(3, s.Read(data, 0, data.Length));
Assert.Equal(new byte[] { 1, 2, 3 }, data);
// Fail reading/writing past the end
s.Position = s.Length;
Assert.Equal(-1, s.ReadByte());
Assert.Throws<NotSupportedException>(() => s.WriteByte(42));
}
/// <summary>
/// Test to verify that Flush is supported regardless of the accessor's access level
/// </summary>
[Theory]
[InlineData(MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite)]
public void FlushSupportedOnBothReadAndWriteAccessors(MemoryMappedFileAccess access)
{
const int Capacity = 256;
foreach (MemoryMappedFile mmf in CreateSampleMaps(Capacity))
{
using (mmf)
using (MemoryMappedViewStream s = mmf.CreateViewStream(0, Capacity, access))
{
s.Flush();
}
}
}
/// <summary>
/// Test to validate that multiple accessors over the same map share data appropriately.
/// </summary>
[Fact]
public void ViewsShareData()
{
const int MapLength = 256;
foreach (MemoryMappedFile mmf in CreateSampleMaps(MapLength))
{
using (mmf)
{
// Create two views over the same map, and verify that data
// written to one is readable by the other.
using (MemoryMappedViewStream s1 = mmf.CreateViewStream())
using (MemoryMappedViewStream s2 = mmf.CreateViewStream())
{
for (int i = 0; i < MapLength; i++)
{
s1.WriteByte((byte)i);
}
s1.Flush();
for (int i = 0; i < MapLength; i++)
{
Assert.Equal(i, s2.ReadByte());
}
}
// Then verify that after those views have been disposed of,
// we can create another view and still read the same data.
using (MemoryMappedViewStream s3 = mmf.CreateViewStream())
{
for (int i = 0; i < MapLength; i++)
{
Assert.Equal(i, s3.ReadByte());
}
}
// Finally, make sure such data is also visible to a stream view
// created subsequently from the same map.
using (MemoryMappedViewAccessor acc4 = mmf.CreateViewAccessor())
{
for (int i = 0; i < MapLength; i++)
{
Assert.Equal(i, acc4.ReadByte(i));
}
}
}
}
}
/// <summary>
/// Test to verify copy-on-write behavior of accessors.
/// </summary>
[Fact]
public void CopyOnWrite()
{
const int MapLength = 256;
foreach (MemoryMappedFile mmf in CreateSampleMaps(MapLength))
{
using (mmf)
{
// Create a normal view, make sure the original data is there, then write some new data.
using (MemoryMappedViewStream s = mmf.CreateViewStream(0, MapLength, MemoryMappedFileAccess.ReadWrite))
{
Assert.Equal(0, s.ReadByte());
s.Position = 0;
s.WriteByte(42);
}
// In a CopyOnWrite view, verify the previously written data is there, then write some new data
// and verify it's visible through this view.
using (MemoryMappedViewStream s = mmf.CreateViewStream(0, MapLength, MemoryMappedFileAccess.CopyOnWrite))
{
Assert.Equal(42, s.ReadByte());
s.Position = 0;
s.WriteByte(84);
s.Position = 0;
Assert.Equal(84, s.ReadByte());
}
// Finally, verify that the CopyOnWrite data is not visible to others using the map.
using (MemoryMappedViewStream s = mmf.CreateViewStream(0, MapLength, MemoryMappedFileAccess.Read))
{
s.Position = 0;
Assert.Equal(42, s.ReadByte());
}
}
}
}
/// <summary>
/// Test to verify that we can dispose of an accessor multiple times.
/// </summary>
[Fact]
public void DisposeMultipleTimes()
{
foreach (MemoryMappedFile mmf in CreateSampleMaps())
{
using (mmf)
{
MemoryMappedViewStream s = mmf.CreateViewStream();
s.Dispose();
s.Dispose();
}
}
}
/// <summary>
/// Test to verify that a view becomes unusable after it's been disposed.
/// </summary>
[Fact]
public void InvalidAfterDisposal()
{
foreach (MemoryMappedFile mmf in CreateSampleMaps())
{
using (mmf)
{
MemoryMappedViewStream s = mmf.CreateViewStream();
SafeMemoryMappedViewHandle handle = s.SafeMemoryMappedViewHandle;
Assert.False(handle.IsClosed);
s.Dispose();
Assert.True(handle.IsClosed);
Assert.Throws<ObjectDisposedException>(() => s.ReadByte());
Assert.Throws<ObjectDisposedException>(() => s.Write(new byte[1], 0, 1));
Assert.Throws<ObjectDisposedException>(() => s.Flush());
}
}
}
/// <summary>
/// Test to verify that we can still use a view after the associated map has been disposed.
/// </summary>
[Fact]
public void UseAfterMMFDisposal()
{
foreach (MemoryMappedFile mmf in CreateSampleMaps(8192))
{
// Create the view, then dispose of the map
MemoryMappedViewStream s;
using (mmf) s = mmf.CreateViewStream();
// Validate we can still use the view
ValidateMemoryMappedViewStream(s, 8192, MemoryMappedFileAccess.ReadWrite);
s.Dispose();
}
}
/// <summary>
/// Test to allow a map and view to be finalized, just to ensure we don't crash.
/// </summary>
[Fact]
public void AllowFinalization()
{
// Explicitly do not dispose, to allow finalization to happen, just to try to verify
// that nothing fails/throws when it does.
WeakReference<MemoryMappedFile> mmfWeak;
WeakReference<MemoryMappedViewStream> mmvsWeak;
CreateWeakMmfAndMmvs(out mmfWeak, out mmvsWeak);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
MemoryMappedFile mmf;
Assert.False(mmfWeak.TryGetTarget(out mmf));
MemoryMappedViewStream s;
Assert.False(mmvsWeak.TryGetTarget(out s));
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void CreateWeakMmfAndMmvs(out WeakReference<MemoryMappedFile> mmfWeak, out WeakReference<MemoryMappedViewStream> mmvsWeak)
{
MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, 4096);
MemoryMappedViewStream s = mmf.CreateViewStream();
mmfWeak = new WeakReference<MemoryMappedFile>(mmf);
mmvsWeak = new WeakReference<MemoryMappedViewStream>(s);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Server.Handlers.Base;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using log4net;
using Nwc.XmlRpc;
using OpenMetaverse;
namespace OpenSim.Server.Handlers.Hypergrid
{
public class UserAgentServerConnector : ServiceConnector
{
// private static readonly ILog m_log =
// LogManager.GetLogger(
// MethodBase.GetCurrentMethod().DeclaringType);
private IUserAgentService m_HomeUsersService;
public IUserAgentService HomeUsersService
{
get { return m_HomeUsersService; }
}
private string[] m_AuthorizedCallers;
private bool m_VerifyCallers = false;
public UserAgentServerConnector(IConfigSource config, IHttpServer server) :
this(config, server, null)
{
}
public UserAgentServerConnector(IConfigSource config, IHttpServer server, IFriendsSimConnector friendsConnector) :
base(config, server, String.Empty)
{
IConfig gridConfig = config.Configs["UserAgentService"];
if (gridConfig != null)
{
string serviceDll = gridConfig.GetString("LocalServiceModule", string.Empty);
Object[] args = new Object[] { config, friendsConnector };
m_HomeUsersService = ServerUtils.LoadPlugin<IUserAgentService>(serviceDll, args);
}
if (m_HomeUsersService == null)
throw new Exception("UserAgent server connector cannot proceed because of missing service");
string loginServerIP = gridConfig.GetString("LoginServerIP", "127.0.0.1");
bool proxy = gridConfig.GetBoolean("HasProxy", false);
m_VerifyCallers = gridConfig.GetBoolean("VerifyCallers", false);
string csv = gridConfig.GetString("AuthorizedCallers", "127.0.0.1");
csv = csv.Replace(" ", "");
m_AuthorizedCallers = csv.Split(',');
server.AddXmlRPCHandler("agent_is_coming_home", AgentIsComingHome, false);
server.AddXmlRPCHandler("get_home_region", GetHomeRegion, false);
server.AddXmlRPCHandler("verify_agent", VerifyAgent, false);
server.AddXmlRPCHandler("verify_client", VerifyClient, false);
server.AddXmlRPCHandler("logout_agent", LogoutAgent, false);
server.AddXmlRPCHandler("status_notification", StatusNotification, false);
server.AddXmlRPCHandler("get_online_friends", GetOnlineFriends, false);
server.AddXmlRPCHandler("get_user_info", GetUserInfo, false);
server.AddXmlRPCHandler("get_server_urls", GetServerURLs, false);
server.AddXmlRPCHandler("locate_user", LocateUser, false);
server.AddXmlRPCHandler("get_uui", GetUUI, false);
server.AddXmlRPCHandler("get_uuid", GetUUID, false);
server.AddHTTPHandler("/homeagent/", new HomeAgentHandler(m_HomeUsersService, loginServerIP, proxy).Handler);
}
public XmlRpcResponse GetHomeRegion(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
string userID_str = (string)requestData["userID"];
UUID userID = UUID.Zero;
UUID.TryParse(userID_str, out userID);
Vector3 position = Vector3.UnitY, lookAt = Vector3.UnitY;
GridRegion regInfo = m_HomeUsersService.GetHomeRegion(userID, out position, out lookAt);
Hashtable hash = new Hashtable();
if (regInfo == null)
hash["result"] = "false";
else
{
hash["result"] = "true";
hash["uuid"] = regInfo.RegionID.ToString();
hash["x"] = regInfo.RegionLocX.ToString();
hash["y"] = regInfo.RegionLocY.ToString();
hash["region_name"] = regInfo.RegionName;
hash["hostname"] = regInfo.ExternalHostName;
hash["http_port"] = regInfo.HttpPort.ToString();
hash["internal_port"] = regInfo.InternalEndPoint.Port.ToString();
hash["position"] = position.ToString();
hash["lookAt"] = lookAt.ToString();
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
public XmlRpcResponse AgentIsComingHome(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
string sessionID_str = (string)requestData["sessionID"];
UUID sessionID = UUID.Zero;
UUID.TryParse(sessionID_str, out sessionID);
string gridName = (string)requestData["externalName"];
bool success = m_HomeUsersService.IsAgentComingHome(sessionID, gridName);
Hashtable hash = new Hashtable();
hash["result"] = success.ToString();
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
public XmlRpcResponse VerifyAgent(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
string sessionID_str = (string)requestData["sessionID"];
UUID sessionID = UUID.Zero;
UUID.TryParse(sessionID_str, out sessionID);
string token = (string)requestData["token"];
bool success = m_HomeUsersService.VerifyAgent(sessionID, token);
Hashtable hash = new Hashtable();
hash["result"] = success.ToString();
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
public XmlRpcResponse VerifyClient(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
string sessionID_str = (string)requestData["sessionID"];
UUID sessionID = UUID.Zero;
UUID.TryParse(sessionID_str, out sessionID);
string token = (string)requestData["token"];
bool success = m_HomeUsersService.VerifyClient(sessionID, token);
Hashtable hash = new Hashtable();
hash["result"] = success.ToString();
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
public XmlRpcResponse LogoutAgent(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
string sessionID_str = (string)requestData["sessionID"];
UUID sessionID = UUID.Zero;
UUID.TryParse(sessionID_str, out sessionID);
string userID_str = (string)requestData["userID"];
UUID userID = UUID.Zero;
UUID.TryParse(userID_str, out userID);
m_HomeUsersService.LogoutAgent(userID, sessionID);
Hashtable hash = new Hashtable();
hash["result"] = "true";
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
[Obsolete]
public XmlRpcResponse StatusNotification(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable hash = new Hashtable();
hash["result"] = "false";
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
if (requestData.ContainsKey("userID") && requestData.ContainsKey("online"))
{
string userID_str = (string)requestData["userID"];
UUID userID = UUID.Zero;
UUID.TryParse(userID_str, out userID);
List<string> ids = new List<string>();
foreach (object key in requestData.Keys)
{
if (key is string && ((string)key).StartsWith("friend_") && requestData[key] != null)
ids.Add(requestData[key].ToString());
}
bool online = false;
bool.TryParse(requestData["online"].ToString(), out online);
// let's spawn a thread for this, because it may take a long time...
List<UUID> friendsOnline = m_HomeUsersService.StatusNotification(ids, userID, online);
if (friendsOnline.Count > 0)
{
int i = 0;
foreach (UUID id in friendsOnline)
{
hash["friend_" + i.ToString()] = id.ToString();
i++;
}
}
else
hash["result"] = "No Friends Online";
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
[Obsolete]
public XmlRpcResponse GetOnlineFriends(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable hash = new Hashtable();
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
if (requestData.ContainsKey("userID"))
{
string userID_str = (string)requestData["userID"];
UUID userID = UUID.Zero;
UUID.TryParse(userID_str, out userID);
List<string> ids = new List<string>();
foreach (object key in requestData.Keys)
{
if (key is string && ((string)key).StartsWith("friend_") && requestData[key] != null)
ids.Add(requestData[key].ToString());
}
//List<UUID> online = m_HomeUsersService.GetOnlineFriends(userID, ids);
//if (online.Count > 0)
//{
// int i = 0;
// foreach (UUID id in online)
// {
// hash["friend_" + i.ToString()] = id.ToString();
// i++;
// }
//}
//else
// hash["result"] = "No Friends Online";
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
public XmlRpcResponse GetUserInfo(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable hash = new Hashtable();
Hashtable requestData = (Hashtable)request.Params[0];
// This needs checking!
if (requestData.ContainsKey("userID"))
{
string userID_str = (string)requestData["userID"];
UUID userID = UUID.Zero;
UUID.TryParse(userID_str, out userID);
//int userFlags = m_HomeUsersService.GetUserFlags(userID);
Dictionary<string,object> userInfo = m_HomeUsersService.GetUserInfo(userID);
if (userInfo.Count > 0)
{
foreach (KeyValuePair<string, object> kvp in userInfo)
{
hash[kvp.Key] = kvp.Value;
}
}
else
{
hash["result"] = "failure";
}
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
public XmlRpcResponse GetServerURLs(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable hash = new Hashtable();
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
if (requestData.ContainsKey("userID"))
{
string userID_str = (string)requestData["userID"];
UUID userID = UUID.Zero;
UUID.TryParse(userID_str, out userID);
Dictionary<string, object> serverURLs = m_HomeUsersService.GetServerURLs(userID);
if (serverURLs.Count > 0)
{
foreach (KeyValuePair<string, object> kvp in serverURLs)
hash["SRV_" + kvp.Key] = kvp.Value.ToString();
}
else
hash["result"] = "No Service URLs";
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
/// <summary>
/// Locates the user.
/// This is a sensitive operation, only authorized IP addresses can perform it.
/// </summary>
/// <param name="request"></param>
/// <param name="remoteClient"></param>
/// <returns></returns>
public XmlRpcResponse LocateUser(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable hash = new Hashtable();
bool authorized = true;
if (m_VerifyCallers)
{
authorized = false;
foreach (string s in m_AuthorizedCallers)
if (s == remoteClient.Address.ToString())
{
authorized = true;
break;
}
}
if (authorized)
{
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
if (requestData.ContainsKey("userID"))
{
string userID_str = (string)requestData["userID"];
UUID userID = UUID.Zero;
UUID.TryParse(userID_str, out userID);
string url = m_HomeUsersService.LocateUser(userID);
if (url != string.Empty)
hash["URL"] = url;
else
hash["result"] = "Unable to locate user";
}
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
/// <summary>
/// Returns the UUI of a user given a UUID.
/// </summary>
/// <param name="request"></param>
/// <param name="remoteClient"></param>
/// <returns></returns>
public XmlRpcResponse GetUUI(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable hash = new Hashtable();
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
if (requestData.ContainsKey("userID") && requestData.ContainsKey("targetUserID"))
{
string userID_str = (string)requestData["userID"];
UUID userID = UUID.Zero;
UUID.TryParse(userID_str, out userID);
string tuserID_str = (string)requestData["targetUserID"];
UUID targetUserID = UUID.Zero;
UUID.TryParse(tuserID_str, out targetUserID);
string uui = m_HomeUsersService.GetUUI(userID, targetUserID);
if (uui != string.Empty)
hash["UUI"] = uui;
else
hash["result"] = "User unknown";
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
/// <summary>
/// Gets the UUID of a user given First name, Last name.
/// </summary>
/// <param name="request"></param>
/// <param name="remoteClient"></param>
/// <returns></returns>
public XmlRpcResponse GetUUID(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable hash = new Hashtable();
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
if (requestData.ContainsKey("first") && requestData.ContainsKey("last"))
{
UUID userID = UUID.Zero;
string first = (string)requestData["first"];
string last = (string)requestData["last"];
UUID uuid = m_HomeUsersService.GetUUID(first, last);
hash["UUID"] = uuid.ToString();
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using GitVersion.Common;
using GitVersion.Configuration;
using GitVersion.Logging;
using GitVersion.Model.Configuration;
using GitVersion.VersionCalculation;
namespace GitVersion
{
public class RepositoryStore : IRepositoryStore
{
private readonly Dictionary<IBranch, List<BranchCommit>> mergeBaseCommitsCache = new();
private readonly Dictionary<Tuple<IBranch, IBranch>, ICommit> mergeBaseCache = new();
private readonly Dictionary<IBranch, List<SemanticVersion>> semanticVersionTagsOnBranchCache = new();
private const string MissingTipFormat = "{0} has no tip. Please see http://example.com/docs for information on how to fix this.";
private readonly ILog log;
private readonly IGitRepository repository;
public RepositoryStore(ILog log, IGitRepository repository)
{
this.log = log ?? throw new ArgumentNullException(nameof(log));
this.repository = repository ?? throw new ArgumentNullException(nameof(log));
}
/// <summary>
/// Find the merge base of the two branches, i.e. the best common ancestor of the two branches' tips.
/// </summary>
public ICommit FindMergeBase(IBranch branch, IBranch otherBranch)
{
var key = Tuple.Create(branch, otherBranch);
if (mergeBaseCache.ContainsKey(key))
{
log.Debug($"Cache hit for merge base between '{branch}' and '{otherBranch}'.");
return mergeBaseCache[key];
}
using (log.IndentLog($"Finding merge base between '{branch}' and '{otherBranch}'."))
{
// Other branch tip is a forward merge
var commitToFindCommonBase = otherBranch.Tip;
var commit = branch.Tip;
if (otherBranch.Tip.Parents.Contains(commit))
{
commitToFindCommonBase = otherBranch.Tip.Parents.First();
}
var findMergeBase = FindMergeBase(commit, commitToFindCommonBase);
if (findMergeBase != null)
{
log.Info($"Found merge base of {findMergeBase}");
// We do not want to include merge base commits which got forward merged into the other branch
ICommit forwardMerge;
do
{
// Now make sure that the merge base is not a forward merge
forwardMerge = GetForwardMerge(commitToFindCommonBase, findMergeBase);
if (forwardMerge != null)
{
// TODO Fix the logging up in this section
var second = forwardMerge.Parents.First();
log.Debug($"Second {second}");
var mergeBase = FindMergeBase(commit, second);
if (mergeBase == null)
{
log.Warning("Could not find mergbase for " + commit);
}
else
{
log.Debug($"New Merge base {mergeBase}");
}
if (Equals(mergeBase, findMergeBase))
{
log.Debug("Breaking");
break;
}
findMergeBase = mergeBase;
commitToFindCommonBase = second;
log.Info($"Merge base was due to a forward merge, next merge base is {findMergeBase}");
}
} while (forwardMerge != null);
}
// Store in cache.
mergeBaseCache.Add(key, findMergeBase);
log.Info($"Merge base of {branch}' and '{otherBranch} is {findMergeBase}");
return findMergeBase;
}
}
public ICommit GetCurrentCommit(IBranch currentBranch, string commitId)
{
ICommit currentCommit = null;
if (!string.IsNullOrWhiteSpace(commitId))
{
log.Info($"Searching for specific commit '{commitId}'");
var commit = repository.Commits.FirstOrDefault(c => string.Equals(c.Sha, commitId, StringComparison.OrdinalIgnoreCase));
if (commit != null)
{
currentCommit = commit;
}
else
{
log.Warning($"Commit '{commitId}' specified but not found");
}
}
if (currentCommit == null)
{
log.Info("Using latest commit on specified branch");
currentCommit = currentBranch.Tip;
}
return currentCommit;
}
public ICommit GetBaseVersionSource(ICommit currentBranchTip)
{
try
{
var filter = new CommitFilter
{
IncludeReachableFrom = currentBranchTip
};
var commitCollection = repository.Commits.QueryBy(filter);
return commitCollection.First(c => !c.Parents.Any());
}
catch (Exception exception)
{
throw new GitVersionException($"Cannot find commit {currentBranchTip}. Please ensure that the repository is an unshallow clone with `git fetch --unshallow`.", exception);
}
}
public IEnumerable<ICommit> GetMainlineCommitLog(ICommit baseVersionSource, ICommit mainlineTip)
{
var filter = new CommitFilter
{
IncludeReachableFrom = mainlineTip,
ExcludeReachableFrom = baseVersionSource,
SortBy = CommitSortStrategies.Reverse,
FirstParentOnly = true
};
return repository.Commits.QueryBy(filter);
}
public IEnumerable<ICommit> GetMergeBaseCommits(ICommit mergeCommit, ICommit mergedHead, ICommit findMergeBase)
{
var filter = new CommitFilter
{
IncludeReachableFrom = mergedHead,
ExcludeReachableFrom = findMergeBase
};
var commitCollection = repository.Commits.QueryBy(filter);
var commits = mergeCommit != null
? new[]
{
mergeCommit
}.Union(commitCollection)
: commitCollection;
return commits;
}
public IBranch GetTargetBranch(string targetBranchName)
{
// By default, we assume HEAD is pointing to the desired branch
var desiredBranch = repository.Head;
// Make sure the desired branch has been specified
if (!string.IsNullOrEmpty(targetBranchName))
{
// There are some edge cases where HEAD is not pointing to the desired branch.
// Therefore it's important to verify if 'currentBranch' is indeed the desired branch.
var targetBranch = FindBranch(targetBranchName);
// CanonicalName can be "refs/heads/develop", so we need to check for "/{TargetBranch}" as well
if (!desiredBranch.Equals(targetBranch))
{
// In the case where HEAD is not the desired branch, try to find the branch with matching name
desiredBranch = repository.Branches?
.Where(b => b.Name.EquivalentTo(targetBranchName))
.OrderBy(b => b.IsRemote)
.FirstOrDefault();
// Failsafe in case the specified branch is invalid
desiredBranch ??= repository.Head;
}
}
return desiredBranch;
}
public IBranch FindBranch(string branchName) => repository.Branches.FirstOrDefault(x => x.Name.EquivalentTo(branchName));
public IBranch GetChosenBranch(Config configuration)
{
var developBranchRegex = configuration.Branches[Config.DevelopBranchKey].Regex;
var mainBranchRegex = configuration.Branches[Config.MainBranchKey].Regex;
var chosenBranch = repository.Branches.FirstOrDefault(b =>
Regex.IsMatch(b.Name.Friendly, developBranchRegex, RegexOptions.IgnoreCase) ||
Regex.IsMatch(b.Name.Friendly, mainBranchRegex, RegexOptions.IgnoreCase));
return chosenBranch;
}
public IEnumerable<IBranch> GetBranchesForCommit(ICommit commit)
{
return repository.Branches.Where(b => !b.IsRemote && Equals(b.Tip, commit)).ToList();
}
public IEnumerable<IBranch> GetExcludedInheritBranches(Config configuration)
{
return repository.Branches.Where(b =>
{
var branchConfig = configuration.GetConfigForBranch(b.Name.WithoutRemote);
return branchConfig == null || branchConfig.Increment == IncrementStrategy.Inherit;
}).ToList();
}
public IEnumerable<IBranch> GetReleaseBranches(IEnumerable<KeyValuePair<string, BranchConfig>> releaseBranchConfig)
{
return repository.Branches
.Where(b => releaseBranchConfig.Any(c => Regex.IsMatch(b.Name.Friendly, c.Value.Regex)));
}
public IEnumerable<IBranch> ExcludingBranches(IEnumerable<IBranch> branchesToExclude)
{
return repository.Branches.ExcludeBranches(branchesToExclude);
}
// TODO Should we cache this?
public IEnumerable<IBranch> GetBranchesContainingCommit(ICommit commit, IEnumerable<IBranch> branches = null, bool onlyTrackedBranches = false)
{
branches ??= repository.Branches.ToList();
static bool IncludeTrackedBranches(IBranch branch, bool includeOnlyTracked) => includeOnlyTracked && branch.IsTracking || !includeOnlyTracked;
if (commit == null)
{
throw new ArgumentNullException(nameof(commit));
}
using (log.IndentLog($"Getting branches containing the commit '{commit.Id}'."))
{
var directBranchHasBeenFound = false;
log.Info("Trying to find direct branches.");
// TODO: It looks wasteful looping through the branches twice. Can't these loops be merged somehow? @asbjornu
var branchList = branches.ToList();
foreach (var branch in branchList)
{
if (branch.Tip != null && branch.Tip.Sha != commit.Sha || IncludeTrackedBranches(branch, onlyTrackedBranches))
{
continue;
}
directBranchHasBeenFound = true;
log.Info($"Direct branch found: '{branch}'.");
yield return branch;
}
if (directBranchHasBeenFound)
{
yield break;
}
log.Info($"No direct branches found, searching through {(onlyTrackedBranches ? "tracked" : "all")} branches.");
foreach (var branch in branchList.Where(b => IncludeTrackedBranches(b, onlyTrackedBranches)))
{
log.Info($"Searching for commits reachable from '{branch}'.");
var commits = GetCommitsReacheableFrom(commit, branch);
if (!commits.Any())
{
log.Info($"The branch '{branch}' has no matching commits.");
continue;
}
log.Info($"The branch '{branch}' has a matching commit.");
yield return branch;
}
}
}
public Dictionary<string, List<IBranch>> GetMainlineBranches(ICommit commit, IEnumerable<KeyValuePair<string, BranchConfig>> mainlineBranchConfigs)
{
return repository.Branches
.Where(b =>
{
return mainlineBranchConfigs.Any(c => Regex.IsMatch(b.Name.Friendly, c.Value.Regex));
})
.Select(b => new
{
MergeBase = FindMergeBase(b.Tip, commit),
Branch = b
})
.Where(a => a.MergeBase != null)
.GroupBy(b => b.MergeBase.Sha, b => b.Branch)
.ToDictionary(b => b.Key, b => b.ToList());
}
/// <summary>
/// Find the commit where the given branch was branched from another branch.
/// If there are multiple such commits and branches, tries to guess based on commit histories.
/// </summary>
public BranchCommit FindCommitBranchWasBranchedFrom(IBranch branch, Config configuration, params IBranch[] excludedBranches)
{
if (branch == null)
{
throw new ArgumentNullException(nameof(branch));
}
using (log.IndentLog($"Finding branch source of '{branch}'"))
{
if (branch.Tip == null)
{
log.Warning(string.Format(MissingTipFormat, branch));
return BranchCommit.Empty;
}
var possibleBranches = GetMergeCommitsForBranch(branch, configuration, excludedBranches)
.Where(b => !branch.Equals(b.Branch))
.ToList();
if (possibleBranches.Count > 1)
{
var first = possibleBranches.First();
log.Info($"Multiple source branches have been found, picking the first one ({first.Branch}).{System.Environment.NewLine}" +
$"This may result in incorrect commit counting.{System.Environment.NewLine}Options were:{System.Environment.NewLine}" +
string.Join(", ", possibleBranches.Select(b => b.Branch.ToString())));
return first;
}
return possibleBranches.SingleOrDefault();
}
}
public SemanticVersion GetCurrentCommitTaggedVersion(ICommit commit, EffectiveConfiguration config)
{
return repository.Tags
.SelectMany(t =>
{
var targetCommit = t.PeeledTargetCommit();
if (targetCommit != null && Equals(targetCommit, commit) && SemanticVersion.TryParse(t.Name.Friendly, config.GitTagPrefix, out var version))
return new[]
{
version
};
return new SemanticVersion[0];
})
.Max();
}
public SemanticVersion MaybeIncrement(BaseVersion baseVersion, GitVersionContext context)
{
var increment = IncrementStrategyFinder.DetermineIncrementedField(repository, context, baseVersion);
return increment != null ? baseVersion.SemanticVersion.IncrementVersion(increment.Value) : baseVersion.SemanticVersion;
}
public IEnumerable<SemanticVersion> GetVersionTagsOnBranch(IBranch branch, string tagPrefixRegex)
{
if (semanticVersionTagsOnBranchCache.ContainsKey(branch))
{
log.Debug($"Cache hit for version tags on branch '{branch.Name.Canonical}");
return semanticVersionTagsOnBranchCache[branch];
}
using (log.IndentLog($"Getting version tags from branch '{branch.Name.Canonical}'."))
{
var tags = GetValidVersionTags(tagPrefixRegex);
var versionTags = branch.Commits.SelectMany(c => tags.Where(t => c.Sha == t.Item1.TargetSha).Select(t => t.Item2)).ToList();
semanticVersionTagsOnBranchCache.Add(branch, versionTags);
return versionTags;
}
}
public IEnumerable<Tuple<ITag, SemanticVersion>> GetValidVersionTags(string tagPrefixRegex, DateTimeOffset? olderThan = null)
{
var tags = new List<Tuple<ITag, SemanticVersion>>();
foreach (var tag in repository.Tags)
{
var commit = tag.PeeledTargetCommit();
if (commit == null)
continue;
if (olderThan.HasValue && commit.When > olderThan.Value)
continue;
if (SemanticVersion.TryParse(tag.Name.Friendly, tagPrefixRegex, out var semver))
{
tags.Add(Tuple.Create(tag, semver));
}
}
return tags;
}
public IEnumerable<ICommit> GetCommitLog(ICommit baseVersionSource, ICommit currentCommit)
{
var filter = new CommitFilter
{
IncludeReachableFrom = currentCommit,
ExcludeReachableFrom = baseVersionSource,
SortBy = CommitSortStrategies.Topological | CommitSortStrategies.Time
};
return repository.Commits.QueryBy(filter);
}
public VersionField? DetermineIncrementedField(BaseVersion baseVersion, GitVersionContext context)
{
return IncrementStrategyFinder.DetermineIncrementedField(repository, context, baseVersion);
}
public bool IsCommitOnBranch(ICommit baseVersionSource, IBranch branch, ICommit firstMatchingCommit)
{
var filter = new CommitFilter
{
IncludeReachableFrom = branch,
ExcludeReachableFrom = baseVersionSource,
FirstParentOnly = true,
};
var commitCollection = repository.Commits.QueryBy(filter);
return commitCollection.Contains(firstMatchingCommit);
}
private IEnumerable<BranchCommit> GetMergeCommitsForBranch(IBranch branch, Config configuration, IEnumerable<IBranch> excludedBranches)
{
if (mergeBaseCommitsCache.ContainsKey(branch))
{
log.Debug($"Cache hit for getting merge commits for branch {branch.Name.Canonical}.");
return mergeBaseCommitsCache[branch];
}
var currentBranchConfig = configuration.GetConfigForBranch(branch.Name.WithoutRemote);
var regexesToCheck = currentBranchConfig == null
? new[] { ".*" } // Match anything if we can't find a branch config
: currentBranchConfig.SourceBranches.Select(sb => configuration.Branches[sb].Regex);
var branchMergeBases = ExcludingBranches(excludedBranches)
.Where(b =>
{
if (Equals(b, branch)) return false;
var branchCanBeMergeBase = regexesToCheck.Any(regex => Regex.IsMatch(b.Name.Friendly, regex));
return branchCanBeMergeBase;
})
.Select(otherBranch =>
{
if (otherBranch.Tip == null)
{
log.Warning(string.Format(MissingTipFormat, otherBranch));
return BranchCommit.Empty;
}
var findMergeBase = FindMergeBase(branch, otherBranch);
return new BranchCommit(findMergeBase, otherBranch);
})
.Where(b => b.Commit != null)
.OrderByDescending(b => b.Commit.When)
.ToList();
mergeBaseCommitsCache.Add(branch, branchMergeBases);
return branchMergeBases;
}
private IEnumerable<ICommit> GetCommitsReacheableFrom(ICommit commit, IBranch branch)
{
var filter = new CommitFilter
{
IncludeReachableFrom = branch
};
var commitCollection = repository.Commits.QueryBy(filter);
return commitCollection.Where(c => c.Sha == commit.Sha);
}
private ICommit GetForwardMerge(ICommit commitToFindCommonBase, ICommit findMergeBase)
{
var filter = new CommitFilter
{
IncludeReachableFrom = commitToFindCommonBase,
ExcludeReachableFrom = findMergeBase
};
var commitCollection = repository.Commits.QueryBy(filter);
return commitCollection.FirstOrDefault(c => c.Parents.Contains(findMergeBase));
}
public ICommit FindMergeBase(ICommit commit, ICommit mainlineTip) => repository.FindMergeBase(commit, mainlineTip);
public int GetNumberOfUncommittedChanges() => repository.GetNumberOfUncommittedChanges();
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Gallio.Framework.Assertions;
using MbUnit.Compatibility.Tests.Framework.Xml;
using MbUnit.Framework;
using MbUnit.Framework.Xml;
using System.IO;
#pragma warning disable 618
namespace MbUnit.Compatibility.Tests.Framework
{
[TestFixture]
[TestsOn(typeof(OldXmlAssert))]
public class OldXmlAssertTest
{
private string _xmlTrueTest;
private string _xmlFalseTest;
[TestFixtureSetUp]
public void StartTest()
{
_xmlTrueTest = "<assert>true</assert>";
_xmlFalseTest = "<assert>false</assert>";
}
#region XmlEquals
[Test]
public void XmlEqualsWithTextReader()
{
OldXmlAssert.XmlEquals(new StringReader(_xmlTrueTest), new StringReader(_xmlTrueTest));
}
[Test, ExpectedException(typeof(AssertionException))]
public void XmlEqualsWithTextReaderFail()
{
OldXmlAssert.XmlEquals(new StringReader(_xmlTrueTest), new StringReader(_xmlFalseTest));
}
[Test]
public void XmlEqualsWithString()
{
OldXmlAssert.XmlEquals(_xmlTrueTest, _xmlTrueTest);
}
[Test, ExpectedException(typeof(AssertionException))]
public void XmlEqualsWithStringFail()
{
OldXmlAssert.XmlEquals(_xmlTrueTest, _xmlFalseTest);
}
[Test]
public void XmlEqualsWithXmlInput()
{
OldXmlAssert.XmlEquals(new XmlInput(_xmlTrueTest), new XmlInput(_xmlTrueTest));
}
[Test, ExpectedException(typeof(AssertionException))]
public void XmlEqualsWithXmlInputFail()
{
OldXmlAssert.XmlEquals(new XmlInput(_xmlTrueTest), new XmlInput(_xmlFalseTest));
}
[Test]
public void XmlEqualsWithXmlDiff()
{
OldXmlAssert.XmlEquals(new XmlDiff(_xmlTrueTest, _xmlTrueTest));
}
[Test, ExpectedException(typeof(AssertionException))]
public void XmlEqualsWithXmlDiffFail()
{
OldXmlAssert.XmlEquals(new XmlDiff(new XmlInput(_xmlTrueTest), new XmlInput(_xmlFalseTest)));
}
[RowTest]
[Row("Optional Description", "Optional Description")]
[Row("", "Xml does not match")]
[Row("XmlDiff", "Xml does not match")]
public void XmlEqualsWithXmlDiffFail_WithDiffConfiguration(string optionalDesciption, string expectedMessage)
{
try
{
OldXmlAssert.XmlEquals(new XmlDiff(new XmlInput(_xmlTrueTest), new XmlInput(_xmlFalseTest), new DiffConfiguration(optionalDesciption)));
}
catch (AssertionException e)
{
Assert.AreEqual(true, e.Message.StartsWith(expectedMessage));
}
}
[Test]
public void XmlEqualsWithXmlDiffFail_WithNullOptionalDescription()
{
try
{
OldXmlAssert.XmlEquals(new XmlDiff(new XmlInput(_xmlTrueTest), new XmlInput(_xmlFalseTest), new DiffConfiguration(null)));
}
catch (AssertionException e)
{
Assert.AreEqual(true, e.Message.StartsWith("Xml does not match"));
}
}
#endregion
[Test]
public void AssertStringEqualAndIdenticalToSelf()
{
string control = _xmlTrueTest;
string test = _xmlTrueTest;
OldXmlAssert.XmlIdentical(control, test);
OldXmlAssert.XmlEquals(control, test);
}
[Test]
public void AssertDifferentStringsNotEqualNorIdentical() {
string control = "<assert>true</assert>";
string test = "<assert>false</assert>";
XmlDiff xmlDiff = new XmlDiff(control, test);
OldXmlAssert.XmlNotIdentical(xmlDiff);
OldXmlAssert.XmlNotEquals(xmlDiff);
}
[Test]
public void AssertXmlIdenticalUsesOptionalDescription()
{
string description = "An Optional Description";
try {
XmlDiff diff = new XmlDiff(new XmlInput("<a/>"), new XmlInput("<b/>"),
new DiffConfiguration(description));
OldXmlAssert.XmlIdentical(diff);
} catch (AssertionException e) {
Assert.AreEqual(true, e.Message.StartsWith(description));
}
}
[Test]
public void AssertXmlEqualsUsesOptionalDescription() {
string description = "Another Optional Description";
try {
XmlDiff diff = new XmlDiff(new XmlInput("<a/>"), new XmlInput("<b/>"),
new DiffConfiguration(description));
OldXmlAssert.XmlEquals(diff);
} catch (AssertionException e) {
Assert.AreEqual(true, e.Message.StartsWith(description));
}
}
[Test]
public void AssertXmlValidTrueForValidFile() {
StreamReader reader = new StreamReader(ValidatorTests.ValidFile);
try {
OldXmlAssert.XmlValid(reader);
} finally {
reader.Close();
}
}
[Test]
public void AssertXmlValidFalseForInvalidFile() {
StreamReader reader = new StreamReader(ValidatorTests.InvalidFile);
try {
OldXmlAssert.XmlValid(reader);
Assert.Fail("Expected assertion failure");
} catch(AssertionException e) {
AvoidUnusedVariableCompilerWarning(e);
} finally {
reader.Close();
}
}
private static readonly string MY_SOLAR_SYSTEM = "<solar-system><planet name='Earth' position='3' supportsLife='yes'/><planet name='Venus' position='4'/></solar-system>";
[Test] public void AssertXPathExistsWorksForExistentXPath() {
OldXmlAssert.XPathExists("//planet[@name='Earth']",
MY_SOLAR_SYSTEM);
}
[Test] public void AssertXPathExistsFailsForNonExistentXPath() {
try {
OldXmlAssert.XPathExists("//star[@name='alpha centauri']",
MY_SOLAR_SYSTEM);
Assert.Fail("Expected assertion failure");
} catch (AssertionException e) {
AvoidUnusedVariableCompilerWarning(e);
}
}
[Test] public void AssertXPathEvaluatesToWorksForMatchingExpression() {
OldXmlAssert.XPathEvaluatesTo("//planet[@position='3']/@supportsLife",
MY_SOLAR_SYSTEM,
"yes");
}
[Test] public void AssertXPathEvaluatesToWorksForNonMatchingExpression() {
OldXmlAssert.XPathEvaluatesTo("//planet[@position='4']/@supportsLife",
MY_SOLAR_SYSTEM,
"");
}
[Test] public void AssertXPathEvaluatesToWorksConstantExpression() {
OldXmlAssert.XPathEvaluatesTo("true()",
MY_SOLAR_SYSTEM,
"True");
OldXmlAssert.XPathEvaluatesTo("false()",
MY_SOLAR_SYSTEM,
"False");
}
[Test]
public void AssertXslTransformResultsWorksWithStrings() {
string xslt = XsltTests.IDENTITY_TRANSFORM;
string someXml = "<a><b>c</b><b/></a>";
OldXmlAssert.XslTransformResults(xslt, someXml, someXml);
}
[Test]
public void AssertXslTransformResultsWorksWithXmlInput() {
StreamReader xsl = ValidatorTests.GetTestReader("animal.xsl");
XmlInput xslt = new XmlInput(xsl);
StreamReader xml = ValidatorTests.GetTestReader("testAnimal.xml");
XmlInput xmlToTransform = new XmlInput(xml);
XmlInput expectedXml = new XmlInput("<dog/>");
OldXmlAssert.XslTransformResults(xslt, xmlToTransform, expectedXml);
}
[Test]
public void AssertXslTransformResultsCatchesFalsePositive() {
StreamReader xsl = ValidatorTests.GetTestReader("animal.xsl");
XmlInput xslt = new XmlInput(xsl);
StreamReader xml = ValidatorTests.GetTestReader("testAnimal.xml");
XmlInput xmlToTransform = new XmlInput(xml);
XmlInput expectedXml = new XmlInput("<cat/>");
bool exceptionExpected = true;
try {
OldXmlAssert.XslTransformResults(xslt, xmlToTransform, expectedXml);
exceptionExpected = false;
Assert.Fail("Expected dog not cat!");
} catch (AssertionException e) {
AvoidUnusedVariableCompilerWarning(e);
if (!exceptionExpected) {
throw e;
}
}
}
private void AvoidUnusedVariableCompilerWarning(AssertionException e) {
string msg = e.Message;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.Net.Mime;
using System.Text;
namespace System.Net.Mail
{
//
// This class stores the basic components of an e-mail address as described in RFC 2822 Section 3.4.
// Any parsing required is done with the MailAddressParser class.
//
public partial class MailAddress
{
// These components form an e-mail address when assembled as follows:
// "EncodedDisplayname" <userName@host>
private readonly Encoding _displayNameEncoding;
private readonly string _displayName;
private readonly string _userName;
private readonly string _host;
// For internal use only by MailAddressParser.
// The components were already validated before this is called.
internal MailAddress(string displayName, string userName, string domain)
{
_host = domain;
_userName = userName;
_displayName = displayName;
_displayNameEncoding = Encoding.GetEncoding(MimeBasePart.DefaultCharSet);
Debug.Assert(_host != null,
"host was null in internal constructor");
Debug.Assert(userName != null,
"userName was null in internal constructor");
Debug.Assert(displayName != null,
"displayName was null in internal constructor");
}
public MailAddress(string address) : this(address, null, (Encoding)null)
{
}
public MailAddress(string address, string displayName) : this(address, displayName, (Encoding)null)
{
}
//
// This constructor validates and stores the components of an e-mail address.
//
// Preconditions:
// - 'address' must not be null or empty.
//
// Postconditions:
// - The e-mail address components from the given 'address' are parsed, which should be formatted as:
// "EncodedDisplayname" <username@host>
// - If a 'displayName' is provided separately, it overrides whatever display name is parsed from the 'address'
// field. The display name does not need to be pre-encoded if a 'displayNameEncoding' is provided.
//
// A FormatException will be thrown if any of the components in 'address' are invalid.
public MailAddress(string address, string displayName, Encoding displayNameEncoding)
{
if (address == null)
{
throw new ArgumentNullException(nameof(address));
}
if (address == string.Empty)
{
throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(address)), nameof(address));
}
_displayNameEncoding = displayNameEncoding ?? Encoding.GetEncoding(MimeBasePart.DefaultCharSet);
_displayName = displayName ?? string.Empty;
// Check for bounding quotes
if (!string.IsNullOrEmpty(_displayName))
{
_displayName = MailAddressParser.NormalizeOrThrow(_displayName);
if (_displayName.Length >= 2 && _displayName[0] == '\"'
&& _displayName[_displayName.Length - 1] == '\"')
{
// Peal bounding quotes, they'll get re-added later.
_displayName = _displayName.Substring(1, _displayName.Length - 2);
}
}
MailAddress result = MailAddressParser.ParseAddress(address);
_host = result._host;
_userName = result._userName;
// If we were not given a display name, use the one parsed from 'address'.
if (string.IsNullOrEmpty(_displayName))
{
_displayName = result._displayName;
}
}
public string DisplayName
{
get
{
return _displayName;
}
}
public string User
{
get
{
return _userName;
}
}
private string GetUser(bool allowUnicode)
{
// Unicode usernames cannot be downgraded
if (!allowUnicode && !MimeBasePart.IsAscii(_userName, true))
{
throw new SmtpException(SR.Format(SR.SmtpNonAsciiUserNotSupported, Address));
}
return _userName;
}
public string Host
{
get
{
return _host;
}
}
private string GetHost(bool allowUnicode)
{
string domain = _host;
// Downgrade Unicode domain names
if (!allowUnicode && !MimeBasePart.IsAscii(domain, true))
{
IdnMapping mapping = new IdnMapping();
try
{
domain = mapping.GetAscii(domain);
}
catch (ArgumentException argEx)
{
throw new SmtpException(SR.Format(SR.SmtpInvalidHostName, Address), argEx);
}
}
return domain;
}
public string Address
{
get
{
return _userName + "@" + _host;
}
}
private string GetAddress(bool allowUnicode)
{
return GetUser(allowUnicode) + "@" + GetHost(allowUnicode);
}
private string SmtpAddress
{
get
{
return "<" + Address + ">";
}
}
internal string GetSmtpAddress(bool allowUnicode)
{
return "<" + GetAddress(allowUnicode) + ">";
}
/// <summary>
/// this returns the full address with quoted display name.
/// i.e. "some email address display name" <user@host>
/// if displayname is not provided then this returns only user@host (no angle brackets)
/// </summary>
public override string ToString()
{
if (string.IsNullOrEmpty(DisplayName))
{
return Address;
}
else
{
return "\"" + DisplayName + "\" " + SmtpAddress;
}
}
public override bool Equals(object value)
{
if (value == null)
{
return false;
}
return ToString().Equals(value.ToString(), StringComparison.InvariantCultureIgnoreCase);
}
public override int GetHashCode()
{
return ToString().GetHashCode();
}
private static readonly EncodedStreamFactory s_encoderFactory = new EncodedStreamFactory();
// Encodes the full email address, folding as needed
internal string Encode(int charsConsumed, bool allowUnicode)
{
string encodedAddress = string.Empty;
IEncodableStream encoder;
byte[] buffer;
Debug.Assert(Address != null, "address was null");
//do we need to take into account the Display name? If so, encode it
if (!string.IsNullOrEmpty(_displayName))
{
//figure out the encoding type. If it's all ASCII and contains no CRLF then
//it does not need to be encoded for parity with other email clients. We will
//however fold at the end of the display name so that the email address itself can
//be appended.
if (MimeBasePart.IsAscii(_displayName, false) || allowUnicode)
{
encodedAddress = "\"" + _displayName + "\"";
}
else
{
//encode the displayname since it's non-ascii
encoder = s_encoderFactory.GetEncoderForHeader(_displayNameEncoding, false, charsConsumed);
buffer = _displayNameEncoding.GetBytes(_displayName);
encoder.EncodeBytes(buffer, 0, buffer.Length);
encodedAddress = encoder.GetEncodedString();
}
//address should be enclosed in <> when a display name is present
encodedAddress += " " + GetSmtpAddress(allowUnicode);
}
else
{
//no display name, just return the address
encodedAddress = GetAddress(allowUnicode);
}
return encodedAddress;
}
}
}
| |
// 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;
namespace DPStressHarness
{
public enum TestPriority
{
BVT = 0,
High = 1,
Medium = 2,
Low = 3
}
public class TestAttributeBase : Attribute
{
private string _title;
private string _description = "none provided";
private string _applicationName = "unknown";
private string _improvement = "ADONETV3";
private string _owner = "unknown";
private string _category = "unknown";
private TestPriority _priority = TestPriority.BVT;
public TestAttributeBase(string title)
{
_title = title;
}
public string Title
{
get { return _title; }
set { _title = value; }
}
public string Description
{
get { return _description; }
set { _description = value; }
}
public string Improvement
{
get { return _improvement; }
set { _improvement = value; }
}
public string Owner
{
get { return _owner; }
set { _owner = value; }
}
public string ApplicationName
{
get { return _applicationName; }
set { _applicationName = value; }
}
public TestPriority Priority
{
get { return _priority; }
set { _priority = value; }
}
public string Category
{
get { return _category; }
set { _category = value; }
}
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class TestAttribute : TestAttributeBase
{
private int _warmupIterations = 0;
private int _testIterations = 1;
public TestAttribute(string title) : base(title)
{
}
public int WarmupIterations
{
get
{
string propName = "WarmupIterations";
if (TestMetrics.Overrides.ContainsKey(propName))
{
return Int32.Parse(TestMetrics.Overrides[propName]);
}
else
{
return _warmupIterations;
}
}
set { _warmupIterations = value; }
}
public int TestIterations
{
get
{
string propName = "TestIterations";
if (TestMetrics.Overrides.ContainsKey(propName))
{
return Int32.Parse(TestMetrics.Overrides[propName]);
}
else
{
return _testIterations;
}
}
set { _testIterations = value; }
}
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class StressTestAttribute : TestAttributeBase
{
private int _weight = 1;
public StressTestAttribute(string title)
: base(title)
{
}
public int Weight
{
get { return _weight; }
set { _weight = value; }
}
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class MultiThreadedTestAttribute : TestAttributeBase
{
private int _warmupDuration = 60;
private int _testDuration = 60;
private int _threads = 16;
public MultiThreadedTestAttribute(string title)
: base(title)
{
}
public int WarmupDuration
{
get
{
string propName = "WarmupDuration";
if (TestMetrics.Overrides.ContainsKey(propName))
{
return Int32.Parse(TestMetrics.Overrides[propName]);
}
else
{
return _warmupDuration;
}
}
set { _warmupDuration = value; }
}
public int TestDuration
{
get
{
string propName = "TestDuration";
if (TestMetrics.Overrides.ContainsKey(propName))
{
return Int32.Parse(TestMetrics.Overrides[propName]);
}
else
{
return _testDuration;
}
}
set { _testDuration = value; }
}
public int Threads
{
get
{
string propName = "Threads";
if (TestMetrics.Overrides.ContainsKey(propName))
{
return Int32.Parse(TestMetrics.Overrides[propName]);
}
else
{
return _threads;
}
}
set { _threads = value; }
}
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class ThreadPoolTestAttribute : TestAttributeBase
{
private int _warmupDuration = 60;
private int _testDuration = 60;
private int _threads = 64;
public ThreadPoolTestAttribute(string title)
: base(title)
{
}
public int WarmupDuration
{
get
{
string propName = "WarmupDuration";
if (TestMetrics.Overrides.ContainsKey(propName))
{
return Int32.Parse(TestMetrics.Overrides[propName]);
}
else
{
return _warmupDuration;
}
}
set { _warmupDuration = value; }
}
public int TestDuration
{
get
{
string propName = "TestDuration";
if (TestMetrics.Overrides.ContainsKey(propName))
{
return Int32.Parse(TestMetrics.Overrides[propName]);
}
else
{
return _testDuration;
}
}
set { _testDuration = value; }
}
public int Threads
{
get
{
string propName = "Threads";
if (TestMetrics.Overrides.ContainsKey(propName))
{
return Int32.Parse(TestMetrics.Overrides[propName]);
}
else
{
return _threads;
}
}
set { _threads = value; }
}
}
}
| |
// RdfParser.cs
//
// Copyright (c) 2008 Ethan Osten
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections;
using System.Xml;
using System.Text;
using NewsKit;
namespace NewsKit {
public class RdfParser : IFeedParser {
private XmlDocument document;
private XmlNamespaceManager mgr;
private string name;
public string Name {
get {
try {
return name;
} catch ( Exception e ) {
Globals.Exception(e);
return "";
}
}
set { name = value; }
}
private string subtitle;
public string Subtitle {
get {
try {
return subtitle;
} catch ( Exception e ) {
Globals.Exception(e);
return "";
}
}
set { subtitle = value; }
}
private string uri;
public string Uri {
get {
try {
return uri;
} catch ( Exception e ) {
Globals.Exception(e);
return "";
}
}
set { uri = value; }
}
private string author;
public string Author {
get {
try {
return author;
} catch ( Exception e ) {
Globals.Exception(e);
return "";
}
}
set { author = value; }
}
private string image;
public string Image {
get {
try {
return image;
} catch ( Exception e ) {
Globals.Exception(e);
return "";
}
}
set { image = value; }
}
private string license;
public string License {
get {
try {
return license;
} catch ( Exception e ) {
Globals.Exception(e);
return "";
}
}
set { license = value; }
}
private string etag;
public string Etag {
get {
try {
return etag;
} catch ( Exception e ) {
Globals.Exception(e);
return "";
}
}
set { etag = value; }
}
private string modified;
public string Modified {
get {
try {
return modified;
} catch ( Exception e ) {
Globals.Exception(e);
return "";
}
}
set { modified = value; }
}
private string favicon;
public string Favicon {
get {
try {
return favicon;
} catch ( Exception e ) {
Globals.Exception(e);
return "";
}
}
set { favicon = value; }
}
private Request request;
public Request Request {
get {
return request;
} set {
request = value;
}
}
private ArrayList items;
public ArrayList Items {
get {
try {
return items;
} catch ( Exception e ) {
Globals.Exception(e);
return new ArrayList();
}
}
set { items = value; }
}
public RdfParser(string uri, string xml) {
this.uri = uri;
this.document = new XmlDocument();
try {
document.LoadXml(xml);
} catch (XmlException e) {
Globals.Exception(e);
bool have_stripped_control = false;
StringBuilder sb = new StringBuilder ();
foreach (char c in xml) {
if (Char.IsControl(c) && c != '\n') {
have_stripped_control = true;
} else {
sb.Append(c);
}
}
bool loaded = false;
if (have_stripped_control) {
try {
document.LoadXml(sb.ToString ());
loaded = true;
} catch (Exception) {
}
}
if (!loaded) {
}
}
mgr = new XmlNamespaceManager(document.NameTable);
mgr.AddNamespace("rss10", "http://purl.org/rss/1.0/");
mgr.AddNamespace("content", "http://purl.org/rss/1.0/modules/content/");
mgr.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
XmlNodeList channodes = document.SelectNodes("//rss10:channel", mgr);
foreach ( XmlNode node in channodes ) {
Name = GetXmlNodeText(node, "rss10:title");
Subtitle = GetXmlNodeText(node, "rss10:description");
}
XmlNodeList nodes = document.SelectNodes("//rss10:item", mgr);
Items = new ArrayList();
foreach (XmlNode node in nodes) {
items.Add(ParseItem(node));
}
}
private Item ParseItem(XmlNode node) {
Item item = new Item();
item.Title = GetXmlNodeText(node, "rss10:title");
item.Author = GetXmlNodeText(node, "rss10:author");
item.Uri = GetXmlNodeText(node, "rss10:link");
item.Contents = GetXmlNodeText(node, "rss10:description");
Console.WriteLine(item.Contents);
try {
if ( item.Contents.Length < GetXmlNodeText(node, "content:encoded").Length ) {
item.Contents = GetXmlNodeText(node, "content:encoded");
}
} catch ( Exception ) {
if ( String.IsNullOrEmpty(item.Contents) ) {
item.Contents = GetXmlNodeText(node, "content:encoded");
}
}
item.Date = Convert.ToDateTime(GetXmlNodeText(node, "dc:date")).ToString();
item.LastUpdated = GetRfc822DateTime(node, "dcterms:modified").ToString();
return item;
}
public string GetXmlNodeText(XmlNode node, string tag) {
XmlNode n = node.SelectSingleNode(tag, mgr);
return (n == null) ? null : n.InnerText.Trim();
}
public DateTime GetRfc822DateTime(XmlNode node, string tag) {
DateTime ret = DateTime.MinValue;
string result = GetXmlNodeText(node, tag);
if (!String.IsNullOrEmpty(result)) {
ret = RssCommon.Parse(result);
}
return ret;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.IO;
using System.Text;
using NUnit.Framework;
using osu.Game.Audio;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Formats;
using osu.Game.IO;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Types;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Osu.Beatmaps;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Screens.Edit;
using osuTK;
using Decoder = osu.Game.Beatmaps.Formats.Decoder;
namespace osu.Game.Tests.Editor
{
[TestFixture]
public class LegacyEditorBeatmapPatcherTest
{
private LegacyEditorBeatmapPatcher patcher;
private EditorBeatmap current;
[SetUp]
public void Setup()
{
patcher = new LegacyEditorBeatmapPatcher(current = new EditorBeatmap(new OsuBeatmap
{
BeatmapInfo =
{
Ruleset = new OsuRuleset().RulesetInfo
}
}));
}
[Test]
public void TestAddHitObject()
{
var patch = new OsuBeatmap
{
HitObjects =
{
new HitCircle { StartTime = 1000 }
}
};
runTest(patch);
}
[Test]
public void TestInsertHitObject()
{
current.AddRange(new[]
{
new HitCircle { StartTime = 1000 },
new HitCircle { StartTime = 3000 },
});
var patch = new OsuBeatmap
{
HitObjects =
{
(OsuHitObject)current.HitObjects[0],
new HitCircle { StartTime = 2000 },
(OsuHitObject)current.HitObjects[1],
}
};
runTest(patch);
}
[Test]
public void TestDeleteHitObject()
{
current.AddRange(new[]
{
new HitCircle { StartTime = 1000 },
new HitCircle { StartTime = 2000 },
new HitCircle { StartTime = 3000 },
});
var patch = new OsuBeatmap
{
HitObjects =
{
(OsuHitObject)current.HitObjects[0],
(OsuHitObject)current.HitObjects[2],
}
};
runTest(patch);
}
[Test]
public void TestChangeStartTime()
{
current.AddRange(new[]
{
new HitCircle { StartTime = 1000 },
new HitCircle { StartTime = 2000 },
new HitCircle { StartTime = 3000 },
});
var patch = new OsuBeatmap
{
HitObjects =
{
new HitCircle { StartTime = 500 },
(OsuHitObject)current.HitObjects[1],
(OsuHitObject)current.HitObjects[2],
}
};
runTest(patch);
}
[Test]
public void TestChangeSample()
{
current.AddRange(new[]
{
new HitCircle { StartTime = 1000 },
new HitCircle { StartTime = 2000 },
new HitCircle { StartTime = 3000 },
});
var patch = new OsuBeatmap
{
HitObjects =
{
(OsuHitObject)current.HitObjects[0],
new HitCircle { StartTime = 2000, Samples = { new HitSampleInfo { Name = HitSampleInfo.HIT_FINISH } } },
(OsuHitObject)current.HitObjects[2],
}
};
runTest(patch);
}
[Test]
public void TestChangeSliderPath()
{
current.AddRange(new OsuHitObject[]
{
new HitCircle { StartTime = 1000 },
new Slider
{
StartTime = 2000,
Path = new SliderPath(new[]
{
new PathControlPoint(Vector2.Zero),
new PathControlPoint(Vector2.One),
new PathControlPoint(new Vector2(2), PathType.Bezier),
new PathControlPoint(new Vector2(3)),
}, 50)
},
new HitCircle { StartTime = 3000 },
});
var patch = new OsuBeatmap
{
HitObjects =
{
(OsuHitObject)current.HitObjects[0],
new Slider
{
StartTime = 2000,
Path = new SliderPath(new[]
{
new PathControlPoint(Vector2.Zero, PathType.Bezier),
new PathControlPoint(new Vector2(4)),
new PathControlPoint(new Vector2(5)),
}, 100)
},
(OsuHitObject)current.HitObjects[2],
}
};
runTest(patch);
}
[Test]
public void TestAddMultipleHitObjects()
{
current.AddRange(new[]
{
new HitCircle { StartTime = 1000 },
new HitCircle { StartTime = 2000 },
new HitCircle { StartTime = 3000 },
});
var patch = new OsuBeatmap
{
HitObjects =
{
new HitCircle { StartTime = 500 },
(OsuHitObject)current.HitObjects[0],
new HitCircle { StartTime = 1500 },
(OsuHitObject)current.HitObjects[1],
new HitCircle { StartTime = 2250 },
new HitCircle { StartTime = 2500 },
(OsuHitObject)current.HitObjects[2],
new HitCircle { StartTime = 3500 },
}
};
runTest(patch);
}
[Test]
public void TestDeleteMultipleHitObjects()
{
current.AddRange(new[]
{
new HitCircle { StartTime = 500 },
new HitCircle { StartTime = 1000 },
new HitCircle { StartTime = 1500 },
new HitCircle { StartTime = 2000 },
new HitCircle { StartTime = 2250 },
new HitCircle { StartTime = 2500 },
new HitCircle { StartTime = 3000 },
new HitCircle { StartTime = 3500 },
});
var patch = new OsuBeatmap
{
HitObjects =
{
(OsuHitObject)current.HitObjects[1],
(OsuHitObject)current.HitObjects[3],
(OsuHitObject)current.HitObjects[6],
}
};
runTest(patch);
}
[Test]
public void TestChangeSamplesOfMultipleHitObjects()
{
current.AddRange(new[]
{
new HitCircle { StartTime = 500 },
new HitCircle { StartTime = 1000 },
new HitCircle { StartTime = 1500 },
new HitCircle { StartTime = 2000 },
new HitCircle { StartTime = 2250 },
new HitCircle { StartTime = 2500 },
new HitCircle { StartTime = 3000 },
new HitCircle { StartTime = 3500 },
});
var patch = new OsuBeatmap
{
HitObjects =
{
(OsuHitObject)current.HitObjects[0],
new HitCircle { StartTime = 1000, Samples = { new HitSampleInfo { Name = HitSampleInfo.HIT_FINISH } } },
(OsuHitObject)current.HitObjects[2],
(OsuHitObject)current.HitObjects[3],
new HitCircle { StartTime = 2250, Samples = { new HitSampleInfo { Name = HitSampleInfo.HIT_WHISTLE } } },
(OsuHitObject)current.HitObjects[5],
new HitCircle { StartTime = 3000, Samples = { new HitSampleInfo { Name = HitSampleInfo.HIT_CLAP } } },
(OsuHitObject)current.HitObjects[7],
}
};
runTest(patch);
}
[Test]
public void TestAddAndDeleteHitObjects()
{
current.AddRange(new[]
{
new HitCircle { StartTime = 500 },
new HitCircle { StartTime = 1000 },
new HitCircle { StartTime = 1500 },
new HitCircle { StartTime = 2000 },
new HitCircle { StartTime = 2250 },
new HitCircle { StartTime = 2500 },
new HitCircle { StartTime = 3000 },
new HitCircle { StartTime = 3500 },
});
var patch = new OsuBeatmap
{
HitObjects =
{
new HitCircle { StartTime = 750 },
(OsuHitObject)current.HitObjects[1],
(OsuHitObject)current.HitObjects[4],
(OsuHitObject)current.HitObjects[5],
new HitCircle { StartTime = 2650 },
new HitCircle { StartTime = 2750 },
new HitCircle { StartTime = 4000 },
}
};
runTest(patch);
}
private void runTest(IBeatmap patch)
{
// Due to the method of testing, "patch" comes in without having been decoded via a beatmap decoder.
// This causes issues because the decoder adds various default properties (e.g. new combo on first object, default samples).
// To resolve "patch" into a sane state it is encoded and then re-decoded.
patch = decode(encode(patch));
// Apply the patch.
patcher.Patch(encode(current), encode(patch));
// Convert beatmaps to strings for assertion purposes.
string currentStr = Encoding.ASCII.GetString(encode(current));
string patchStr = Encoding.ASCII.GetString(encode(patch));
Assert.That(currentStr, Is.EqualTo(patchStr));
}
private byte[] encode(IBeatmap beatmap)
{
using (var encoded = new MemoryStream())
{
using (var sw = new StreamWriter(encoded))
new LegacyBeatmapEncoder(beatmap).Encode(sw);
return encoded.ToArray();
}
}
private IBeatmap decode(byte[] state)
{
using (var stream = new MemoryStream(state))
using (var reader = new LineBufferedReader(stream))
return Decoder.GetDecoder<Beatmap>(reader).Decode(reader);
}
}
}
| |
// 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.Xml.Schema;
using System.Collections;
using System.Diagnostics;
namespace System.Xml
{
internal partial class XmlWrappingWriter : XmlWriter
{
//
// Fields
//
protected XmlWriter writer;
//
// Constructor
//
internal XmlWrappingWriter(XmlWriter baseWriter)
{
Debug.Assert(baseWriter != null);
this.writer = baseWriter;
}
//
// XmlWriter implementation
//
public override XmlWriterSettings Settings { get { return writer.Settings; } }
public override WriteState WriteState { get { return writer.WriteState; } }
public override XmlSpace XmlSpace { get { return writer.XmlSpace; } }
public override string XmlLang { get { return writer.XmlLang; } }
public override void WriteStartDocument()
{
writer.WriteStartDocument();
}
public override void WriteStartDocument(bool standalone)
{
writer.WriteStartDocument(standalone);
}
public override void WriteEndDocument()
{
writer.WriteEndDocument();
}
public override void WriteDocType(string name, string pubid, string sysid, string subset)
{
writer.WriteDocType(name, pubid, sysid, subset);
}
public override void WriteStartElement(string prefix, string localName, string ns)
{
writer.WriteStartElement(prefix, localName, ns);
}
public override void WriteEndElement()
{
writer.WriteEndElement();
}
public override void WriteFullEndElement()
{
writer.WriteFullEndElement();
}
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
writer.WriteStartAttribute(prefix, localName, ns);
}
public override void WriteEndAttribute()
{
writer.WriteEndAttribute();
}
public override void WriteCData(string text)
{
writer.WriteCData(text);
}
public override void WriteComment(string text)
{
writer.WriteComment(text);
}
public override void WriteProcessingInstruction(string name, string text)
{
writer.WriteProcessingInstruction(name, text);
}
public override void WriteEntityRef(string name)
{
writer.WriteEntityRef(name);
}
public override void WriteCharEntity(char ch)
{
writer.WriteCharEntity(ch);
}
public override void WriteWhitespace(string ws)
{
writer.WriteWhitespace(ws);
}
public override void WriteString(string text)
{
writer.WriteString(text);
}
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
{
writer.WriteSurrogateCharEntity(lowChar, highChar);
}
public override void WriteChars(char[] buffer, int index, int count)
{
writer.WriteChars(buffer, index, count);
}
public override void WriteRaw(char[] buffer, int index, int count)
{
writer.WriteRaw(buffer, index, count);
}
public override void WriteRaw(string data)
{
writer.WriteRaw(data);
}
public override void WriteBase64(byte[] buffer, int index, int count)
{
writer.WriteBase64(buffer, index, count);
}
public override void Close()
{
writer.Close();
}
public override void Flush()
{
writer.Flush();
}
public override string LookupPrefix(string ns)
{
return writer.LookupPrefix(ns);
}
public override void WriteValue(object value)
{
writer.WriteValue(value);
}
public override void WriteValue(string value)
{
writer.WriteValue(value);
}
public override void WriteValue(bool value)
{
writer.WriteValue(value);
}
public override void WriteValue(DateTime value)
{
writer.WriteValue(value);
}
public override void WriteValue(DateTimeOffset value)
{
writer.WriteValue(value);
}
public override void WriteValue(double value)
{
writer.WriteValue(value);
}
public override void WriteValue(float value)
{
writer.WriteValue(value);
}
public override void WriteValue(decimal value)
{
writer.WriteValue(value);
}
public override void WriteValue(int value)
{
writer.WriteValue(value);
}
public override void WriteValue(long value)
{
writer.WriteValue(value);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
((IDisposable)writer).Dispose();
}
}
}
}
| |
// LICENSE
// You are hereafter granted an unending, unlimited, license to make use of,
// derivative works of, and free distributions of, the source code and contents
// of this file.
//
// DISCLAIMER
// BECAUSE THIS FILE IS LICENSED FREE OF CHARGE, THERE IS NO
// WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE
// LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
// HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
// WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT
// NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE
// QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
// PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY
// SERVICING, REPAIR OR CORRECTION.
//
// IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
// WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY
// MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE
// LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
// INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR
// INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
// DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU
// OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY
// OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
//
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using System.Security;
using System.IO.Compression;
namespace OpenDMD.URLSecurity
{
/// <summary>
/// Provides cryptographic services
/// </summary>
public sealed class Crypto
{
private readonly static byte[] _PadKey = new byte[] { 0x69, 0xfe, 0xee, 0x70, 0xbe, 0xef, 0x96 };
private static string _COMMON_KEY = "[enter something here]";
private static char _MARKER = '_';
private static char _Base64MARKER = '-';
#region MD5
/// <summary>
/// Returns an MD5 hashed and base64-encoded result from the given plain text.
/// </summary>
/// <param name="plainText"></param>
/// <returns></returns>
public static string HashBase64(string plainText)
{
MD5 sp = MD5CryptoServiceProvider.Create();
byte[] hash = sp.ComputeHash(System.Text.Encoding.Default.GetBytes(plainText));
return(Convert.ToBase64String(hash));
}
/// <summary>
/// Returns an MD5 hashed and hex-encoded result from the given plain text.
/// </summary>
/// <param name="plainText"></param>
/// <returns></returns>
public static string Hash(string plainText)
{
MD5 sp = MD5CryptoServiceProvider.Create();
byte[] hash = sp.ComputeHash(System.Text.Encoding.Default.GetBytes(plainText));
// Convert the hash to a hex-encoded string
string ss = HexStringFromBytes(hash, hash.Length);
return(ss);
}
#endregion
#region SHA512
/// <summary>
/// Returns an SHA512 hashed and base64-encoded result from the given plain text.
/// </summary>
/// <param name="plainText"></param>
/// <returns></returns>
public static string SHAHashBase64(string plainText)
{
SHA512 sp = SHA512CryptoServiceProvider.Create();
byte[] hash = sp.ComputeHash(System.Text.Encoding.Default.GetBytes(plainText));
return (Convert.ToBase64String(hash));
}
/// <summary>
/// Returns an SHA512 hashed and hex-encoded result from the given plain text.
/// </summary>
/// <param name="plainText"></param>
/// <returns></returns>
public static string SHAHash(string plainText)
{
SHA512 sp = SHA512CryptoServiceProvider.Create();
byte[] hash = sp.ComputeHash(System.Text.Encoding.Default.GetBytes(plainText));
// Convert the hash to a hex-encoded string
string ss = HexStringFromBytes(hash, hash.Length);
return (ss);
}
#endregion
private static byte[] MakeCipherKey(string key, SymmetricAlgorithm algo)
{
byte[] bytesKey = System.Text.Encoding.Default.GetBytes(key);
int nKeyBytes = algo.KeySize / 8;
if(bytesKey.Length > nKeyBytes)
{
byte[] bb = new byte[nKeyBytes];
Array.Copy(bytesKey, 0L, bb, 0L, (long)nKeyBytes);
bytesKey = bb;
}
else if(bytesKey.Length < nKeyBytes)
{
byte[] bb = new byte[nKeyBytes];
for(int i=0; i < nKeyBytes; i++)
{
if(i >= bytesKey.Length)
{
bb[i] = _PadKey[(i - bytesKey.Length) % _PadKey.Length];
}
else
{
bb[i] = bytesKey[i];
}
}
bytesKey = bb;
}
return(bytesKey);
}
#region DES Decryption
/// <summary>
/// Decrypts the given data using the common key.
/// </summary>
/// <param name="strData"></param>
/// <returns></returns>
public static string Decrypt(string strData)
{
return(Decrypt(strData, _COMMON_KEY));
}
/// <summary>
/// Decrypts the given data using the common key.
/// </summary>
/// <param name="strData"></param>
/// <returns>The original plain text as a byte array.</returns>
public static byte[] DecryptToBytes(string strData)
{
return (DecryptToBytes(strData,_COMMON_KEY));
}
/// <summary>
/// Decrypts the given data using the common key.
/// </summary>
/// <param name="strData"></param>
/// <returns>The original plain text as a byte array.</returns>
public static byte[] DecryptBase64ToBytes(string strData)
{
return (DecryptBase64ToBytes(strData,_COMMON_KEY));
}
/// <summary>
/// Decrypts the given string of cipher text with the given key string. The IV for the
/// cipher text is assumed to be appended to the cipher text after a MARKER character, e.g.
/// 123544151-43234324. This method uses DES as the crypto provider and assumes also
/// that the cipher text is hexadecimal encodes.
/// </summary>
/// <param name="strData">The cipher text + the IV</param>
/// <param name="strKey">The cipher key</param>
/// <returns>The plain text</returns>
public static string Decrypt(string strData, string strKey)
{
byte[] plain = DecryptToBytes(strData,strKey);
string strText = System.Text.Encoding.Default.GetString(plain);
return(strText);
}
/// <summary>
/// Decrypts the given string of cipher text with the given key string. The IV for the
/// cipher text is assumed to be appended to the cipher text after a MARKER character, e.g.
/// 123544151-43234324. This method uses DES as the crypto provider and assumes also
/// that the cipher text is hexadecimal encodes.
/// </summary>
/// <param name="strData">The cipher text + the IV</param>
/// <param name="strKey">The cipher key</param>
/// <returns>The original plain text as an array of bytes</returns>
public static byte[] DecryptToBytes(string strData,string strKey)
{
int ldx = strData.LastIndexOf(_MARKER);
if (ldx < 1)
{
ldx = strData.LastIndexOf('-');
}
if (ldx < 1)
{
throw (new SecurityException("Missing IV from cipher text"));
}
string strIV = strData.Substring(ldx + 1);
strData = strData.Substring(0,ldx);
DES des = DESCryptoServiceProvider.Create();
des.Mode = CipherMode.CBC;
byte[] bytesKey = MakeCipherKey(strKey,des);
byte[] bytesIV = BytesFromHexString(strIV);
CryptoStream decStream = new CryptoStream(new MemoryStream(BytesFromHexString(strData)),
des.CreateDecryptor(bytesKey,bytesIV),
CryptoStreamMode.Read);
MemoryStream ms = new MemoryStream();
byte[] buf = new byte[4096];
while (true)
{
int amt = decStream.Read(buf,0,buf.Length);
if (amt < 1)
{
break;
}
ms.Write(buf,0,amt);
}
return (ms.ToArray());
}
/// <summary>
/// Decrypts the given string of cipher text with the given key string. The IV for the
/// cipher text is assumed to be appended to the cipher text after a MARKER character, e.g.
/// 123544151-43234324. This method uses DES as the crypto provider and assumes also
/// that the cipher text is hexadecimal encodes.
/// </summary>
/// <param name="strData">The cipher text + the IV</param>
/// <param name="strKey">The cipher key</param>
/// <returns>The original plain text as an array of bytes</returns>
public static byte[] DecryptBase64ToBytes(string strData,string strKey)
{
int ldx = strData.LastIndexOf(_Base64MARKER);
if (ldx < 1)
{
ldx = strData.LastIndexOf('-');
}
if (ldx < 1)
{
throw (new SecurityException("Missing IV from cipher text"));
}
string strIV = strData.Substring(ldx + 1);
strData = strData.Substring(0,ldx);
DES des = DESCryptoServiceProvider.Create();
des.Mode = CipherMode.CBC;
byte[] bytesKey = MakeCipherKey(strKey,des);
byte[] bytesIV = Base64ToBytes(strIV);
CryptoStream decStream = new CryptoStream(new MemoryStream(Base64ToBytes(strData)),
des.CreateDecryptor(bytesKey,bytesIV),
CryptoStreamMode.Read);
MemoryStream ms = new MemoryStream();
byte[] buf = new byte[4096];
while (true)
{
int amt = decStream.Read(buf,0,buf.Length);
if (amt < 1)
{
break;
}
ms.Write(buf,0,amt);
}
return (ms.ToArray());
}
#endregion
#region AES Decryption
/// <summary>
/// Decrypts the given data using the common key.
/// </summary>
/// <param name="strData"></param>
/// <returns></returns>
public static string DecryptAES(string strData)
{
if (strData == null)
{
return (null);
}
return (DecryptAES(strData, _COMMON_KEY));
}
public static string DecryptAESBase64(string strData)
{
if (strData == null)
{
return (null);
}
return (DecryptAESBase64(strData, _COMMON_KEY));
}
/// <summary>
/// Decrypts the given data using the common key.
/// </summary>
/// <param name="strData"></param>
/// <returns>The original plain text as a byte array.</returns>
public static byte[] DecryptAESToBytes(string strData)
{
if (strData == null)
{
return (null);
}
return (DecryptAESToBytes(strData, _COMMON_KEY));
}
/// <summary>
/// Decrypts the given data using the common key.
/// </summary>
/// <param name="strData"></param>
/// <returns>The original plain text as a byte array.</returns>
public static byte[] DecryptAESBase64ToBytes(string strData)
{
if (strData == null)
{
return (null);
}
return (DecryptAESBase64ToBytes(strData, _COMMON_KEY));
}
/// <summary>
/// Decrypts the given string of cipher text with the given key string. The IV for the
/// cipher text is assumed to be appended to the cipher text after a MARKER character, e.g.
/// 123544151-43234324. This method uses DES as the crypto provider and assumes also
/// that the cipher text is hexadecimal encodes.
/// </summary>
/// <param name="strData">The cipher text + the IV</param>
/// <param name="strKey">The cipher key</param>
/// <returns>The plain text</returns>
public static string DecryptAES(string strData, string strKey)
{
if (strData == null)
{
return (null);
}
byte[] plain = DecryptAESToBytes(strData, strKey);
string strText = System.Text.Encoding.Default.GetString(plain);
return (strText);
}
public static string DecryptAES(string strData, byte[] key)
{
if (strData == null)
{
return (null);
}
byte[] plain = DecryptAESToBytes(strData, key);
string strText = System.Text.Encoding.Default.GetString(plain);
return (strText);
}
public static string DecryptAESBase64(string strData, string strKey)
{
if (strData == null)
{
return (null);
}
byte[] plain = DecryptAESBase64ToBytes(strData, strKey);
string strText = System.Text.Encoding.Default.GetString(plain);
return (strText);
}
public static string DecryptAESBase64(string strData, byte[] bytesKey)
{
if (strData == null)
{
return (null);
}
byte[] plain = DecryptAESBase64ToBytes(strData, bytesKey);
string strText = System.Text.Encoding.Default.GetString(plain);
return (strText);
}
/// <summary>
/// Decrypts the given string of cipher text with the given key string. The IV for the
/// cipher text is assumed to be appended to the cipher text after a MARKER character, e.g.
/// 123544151-43234324. This method uses DES as the crypto provider and assumes also
/// that the cipher text is hexadecimal encodes.
/// </summary>
/// <param name="strData">The cipher text + the IV</param>
/// <param name="strKey">The cipher key</param>
/// <returns>The original plain text as an array of bytes</returns>
public static byte[] DecryptAESToBytes(string strData, string strKey)
{
if (strData == null)
{
return (null);
}
Aes des = AesCryptoServiceProvider.Create();
des.Mode = CipherMode.CBC;
byte[] bytesKey = MakeCipherKey(strKey, des);
return (DecryptAESToBytes(strData, bytesKey));
}
/// <summary>
/// Decrypts the given string of cipher text with the given key string. The IV for the
/// cipher text is assumed to be appended to the cipher text after a MARKER character, e.g.
/// 123544151-43234324. This method uses DES as the crypto provider and assumes also
/// that the cipher text is hexadecimal encodes.
/// </summary>
/// <param name="strData">The cipher text + the IV</param>
/// <param name="strKey">The cipher key</param>
/// <returns>The original plain text as an array of bytes</returns>
public static byte[] DecryptAESToBytes(string strData, byte[] bytesKey)
{
if (strData == null)
{
return (null);
}
int ldx = strData.LastIndexOf(_MARKER);
if (ldx < 1)
{
ldx = strData.LastIndexOf('-');
}
if (ldx < 1)
{
throw (new SecurityException("Missing IV from cipher text"));
}
string strIV = strData.Substring(ldx + 1);
strData = strData.Substring(0, ldx);
Aes des = AesCryptoServiceProvider.Create();
des.Mode = CipherMode.CBC;
byte[] bytesIV = BytesFromHexString(strIV);
CryptoStream decStream = new CryptoStream(new MemoryStream(BytesFromHexString(strData)),
des.CreateDecryptor(bytesKey, bytesIV),
CryptoStreamMode.Read);
MemoryStream ms = new MemoryStream();
byte[] buf = new byte[4096];
while (true)
{
int amt = decStream.Read(buf, 0, buf.Length);
if (amt < 1)
{
break;
}
ms.Write(buf, 0, amt);
}
return (ms.ToArray());
}
/// <summary>
/// Decrypts the given string of cipher text with the given key string. The IV for the
/// cipher text is assumed to be appended to the cipher text after a MARKER character, e.g.
/// 123544151-43234324. This method uses DES as the crypto provider and assumes also
/// that the cipher text is hexadecimal encodes.
/// </summary>
/// <param name="strData">The cipher text + the IV</param>
/// <param name="strKey">The cipher key</param>
/// <returns>The original plain text as an array of bytes</returns>
public static byte[] DecryptAESBase64ToBytes(string strData, string strKey)
{
if (strData == null)
{
return (null);
}
int ldx = strData.LastIndexOf(_Base64MARKER);
if (ldx < 1)
{
ldx = strData.LastIndexOf('-');
}
if (ldx < 1)
{
throw (new SecurityException("Missing IV from cipher text"));
}
string strIV = strData.Substring(ldx + 1);
strData = strData.Substring(0, ldx);
Aes des = AesCryptoServiceProvider.Create();
des.Mode = CipherMode.CBC;
byte[] bytesKey = MakeCipherKey(strKey, des);
byte[] bytesIV = Base64ToBytes(strIV);
CryptoStream decStream = new CryptoStream(new MemoryStream(Base64ToBytes(strData)),
des.CreateDecryptor(bytesKey, bytesIV),
CryptoStreamMode.Read);
MemoryStream ms = new MemoryStream();
byte[] buf = new byte[4096];
while (true)
{
int amt = decStream.Read(buf, 0, buf.Length);
if (amt < 1)
{
break;
}
ms.Write(buf, 0, amt);
}
return (ms.ToArray());
}
public static byte[] DecryptAESBase64ToBytes(string strData, byte[] bytesKey)
{
if (strData == null)
{
return (null);
}
int ldx = strData.LastIndexOf(_Base64MARKER);
if (ldx < 1)
{
ldx = strData.LastIndexOf('-');
}
if (ldx < 1)
{
throw (new SecurityException("Missing IV from cipher text"));
}
string strIV = strData.Substring(ldx + 1);
strData = strData.Substring(0, ldx);
Aes des = AesCryptoServiceProvider.Create();
des.Mode = CipherMode.CBC;
byte[] bytesIV = Base64ToBytes(strIV);
CryptoStream decStream = new CryptoStream(new MemoryStream(Base64ToBytes(strData)),
des.CreateDecryptor(bytesKey, bytesIV),
CryptoStreamMode.Read);
MemoryStream ms = new MemoryStream();
byte[] buf = new byte[4096];
while (true)
{
int amt = decStream.Read(buf, 0, buf.Length);
if (amt < 1)
{
break;
}
ms.Write(buf, 0, amt);
}
return (ms.ToArray());
}
#endregion
/// <summary>
/// Takes a hex string and converts it to its byte equivalent.
/// </summary>
/// <param name="strHex"></param>
/// <returns></returns>
public static byte[] BytesFromHexString(string strHex)
{
string HexLookup = "0123456789ABCDEF";
strHex = strHex.ToUpper();
MemoryStream ms = new MemoryStream();
for(int i=0; i < strHex.Length; i+=2)
{
// Convert base 16 to binary
byte b = 0;
int ival = HexLookup.IndexOf(strHex[i]);
b = (byte)((ival << 4) & 0xF0);
ival = HexLookup.IndexOf(strHex[i+1]);
b |= (byte)(ival & 0x0F);
ms.WriteByte(b);
}
byte[] bb = new byte[ms.Length];
byte[] buf = ms.GetBuffer();
for(int i=0; i < bb.Length; i++)
{
bb[i] = buf[i];
}
return(bb);
}
/// <summary>
/// Encodes the given byte array using Base64 encoding (not quoted-printable), and
/// returns a string of the base64 encoding.
/// </summary>
/// <param name="bytes"></param>
/// <param name="length"></param>
/// <returns></returns>
public static string Base64FromBytes(byte[] bytes, int length)
{
return(Convert.ToBase64String(bytes, 0, length));
}
/// <summary>
/// Encodes the given byte array using Base64 encoding (not quoted-printable), and
/// returns a string of the base64 encoding.
/// </summary>
/// <param name="input">The original base64 string to decode</param>
/// <returns>The decoded bytes.</returns>
public static byte[] Base64ToBytes(string input)
{
return (Convert.FromBase64String(input));
}
/// <summary>
/// Returns a hex encoded string from the given byte array.
/// </summary>
/// <param name="bytes"></param>
/// <param name="length"></param>
/// <returns></returns>
public static string HexStringFromBytes(byte[] bytes, int length)
{
string HexLookup = "0123456789ABCDEF";
char[] cc = new char[length*2];
int idx = 0;
for(int i=0; i < length; i++)
{
int ival = ((int)((bytes[i] & 0xF0) >> 4)) & 0xFF;
cc[idx++] = HexLookup[ival];
ival = ((int)(bytes[i] & 0x0F)) & 0xFF;
cc[idx++] = HexLookup[ival];
}
return(new string(cc));
}
#region DES Encryption
/// <summary>
/// Uses the common key to encrypt the given data.
/// </summary>
/// <param name="strData"></param>
/// <returns></returns>
public static string Encrypt(string strData)
{
return(Encrypt(strData, _COMMON_KEY));
}
/// <summary>
/// Encrypts the given byte array using the given key. The resulting
/// cipher text is then converted to base-64 encoding.
/// </summary>
/// <param name="data">Data to be encrypted.</param>
/// <returns>base-16 encoded data of the given byte array.</returns>
public static string Encrypt(byte[] data)
{
return (Encrypt(data,_COMMON_KEY));
}
/// <summary>
/// Encrypts the given byte array using the given key. The resulting
/// cipher text is then converted to base-64 encoding.
/// </summary>
/// <param name="data">Data to be encrypted.</param>
/// <returns>base-64 encoded data of the given byte array.</returns>
public static string EncryptBase64(byte[] data)
{
return (EncryptBase64(data,_COMMON_KEY));
}
/// Encrypts the given byte array using the given key. The resulting
/// cipher text is then converted to base-64 encoding.
/// </summary>
/// <param name="bytesPlain"></param>
/// <param name="strKey"></param>
/// <returns>base-64 encoded data of the given byte array.</returns>
public static string EncryptBase64(byte[] bytesPlain,string strKey)
{
DES des = DESCryptoServiceProvider.Create();
des.Mode = CipherMode.CBC;
byte[] bytesKey = MakeCipherKey(strKey,des);
des.GenerateIV();
byte[] bytesIV = des.IV;
StringBuilder sb = new StringBuilder();
MemoryStream ms = new MemoryStream();
CryptoStream encStream = new CryptoStream(ms,des.CreateEncryptor(bytesKey,bytesIV),CryptoStreamMode.Write);
// Encrypt the data using default encoding
int remainder = bytesPlain.Length % des.BlockSize;
byte[] bytesToEncrypt = new byte[bytesPlain.Length + remainder];
bytesPlain.CopyTo(bytesToEncrypt,0);
encStream.Write(bytesToEncrypt,0,bytesPlain.Length);
encStream.FlushFinalBlock();
encStream.Close();
byte[] cryptText = ms.ToArray();
sb.Append(Base64FromBytes(cryptText,cryptText.Length));
sb.Append(_Base64MARKER);
sb.Append(Base64FromBytes(bytesIV,bytesIV.Length));
return (sb.ToString());
}
/// Encrypts the given byte array using the given key. The resulting
/// cipher text is then converted to base-64 encoding.
/// </summary>
/// <param name="bytesPlain"></param>
/// <param name="strKey"></param>
/// <returns></returns>
public static string Encrypt(byte[] bytesPlain, string strKey)
{
DES des = DESCryptoServiceProvider.Create();
des.Mode = CipherMode.CBC;
byte[] bytesKey = MakeCipherKey(strKey,des);
des.GenerateIV();
byte[] bytesIV = des.IV;
StringBuilder sb = new StringBuilder();
MemoryStream ms = new MemoryStream();
CryptoStream encStream = new CryptoStream(ms,des.CreateEncryptor(bytesKey,bytesIV),CryptoStreamMode.Write);
// Encrypt the data using default encoding
int remainder = bytesPlain.Length % des.BlockSize;
byte[] bytesToEncrypt = new byte[bytesPlain.Length + remainder];
bytesPlain.CopyTo(bytesToEncrypt,0);
encStream.Write(bytesToEncrypt,0,bytesPlain.Length);
encStream.FlushFinalBlock();
encStream.Close();
byte[] cryptText = ms.ToArray();
sb.Append(HexStringFromBytes(cryptText,cryptText.Length));
sb.Append(_MARKER);
sb.Append(HexStringFromBytes(bytesIV,bytesIV.Length));
return (sb.ToString());
}
/// <summary>
/// Encrypts data in the given argument and returns the result as a hex encoded
/// string.
/// </summary>
/// <param name="strData"></param>
/// <param name="strKey"></param>
/// <returns></returns>
public static string Encrypt(string strData, string strKey)
{
// Encrypt the data using default encoding
byte[] bytesPlain = Encoding.Default.GetBytes(strData);
return(Encrypt(bytesPlain,strKey));
}
#endregion
#region AES Encryption
/// <summary>
/// Encrypts data in the given argument and returns the result as a hex encoded
/// string.
/// </summary>
/// <param name="strData"></param>
/// <param name="strKey"></param>
/// <returns></returns>
public static string EncryptAES(string strData, string strKey)
{
if (strData == null)
{
return (null);
}
// Encrypt the data using default encoding
byte[] bytesPlain = Encoding.Default.GetBytes(strData);
return(EncryptAES(bytesPlain,strKey));
}
public static string EncryptAES(string strData, byte[] key)
{
if (strData == null)
{
return (null);
}
// Encrypt the data using default encoding
byte[] bytesPlain = Encoding.Default.GetBytes(strData);
return (EncryptAES(bytesPlain, key));
}
public static string EncryptAESBase64(string strData, string strKey)
{
if (strData == null)
{
return (null);
}
// Encrypt the data using default encoding
byte[] bytesPlain = Encoding.Default.GetBytes(strData);
return (EncryptAESBase64(bytesPlain, strKey));
}
public static string EncryptAESBase64(string strData, byte[] bytesKey)
{
if (strData == null)
{
return (null);
}
// Encrypt the data using default encoding
byte[] bytesPlain = Encoding.Default.GetBytes(strData);
return (EncryptAESBase64(bytesPlain, bytesKey));
}
/// Encrypts the given byte array using the given key. The resulting
/// cipher text is then converted to base-64 encoding.
/// </summary>
/// <param name="bytesPlain"></param>
/// <param name="strKey"></param>
/// <returns></returns>
public static string EncryptAES(byte[] bytesPlain, string strKey)
{
if (bytesPlain == null)
{
return (null);
}
Aes des = AesCryptoServiceProvider.Create();
des.Mode = CipherMode.CBC;
byte[] bytesKey = MakeCipherKey(strKey, des);
return (EncryptAES(bytesPlain, bytesKey));
}
public static string EncryptAES(byte[] bytesPlain, byte[] bytesKey)
{
if (bytesPlain == null)
{
return (null);
}
Aes des = AesCryptoServiceProvider.Create();
des.Mode = CipherMode.CBC;
des.GenerateIV();
byte[] bytesIV = des.IV;
StringBuilder sb = new StringBuilder();
MemoryStream ms = new MemoryStream();
CryptoStream encStream = new CryptoStream(ms, des.CreateEncryptor(bytesKey, bytesIV), CryptoStreamMode.Write);
// Encrypt the data using default encoding
int remainder = bytesPlain.Length % des.BlockSize;
byte[] bytesToEncrypt = new byte[bytesPlain.Length + remainder];
bytesPlain.CopyTo(bytesToEncrypt, 0);
encStream.Write(bytesToEncrypt, 0, bytesPlain.Length);
encStream.FlushFinalBlock();
encStream.Close();
byte[] cryptText = ms.ToArray();
sb.Append(HexStringFromBytes(cryptText, cryptText.Length));
sb.Append(_MARKER);
sb.Append(HexStringFromBytes(bytesIV, bytesIV.Length));
return (sb.ToString());
}
/// Encrypts the given byte array using the given key. The resulting
/// cipher text is then converted to base-64 encoding.
/// </summary>
/// <param name="bytesPlain"></param>
/// <param name="strKey"></param>
/// <returns>base-64 encoded data of the given byte array.</returns>
public static string EncryptAESBase64(byte[] bytesPlain,string strKey)
{
if (bytesPlain == null)
{
return (null);
}
Aes des = AesCryptoServiceProvider.Create();
des.Mode = CipherMode.CBC;
byte[] bytesKey = MakeCipherKey(strKey,des);
des.GenerateIV();
byte[] bytesIV = des.IV;
StringBuilder sb = new StringBuilder();
MemoryStream ms = new MemoryStream();
CryptoStream encStream = new CryptoStream(ms,des.CreateEncryptor(bytesKey,bytesIV),CryptoStreamMode.Write);
// Encrypt the data using default encoding
int remainder = bytesPlain.Length % des.BlockSize;
byte[] bytesToEncrypt = new byte[bytesPlain.Length + remainder];
bytesPlain.CopyTo(bytesToEncrypt,0);
encStream.Write(bytesToEncrypt,0,bytesPlain.Length);
encStream.FlushFinalBlock();
encStream.Close();
byte[] cryptText = ms.ToArray();
sb.Append(Base64FromBytes(cryptText,cryptText.Length));
sb.Append(_Base64MARKER);
sb.Append(Base64FromBytes(bytesIV,bytesIV.Length));
return (sb.ToString());
}
public static string EncryptAESBase64(byte[] bytesPlain, byte[] bytesKey)
{
if (bytesPlain == null)
{
return (null);
}
Aes des = AesCryptoServiceProvider.Create();
des.Mode = CipherMode.CBC;
des.GenerateIV();
byte[] bytesIV = des.IV;
StringBuilder sb = new StringBuilder();
MemoryStream ms = new MemoryStream();
CryptoStream encStream = new CryptoStream(ms, des.CreateEncryptor(bytesKey, bytesIV), CryptoStreamMode.Write);
// Encrypt the data using default encoding
int remainder = bytesPlain.Length % des.BlockSize;
byte[] bytesToEncrypt = new byte[bytesPlain.Length + remainder];
bytesPlain.CopyTo(bytesToEncrypt, 0);
encStream.Write(bytesToEncrypt, 0, bytesPlain.Length);
encStream.FlushFinalBlock();
encStream.Close();
byte[] cryptText = ms.ToArray();
sb.Append(Base64FromBytes(cryptText, cryptText.Length));
sb.Append(_Base64MARKER);
sb.Append(Base64FromBytes(bytesIV, bytesIV.Length));
return (sb.ToString());
}
/// <summary>
/// Encrypts the given byte array using the given key. The resulting
/// cipher text is then converted to base-64 encoding.
/// </summary>
/// <param name="data">Data to be encrypted.</param>
/// <returns>base-64 encoded data of the given byte array.</returns>
public static string EncryptAESBase64(byte[] data)
{
return (EncryptAESBase64(data,_COMMON_KEY));
}
/// <summary>
/// Uses the common key to encrypt the given data.
/// </summary>
/// <param name="strData"></param>
/// <returns></returns>
public static string EncryptAES(string strData)
{
return(EncryptAES(strData, _COMMON_KEY));
}
public static string EncryptAESBase64(string strData)
{
return (EncryptAESBase64(strData, _COMMON_KEY));
}
/// <summary>
/// Encrypts the given byte array using the given key. The resulting
/// cipher text is then converted to base-64 encoding.
/// </summary>
/// <param name="data">Data to be encrypted.</param>
/// <returns>base-16 encoded data of the given byte array.</returns>
public static string EncryptAES(byte[] data)
{
return (EncryptAES(data,_COMMON_KEY));
}
#endregion
#region DES Data Wrapping Methods
public static string UnwrapData(string src, string key = null)
{
if (key == null)
{
key = _COMMON_KEY;
}
// 1. Decrypt the data
string plain = Crypto.Decrypt(src, key);
byte[] data = null;
// 2. Try to decode the base-64
try
{
data = Convert.FromBase64String(plain);
}
catch (FormatException ex)
{
// Not in base 64, so return it
return (plain);
}
// 3. Uncompress
MemoryStream ms = new MemoryStream(data);
GZipStream gis = new GZipStream(ms, CompressionMode.Decompress);
StreamReader sr = new StreamReader(gis);
plain = sr.ReadToEnd();
return (plain);
}
public static byte[] UnwrapDataToBytes(string src, string key = null)
{
if (key == null)
{
key = _COMMON_KEY;
}
// 1. Decrypt the data
string plain = Crypto.Decrypt(src);
byte[] data = null;
// 2. Try to decode the base-64
try
{
data = Convert.FromBase64String(plain);
}
catch (FormatException ex)
{
// Not in base 64, so return it
return (data);
}
// 3. Uncompress
MemoryStream ms = new MemoryStream(data);
GZipStream gis = new GZipStream(ms, CompressionMode.Decompress);
MemoryStream ms2 = new MemoryStream();
byte[] buf = new byte[4096];
while (gis.CanRead)
{
int amt = gis.Read(buf, 0, buf.Length);
if (amt < 1)
{
break;
}
ms2.Write(buf, 0, amt);
}
data = ms2.ToArray();
return (data);
}
public static string WrapData(byte[] src, string key = null)
{
if (key == null)
{
key = _COMMON_KEY;
}
string str = null;
// 1. Compress the data
MemoryStream ms = new MemoryStream();
GZipStream gos = new GZipStream(ms, CompressionMode.Compress);
gos.Write(src, 0, src.Length);
gos.Flush();
byte[] data = ms.ToArray();
// 2. Base 64 encode
str = Convert.ToBase64String(data);
// 3. Encrypt the data
string crypto = Crypto.Encrypt(str);
return (crypto);
}
public static string WrapData(string src, string key = null)
{
if (key == null)
{
key = _COMMON_KEY;
}
string str = src;
// 1. Compress the data
MemoryStream ms = new MemoryStream();
GZipStream gos = new GZipStream(ms, CompressionMode.Compress);
StreamWriter sw = new StreamWriter(gos);
sw.Write(src);
sw.Flush();
gos.Flush();
byte[] data = ms.ToArray();
// 2. Base 64 encode
str = Convert.ToBase64String(data);
// 3. Encrypt the data
string crypto = Crypto.Encrypt(str);
return (crypto);
}
#endregion
#region AES Data Wrapping Methods
public static string WrapAESData(byte[] src, string key = null)
{
if (key == null)
{
key = _COMMON_KEY;
}
string str = null;
// 1. Compress the data
MemoryStream ms = new MemoryStream();
GZipStream gos = new GZipStream(ms, CompressionMode.Compress);
gos.Write(src, 0, src.Length);
gos.Flush();
gos.Close();
byte[] data = ms.ToArray();
// 2. Base 64 encode
str = Convert.ToBase64String(data);
// 3. Encrypt the data
string crypto = Crypto.EncryptAES(str, key);
return (crypto);
}
public static string WrapAESData(byte[] src, byte[] key)
{
string str = null;
// 1. Compress the data
MemoryStream ms = new MemoryStream();
GZipStream gos = new GZipStream(ms, CompressionMode.Compress);
gos.Write(src, 0, src.Length);
gos.Flush();
gos.Close();
byte[] data = ms.ToArray();
// 2. Base 64 encode
str = Convert.ToBase64String(data);
// 3. Encrypt the data
string crypto = Crypto.EncryptAES(str, key);
return (crypto);
}
public static string WrapAESData(Stream src, byte[] key)
{
string str = null;
// 1. Compress the data
MemoryStream ms = new MemoryStream();
GZipStream gos = new GZipStream(ms, CompressionMode.Compress);
src.CopyTo(gos);
gos.Flush();
gos.Close();
byte[] data = ms.ToArray();
// 2. Base 64 encode
str = Convert.ToBase64String(data);
// 3. Encrypt the data
string crypto = Crypto.EncryptAES(str, key);
return (crypto);
}
public static string WrapAESData(string src, byte[] key)
{
string str = src;
// 1. Compress the data
MemoryStream ms = new MemoryStream();
GZipStream gos = new GZipStream(ms, CompressionMode.Compress);
StreamWriter sw = new StreamWriter(gos);
sw.Write(src);
sw.Flush();
gos.Flush();
sw.Close();
byte[] data = ms.ToArray();
// 2. Base 64 encode
str = Convert.ToBase64String(data);
// 3. Encrypt the data
string crypto = Crypto.EncryptAES(str, key);
return (crypto);
}
public static string WrapAESData(string src, string key = null)
{
if (key == null)
{
key = _COMMON_KEY;
}
string str = src;
// 1. Compress the data
MemoryStream ms = new MemoryStream();
GZipStream gos = new GZipStream(ms, CompressionMode.Compress);
StreamWriter sw = new StreamWriter(gos);
sw.Write(src);
sw.Flush();
gos.Flush();
sw.Close();
byte[] data = ms.ToArray();
// 2. Base 64 encode
str = Convert.ToBase64String(data);
// 3. Encrypt the data
string crypto = Crypto.EncryptAES(str, key);
return (crypto);
}
public static string UnwrapAESData(string src, byte[] key)
{
// 1. Decrypt the data
string plain = Crypto.DecryptAES(src, key);
byte[] data = null;
// 2. Try to decode the base-64
try
{
data = Convert.FromBase64String(plain);
}
catch (FormatException ex)
{
// Not in base 64, so return it
return (plain);
}
// 3. Uncompress
MemoryStream ms = new MemoryStream(data);
GZipStream gis = new GZipStream(ms, CompressionMode.Decompress);
StreamReader sr = new StreamReader(gis);
plain = sr.ReadToEnd();
return (plain);
}
public static string UnwrapAESData(string src, string key = null)
{
if (key == null)
{
key = _COMMON_KEY;
}
// 1. Decrypt the data
string plain = Crypto.DecryptAES(src, key);
byte[] data = null;
// 2. Try to decode the base-64
try
{
data = Convert.FromBase64String(plain);
}
catch (FormatException ex)
{
// Not in base 64, so return it
return (plain);
}
// 3. Uncompress
MemoryStream ms = new MemoryStream(data);
GZipStream gis = new GZipStream(ms, CompressionMode.Decompress);
StreamReader sr = new StreamReader(gis);
plain = sr.ReadToEnd();
return (plain);
}
public static byte[] UnwrapAESDataToBytes(string src, string key = null)
{
if (key == null)
{
key = _COMMON_KEY;
}
// 1. Decrypt the data
string plain = Crypto.DecryptAES(src, key);
byte[] data = null;
// 2. Try to decode the base-64
try
{
data = Convert.FromBase64String(plain);
}
catch (FormatException ex)
{
// Not in base 64, so return it
return (data);
}
// 3. Uncompress
MemoryStream ms = new MemoryStream(data);
GZipStream gis = new GZipStream(ms, CompressionMode.Decompress);
MemoryStream ms2 = new MemoryStream();
byte[] buf = new byte[4096];
while (gis.CanRead)
{
int amt = gis.Read(buf, 0, buf.Length);
if (amt < 1)
{
break;
}
ms2.Write(buf, 0, amt);
}
data = ms2.ToArray();
return (data);
}
public static byte[] UnwrapAESDataToBytes(string src, byte[] key)
{
// 1. Decrypt the data
string plain = Crypto.DecryptAES(src, key);
byte[] data = null;
// 2. Try to decode the base-64
try
{
data = Convert.FromBase64String(plain);
}
catch (FormatException ex)
{
// Not in base 64, so return it
return (data);
}
// 3. Uncompress
MemoryStream ms = new MemoryStream(data);
GZipStream gis = new GZipStream(ms, CompressionMode.Decompress);
MemoryStream ms2 = new MemoryStream();
byte[] buf = new byte[4096];
while (gis.CanRead)
{
int amt = gis.Read(buf, 0, buf.Length);
if (amt < 1)
{
break;
}
ms2.Write(buf, 0, amt);
}
data = ms2.ToArray();
return (data);
}
#endregion
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlTypes;
public partial class Backoffice_Controls_EditRegistrasiFIS : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void Draw(string RawatJalanId)
{
SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan();
myObj.RawatJalanId = Int64.Parse(RawatJalanId);
DataTable dt = myObj.SelectOne();
if (dt.Rows.Count > 0)
{
DataRow row = dt.Rows[0];
HFRegistrasiId.Value = row["RegistrasiId"].ToString();
HFRawatJalanId.Value = row["RawatJalanId"].ToString();
HFPasienId.Value = row["PasienId"].ToString();
HFStatusRawatJalan.Value = row["StatusRawatJalan"].ToString();
HFPenjaminId.Value = row["PenjaminId"].ToString() == "" ? "0" : row["PenjaminId"].ToString();
lblNoRM.Text = row["NoRM"].ToString();
lblNamaPasien.Text = row["Nama"].ToString();
//Data Registrasi
lblNoRegistrasi.Text = row["NoRegistrasi"].ToString();
txtNoRegistrasi.Text = row["NoRegistrasi"].ToString();
txtTanggalRegistrasi.Text = row["TanggalBerobat"].ToString() != "" ? ((DateTime)row["TanggalBerobat"]).ToString("dd/MM/yyyy") : "";
txtNomorTunggu.Text = row["NomorTunggu"].ToString();
GetListJenisPenjamin(row["JenisPenjaminId"].ToString());
string JenisPenjaminId = row["JenisPenjaminId"].ToString();
GetListHubungan(row["HubunganId"].ToString());
GetListAgama(row["AgamaIdPenjamin"].ToString());
GetListPendidikan(row["PendidikanIdPenjamin"].ToString());
GetListStatus(row["StatusIdPenjamin"].ToString());
GetListPangkatPenjamin(row["PangkatIdPenjamin"].ToString());
if (JenisPenjaminId == "2")
{
tblPenjaminKeluarga.Visible = true;
tblPenjaminPerusahaan.Visible = false;
//Data Keluarga Penjamin
txtNamaPenjamin.Text = row["NamaPenjamin"].ToString();
txtUmurPenjamin.Text = row["UmurPenjamin"].ToString();
txtAlamatPenjamin.Text = row["AlamatPenjamin"].ToString();
txtTeleponPenjamin.Text = row["TeleponPenjamin"].ToString();
txtNRPPenjamin.Text = row["NRPPenjamin"].ToString();
txtJabatanPenjamin.Text = row["JabatanPenjamin"].ToString();
txtKesatuanPenjamin.Text = row["KesatuanPenjamin"].ToString();
txtAlamatKesatuanPenjamin.Text = row["AlamatKesatuan"].ToString();
txtNoKTPPenjamin.Text = row["NoKTPPenjamin"].ToString();
txtGolDarahPenjamin.Text = row["GolDarahPenjamin"].ToString();
txtKeteranganPenjamin.Text = row["KeteranganPenjamin"].ToString();
}
else if (JenisPenjaminId == "3" || JenisPenjaminId == "4")
{
tblPenjaminKeluarga.Visible = false;
tblPenjaminPerusahaan.Visible = true;
txtNamaPerusahaan.Text = row["NamaPenjamin"].ToString();
txtNamaKontak.Text = row["NamaKontakPenjamin"].ToString();
txtAlamatPerusahaan.Text = row["AlamatPenjamin"].ToString();
txtTeleponPerusahaan.Text = row["TeleponPenjamin"].ToString();
txtFAXPerusahaan.Text = row["FaxPenjamin"].ToString();
txtKeteranganPerusahaan.Text = row["KeteranganPenjamin"].ToString();
}
else
{
tblPenjaminKeluarga.Visible = false;
tblPenjaminPerusahaan.Visible = false;
}
}
}
public void GetListStatus(string StatusId)
{
SIMRS.DataAccess.RS_Status myObj = new SIMRS.DataAccess.RS_Status();
DataTable dt = myObj.GetList();
cmbStatusPenjamin.Items.Clear();
int i = 0;
cmbStatusPenjamin.Items.Add("");
cmbStatusPenjamin.Items[i].Text = "";
cmbStatusPenjamin.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbStatusPenjamin.Items.Add("");
cmbStatusPenjamin.Items[i].Text = dr["Nama"].ToString();
cmbStatusPenjamin.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == StatusId)
{
cmbStatusPenjamin.SelectedIndex = i;
}
i++;
}
}
public void GetListPangkatPenjamin(string PangkatId)
{
SIMRS.DataAccess.RS_Pangkat myObj = new SIMRS.DataAccess.RS_Pangkat();
if (cmbStatusPenjamin.SelectedIndex > 0)
myObj.StatusId = int.Parse(cmbStatusPenjamin.SelectedItem.Value);
DataTable dt = myObj.GetListByStatusId();
cmbPangkatPenjamin.Items.Clear();
int i = 0;
cmbPangkatPenjamin.Items.Add("");
cmbPangkatPenjamin.Items[i].Text = "";
cmbPangkatPenjamin.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbPangkatPenjamin.Items.Add("");
cmbPangkatPenjamin.Items[i].Text = dr["Nama"].ToString();
cmbPangkatPenjamin.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == PangkatId)
{
cmbPangkatPenjamin.SelectedIndex = i;
}
i++;
}
}
public void GetNomorTunggu()
{
SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan();
myObj.PoliklinikId = 34;//FIS
myObj.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text);
txtNomorTunggu.Text = myObj.GetNomorTunggu().ToString();
}
public void GetListAgama(string AgamaId)
{
BkNet.DataAccess.Agama myObj = new BkNet.DataAccess.Agama();
DataTable dt = myObj.GetList();
cmbAgamaPenjamin.Items.Clear();
int i = 0;
cmbAgamaPenjamin.Items.Add("");
cmbAgamaPenjamin.Items[i].Text = "";
cmbAgamaPenjamin.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbAgamaPenjamin.Items.Add("");
cmbAgamaPenjamin.Items[i].Text = dr["Nama"].ToString();
cmbAgamaPenjamin.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == AgamaId)
cmbAgamaPenjamin.SelectedIndex = i;
i++;
}
}
public void GetListPendidikan(string PendidikanId)
{
BkNet.DataAccess.Pendidikan myObj = new BkNet.DataAccess.Pendidikan();
DataTable dt = myObj.GetList();
cmbPendidikanPenjamin.Items.Clear();
int i = 0;
cmbPendidikanPenjamin.Items.Add("");
cmbPendidikanPenjamin.Items[i].Text = "";
cmbPendidikanPenjamin.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbPendidikanPenjamin.Items.Add("");
cmbPendidikanPenjamin.Items[i].Text = "[" + dr["Kode"].ToString() + "] " + dr["Nama"].ToString();
cmbPendidikanPenjamin.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == PendidikanId)
cmbPendidikanPenjamin.SelectedIndex = i;
i++;
}
}
public void GetListJenisPenjamin(string JenisPenjaminId)
{
SIMRS.DataAccess.RS_JenisPenjamin myObj = new SIMRS.DataAccess.RS_JenisPenjamin();
DataTable dt = myObj.GetList();
cmbJenisPenjamin.Items.Clear();
int i = 0;
foreach (DataRow dr in dt.Rows)
{
cmbJenisPenjamin.Items.Add("");
cmbJenisPenjamin.Items[i].Text = dr["Nama"].ToString();
cmbJenisPenjamin.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == JenisPenjaminId)
cmbJenisPenjamin.SelectedIndex = i;
i++;
}
}
public void GetListHubungan(string HubunganId)
{
SIMRS.DataAccess.RS_Hubungan myObj = new SIMRS.DataAccess.RS_Hubungan();
DataTable dt = myObj.GetList();
cmbHubungan.Items.Clear();
int i = 0;
cmbHubungan.Items.Add("");
cmbHubungan.Items[i].Text = "";
cmbHubungan.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbHubungan.Items.Add("");
cmbHubungan.Items[i].Text = dr["Nama"].ToString();
cmbHubungan.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == HubunganId)
cmbHubungan.SelectedIndex = i;
i++;
}
}
public void GetNomorRegistrasi()
{
SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan();
myObj.PoliklinikId = 34;//FIS
myObj.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text);
txtNoRegistrasi.Text = myObj.GetNomorRegistrasi();
}
public bool OnSave()
{
bool result = false;
lblError.Text = "";
if (Session["SIMRS.UserId"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx");
}
int UserId = (int)Session["SIMRS.UserId"];
if (!Page.IsValid)
{
return false;
}
SIMRS.DataAccess.RS_Penjamin myPenj = new SIMRS.DataAccess.RS_Penjamin();
myPenj.PenjaminId = Int64.Parse(HFPenjaminId.Value);
myPenj.SelectOne();
if (cmbJenisPenjamin.SelectedIndex > 0)
{
//Input Data Penjamin
if (cmbJenisPenjamin.SelectedIndex == 1)
{
if (cmbHubungan.SelectedIndex > 0)
myPenj.HubunganId = int.Parse(cmbHubungan.SelectedItem.Value);
myPenj.Nama = txtNamaPenjamin.Text;
myPenj.Umur = txtUmurPenjamin.Text;
myPenj.Alamat = txtAlamatPenjamin.Text;
myPenj.Telepon = txtTeleponPenjamin.Text;
if (cmbAgamaPenjamin.SelectedIndex > 0)
myPenj.AgamaId = int.Parse(cmbAgamaPenjamin.SelectedItem.Value);
if (cmbPendidikanPenjamin.SelectedIndex > 0)
myPenj.PendidikanId = int.Parse(cmbPendidikanPenjamin.SelectedItem.Value);
if (cmbStatusPenjamin.SelectedIndex > 0)
myPenj.StatusId = int.Parse(cmbStatusPenjamin.SelectedItem.Value);
if (cmbPangkatPenjamin.SelectedIndex > 0)
myPenj.PangkatId = int.Parse(cmbPangkatPenjamin.SelectedItem.Value);
myPenj.NRP = txtNRPPenjamin.Text;
myPenj.Jabatan = txtJabatanPenjamin.Text;
myPenj.Kesatuan = txtKesatuanPenjamin.Text;
myPenj.AlamatKesatuan = txtAlamatKesatuanPenjamin.Text;
myPenj.NoKTP = txtNoKTPPenjamin.Text;
myPenj.GolDarah = txtGolDarahPenjamin.Text;
myPenj.Keterangan = txtKeteranganPenjamin.Text;
}
else
{
myPenj.Nama = txtNamaPerusahaan.Text;
myPenj.NamaKontak = txtNamaKontak.Text;
myPenj.Alamat = txtAlamatPerusahaan.Text;
myPenj.Telepon = txtTeleponPerusahaan.Text;
myPenj.Fax = txtFAXPerusahaan.Text;
}
if (HFPenjaminId.Value == "0")
{
myPenj.CreatedBy = UserId;
myPenj.CreatedDate = DateTime.Now;
result = myPenj.Insert();
}
else
{
myPenj.ModifiedBy = UserId;
myPenj.ModifiedDate = DateTime.Now;
result = myPenj.Update();
}
HFPenjaminId.Value = myPenj.PenjaminId.ToString();
}
else
{
if (HFPenjaminId.Value != "0")
myPenj.Delete();
HFPenjaminId.Value = "0";
}
//Input Data Registrasi
SIMRS.DataAccess.RS_Registrasi myReg = new SIMRS.DataAccess.RS_Registrasi();
myReg.RegistrasiId = Int64.Parse(HFRegistrasiId.Value);
myReg.SelectOne();
//GetNomorRegistrasi();
myReg.NoRegistrasi = txtNoRegistrasi.Text;
myReg.JenisRegistrasiId = 1;
myReg.TanggalRegistrasi = DateTime.Parse(txtTanggalRegistrasi.Text);
myReg.JenisPenjaminId = int.Parse(cmbJenisPenjamin.SelectedItem.Value);
if (cmbJenisPenjamin.SelectedIndex > 0)
myReg.PenjaminId = Int64.Parse(HFPenjaminId.Value);
else
myReg.PenjaminId = SqlInt64.Null;
myReg.ModifiedBy = UserId;
myReg.ModifiedDate = DateTime.Now;
result = myReg.Update();
//Update Data Rawat Jalan
SIMRS.DataAccess.RS_RawatJalan myRJ = new SIMRS.DataAccess.RS_RawatJalan();
myRJ.RawatJalanId = Int64.Parse(HFRawatJalanId.Value);
myRJ.SelectOne();
myRJ.RegistrasiId = myReg.RegistrasiId;
myRJ.PoliklinikId = 43;//FIS
myRJ.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text);
//GetNomorTunggu();
if (txtNomorTunggu.Text != "")
myRJ.NomorTunggu = int.Parse(txtNomorTunggu.Text);
myRJ.Status = 0;//Baru daftar
myRJ.ModifiedBy = UserId;
myRJ.ModifiedDate = DateTime.Now;
result = myRJ.Update();
return result;
//string CurrentPage = "";
//if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "")
// CurrentPage = Request.QueryString["CurrentPage"].ToString();
//Response.Redirect("RJView.aspx?CurrentPage=" + CurrentPage + "&RawatJalanId=" + myRJ.RawatJalanId);
}
public void OnCancel()
{
//string CurrentPage = "";
//if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "")
// CurrentPage = Request.QueryString["CurrentPage"].ToString();
//Response.Redirect("RJList.aspx?CurrentPage=" + CurrentPage);
}
protected void cmbJenisPenjamin_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbJenisPenjamin.SelectedIndex == 1)
{
tblPenjaminKeluarga.Visible = true;
tblPenjaminPerusahaan.Visible = false;
}
else if (cmbJenisPenjamin.SelectedIndex == 2 || cmbJenisPenjamin.SelectedIndex == 3)
{
tblPenjaminKeluarga.Visible = false;
tblPenjaminPerusahaan.Visible = true;
}
else
{
tblPenjaminKeluarga.Visible = false;
tblPenjaminPerusahaan.Visible = false;
}
}
protected void txtTanggalRegistrasi_TextChanged(object sender, EventArgs e)
{
GetNomorTunggu();
GetNomorRegistrasi();
}
protected void cmbStatusPenjamin_SelectedIndexChanged(object sender, EventArgs e)
{
GetListPangkatPenjamin("");
}
}
| |
namespace android.widget
{
[global::MonoJavaBridge.JavaClass()]
public partial class MultiAutoCompleteTextView : android.widget.AutoCompleteTextView
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static MultiAutoCompleteTextView()
{
InitJNI();
}
protected MultiAutoCompleteTextView(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass()]
public partial class CommaTokenizer : java.lang.Object, Tokenizer
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static CommaTokenizer()
{
InitJNI();
}
protected CommaTokenizer(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _findTokenStart11608;
public virtual int findTokenStart(java.lang.CharSequence arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.MultiAutoCompleteTextView.CommaTokenizer._findTokenStart11608, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.MultiAutoCompleteTextView.CommaTokenizer.staticClass, global::android.widget.MultiAutoCompleteTextView.CommaTokenizer._findTokenStart11608, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
public int findTokenStart(string arg0, int arg1)
{
return findTokenStart((global::java.lang.CharSequence)(global::java.lang.String)arg0, arg1);
}
internal static global::MonoJavaBridge.MethodId _findTokenEnd11609;
public virtual int findTokenEnd(java.lang.CharSequence arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.MultiAutoCompleteTextView.CommaTokenizer._findTokenEnd11609, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.MultiAutoCompleteTextView.CommaTokenizer.staticClass, global::android.widget.MultiAutoCompleteTextView.CommaTokenizer._findTokenEnd11609, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
public int findTokenEnd(string arg0, int arg1)
{
return findTokenEnd((global::java.lang.CharSequence)(global::java.lang.String)arg0, arg1);
}
internal static global::MonoJavaBridge.MethodId _terminateToken11610;
public virtual global::java.lang.CharSequence terminateToken(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.MultiAutoCompleteTextView.CommaTokenizer._terminateToken11610, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.CharSequence;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.MultiAutoCompleteTextView.CommaTokenizer.staticClass, global::android.widget.MultiAutoCompleteTextView.CommaTokenizer._terminateToken11610, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.CharSequence;
}
public java.lang.CharSequence terminateToken(string arg0)
{
return terminateToken((global::java.lang.CharSequence)(global::java.lang.String)arg0);
}
internal static global::MonoJavaBridge.MethodId _CommaTokenizer11611;
public CommaTokenizer() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.MultiAutoCompleteTextView.CommaTokenizer.staticClass, global::android.widget.MultiAutoCompleteTextView.CommaTokenizer._CommaTokenizer11611);
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.MultiAutoCompleteTextView.CommaTokenizer.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/MultiAutoCompleteTextView$CommaTokenizer"));
global::android.widget.MultiAutoCompleteTextView.CommaTokenizer._findTokenStart11608 = @__env.GetMethodIDNoThrow(global::android.widget.MultiAutoCompleteTextView.CommaTokenizer.staticClass, "findTokenStart", "(Ljava/lang/CharSequence;I)I");
global::android.widget.MultiAutoCompleteTextView.CommaTokenizer._findTokenEnd11609 = @__env.GetMethodIDNoThrow(global::android.widget.MultiAutoCompleteTextView.CommaTokenizer.staticClass, "findTokenEnd", "(Ljava/lang/CharSequence;I)I");
global::android.widget.MultiAutoCompleteTextView.CommaTokenizer._terminateToken11610 = @__env.GetMethodIDNoThrow(global::android.widget.MultiAutoCompleteTextView.CommaTokenizer.staticClass, "terminateToken", "(Ljava/lang/CharSequence;)Ljava/lang/CharSequence;");
global::android.widget.MultiAutoCompleteTextView.CommaTokenizer._CommaTokenizer11611 = @__env.GetMethodIDNoThrow(global::android.widget.MultiAutoCompleteTextView.CommaTokenizer.staticClass, "<init>", "()V");
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.widget.MultiAutoCompleteTextView.Tokenizer_))]
public interface Tokenizer : global::MonoJavaBridge.IJavaObject
{
int findTokenStart(java.lang.CharSequence arg0, int arg1);
int findTokenEnd(java.lang.CharSequence arg0, int arg1);
global::java.lang.CharSequence terminateToken(java.lang.CharSequence arg0);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.MultiAutoCompleteTextView.Tokenizer))]
public sealed partial class Tokenizer_ : java.lang.Object, Tokenizer
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static Tokenizer_()
{
InitJNI();
}
internal Tokenizer_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _findTokenStart11612;
int android.widget.MultiAutoCompleteTextView.Tokenizer.findTokenStart(java.lang.CharSequence arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.MultiAutoCompleteTextView.Tokenizer_._findTokenStart11612, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.MultiAutoCompleteTextView.Tokenizer_.staticClass, global::android.widget.MultiAutoCompleteTextView.Tokenizer_._findTokenStart11612, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _findTokenEnd11613;
int android.widget.MultiAutoCompleteTextView.Tokenizer.findTokenEnd(java.lang.CharSequence arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.MultiAutoCompleteTextView.Tokenizer_._findTokenEnd11613, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.MultiAutoCompleteTextView.Tokenizer_.staticClass, global::android.widget.MultiAutoCompleteTextView.Tokenizer_._findTokenEnd11613, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _terminateToken11614;
global::java.lang.CharSequence android.widget.MultiAutoCompleteTextView.Tokenizer.terminateToken(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.MultiAutoCompleteTextView.Tokenizer_._terminateToken11614, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.CharSequence;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.MultiAutoCompleteTextView.Tokenizer_.staticClass, global::android.widget.MultiAutoCompleteTextView.Tokenizer_._terminateToken11614, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.CharSequence;
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.MultiAutoCompleteTextView.Tokenizer_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/MultiAutoCompleteTextView$Tokenizer"));
global::android.widget.MultiAutoCompleteTextView.Tokenizer_._findTokenStart11612 = @__env.GetMethodIDNoThrow(global::android.widget.MultiAutoCompleteTextView.Tokenizer_.staticClass, "findTokenStart", "(Ljava/lang/CharSequence;I)I");
global::android.widget.MultiAutoCompleteTextView.Tokenizer_._findTokenEnd11613 = @__env.GetMethodIDNoThrow(global::android.widget.MultiAutoCompleteTextView.Tokenizer_.staticClass, "findTokenEnd", "(Ljava/lang/CharSequence;I)I");
global::android.widget.MultiAutoCompleteTextView.Tokenizer_._terminateToken11614 = @__env.GetMethodIDNoThrow(global::android.widget.MultiAutoCompleteTextView.Tokenizer_.staticClass, "terminateToken", "(Ljava/lang/CharSequence;)Ljava/lang/CharSequence;");
}
}
internal static global::MonoJavaBridge.MethodId _setTokenizer11615;
public virtual void setTokenizer(android.widget.MultiAutoCompleteTextView.Tokenizer arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.MultiAutoCompleteTextView._setTokenizer11615, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.MultiAutoCompleteTextView.staticClass, global::android.widget.MultiAutoCompleteTextView._setTokenizer11615, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _performFiltering11616;
protected override void performFiltering(java.lang.CharSequence arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.MultiAutoCompleteTextView._performFiltering11616, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.MultiAutoCompleteTextView.staticClass, global::android.widget.MultiAutoCompleteTextView._performFiltering11616, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _performFiltering11617;
protected virtual void performFiltering(java.lang.CharSequence arg0, int arg1, int arg2, int arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.MultiAutoCompleteTextView._performFiltering11617, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.MultiAutoCompleteTextView.staticClass, global::android.widget.MultiAutoCompleteTextView._performFiltering11617, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _enoughToFilter11618;
public override bool enoughToFilter()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.MultiAutoCompleteTextView._enoughToFilter11618);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.MultiAutoCompleteTextView.staticClass, global::android.widget.MultiAutoCompleteTextView._enoughToFilter11618);
}
internal static global::MonoJavaBridge.MethodId _performValidation11619;
public override void performValidation()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.MultiAutoCompleteTextView._performValidation11619);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.MultiAutoCompleteTextView.staticClass, global::android.widget.MultiAutoCompleteTextView._performValidation11619);
}
internal static global::MonoJavaBridge.MethodId _replaceText11620;
protected override void replaceText(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.MultiAutoCompleteTextView._replaceText11620, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.MultiAutoCompleteTextView.staticClass, global::android.widget.MultiAutoCompleteTextView._replaceText11620, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _MultiAutoCompleteTextView11621;
public MultiAutoCompleteTextView(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.MultiAutoCompleteTextView.staticClass, global::android.widget.MultiAutoCompleteTextView._MultiAutoCompleteTextView11621, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _MultiAutoCompleteTextView11622;
public MultiAutoCompleteTextView(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.MultiAutoCompleteTextView.staticClass, global::android.widget.MultiAutoCompleteTextView._MultiAutoCompleteTextView11622, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _MultiAutoCompleteTextView11623;
public MultiAutoCompleteTextView(android.content.Context arg0, android.util.AttributeSet arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.MultiAutoCompleteTextView.staticClass, global::android.widget.MultiAutoCompleteTextView._MultiAutoCompleteTextView11623, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.MultiAutoCompleteTextView.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/MultiAutoCompleteTextView"));
global::android.widget.MultiAutoCompleteTextView._setTokenizer11615 = @__env.GetMethodIDNoThrow(global::android.widget.MultiAutoCompleteTextView.staticClass, "setTokenizer", "(Landroid/widget/MultiAutoCompleteTextView$Tokenizer;)V");
global::android.widget.MultiAutoCompleteTextView._performFiltering11616 = @__env.GetMethodIDNoThrow(global::android.widget.MultiAutoCompleteTextView.staticClass, "performFiltering", "(Ljava/lang/CharSequence;I)V");
global::android.widget.MultiAutoCompleteTextView._performFiltering11617 = @__env.GetMethodIDNoThrow(global::android.widget.MultiAutoCompleteTextView.staticClass, "performFiltering", "(Ljava/lang/CharSequence;III)V");
global::android.widget.MultiAutoCompleteTextView._enoughToFilter11618 = @__env.GetMethodIDNoThrow(global::android.widget.MultiAutoCompleteTextView.staticClass, "enoughToFilter", "()Z");
global::android.widget.MultiAutoCompleteTextView._performValidation11619 = @__env.GetMethodIDNoThrow(global::android.widget.MultiAutoCompleteTextView.staticClass, "performValidation", "()V");
global::android.widget.MultiAutoCompleteTextView._replaceText11620 = @__env.GetMethodIDNoThrow(global::android.widget.MultiAutoCompleteTextView.staticClass, "replaceText", "(Ljava/lang/CharSequence;)V");
global::android.widget.MultiAutoCompleteTextView._MultiAutoCompleteTextView11621 = @__env.GetMethodIDNoThrow(global::android.widget.MultiAutoCompleteTextView.staticClass, "<init>", "(Landroid/content/Context;)V");
global::android.widget.MultiAutoCompleteTextView._MultiAutoCompleteTextView11622 = @__env.GetMethodIDNoThrow(global::android.widget.MultiAutoCompleteTextView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V");
global::android.widget.MultiAutoCompleteTextView._MultiAutoCompleteTextView11623 = @__env.GetMethodIDNoThrow(global::android.widget.MultiAutoCompleteTextView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;I)V");
}
}
}
| |
using UnityEngine;
using UnityEngine.Audio;
namespace OVR
{
public enum SoundFXNext {
Random = 0,
Sequential = 1,
}
public enum FreqHint {
None = 0,
Wide = 1,
Narrow = 2,
}
public enum SoundPriority {
VeryLow = -2,
Low = -1,
Default = 0,
High = 1,
VeryHigh = 2,
}
[System.Serializable]
public class OSPProps {
public OSPProps() {
enableSpatialization = false;
useFastOverride = false;
gain = 0.0f;
enableInvSquare = false;
volumetric = 0.0f;
invSquareFalloff = new Vector2( 1.0f, 25.0f );
}
[Tooltip( "Set to true to play the sound FX spatialized with binaural HRTF, default = false")]
public bool enableSpatialization = false;
[Tooltip( "Play the sound FX with reflections, default = false")]
public bool useFastOverride = false;
[Tooltip( "Boost the gain on the spatialized sound FX, default = 0.0")]
[Range( 0.0f, 24.0f )]
public float gain = 0.0f;
[Tooltip("Enable Inverse Square attenuation curve, default = false")]
public bool enableInvSquare = false;
[Tooltip("Change the sound from point source (0.0f) to a spherical volume, default = 0.0")]
[Range(0.0f, 1000.0f)]
public float volumetric = 0.0f;
[Tooltip("Set the near and far falloff value for the OSP attenuation curve, default = 1.0")]
[MinMax ( 1.0f, 25.0f, 0.0f, 250.0f )]
public Vector2 invSquareFalloff = new Vector2( 1.0f, 25.0f );
}
/*
-----------------------
SoundFX
-----------------------
*/
[System.Serializable]
public class SoundFX {
public SoundFX() {
playback = SoundFXNext.Random;
volume = 1.0f;
pitchVariance = Vector2.one;
falloffDistance = new Vector2( 1.0f, 25.0f );
falloffCurve = AudioRolloffMode.Linear;
volumeFalloffCurve = new AnimationCurve( new Keyframe[2] { new Keyframe( 0f, 1.0f ), new Keyframe( 1f, 1f ) } );
reverbZoneMix = new AnimationCurve( new Keyframe[2] { new Keyframe( 0f, 1.0f ), new Keyframe( 1f, 1f ) } );
spread = 0.0f;
pctChanceToPlay = 1.0f;
priority = SoundPriority.Default;
delay = Vector2.zero;
looping = false;
ospProps = new OSPProps();
}
[Tooltip( "Each sound FX should have a unique name")]
public string name = string.Empty;
[Tooltip( "Sound diversity playback option when multiple audio clips are defined, default = Random")]
public SoundFXNext playback = SoundFXNext.Random;
[Tooltip( "Default volume for this sound FX, default = 1.0")]
[Range (0.0f, 1.0f)]
public float volume = 1.0f;
[Tooltip( "Random pitch variance each time a sound FX is played, default = 1.0 (none)")]
[MinMax ( 1.0f, 1.0f, 0.0f, 2.0f )]
public Vector2 pitchVariance = Vector2.one;
[Tooltip( "Falloff distance for the sound FX, default = 1m min to 25m max")]
[MinMax ( 1.0f, 25.0f, 0.0f, 250.0f )]
public Vector2 falloffDistance = new Vector2( 1.0f, 25.0f );
[Tooltip( "Volume falloff curve - sets how the sound FX attenuates over distance, default = Linear")]
public AudioRolloffMode falloffCurve = AudioRolloffMode.Linear;
[Tooltip( "Defines the custom volume falloff curve")]
public AnimationCurve volumeFalloffCurve = new AnimationCurve( new Keyframe[2] { new Keyframe( 0f, 1.0f ), new Keyframe( 1f, 1f ) } );
[Tooltip( "The amount by which the signal from the AudioSource will be mixed into the global reverb associated with the Reverb Zones | Valid range is 0.0 - 1.1, default = 1.0" )]
public AnimationCurve reverbZoneMix = new AnimationCurve( new Keyframe[2] { new Keyframe( 0f, 1.0f ), new Keyframe( 1f, 1f ) } );
[Tooltip( "Sets the spread angle (in degrees) of a 3d stereo or multichannel sound in speaker space, default = 0")]
[Range (0.0f, 360.0f)]
public float spread = 0.0f;
[Tooltip( "The percentage chance that this sound FX will play | 0.0 = none, 1.0 = 100%, default = 1.0")]
[Range (0.0f, 1.0f)]
public float pctChanceToPlay = 1.0f;
[Tooltip( "Sets the priority for this sound to play and/or to override a currently playing sound FX, default = Default")]
public SoundPriority priority = SoundPriority.Default;
[Tooltip( "Specifies the default delay when this sound FX is played, default = 0.0 secs")]
[MinMax ( 0.0f, 0.0f, 0.0f, 2.0f )]
public Vector2 delay = Vector2.zero; // this overrides any delay passed into PlaySound() or PlaySoundAt()
[Tooltip( "Set to true for the sound to loop continuously, default = false")]
public bool looping = false;
public OSPProps ospProps = new OSPProps();
[Tooltip( "List of the audio clips assigned to this sound FX")]
public AudioClip[] soundClips = new AudioClip[1];
// editor only - unfortunately if we set it not to serialize, we can't query it from the editor
public bool visibilityToggle = false;
// runtime vars
[System.NonSerialized]
private SoundGroup soundGroup = null;
private int lastIdx = -1;
private int playingIdx = -1;
public int Length { get { return soundClips.Length; } }
public bool IsValid { get { return ( ( soundClips.Length != 0 ) && ( soundClips[0] != null ) ); } }
public SoundGroup Group { get { return soundGroup; } set { soundGroup = value; } }
public float MaxFalloffDistSquared { get { return falloffDistance.y * falloffDistance.y; } }
public float GroupVolumeOverride { get { return ( soundGroup != null ) ? soundGroup.volumeOverride : 1.0f; } }
/*
-----------------------
GetClip()
-----------------------
*/
public AudioClip GetClip() {
if ( soundClips.Length == 0 ) {
return null;
} else if ( soundClips.Length == 1 ) {
return soundClips[0];
}
if ( playback == SoundFXNext.Random ) {
// random, but don't pick the last one
int idx = Random.Range( 0, soundClips.Length );
while ( idx == lastIdx ) {
idx = Random.Range( 0, soundClips.Length );
}
lastIdx = idx;
return soundClips[idx];
} else {
// sequential
if ( ++lastIdx >= soundClips.Length ) {
lastIdx = 0;
}
return soundClips[lastIdx];
}
}
/*
-----------------------
GetMixerGroup()
-----------------------
*/
public AudioMixerGroup GetMixerGroup( AudioMixerGroup defaultMixerGroup ) {
if ( soundGroup != null ) {
return ( soundGroup.mixerGroup != null ) ? soundGroup.mixerGroup : defaultMixerGroup;
}
return defaultMixerGroup;
}
/*
-----------------------
ReachedGroupPlayLimit()
-----------------------
*/
public bool ReachedGroupPlayLimit() {
if ( soundGroup != null ) {
return !soundGroup.CanPlaySound();
}
return false;
}
/*
-----------------------
GetClipLength()
-----------------------
*/
public float GetClipLength( int idx ) {
if ( ( idx == -1 ) || ( soundClips.Length == 0 ) || ( idx >= soundClips.Length ) || ( soundClips[idx] == null ) ) {
return 0.0f;
} else {
return soundClips[idx].length;
}
}
/*
-----------------------
GetPitch()
-----------------------
*/
public float GetPitch() {
return Random.Range( pitchVariance.x, pitchVariance.y );
}
/*
-----------------------
PlaySound()
-----------------------
*/
public int PlaySound( float delaySecs = 0.0f ) {
playingIdx = -1;
if ( !IsValid ) {
return playingIdx;
}
// check the random chance to play here to save the function calls
if ( ( pctChanceToPlay > 0.99f ) || ( Random.value < pctChanceToPlay ) ) {
if ( delay.y > 0.0f ) {
delaySecs = Random.Range( delay.x, delay.y );
}
playingIdx = AudioManager.PlaySound( this, EmitterChannel.Any, delaySecs );
}
return playingIdx;
}
/*
-----------------------
PlaySoundAt()
-----------------------
*/
public int PlaySoundAt( Vector3 pos, float delaySecs = 0.0f, float volumeOverride = 1.0f, float pitchMultiplier = 1.0f ) {
playingIdx = -1;
if ( !IsValid ) {
return playingIdx;
}
// check the random chance to play here to save the function calls
if ( ( pctChanceToPlay > 0.99f ) || ( Random.value < pctChanceToPlay ) ) {
if ( delay.y > 0.0f ) {
delaySecs = Random.Range( delay.x, delay.y );
}
playingIdx = AudioManager.PlaySoundAt( pos, this, EmitterChannel.Any, delaySecs, volumeOverride, pitchMultiplier );
}
return playingIdx;
}
/*
-----------------------
SetOnFinished()
get a callback when the sound is finished playing
-----------------------
*/
public void SetOnFinished( System.Action onFinished ) {
if ( playingIdx > -1 ) {
AudioManager.SetOnFinished( playingIdx, onFinished );
}
}
/*
-----------------------
SetOnFinished()
get a callback with an object parameter when the sound is finished playing
-----------------------
*/
public void SetOnFinished( System.Action<object> onFinished, object obj ) {
if ( playingIdx > -1 ) {
AudioManager.SetOnFinished( playingIdx, onFinished, obj );
}
}
/*
-----------------------
StopSound()
-----------------------
*/
public bool StopSound() {
bool stopped = false;
if (playingIdx > -1){
stopped = AudioManager.StopSound(playingIdx);
playingIdx = -1;
}
return stopped;
}
/*
-----------------------
AttachToParent()
-----------------------
*/
public void AttachToParent( Transform parent) {
if (playingIdx > -1) {
AudioManager.AttachSoundToParent(playingIdx, parent);
}
}
/*
-----------------------
DetachFromParent()
-----------------------
*/
public void DetachFromParent() {
if (playingIdx > -1) {
AudioManager.DetachSoundFromParent(playingIdx);
}
}
}
} // namespace OVR
| |
namespace Microsoft.Azure.Management.StorSimple8000Series
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Rest.Azure.OData;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// VolumesOperations operations.
/// </summary>
public partial interface IVolumesOperations
{
/// <summary>
/// Retrieves all the volumes in a volume container.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='volumeContainerName'>
/// The volume container name.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IEnumerable<Volume>>> ListByVolumeContainerWithHttpMessagesAsync(string deviceName, string volumeContainerName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns the properties of the specified volume name.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='volumeContainerName'>
/// The volume container name.
/// </param>
/// <param name='volumeName'>
/// The volume name.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<Volume>> GetWithHttpMessagesAsync(string deviceName, string volumeContainerName, string volumeName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates the volume.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='volumeContainerName'>
/// The volume container name.
/// </param>
/// <param name='volumeName'>
/// The volume name.
/// </param>
/// <param name='parameters'>
/// Volume to be created or updated.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<Volume>> CreateOrUpdateWithHttpMessagesAsync(string deviceName, string volumeContainerName, string volumeName, Volume parameters, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the volume.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='volumeContainerName'>
/// The volume container name.
/// </param>
/// <param name='volumeName'>
/// The volume name.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string deviceName, string volumeContainerName, string volumeName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the metrics for the specified volume.
/// </summary>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='volumeContainerName'>
/// The volume container name.
/// </param>
/// <param name='volumeName'>
/// The volume name.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IEnumerable<Metrics>>> ListMetricsWithHttpMessagesAsync(ODataQuery<MetricFilter> odataQuery, string deviceName, string volumeContainerName, string volumeName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the metric definitions for the specified volume.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='volumeContainerName'>
/// The volume container name.
/// </param>
/// <param name='volumeName'>
/// The volume name.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IEnumerable<MetricDefinition>>> ListMetricDefinitionWithHttpMessagesAsync(string deviceName, string volumeContainerName, string volumeName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Retrieves all the volumes in a device.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IEnumerable<Volume>>> ListByDeviceWithHttpMessagesAsync(string deviceName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates the volume.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='volumeContainerName'>
/// The volume container name.
/// </param>
/// <param name='volumeName'>
/// The volume name.
/// </param>
/// <param name='parameters'>
/// Volume to be created or updated.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<Volume>> BeginCreateOrUpdateWithHttpMessagesAsync(string deviceName, string volumeContainerName, string volumeName, Volume parameters, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the volume.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='volumeContainerName'>
/// The volume container name.
/// </param>
/// <param name='volumeName'>
/// The volume name.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string deviceName, string volumeContainerName, string volumeName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using OpenTK;
namespace Bearded.Utilities.Math
{
/// <summary>
/// A typesafe representation of a signed angle.
/// </summary>
public struct Angle : IEquatable<Angle>
{
const float fromDegrees = Mathf.TwoPi / 360f;
const float toDegrees = 360f / Mathf.TwoPi;
private readonly float radians;
#region Constructing
private Angle(float radians)
{
this.radians = radians;
}
/// <summary>
/// Initialises an angle from a relative angle value in radians.
/// </summary>
public static Angle FromRadians(float radians)
{
return new Angle(radians);
}
/// <summary>
/// Initialises an angle from a relative angle value in degrees.
/// </summary>
public static Angle FromDegrees(float degrees)
{
return new Angle(degrees * Angle.fromDegrees);
}
/// <summary>
/// Initialises an angle as the signed difference between two directional unit vectors in the 2D plane.
/// If the vectors are not unit length the result is undefined.
/// </summary>
public static Angle Between(Vector2 from, Vector2 to)
{
float perpDot = from.Y * to.X - from.X * to.Y;
return Angle.FromRadians(Mathf.Atan2(perpDot, Vector2.Dot(from, to)));
}
/// <summary>
/// Initialises an angle as the signed difference between two directions in the 2D plane.
/// The returned value is the smallest possible angle from one direction to the other.
/// </summary>
public static Angle Between(Direction2 from, Direction2 to)
{
return to - from;
}
/// <summary>
/// Initialises an angle as the signed difference between two directions in the 2D plane.
/// The returned value is the smallest positive angle from one direction to the other.
/// </summary>
public static Angle BetweenPositive(Direction2 from, Direction2 to)
{
var a = Angle.Between(from, to);
if (a.radians < 0)
a += Mathf.TwoPi.Radians();
return a;
}
/// <summary>
/// Initialises an angle as the signed difference between two directions in the 2D plane.
/// The returned value is the smallest negative angle from one direction to the other.
/// </summary>
public static Angle BetweenNegative(Direction2 from, Direction2 to)
{
var a = Angle.Between(from, to);
if (a.radians > 0)
a -= Mathf.TwoPi.Radians();
return a;
}
#endregion
#region Static Fields
/// <summary>
/// The default zero angle.
/// </summary>
public static readonly Angle Zero = new Angle(0);
#endregion
#region Properties
/// <summary>
/// Gets the value of the angle in radians.
/// </summary>
public float Radians { get { return this.radians; } }
/// <summary>
/// Gets the value of the angle in degrees.
/// </summary>
public float Degrees { get { return this.radians * Angle.toDegrees; } }
/// <summary>
/// Gets a 2x2 rotation matrix that rotates vectors by this angle.
/// </summary>
public Matrix2 Transformation { get { return Matrix2.CreateRotation(this.radians); } }
/// <summary>
/// Gets the magnitude (absolute value) of the angle in radians.
/// </summary>
public float MagnitudeInRadians { get { return System.Math.Abs(this.radians); } }
/// <summary>
/// Gets the magnitude (absolute value) of the angle in degrees.
/// </summary>
public float MagnitudeInDegrees { get { return System.Math.Abs(this.radians * Angle.toDegrees); } }
#endregion
#region Methods
#region Arithmetic
/// <summary>
/// Returns the Sine of the angle.
/// </summary>
public float Sin()
{
return Mathf.Sin(this.radians);
}
/// <summary>
/// Returns the Cosine of the angle.
/// </summary>
public float Cos()
{
return Mathf.Cos(this.radians);
}
/// <summary>
/// Returns the Tangent of the angle.
/// </summary>
public float Tan()
{
return Mathf.Tan(this.radians);
}
/// <summary>
/// Returns the Sign of the angle.
/// </summary>
public int Sign()
{
return System.Math.Sign(this.radians);
}
/// <summary>
/// Returns the absolute value of the angle in radians.
/// </summary>
public Angle Abs()
{
return new Angle(System.Math.Abs(this.radians));
}
/// <summary>
/// Returns a new Angle with |value| == 1 radians and the same sign as this angle.
/// </summary>
public Angle Normalized()
{
return new Angle(System.Math.Sign(this.radians));
}
/// <summary>
/// Clamps this angle between a minimum and a maximum angle.
/// </summary>
public Angle Clamped(Angle min, Angle max)
{
return Angle.Clamp(this, min, max);
}
#region Statics
/// <summary>
/// Returns the larger of two angles.
/// </summary>
public static Angle Max(Angle a1, Angle a2)
{
return a1 > a2 ? a1 : a2;
}
/// <summary>
/// Returns the smaller of two angles.
/// </summary>
public static Angle Min(Angle a1, Angle a2)
{
return a1 < a2 ? a1 : a2;
}
/// <summary>
/// Clamps one angle between a minimum and a maximum angle.
/// </summary>
public static Angle Clamp(Angle a, Angle min, Angle max)
{
return a < max ? a > min ? a : min : max;
}
#endregion
#endregion
#endregion
#region Operators
#region Arithmetic
/// <summary>
/// Adds two angles.
/// </summary>
public static Angle operator +(Angle angle1, Angle angle2)
{
return new Angle(angle1.radians + angle2.radians);
}
/// <summary>
/// Substracts an angle from another.
/// </summary>
public static Angle operator -(Angle angle1, Angle angle2)
{
return new Angle(angle1.radians - angle2.radians);
}
/// <summary>
/// Inverts an angle.
/// </summary>
public static Angle operator -(Angle angle)
{
return new Angle(-angle.radians);
}
/// <summary>
/// Multiplies an angle with a scalar.
/// </summary>
public static Angle operator *(Angle angle, float scalar)
{
return new Angle(angle.radians * scalar);
}
/// <summary>
/// Multiplies an angle with a scalar.
/// </summary>
public static Angle operator *(float scalar, Angle angle)
{
return new Angle(angle.radians * scalar);
}
/// <summary>
/// Divides an angle by an inverse scalar.
/// </summary>
public static Angle operator /(Angle angle, float invScalar)
{
return new Angle(angle.radians / invScalar);
}
/// <summary>
/// Linearly interpolates between two angles.
/// </summary>
public static Angle Lerp(Angle angle0, Angle angle1, float t)
{
return angle0 + (angle1 - angle0) * t;
}
#endregion
#region Boolean
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.
/// </returns>
public bool Equals(Angle other)
{
return this.radians == other.radians;
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/>, is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return obj is Angle && this.radians == ((Angle)obj).radians;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
return this.radians.GetHashCode();
}
/// <summary>
/// Checks two angles for equality.
/// </summary>
public static bool operator ==(Angle x, Angle y)
{
return x.radians == y.radians;
}
/// <summary>
/// Checks two angles for inequality.
/// </summary>
public static bool operator !=(Angle x, Angle y)
{
return x.radians != y.radians;
}
/// <summary>
/// Checks whether one angle is smaller than another.
/// </summary>
public static bool operator <(Angle x, Angle y)
{
return x.radians < y.radians;
}
/// <summary>
/// Checks whether one angle is greater than another.
/// </summary>
public static bool operator >(Angle x, Angle y)
{
return x.radians > y.radians;
}
/// <summary>
/// Checks whether one angle is smaller or equal to another.
/// </summary>
public static bool operator <=(Angle x, Angle y)
{
return x.radians <= y.radians;
}
/// <summary>
/// Checks whether one angle is greater or equal to another.
/// </summary>
public static bool operator >=(Angle x, Angle y)
{
return x.radians >= y.radians;
}
#endregion
#region Casts
/// <summary>
/// Casts an angle to a direction in the 2D plane.
/// This is the same as Direction.Zero + angle.
/// </summary>
public static explicit operator Direction2(Angle angle)
{
return Direction2.FromRadians(angle.radians);
}
#endregion
#endregion
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Talent.V4Beta1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedProfileServiceClientTest
{
[xunit::FactAttribute]
public void CreateProfileRequestObject()
{
moq::Mock<ProfileService.ProfileServiceClient> mockGrpcClient = new moq::Mock<ProfileService.ProfileServiceClient>(moq::MockBehavior.Strict);
CreateProfileRequest request = new CreateProfileRequest
{
ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
Profile = new Profile(),
};
Profile expectedResponse = new Profile
{
ProfileName = ProfileName.FromProjectTenantProfile("[PROJECT]", "[TENANT]", "[PROFILE]"),
ExternalId = "external_id9442680e",
Source = "sourcef438cd36",
Uri = "uri3db70593",
GroupId = "group_id4f9a930e",
IsHirable = true,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PersonNames = { new PersonName(), },
Addresses = { new Address(), },
EmailAddresses = { new Email(), },
PhoneNumbers = { new Phone(), },
PersonalUris = { new PersonalUri(), },
AdditionalContactInfo =
{
new AdditionalContactInfo(),
},
EmploymentRecords =
{
new EmploymentRecord(),
},
EducationRecords =
{
new EducationRecord(),
},
Skills = { new Skill(), },
Activities = { new Activity(), },
Publications = { new Publication(), },
Patents = { new Patent(), },
Certifications =
{
new Certification(),
},
CustomAttributes =
{
{
"key8a0b6e3c",
new CustomAttribute()
},
},
Processed = true,
KeywordSnippet = "keyword_snippet7289f6ef",
Applications =
{
"applicationsffa9fbb5",
},
Assignments =
{
"assignments2923b317",
},
Resume = new Resume(),
DerivedAddresses = { new Location(), },
CandidateUpdateTime = new wkt::Timestamp(),
ResumeUpdateTime = new wkt::Timestamp(),
AvailabilitySignals =
{
new AvailabilitySignal(),
},
};
mockGrpcClient.Setup(x => x.CreateProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ProfileServiceClient client = new ProfileServiceClientImpl(mockGrpcClient.Object, null);
Profile response = client.CreateProfile(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateProfileRequestObjectAsync()
{
moq::Mock<ProfileService.ProfileServiceClient> mockGrpcClient = new moq::Mock<ProfileService.ProfileServiceClient>(moq::MockBehavior.Strict);
CreateProfileRequest request = new CreateProfileRequest
{
ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
Profile = new Profile(),
};
Profile expectedResponse = new Profile
{
ProfileName = ProfileName.FromProjectTenantProfile("[PROJECT]", "[TENANT]", "[PROFILE]"),
ExternalId = "external_id9442680e",
Source = "sourcef438cd36",
Uri = "uri3db70593",
GroupId = "group_id4f9a930e",
IsHirable = true,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PersonNames = { new PersonName(), },
Addresses = { new Address(), },
EmailAddresses = { new Email(), },
PhoneNumbers = { new Phone(), },
PersonalUris = { new PersonalUri(), },
AdditionalContactInfo =
{
new AdditionalContactInfo(),
},
EmploymentRecords =
{
new EmploymentRecord(),
},
EducationRecords =
{
new EducationRecord(),
},
Skills = { new Skill(), },
Activities = { new Activity(), },
Publications = { new Publication(), },
Patents = { new Patent(), },
Certifications =
{
new Certification(),
},
CustomAttributes =
{
{
"key8a0b6e3c",
new CustomAttribute()
},
},
Processed = true,
KeywordSnippet = "keyword_snippet7289f6ef",
Applications =
{
"applicationsffa9fbb5",
},
Assignments =
{
"assignments2923b317",
},
Resume = new Resume(),
DerivedAddresses = { new Location(), },
CandidateUpdateTime = new wkt::Timestamp(),
ResumeUpdateTime = new wkt::Timestamp(),
AvailabilitySignals =
{
new AvailabilitySignal(),
},
};
mockGrpcClient.Setup(x => x.CreateProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Profile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ProfileServiceClient client = new ProfileServiceClientImpl(mockGrpcClient.Object, null);
Profile responseCallSettings = await client.CreateProfileAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Profile responseCancellationToken = await client.CreateProfileAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateProfile()
{
moq::Mock<ProfileService.ProfileServiceClient> mockGrpcClient = new moq::Mock<ProfileService.ProfileServiceClient>(moq::MockBehavior.Strict);
CreateProfileRequest request = new CreateProfileRequest
{
ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
Profile = new Profile(),
};
Profile expectedResponse = new Profile
{
ProfileName = ProfileName.FromProjectTenantProfile("[PROJECT]", "[TENANT]", "[PROFILE]"),
ExternalId = "external_id9442680e",
Source = "sourcef438cd36",
Uri = "uri3db70593",
GroupId = "group_id4f9a930e",
IsHirable = true,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PersonNames = { new PersonName(), },
Addresses = { new Address(), },
EmailAddresses = { new Email(), },
PhoneNumbers = { new Phone(), },
PersonalUris = { new PersonalUri(), },
AdditionalContactInfo =
{
new AdditionalContactInfo(),
},
EmploymentRecords =
{
new EmploymentRecord(),
},
EducationRecords =
{
new EducationRecord(),
},
Skills = { new Skill(), },
Activities = { new Activity(), },
Publications = { new Publication(), },
Patents = { new Patent(), },
Certifications =
{
new Certification(),
},
CustomAttributes =
{
{
"key8a0b6e3c",
new CustomAttribute()
},
},
Processed = true,
KeywordSnippet = "keyword_snippet7289f6ef",
Applications =
{
"applicationsffa9fbb5",
},
Assignments =
{
"assignments2923b317",
},
Resume = new Resume(),
DerivedAddresses = { new Location(), },
CandidateUpdateTime = new wkt::Timestamp(),
ResumeUpdateTime = new wkt::Timestamp(),
AvailabilitySignals =
{
new AvailabilitySignal(),
},
};
mockGrpcClient.Setup(x => x.CreateProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ProfileServiceClient client = new ProfileServiceClientImpl(mockGrpcClient.Object, null);
Profile response = client.CreateProfile(request.Parent, request.Profile);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateProfileAsync()
{
moq::Mock<ProfileService.ProfileServiceClient> mockGrpcClient = new moq::Mock<ProfileService.ProfileServiceClient>(moq::MockBehavior.Strict);
CreateProfileRequest request = new CreateProfileRequest
{
ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
Profile = new Profile(),
};
Profile expectedResponse = new Profile
{
ProfileName = ProfileName.FromProjectTenantProfile("[PROJECT]", "[TENANT]", "[PROFILE]"),
ExternalId = "external_id9442680e",
Source = "sourcef438cd36",
Uri = "uri3db70593",
GroupId = "group_id4f9a930e",
IsHirable = true,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PersonNames = { new PersonName(), },
Addresses = { new Address(), },
EmailAddresses = { new Email(), },
PhoneNumbers = { new Phone(), },
PersonalUris = { new PersonalUri(), },
AdditionalContactInfo =
{
new AdditionalContactInfo(),
},
EmploymentRecords =
{
new EmploymentRecord(),
},
EducationRecords =
{
new EducationRecord(),
},
Skills = { new Skill(), },
Activities = { new Activity(), },
Publications = { new Publication(), },
Patents = { new Patent(), },
Certifications =
{
new Certification(),
},
CustomAttributes =
{
{
"key8a0b6e3c",
new CustomAttribute()
},
},
Processed = true,
KeywordSnippet = "keyword_snippet7289f6ef",
Applications =
{
"applicationsffa9fbb5",
},
Assignments =
{
"assignments2923b317",
},
Resume = new Resume(),
DerivedAddresses = { new Location(), },
CandidateUpdateTime = new wkt::Timestamp(),
ResumeUpdateTime = new wkt::Timestamp(),
AvailabilitySignals =
{
new AvailabilitySignal(),
},
};
mockGrpcClient.Setup(x => x.CreateProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Profile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ProfileServiceClient client = new ProfileServiceClientImpl(mockGrpcClient.Object, null);
Profile responseCallSettings = await client.CreateProfileAsync(request.Parent, request.Profile, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Profile responseCancellationToken = await client.CreateProfileAsync(request.Parent, request.Profile, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateProfileResourceNames()
{
moq::Mock<ProfileService.ProfileServiceClient> mockGrpcClient = new moq::Mock<ProfileService.ProfileServiceClient>(moq::MockBehavior.Strict);
CreateProfileRequest request = new CreateProfileRequest
{
ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
Profile = new Profile(),
};
Profile expectedResponse = new Profile
{
ProfileName = ProfileName.FromProjectTenantProfile("[PROJECT]", "[TENANT]", "[PROFILE]"),
ExternalId = "external_id9442680e",
Source = "sourcef438cd36",
Uri = "uri3db70593",
GroupId = "group_id4f9a930e",
IsHirable = true,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PersonNames = { new PersonName(), },
Addresses = { new Address(), },
EmailAddresses = { new Email(), },
PhoneNumbers = { new Phone(), },
PersonalUris = { new PersonalUri(), },
AdditionalContactInfo =
{
new AdditionalContactInfo(),
},
EmploymentRecords =
{
new EmploymentRecord(),
},
EducationRecords =
{
new EducationRecord(),
},
Skills = { new Skill(), },
Activities = { new Activity(), },
Publications = { new Publication(), },
Patents = { new Patent(), },
Certifications =
{
new Certification(),
},
CustomAttributes =
{
{
"key8a0b6e3c",
new CustomAttribute()
},
},
Processed = true,
KeywordSnippet = "keyword_snippet7289f6ef",
Applications =
{
"applicationsffa9fbb5",
},
Assignments =
{
"assignments2923b317",
},
Resume = new Resume(),
DerivedAddresses = { new Location(), },
CandidateUpdateTime = new wkt::Timestamp(),
ResumeUpdateTime = new wkt::Timestamp(),
AvailabilitySignals =
{
new AvailabilitySignal(),
},
};
mockGrpcClient.Setup(x => x.CreateProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ProfileServiceClient client = new ProfileServiceClientImpl(mockGrpcClient.Object, null);
Profile response = client.CreateProfile(request.ParentAsTenantName, request.Profile);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateProfileResourceNamesAsync()
{
moq::Mock<ProfileService.ProfileServiceClient> mockGrpcClient = new moq::Mock<ProfileService.ProfileServiceClient>(moq::MockBehavior.Strict);
CreateProfileRequest request = new CreateProfileRequest
{
ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
Profile = new Profile(),
};
Profile expectedResponse = new Profile
{
ProfileName = ProfileName.FromProjectTenantProfile("[PROJECT]", "[TENANT]", "[PROFILE]"),
ExternalId = "external_id9442680e",
Source = "sourcef438cd36",
Uri = "uri3db70593",
GroupId = "group_id4f9a930e",
IsHirable = true,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PersonNames = { new PersonName(), },
Addresses = { new Address(), },
EmailAddresses = { new Email(), },
PhoneNumbers = { new Phone(), },
PersonalUris = { new PersonalUri(), },
AdditionalContactInfo =
{
new AdditionalContactInfo(),
},
EmploymentRecords =
{
new EmploymentRecord(),
},
EducationRecords =
{
new EducationRecord(),
},
Skills = { new Skill(), },
Activities = { new Activity(), },
Publications = { new Publication(), },
Patents = { new Patent(), },
Certifications =
{
new Certification(),
},
CustomAttributes =
{
{
"key8a0b6e3c",
new CustomAttribute()
},
},
Processed = true,
KeywordSnippet = "keyword_snippet7289f6ef",
Applications =
{
"applicationsffa9fbb5",
},
Assignments =
{
"assignments2923b317",
},
Resume = new Resume(),
DerivedAddresses = { new Location(), },
CandidateUpdateTime = new wkt::Timestamp(),
ResumeUpdateTime = new wkt::Timestamp(),
AvailabilitySignals =
{
new AvailabilitySignal(),
},
};
mockGrpcClient.Setup(x => x.CreateProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Profile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ProfileServiceClient client = new ProfileServiceClientImpl(mockGrpcClient.Object, null);
Profile responseCallSettings = await client.CreateProfileAsync(request.ParentAsTenantName, request.Profile, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Profile responseCancellationToken = await client.CreateProfileAsync(request.ParentAsTenantName, request.Profile, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetProfileRequestObject()
{
moq::Mock<ProfileService.ProfileServiceClient> mockGrpcClient = new moq::Mock<ProfileService.ProfileServiceClient>(moq::MockBehavior.Strict);
GetProfileRequest request = new GetProfileRequest
{
ProfileName = ProfileName.FromProjectTenantProfile("[PROJECT]", "[TENANT]", "[PROFILE]"),
};
Profile expectedResponse = new Profile
{
ProfileName = ProfileName.FromProjectTenantProfile("[PROJECT]", "[TENANT]", "[PROFILE]"),
ExternalId = "external_id9442680e",
Source = "sourcef438cd36",
Uri = "uri3db70593",
GroupId = "group_id4f9a930e",
IsHirable = true,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PersonNames = { new PersonName(), },
Addresses = { new Address(), },
EmailAddresses = { new Email(), },
PhoneNumbers = { new Phone(), },
PersonalUris = { new PersonalUri(), },
AdditionalContactInfo =
{
new AdditionalContactInfo(),
},
EmploymentRecords =
{
new EmploymentRecord(),
},
EducationRecords =
{
new EducationRecord(),
},
Skills = { new Skill(), },
Activities = { new Activity(), },
Publications = { new Publication(), },
Patents = { new Patent(), },
Certifications =
{
new Certification(),
},
CustomAttributes =
{
{
"key8a0b6e3c",
new CustomAttribute()
},
},
Processed = true,
KeywordSnippet = "keyword_snippet7289f6ef",
Applications =
{
"applicationsffa9fbb5",
},
Assignments =
{
"assignments2923b317",
},
Resume = new Resume(),
DerivedAddresses = { new Location(), },
CandidateUpdateTime = new wkt::Timestamp(),
ResumeUpdateTime = new wkt::Timestamp(),
AvailabilitySignals =
{
new AvailabilitySignal(),
},
};
mockGrpcClient.Setup(x => x.GetProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ProfileServiceClient client = new ProfileServiceClientImpl(mockGrpcClient.Object, null);
Profile response = client.GetProfile(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetProfileRequestObjectAsync()
{
moq::Mock<ProfileService.ProfileServiceClient> mockGrpcClient = new moq::Mock<ProfileService.ProfileServiceClient>(moq::MockBehavior.Strict);
GetProfileRequest request = new GetProfileRequest
{
ProfileName = ProfileName.FromProjectTenantProfile("[PROJECT]", "[TENANT]", "[PROFILE]"),
};
Profile expectedResponse = new Profile
{
ProfileName = ProfileName.FromProjectTenantProfile("[PROJECT]", "[TENANT]", "[PROFILE]"),
ExternalId = "external_id9442680e",
Source = "sourcef438cd36",
Uri = "uri3db70593",
GroupId = "group_id4f9a930e",
IsHirable = true,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PersonNames = { new PersonName(), },
Addresses = { new Address(), },
EmailAddresses = { new Email(), },
PhoneNumbers = { new Phone(), },
PersonalUris = { new PersonalUri(), },
AdditionalContactInfo =
{
new AdditionalContactInfo(),
},
EmploymentRecords =
{
new EmploymentRecord(),
},
EducationRecords =
{
new EducationRecord(),
},
Skills = { new Skill(), },
Activities = { new Activity(), },
Publications = { new Publication(), },
Patents = { new Patent(), },
Certifications =
{
new Certification(),
},
CustomAttributes =
{
{
"key8a0b6e3c",
new CustomAttribute()
},
},
Processed = true,
KeywordSnippet = "keyword_snippet7289f6ef",
Applications =
{
"applicationsffa9fbb5",
},
Assignments =
{
"assignments2923b317",
},
Resume = new Resume(),
DerivedAddresses = { new Location(), },
CandidateUpdateTime = new wkt::Timestamp(),
ResumeUpdateTime = new wkt::Timestamp(),
AvailabilitySignals =
{
new AvailabilitySignal(),
},
};
mockGrpcClient.Setup(x => x.GetProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Profile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ProfileServiceClient client = new ProfileServiceClientImpl(mockGrpcClient.Object, null);
Profile responseCallSettings = await client.GetProfileAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Profile responseCancellationToken = await client.GetProfileAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetProfile()
{
moq::Mock<ProfileService.ProfileServiceClient> mockGrpcClient = new moq::Mock<ProfileService.ProfileServiceClient>(moq::MockBehavior.Strict);
GetProfileRequest request = new GetProfileRequest
{
ProfileName = ProfileName.FromProjectTenantProfile("[PROJECT]", "[TENANT]", "[PROFILE]"),
};
Profile expectedResponse = new Profile
{
ProfileName = ProfileName.FromProjectTenantProfile("[PROJECT]", "[TENANT]", "[PROFILE]"),
ExternalId = "external_id9442680e",
Source = "sourcef438cd36",
Uri = "uri3db70593",
GroupId = "group_id4f9a930e",
IsHirable = true,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PersonNames = { new PersonName(), },
Addresses = { new Address(), },
EmailAddresses = { new Email(), },
PhoneNumbers = { new Phone(), },
PersonalUris = { new PersonalUri(), },
AdditionalContactInfo =
{
new AdditionalContactInfo(),
},
EmploymentRecords =
{
new EmploymentRecord(),
},
EducationRecords =
{
new EducationRecord(),
},
Skills = { new Skill(), },
Activities = { new Activity(), },
Publications = { new Publication(), },
Patents = { new Patent(), },
Certifications =
{
new Certification(),
},
CustomAttributes =
{
{
"key8a0b6e3c",
new CustomAttribute()
},
},
Processed = true,
KeywordSnippet = "keyword_snippet7289f6ef",
Applications =
{
"applicationsffa9fbb5",
},
Assignments =
{
"assignments2923b317",
},
Resume = new Resume(),
DerivedAddresses = { new Location(), },
CandidateUpdateTime = new wkt::Timestamp(),
ResumeUpdateTime = new wkt::Timestamp(),
AvailabilitySignals =
{
new AvailabilitySignal(),
},
};
mockGrpcClient.Setup(x => x.GetProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ProfileServiceClient client = new ProfileServiceClientImpl(mockGrpcClient.Object, null);
Profile response = client.GetProfile(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetProfileAsync()
{
moq::Mock<ProfileService.ProfileServiceClient> mockGrpcClient = new moq::Mock<ProfileService.ProfileServiceClient>(moq::MockBehavior.Strict);
GetProfileRequest request = new GetProfileRequest
{
ProfileName = ProfileName.FromProjectTenantProfile("[PROJECT]", "[TENANT]", "[PROFILE]"),
};
Profile expectedResponse = new Profile
{
ProfileName = ProfileName.FromProjectTenantProfile("[PROJECT]", "[TENANT]", "[PROFILE]"),
ExternalId = "external_id9442680e",
Source = "sourcef438cd36",
Uri = "uri3db70593",
GroupId = "group_id4f9a930e",
IsHirable = true,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PersonNames = { new PersonName(), },
Addresses = { new Address(), },
EmailAddresses = { new Email(), },
PhoneNumbers = { new Phone(), },
PersonalUris = { new PersonalUri(), },
AdditionalContactInfo =
{
new AdditionalContactInfo(),
},
EmploymentRecords =
{
new EmploymentRecord(),
},
EducationRecords =
{
new EducationRecord(),
},
Skills = { new Skill(), },
Activities = { new Activity(), },
Publications = { new Publication(), },
Patents = { new Patent(), },
Certifications =
{
new Certification(),
},
CustomAttributes =
{
{
"key8a0b6e3c",
new CustomAttribute()
},
},
Processed = true,
KeywordSnippet = "keyword_snippet7289f6ef",
Applications =
{
"applicationsffa9fbb5",
},
Assignments =
{
"assignments2923b317",
},
Resume = new Resume(),
DerivedAddresses = { new Location(), },
CandidateUpdateTime = new wkt::Timestamp(),
ResumeUpdateTime = new wkt::Timestamp(),
AvailabilitySignals =
{
new AvailabilitySignal(),
},
};
mockGrpcClient.Setup(x => x.GetProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Profile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ProfileServiceClient client = new ProfileServiceClientImpl(mockGrpcClient.Object, null);
Profile responseCallSettings = await client.GetProfileAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Profile responseCancellationToken = await client.GetProfileAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetProfileResourceNames()
{
moq::Mock<ProfileService.ProfileServiceClient> mockGrpcClient = new moq::Mock<ProfileService.ProfileServiceClient>(moq::MockBehavior.Strict);
GetProfileRequest request = new GetProfileRequest
{
ProfileName = ProfileName.FromProjectTenantProfile("[PROJECT]", "[TENANT]", "[PROFILE]"),
};
Profile expectedResponse = new Profile
{
ProfileName = ProfileName.FromProjectTenantProfile("[PROJECT]", "[TENANT]", "[PROFILE]"),
ExternalId = "external_id9442680e",
Source = "sourcef438cd36",
Uri = "uri3db70593",
GroupId = "group_id4f9a930e",
IsHirable = true,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PersonNames = { new PersonName(), },
Addresses = { new Address(), },
EmailAddresses = { new Email(), },
PhoneNumbers = { new Phone(), },
PersonalUris = { new PersonalUri(), },
AdditionalContactInfo =
{
new AdditionalContactInfo(),
},
EmploymentRecords =
{
new EmploymentRecord(),
},
EducationRecords =
{
new EducationRecord(),
},
Skills = { new Skill(), },
Activities = { new Activity(), },
Publications = { new Publication(), },
Patents = { new Patent(), },
Certifications =
{
new Certification(),
},
CustomAttributes =
{
{
"key8a0b6e3c",
new CustomAttribute()
},
},
Processed = true,
KeywordSnippet = "keyword_snippet7289f6ef",
Applications =
{
"applicationsffa9fbb5",
},
Assignments =
{
"assignments2923b317",
},
Resume = new Resume(),
DerivedAddresses = { new Location(), },
CandidateUpdateTime = new wkt::Timestamp(),
ResumeUpdateTime = new wkt::Timestamp(),
AvailabilitySignals =
{
new AvailabilitySignal(),
},
};
mockGrpcClient.Setup(x => x.GetProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ProfileServiceClient client = new ProfileServiceClientImpl(mockGrpcClient.Object, null);
Profile response = client.GetProfile(request.ProfileName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetProfileResourceNamesAsync()
{
moq::Mock<ProfileService.ProfileServiceClient> mockGrpcClient = new moq::Mock<ProfileService.ProfileServiceClient>(moq::MockBehavior.Strict);
GetProfileRequest request = new GetProfileRequest
{
ProfileName = ProfileName.FromProjectTenantProfile("[PROJECT]", "[TENANT]", "[PROFILE]"),
};
Profile expectedResponse = new Profile
{
ProfileName = ProfileName.FromProjectTenantProfile("[PROJECT]", "[TENANT]", "[PROFILE]"),
ExternalId = "external_id9442680e",
Source = "sourcef438cd36",
Uri = "uri3db70593",
GroupId = "group_id4f9a930e",
IsHirable = true,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PersonNames = { new PersonName(), },
Addresses = { new Address(), },
EmailAddresses = { new Email(), },
PhoneNumbers = { new Phone(), },
PersonalUris = { new PersonalUri(), },
AdditionalContactInfo =
{
new AdditionalContactInfo(),
},
EmploymentRecords =
{
new EmploymentRecord(),
},
EducationRecords =
{
new EducationRecord(),
},
Skills = { new Skill(), },
Activities = { new Activity(), },
Publications = { new Publication(), },
Patents = { new Patent(), },
Certifications =
{
new Certification(),
},
CustomAttributes =
{
{
"key8a0b6e3c",
new CustomAttribute()
},
},
Processed = true,
KeywordSnippet = "keyword_snippet7289f6ef",
Applications =
{
"applicationsffa9fbb5",
},
Assignments =
{
"assignments2923b317",
},
Resume = new Resume(),
DerivedAddresses = { new Location(), },
CandidateUpdateTime = new wkt::Timestamp(),
ResumeUpdateTime = new wkt::Timestamp(),
AvailabilitySignals =
{
new AvailabilitySignal(),
},
};
mockGrpcClient.Setup(x => x.GetProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Profile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ProfileServiceClient client = new ProfileServiceClientImpl(mockGrpcClient.Object, null);
Profile responseCallSettings = await client.GetProfileAsync(request.ProfileName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Profile responseCancellationToken = await client.GetProfileAsync(request.ProfileName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateProfileRequestObject()
{
moq::Mock<ProfileService.ProfileServiceClient> mockGrpcClient = new moq::Mock<ProfileService.ProfileServiceClient>(moq::MockBehavior.Strict);
UpdateProfileRequest request = new UpdateProfileRequest
{
Profile = new Profile(),
UpdateMask = new wkt::FieldMask(),
};
Profile expectedResponse = new Profile
{
ProfileName = ProfileName.FromProjectTenantProfile("[PROJECT]", "[TENANT]", "[PROFILE]"),
ExternalId = "external_id9442680e",
Source = "sourcef438cd36",
Uri = "uri3db70593",
GroupId = "group_id4f9a930e",
IsHirable = true,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PersonNames = { new PersonName(), },
Addresses = { new Address(), },
EmailAddresses = { new Email(), },
PhoneNumbers = { new Phone(), },
PersonalUris = { new PersonalUri(), },
AdditionalContactInfo =
{
new AdditionalContactInfo(),
},
EmploymentRecords =
{
new EmploymentRecord(),
},
EducationRecords =
{
new EducationRecord(),
},
Skills = { new Skill(), },
Activities = { new Activity(), },
Publications = { new Publication(), },
Patents = { new Patent(), },
Certifications =
{
new Certification(),
},
CustomAttributes =
{
{
"key8a0b6e3c",
new CustomAttribute()
},
},
Processed = true,
KeywordSnippet = "keyword_snippet7289f6ef",
Applications =
{
"applicationsffa9fbb5",
},
Assignments =
{
"assignments2923b317",
},
Resume = new Resume(),
DerivedAddresses = { new Location(), },
CandidateUpdateTime = new wkt::Timestamp(),
ResumeUpdateTime = new wkt::Timestamp(),
AvailabilitySignals =
{
new AvailabilitySignal(),
},
};
mockGrpcClient.Setup(x => x.UpdateProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ProfileServiceClient client = new ProfileServiceClientImpl(mockGrpcClient.Object, null);
Profile response = client.UpdateProfile(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateProfileRequestObjectAsync()
{
moq::Mock<ProfileService.ProfileServiceClient> mockGrpcClient = new moq::Mock<ProfileService.ProfileServiceClient>(moq::MockBehavior.Strict);
UpdateProfileRequest request = new UpdateProfileRequest
{
Profile = new Profile(),
UpdateMask = new wkt::FieldMask(),
};
Profile expectedResponse = new Profile
{
ProfileName = ProfileName.FromProjectTenantProfile("[PROJECT]", "[TENANT]", "[PROFILE]"),
ExternalId = "external_id9442680e",
Source = "sourcef438cd36",
Uri = "uri3db70593",
GroupId = "group_id4f9a930e",
IsHirable = true,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PersonNames = { new PersonName(), },
Addresses = { new Address(), },
EmailAddresses = { new Email(), },
PhoneNumbers = { new Phone(), },
PersonalUris = { new PersonalUri(), },
AdditionalContactInfo =
{
new AdditionalContactInfo(),
},
EmploymentRecords =
{
new EmploymentRecord(),
},
EducationRecords =
{
new EducationRecord(),
},
Skills = { new Skill(), },
Activities = { new Activity(), },
Publications = { new Publication(), },
Patents = { new Patent(), },
Certifications =
{
new Certification(),
},
CustomAttributes =
{
{
"key8a0b6e3c",
new CustomAttribute()
},
},
Processed = true,
KeywordSnippet = "keyword_snippet7289f6ef",
Applications =
{
"applicationsffa9fbb5",
},
Assignments =
{
"assignments2923b317",
},
Resume = new Resume(),
DerivedAddresses = { new Location(), },
CandidateUpdateTime = new wkt::Timestamp(),
ResumeUpdateTime = new wkt::Timestamp(),
AvailabilitySignals =
{
new AvailabilitySignal(),
},
};
mockGrpcClient.Setup(x => x.UpdateProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Profile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ProfileServiceClient client = new ProfileServiceClientImpl(mockGrpcClient.Object, null);
Profile responseCallSettings = await client.UpdateProfileAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Profile responseCancellationToken = await client.UpdateProfileAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateProfile()
{
moq::Mock<ProfileService.ProfileServiceClient> mockGrpcClient = new moq::Mock<ProfileService.ProfileServiceClient>(moq::MockBehavior.Strict);
UpdateProfileRequest request = new UpdateProfileRequest
{
Profile = new Profile(),
};
Profile expectedResponse = new Profile
{
ProfileName = ProfileName.FromProjectTenantProfile("[PROJECT]", "[TENANT]", "[PROFILE]"),
ExternalId = "external_id9442680e",
Source = "sourcef438cd36",
Uri = "uri3db70593",
GroupId = "group_id4f9a930e",
IsHirable = true,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PersonNames = { new PersonName(), },
Addresses = { new Address(), },
EmailAddresses = { new Email(), },
PhoneNumbers = { new Phone(), },
PersonalUris = { new PersonalUri(), },
AdditionalContactInfo =
{
new AdditionalContactInfo(),
},
EmploymentRecords =
{
new EmploymentRecord(),
},
EducationRecords =
{
new EducationRecord(),
},
Skills = { new Skill(), },
Activities = { new Activity(), },
Publications = { new Publication(), },
Patents = { new Patent(), },
Certifications =
{
new Certification(),
},
CustomAttributes =
{
{
"key8a0b6e3c",
new CustomAttribute()
},
},
Processed = true,
KeywordSnippet = "keyword_snippet7289f6ef",
Applications =
{
"applicationsffa9fbb5",
},
Assignments =
{
"assignments2923b317",
},
Resume = new Resume(),
DerivedAddresses = { new Location(), },
CandidateUpdateTime = new wkt::Timestamp(),
ResumeUpdateTime = new wkt::Timestamp(),
AvailabilitySignals =
{
new AvailabilitySignal(),
},
};
mockGrpcClient.Setup(x => x.UpdateProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ProfileServiceClient client = new ProfileServiceClientImpl(mockGrpcClient.Object, null);
Profile response = client.UpdateProfile(request.Profile);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateProfileAsync()
{
moq::Mock<ProfileService.ProfileServiceClient> mockGrpcClient = new moq::Mock<ProfileService.ProfileServiceClient>(moq::MockBehavior.Strict);
UpdateProfileRequest request = new UpdateProfileRequest
{
Profile = new Profile(),
};
Profile expectedResponse = new Profile
{
ProfileName = ProfileName.FromProjectTenantProfile("[PROJECT]", "[TENANT]", "[PROFILE]"),
ExternalId = "external_id9442680e",
Source = "sourcef438cd36",
Uri = "uri3db70593",
GroupId = "group_id4f9a930e",
IsHirable = true,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PersonNames = { new PersonName(), },
Addresses = { new Address(), },
EmailAddresses = { new Email(), },
PhoneNumbers = { new Phone(), },
PersonalUris = { new PersonalUri(), },
AdditionalContactInfo =
{
new AdditionalContactInfo(),
},
EmploymentRecords =
{
new EmploymentRecord(),
},
EducationRecords =
{
new EducationRecord(),
},
Skills = { new Skill(), },
Activities = { new Activity(), },
Publications = { new Publication(), },
Patents = { new Patent(), },
Certifications =
{
new Certification(),
},
CustomAttributes =
{
{
"key8a0b6e3c",
new CustomAttribute()
},
},
Processed = true,
KeywordSnippet = "keyword_snippet7289f6ef",
Applications =
{
"applicationsffa9fbb5",
},
Assignments =
{
"assignments2923b317",
},
Resume = new Resume(),
DerivedAddresses = { new Location(), },
CandidateUpdateTime = new wkt::Timestamp(),
ResumeUpdateTime = new wkt::Timestamp(),
AvailabilitySignals =
{
new AvailabilitySignal(),
},
};
mockGrpcClient.Setup(x => x.UpdateProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Profile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ProfileServiceClient client = new ProfileServiceClientImpl(mockGrpcClient.Object, null);
Profile responseCallSettings = await client.UpdateProfileAsync(request.Profile, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Profile responseCancellationToken = await client.UpdateProfileAsync(request.Profile, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteProfileRequestObject()
{
moq::Mock<ProfileService.ProfileServiceClient> mockGrpcClient = new moq::Mock<ProfileService.ProfileServiceClient>(moq::MockBehavior.Strict);
DeleteProfileRequest request = new DeleteProfileRequest
{
ProfileName = ProfileName.FromProjectTenantProfile("[PROJECT]", "[TENANT]", "[PROFILE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ProfileServiceClient client = new ProfileServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteProfile(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteProfileRequestObjectAsync()
{
moq::Mock<ProfileService.ProfileServiceClient> mockGrpcClient = new moq::Mock<ProfileService.ProfileServiceClient>(moq::MockBehavior.Strict);
DeleteProfileRequest request = new DeleteProfileRequest
{
ProfileName = ProfileName.FromProjectTenantProfile("[PROJECT]", "[TENANT]", "[PROFILE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ProfileServiceClient client = new ProfileServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteProfileAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteProfileAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteProfile()
{
moq::Mock<ProfileService.ProfileServiceClient> mockGrpcClient = new moq::Mock<ProfileService.ProfileServiceClient>(moq::MockBehavior.Strict);
DeleteProfileRequest request = new DeleteProfileRequest
{
ProfileName = ProfileName.FromProjectTenantProfile("[PROJECT]", "[TENANT]", "[PROFILE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ProfileServiceClient client = new ProfileServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteProfile(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteProfileAsync()
{
moq::Mock<ProfileService.ProfileServiceClient> mockGrpcClient = new moq::Mock<ProfileService.ProfileServiceClient>(moq::MockBehavior.Strict);
DeleteProfileRequest request = new DeleteProfileRequest
{
ProfileName = ProfileName.FromProjectTenantProfile("[PROJECT]", "[TENANT]", "[PROFILE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ProfileServiceClient client = new ProfileServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteProfileAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteProfileAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteProfileResourceNames()
{
moq::Mock<ProfileService.ProfileServiceClient> mockGrpcClient = new moq::Mock<ProfileService.ProfileServiceClient>(moq::MockBehavior.Strict);
DeleteProfileRequest request = new DeleteProfileRequest
{
ProfileName = ProfileName.FromProjectTenantProfile("[PROJECT]", "[TENANT]", "[PROFILE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ProfileServiceClient client = new ProfileServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteProfile(request.ProfileName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteProfileResourceNamesAsync()
{
moq::Mock<ProfileService.ProfileServiceClient> mockGrpcClient = new moq::Mock<ProfileService.ProfileServiceClient>(moq::MockBehavior.Strict);
DeleteProfileRequest request = new DeleteProfileRequest
{
ProfileName = ProfileName.FromProjectTenantProfile("[PROJECT]", "[TENANT]", "[PROFILE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ProfileServiceClient client = new ProfileServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteProfileAsync(request.ProfileName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteProfileAsync(request.ProfileName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SearchProfilesRequestObject()
{
moq::Mock<ProfileService.ProfileServiceClient> mockGrpcClient = new moq::Mock<ProfileService.ProfileServiceClient>(moq::MockBehavior.Strict);
SearchProfilesRequest request = new SearchProfilesRequest
{
ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
RequestMetadata = new RequestMetadata(),
ProfileQuery = new ProfileQuery(),
PageSize = -226905851,
PageToken = "page_tokenf09e5538",
Offset = 1472300666,
DisableSpellCheck = true,
OrderBy = "order_byb4d33ada",
CaseSensitiveSort = true,
HistogramQueries =
{
new HistogramQuery(),
},
ResultSetId = "result_set_id6cf58a14",
StrictKeywordsSearch = true,
};
SearchProfilesResponse expectedResponse = new SearchProfilesResponse
{
EstimatedTotalSize = 5269174732212511261L,
SpellCorrection = new SpellingCorrection(),
Metadata = new ResponseMetadata(),
NextPageToken = "next_page_tokendbee0940",
HistogramQueryResults =
{
new HistogramQueryResult(),
},
SummarizedProfiles =
{
new SummarizedProfile(),
},
ResultSetId = "result_set_id6cf58a14",
};
mockGrpcClient.Setup(x => x.SearchProfiles(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ProfileServiceClient client = new ProfileServiceClientImpl(mockGrpcClient.Object, null);
SearchProfilesResponse response = client.SearchProfiles(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SearchProfilesRequestObjectAsync()
{
moq::Mock<ProfileService.ProfileServiceClient> mockGrpcClient = new moq::Mock<ProfileService.ProfileServiceClient>(moq::MockBehavior.Strict);
SearchProfilesRequest request = new SearchProfilesRequest
{
ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
RequestMetadata = new RequestMetadata(),
ProfileQuery = new ProfileQuery(),
PageSize = -226905851,
PageToken = "page_tokenf09e5538",
Offset = 1472300666,
DisableSpellCheck = true,
OrderBy = "order_byb4d33ada",
CaseSensitiveSort = true,
HistogramQueries =
{
new HistogramQuery(),
},
ResultSetId = "result_set_id6cf58a14",
StrictKeywordsSearch = true,
};
SearchProfilesResponse expectedResponse = new SearchProfilesResponse
{
EstimatedTotalSize = 5269174732212511261L,
SpellCorrection = new SpellingCorrection(),
Metadata = new ResponseMetadata(),
NextPageToken = "next_page_tokendbee0940",
HistogramQueryResults =
{
new HistogramQueryResult(),
},
SummarizedProfiles =
{
new SummarizedProfile(),
},
ResultSetId = "result_set_id6cf58a14",
};
mockGrpcClient.Setup(x => x.SearchProfilesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SearchProfilesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ProfileServiceClient client = new ProfileServiceClientImpl(mockGrpcClient.Object, null);
SearchProfilesResponse responseCallSettings = await client.SearchProfilesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SearchProfilesResponse responseCancellationToken = await client.SearchProfilesAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.Collections.Generic;
namespace Lucene.Net.Search.Spans
{
/*
* 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 AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using Bits = Lucene.Net.Util.Bits;
using IndexReader = Lucene.Net.Index.IndexReader;
using Term = Lucene.Net.Index.Term;
using TermContext = Lucene.Net.Index.TermContext;
/// <summary>
/// Base class for filtering a SpanQuery based on the position of a match.
///
/// </summary>
public abstract class SpanPositionCheckQuery : SpanQuery, ICloneable
{
protected internal SpanQuery match;
public SpanPositionCheckQuery(SpanQuery match)
{
this.match = match;
}
/// <returns> the SpanQuery whose matches are filtered.
///
/// </returns>
public virtual SpanQuery Match
{
get
{
return match;
}
}
public override string Field
{
get
{
return match.Field;
}
}
public override void ExtractTerms(ISet<Term> terms)
{
match.ExtractTerms(terms);
}
/// <summary>
/// Return value for <seealso cref="SpanPositionCheckQuery#acceptPosition(Spans)"/>.
/// </summary>
protected internal enum AcceptStatus
{
/// <summary>
/// Indicates the match should be accepted </summary>
YES,
/// <summary>
/// Indicates the match should be rejected </summary>
NO,
/// <summary>
/// Indicates the match should be rejected, and the enumeration should advance
/// to the next document.
/// </summary>
NO_AND_ADVANCE
}
/// <summary>
/// Implementing classes are required to return whether the current position is a match for the passed in
/// "match" <seealso cref="Lucene.Net.Search.Spans.SpanQuery"/>.
///
/// this is only called if the underlying <seealso cref="Lucene.Net.Search.Spans.Spans#next()"/> for the
/// match is successful
///
/// </summary>
/// <param name="spans"> The <seealso cref="Lucene.Net.Search.Spans.Spans"/> instance, positioned at the spot to check </param>
/// <returns> whether the match is accepted, rejected, or rejected and should move to the next doc.
/// </returns>
/// <seealso cref= Lucene.Net.Search.Spans.Spans#next()
/// </seealso>
protected internal abstract AcceptStatus AcceptPosition(Spans spans);
public override Spans GetSpans(AtomicReaderContext context, Bits acceptDocs, IDictionary<Term, TermContext> termContexts)
{
return new PositionCheckSpan(this, context, acceptDocs, termContexts);
}
public override Query Rewrite(IndexReader reader)
{
SpanPositionCheckQuery clone = null;
var rewritten = (SpanQuery)match.Rewrite(reader);
if (rewritten != match)
{
clone = (SpanPositionCheckQuery)this.Clone();
clone.match = rewritten;
}
if (clone != null)
{
return clone; // some clauses rewrote
}
else
{
return this; // no clauses rewrote
}
}
protected internal class PositionCheckSpan : Spans
{
private readonly SpanPositionCheckQuery OuterInstance;
internal Spans Spans;
public PositionCheckSpan(SpanPositionCheckQuery outerInstance, AtomicReaderContext context, Bits acceptDocs, IDictionary<Term, TermContext> termContexts)
{
this.OuterInstance = outerInstance;
Spans = outerInstance.match.GetSpans(context, acceptDocs, termContexts);
}
public override bool Next()
{
if (!Spans.Next())
{
return false;
}
return DoNext();
}
public override bool SkipTo(int target)
{
if (!Spans.SkipTo(target))
{
return false;
}
return DoNext();
}
protected internal virtual bool DoNext()
{
for (; ; )
{
switch (OuterInstance.AcceptPosition(this))
{
case AcceptStatus.YES:
return true;
case AcceptStatus.NO:
if (!Spans.Next())
{
return false;
}
break;
case AcceptStatus.NO_AND_ADVANCE:
if (!Spans.SkipTo(Spans.Doc() + 1))
{
return false;
}
break;
}
}
}
public override int Doc()
{
return Spans.Doc();
}
public override int Start()
{
return Spans.Start();
}
public override int End()
// TODO: Remove warning after API has been finalized
{
return Spans.End();
}
public override ICollection<byte[]> Payload
{
get
{
List<byte[]> result = null;
if (Spans.PayloadAvailable)
{
result = new List<byte[]>(Spans.Payload);
}
return result; //TODO: any way to avoid the new construction?
}
}
// TODO: Remove warning after API has been finalized
public override bool PayloadAvailable
{
get
{
return Spans.PayloadAvailable;
}
}
public override long Cost()
{
return Spans.Cost();
}
public override string ToString()
{
return "spans(" + OuterInstance.ToString() + ")";
}
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.IO;
using DiscUtils;
using DiscUtils.Streams;
using DiscUtils.Vmdk;
using Xunit;
namespace LibraryTests.Vmdk
{
public class DynamicStreamTest
{
[Fact]
public void Attributes()
{
DiscFileSystem fs = new InMemoryFileSystem();
using (Disk disk = Disk.Initialize(fs, "a.vmdk", 16 * 1024L * 1024 * 1024, DiskCreateType.MonolithicSparse))
{
Stream s = disk.Content;
Assert.True(s.CanRead);
Assert.True(s.CanWrite);
Assert.True(s.CanSeek);
}
}
[Fact]
public void ReadWriteSmall()
{
DiscFileSystem fs = new InMemoryFileSystem();
using (Disk disk = Disk.Initialize(fs, "a.vmdk",16 * 1024L * 1024 * 1024, DiskCreateType.TwoGbMaxExtentSparse))
{
byte[] content = new byte[100];
for(int i = 0; i < content.Length; ++i)
{
content[i] = (byte)i;
}
Stream s = disk.Content;
s.Write(content, 10, 40);
Assert.Equal(40, s.Position);
s.Write(content, 50, 50);
Assert.Equal(90, s.Position);
s.Position = 0;
byte[] buffer = new byte[100];
s.Read(buffer, 10, 60);
Assert.Equal(60, s.Position);
for (int i = 0; i < 10; ++i)
{
Assert.Equal(0, buffer[i]);
}
for (int i = 10; i < 60; ++i)
{
Assert.Equal(i, buffer[i]);
}
}
// Check the data persisted
using (Disk disk = new Disk(fs, "a.vmdk", FileAccess.Read))
{
Stream s = disk.Content;
byte[] buffer = new byte[100];
s.Read(buffer, 10, 20);
Assert.Equal(20, s.Position);
for (int i = 0; i < 10; ++i)
{
Assert.Equal(0, buffer[i]);
}
for (int i = 10; i < 20; ++i)
{
Assert.Equal(i, buffer[i]);
}
}
}
[Fact]
public void ReadWriteLarge()
{
DiscFileSystem fs = new InMemoryFileSystem();
using (Disk disk = Disk.Initialize(fs, "a.vmdk", 16 * 1024L * 1024 * 1024, DiskCreateType.TwoGbMaxExtentSparse))
{
byte[] content = new byte[3 * 1024 * 1024];
for (int i = 0; i < content.Length / 4; ++i)
{
content[i * 4 + 0] = (byte)((i >> 24) & 0xFF);
content[i * 4 + 1] = (byte)((i >> 16) & 0xFF);
content[i * 4 + 2] = (byte)((i >> 8) & 0xFF);
content[i * 4 + 3] = (byte)(i & 0xFF);
}
Stream s = disk.Content;
s.Position = 10;
s.Write(content, 0, content.Length);
byte[] buffer = new byte[content.Length];
s.Position = 10;
s.Read(buffer, 0, buffer.Length);
for (int i = 0; i < content.Length; ++i)
{
if (buffer[i] != content[i])
{
Assert.True(false);
}
}
}
}
[Fact]
public void DisposeTest()
{
Stream contentStream;
DiscFileSystem fs = new InMemoryFileSystem();
using (Disk disk = Disk.Initialize(fs, "a.vmdk", 16 * 1024L * 1024 * 1024, DiskCreateType.TwoGbMaxExtentSparse))
{
contentStream = disk.Content;
}
try
{
contentStream.Position = 0;
Assert.True(false);
}
catch(ObjectDisposedException) { }
}
[Fact]
public void DisposeTestMonolithicSparse()
{
Stream contentStream;
DiscFileSystem fs = new InMemoryFileSystem();
using (Disk disk = Disk.Initialize(fs, "a.vmdk", 16 * 1024L * 1024 * 1024, DiskCreateType.MonolithicSparse))
{
contentStream = disk.Content;
}
try
{
contentStream.Position = 0;
Assert.True(false);
}
catch (ObjectDisposedException) { }
}
[Fact]
public void ReadNotPresent()
{
DiscFileSystem fs = new InMemoryFileSystem();
using (Disk disk = Disk.Initialize(fs, "a.vmdk", 16 * 1024L * 1024 * 1024, DiskCreateType.TwoGbMaxExtentSparse))
{
byte[] buffer = new byte[100];
disk.Content.Seek(2 * 1024 * 1024, SeekOrigin.Current);
disk.Content.Read(buffer, 0, buffer.Length);
for (int i = 0; i < 100; ++i)
{
if (buffer[i] != 0)
{
Assert.True(false);
}
}
}
}
[Fact]
public void AttributesVmfs()
{
DiscFileSystem fs = new InMemoryFileSystem();
using (Disk disk = Disk.Initialize(fs, "a.vmdk", 16 * 1024L * 1024 * 1024, DiskCreateType.VmfsSparse))
{
Stream s = disk.Content;
Assert.True(s.CanRead);
Assert.True(s.CanWrite);
Assert.True(s.CanSeek);
}
}
[Fact]
public void ReadWriteSmallVmfs()
{
DiscFileSystem fs = new InMemoryFileSystem();
using (Disk disk = Disk.Initialize(fs, "a.vmdk", 16 * 1024L * 1024 * 1024, DiskCreateType.VmfsSparse))
{
byte[] content = new byte[100];
for (int i = 0; i < content.Length; ++i)
{
content[i] = (byte)i;
}
Stream s = disk.Content;
s.Write(content, 10, 40);
Assert.Equal(40, s.Position);
s.Write(content, 50, 50);
Assert.Equal(90, s.Position);
s.Position = 0;
byte[] buffer = new byte[100];
s.Read(buffer, 10, 60);
Assert.Equal(60, s.Position);
for (int i = 0; i < 10; ++i)
{
Assert.Equal(0, buffer[i]);
}
for (int i = 10; i < 60; ++i)
{
Assert.Equal(i, buffer[i]);
}
}
// Check the data persisted
using (Disk disk = new Disk(fs, "a.vmdk", FileAccess.Read))
{
Stream s = disk.Content;
byte[] buffer = new byte[100];
s.Read(buffer, 10, 20);
Assert.Equal(20, s.Position);
for (int i = 0; i < 10; ++i)
{
Assert.Equal(0, buffer[i]);
}
for (int i = 10; i < 20; ++i)
{
Assert.Equal(i, buffer[i]);
}
}
}
[Fact]
public void ReadWriteLargeVmfs()
{
DiscFileSystem fs = new InMemoryFileSystem();
using (Disk disk = Disk.Initialize(fs, "a.vmdk", 16 * 1024L * 1024 * 1024, DiskCreateType.VmfsSparse))
{
byte[] content = new byte[3 * 1024 * 1024];
for (int i = 0; i < content.Length / 4; ++i)
{
content[i * 4 + 0] = (byte)((i >> 24) & 0xFF);
content[i * 4 + 1] = (byte)((i >> 16) & 0xFF);
content[i * 4 + 2] = (byte)((i >> 8) & 0xFF);
content[i * 4 + 3] = (byte)(i & 0xFF);
}
Stream s = disk.Content;
s.Position = 10;
s.Write(content, 0, content.Length);
byte[] buffer = new byte[content.Length];
s.Position = 10;
s.Read(buffer, 0, buffer.Length);
for (int i = 0; i < content.Length; ++i)
{
if (buffer[i] != content[i])
{
Assert.True(false);
}
}
}
}
[Fact]
public void DisposeTestVmfs()
{
Stream contentStream;
DiscFileSystem fs = new InMemoryFileSystem();
using (Disk disk = Disk.Initialize(fs, "a.vmdk", 16 * 1024L * 1024 * 1024, DiskCreateType.VmfsSparse))
{
contentStream = disk.Content;
}
try
{
contentStream.Position = 0;
Assert.True(false);
}
catch (ObjectDisposedException) { }
}
[Fact]
public void ReadNotPresentVmfs()
{
DiscFileSystem fs = new InMemoryFileSystem();
using (Disk disk = Disk.Initialize(fs, "a.vmdk", 16 * 1024L * 1024 * 1024, DiskCreateType.VmfsSparse))
{
byte[] buffer = new byte[100];
disk.Content.Seek(2 * 1024 * 1024, SeekOrigin.Current);
disk.Content.Read(buffer, 0, buffer.Length);
for (int i = 0; i < 100; ++i)
{
if (buffer[i] != 0)
{
Assert.True(false);
}
}
}
}
[Fact]
public void Extents()
{
// Fragile - this is the grain size in bytes of the VMDK file, so dependant on algorithm that
// determines grain size for new VMDKs...
const int unit = 128 * 512;
DiscFileSystem fs = new InMemoryFileSystem();
using (Disk disk = Disk.Initialize(fs, "a.vmdk", 16 * 1024L * 1024 * 1024, DiskCreateType.TwoGbMaxExtentSparse))
{
disk.Content.Position = 20 * unit;
disk.Content.Write(new byte[4 * unit], 0, 4 * unit);
// Starts before first extent, ends before end of extent
List<StreamExtent> extents = new List<StreamExtent>(disk.Content.GetExtentsInRange(0, 21 * unit));
Assert.Equal(1, extents.Count);
Assert.Equal(20 * unit, extents[0].Start);
Assert.Equal(1 * unit, extents[0].Length);
// Limit to disk content length
extents = new List<StreamExtent>(disk.Content.GetExtentsInRange(21 * unit, 20 * unit));
Assert.Equal(1, extents.Count);
Assert.Equal(21 * unit, extents[0].Start);
Assert.Equal(3 * unit, extents[0].Length);
// Out of range
extents = new List<StreamExtent>(disk.Content.GetExtentsInRange(25 * unit, 4 * unit));
Assert.Equal(0, extents.Count);
// Non-unit multiples
extents = new List<StreamExtent>(disk.Content.GetExtentsInRange(21 * unit + 10, 20 * unit));
Assert.Equal(1, extents.Count);
Assert.Equal(21 * unit + 10, extents[0].Start);
Assert.Equal(3 * unit - 10, extents[0].Length);
}
}
}
}
| |
#region Copyright
////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Dynastream Innovations Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2015 Dynastream Innovations Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 16.10Release
// Tag = development-akw-16.10.00-0
////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.IO;
namespace FickleFrostbite.FIT
{
/// <summary>
/// Implements the Monitoring profile message.
/// </summary>
public class MonitoringMesg : Mesg
{
#region Fields
static class CyclesSubfield
{
public static ushort Steps = 0;
public static ushort Strokes = 1;
public static ushort Subfields = 2;
public static ushort Active = Fit.SubfieldIndexActiveSubfield;
public static ushort MainField = Fit.SubfieldIndexMainField;
}
#endregion
#region Constructors
public MonitoringMesg() : base(Profile.mesgs[Profile.MonitoringIndex])
{
}
public MonitoringMesg(Mesg mesg) : base(mesg)
{
}
#endregion // Constructors
#region Methods
///<summary>
/// Retrieves the Timestamp field
/// Units: s
/// Comment: Must align to logging interval, for example, time must be 00:00:00 for daily log.</summary>
/// <returns>Returns DateTime representing the Timestamp field</returns>
public DateTime GetTimestamp()
{
return TimestampToDateTime((uint?)GetFieldValue(253, 0, Fit.SubfieldIndexMainField));
}
/// <summary>
/// Set Timestamp field
/// Units: s
/// Comment: Must align to logging interval, for example, time must be 00:00:00 for daily log.</summary>
/// <param name="timestamp_">Nullable field value to be set</param>
public void SetTimestamp(DateTime timestamp_)
{
SetFieldValue(253, 0, timestamp_.GetTimeStamp(), Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the DeviceIndex field
/// Comment: Associates this data to device_info message. Not required for file with single device (sensor).</summary>
/// <returns>Returns nullable byte representing the DeviceIndex field</returns>
public byte? GetDeviceIndex()
{
return (byte?)GetFieldValue(0, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set DeviceIndex field
/// Comment: Associates this data to device_info message. Not required for file with single device (sensor).</summary>
/// <param name="deviceIndex_">Nullable field value to be set</param>
public void SetDeviceIndex(byte? deviceIndex_)
{
SetFieldValue(0, 0, deviceIndex_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Calories field
/// Units: kcal
/// Comment: Accumulated total calories. Maintained by MonitoringReader for each activity_type. See SDK documentation</summary>
/// <returns>Returns nullable ushort representing the Calories field</returns>
public ushort? GetCalories()
{
return (ushort?)GetFieldValue(1, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Calories field
/// Units: kcal
/// Comment: Accumulated total calories. Maintained by MonitoringReader for each activity_type. See SDK documentation</summary>
/// <param name="calories_">Nullable field value to be set</param>
public void SetCalories(ushort? calories_)
{
SetFieldValue(1, 0, calories_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Distance field
/// Units: m
/// Comment: Accumulated distance. Maintained by MonitoringReader for each activity_type. See SDK documentation.</summary>
/// <returns>Returns nullable float representing the Distance field</returns>
public float? GetDistance()
{
return (float?)GetFieldValue(2, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Distance field
/// Units: m
/// Comment: Accumulated distance. Maintained by MonitoringReader for each activity_type. See SDK documentation.</summary>
/// <param name="distance_">Nullable field value to be set</param>
public void SetDistance(float? distance_)
{
SetFieldValue(2, 0, distance_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Cycles field
/// Units: cycles
/// Comment: Accumulated cycles. Maintained by MonitoringReader for each activity_type. See SDK documentation.</summary>
/// <returns>Returns nullable float representing the Cycles field</returns>
public float? GetCycles()
{
return (float?)GetFieldValue(3, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Cycles field
/// Units: cycles
/// Comment: Accumulated cycles. Maintained by MonitoringReader for each activity_type. See SDK documentation.</summary>
/// <param name="cycles_">Nullable field value to be set</param>
public void SetCycles(float? cycles_)
{
SetFieldValue(3, 0, cycles_, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Retrieves the Steps subfield
/// Units: steps</summary>
/// <returns>Nullable uint representing the Steps subfield</returns>
public uint? GetSteps()
{
return (uint?)GetFieldValue(3, 0, CyclesSubfield.Steps);
}
/// <summary>
///
/// Set Steps subfield
/// Units: steps</summary>
/// <param name="steps">Subfield value to be set</param>
public void SetSteps(uint? steps)
{
SetFieldValue(3, 0, steps, CyclesSubfield.Steps);
}
/// <summary>
/// Retrieves the Strokes subfield
/// Units: strokes</summary>
/// <returns>Nullable float representing the Strokes subfield</returns>
public float? GetStrokes()
{
return (float?)GetFieldValue(3, 0, CyclesSubfield.Strokes);
}
/// <summary>
///
/// Set Strokes subfield
/// Units: strokes</summary>
/// <param name="strokes">Subfield value to be set</param>
public void SetStrokes(float? strokes)
{
SetFieldValue(3, 0, strokes, CyclesSubfield.Strokes);
}
///<summary>
/// Retrieves the ActiveTime field
/// Units: s</summary>
/// <returns>Returns nullable float representing the ActiveTime field</returns>
public float? GetActiveTime()
{
return (float?)GetFieldValue(4, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set ActiveTime field
/// Units: s</summary>
/// <param name="activeTime_">Nullable field value to be set</param>
public void SetActiveTime(float? activeTime_)
{
SetFieldValue(4, 0, activeTime_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the ActivityType field</summary>
/// <returns>Returns nullable ActivityType enum representing the ActivityType field</returns>
public ActivityType? GetActivityType()
{
object obj = GetFieldValue(5, 0, Fit.SubfieldIndexMainField);
ActivityType? value = obj == null ? (ActivityType?)null : (ActivityType)obj;
return value;
}
/// <summary>
/// Set ActivityType field</summary>
/// <param name="activityType_">Nullable field value to be set</param>
public void SetActivityType(ActivityType? activityType_)
{
SetFieldValue(5, 0, activityType_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the ActivitySubtype field</summary>
/// <returns>Returns nullable ActivitySubtype enum representing the ActivitySubtype field</returns>
public ActivitySubtype? GetActivitySubtype()
{
object obj = GetFieldValue(6, 0, Fit.SubfieldIndexMainField);
ActivitySubtype? value = obj == null ? (ActivitySubtype?)null : (ActivitySubtype)obj;
return value;
}
/// <summary>
/// Set ActivitySubtype field</summary>
/// <param name="activitySubtype_">Nullable field value to be set</param>
public void SetActivitySubtype(ActivitySubtype? activitySubtype_)
{
SetFieldValue(6, 0, activitySubtype_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the ActivityLevel field</summary>
/// <returns>Returns nullable ActivityLevel enum representing the ActivityLevel field</returns>
public ActivityLevel? GetActivityLevel()
{
object obj = GetFieldValue(7, 0, Fit.SubfieldIndexMainField);
ActivityLevel? value = obj == null ? (ActivityLevel?)null : (ActivityLevel)obj;
return value;
}
/// <summary>
/// Set ActivityLevel field</summary>
/// <param name="activityLevel_">Nullable field value to be set</param>
public void SetActivityLevel(ActivityLevel? activityLevel_)
{
SetFieldValue(7, 0, activityLevel_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Distance16 field
/// Units: 100 * m</summary>
/// <returns>Returns nullable ushort representing the Distance16 field</returns>
public ushort? GetDistance16()
{
return (ushort?)GetFieldValue(8, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Distance16 field
/// Units: 100 * m</summary>
/// <param name="distance16_">Nullable field value to be set</param>
public void SetDistance16(ushort? distance16_)
{
SetFieldValue(8, 0, distance16_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Cycles16 field
/// Units: 2 * cycles (steps)</summary>
/// <returns>Returns nullable ushort representing the Cycles16 field</returns>
public ushort? GetCycles16()
{
return (ushort?)GetFieldValue(9, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Cycles16 field
/// Units: 2 * cycles (steps)</summary>
/// <param name="cycles16_">Nullable field value to be set</param>
public void SetCycles16(ushort? cycles16_)
{
SetFieldValue(9, 0, cycles16_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the ActiveTime16 field
/// Units: s</summary>
/// <returns>Returns nullable ushort representing the ActiveTime16 field</returns>
public ushort? GetActiveTime16()
{
return (ushort?)GetFieldValue(10, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set ActiveTime16 field
/// Units: s</summary>
/// <param name="activeTime16_">Nullable field value to be set</param>
public void SetActiveTime16(ushort? activeTime16_)
{
SetFieldValue(10, 0, activeTime16_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the LocalTimestamp field
/// Comment: Must align to logging interval, for example, time must be 00:00:00 for daily log.</summary>
/// <returns>Returns nullable uint representing the LocalTimestamp field</returns>
public uint? GetLocalTimestamp()
{
return (uint?)GetFieldValue(11, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set LocalTimestamp field
/// Comment: Must align to logging interval, for example, time must be 00:00:00 for daily log.</summary>
/// <param name="localTimestamp_">Nullable field value to be set</param>
public void SetLocalTimestamp(uint? localTimestamp_)
{
SetFieldValue(11, 0, localTimestamp_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Temperature field
/// Units: C
/// Comment: Avg temperature during the logging interval ended at timestamp</summary>
/// <returns>Returns nullable float representing the Temperature field</returns>
public float? GetTemperature()
{
return (float?)GetFieldValue(12, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Temperature field
/// Units: C
/// Comment: Avg temperature during the logging interval ended at timestamp</summary>
/// <param name="temperature_">Nullable field value to be set</param>
public void SetTemperature(float? temperature_)
{
SetFieldValue(12, 0, temperature_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the TemperatureMin field
/// Units: C
/// Comment: Min temperature during the logging interval ended at timestamp</summary>
/// <returns>Returns nullable float representing the TemperatureMin field</returns>
public float? GetTemperatureMin()
{
return (float?)GetFieldValue(14, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set TemperatureMin field
/// Units: C
/// Comment: Min temperature during the logging interval ended at timestamp</summary>
/// <param name="temperatureMin_">Nullable field value to be set</param>
public void SetTemperatureMin(float? temperatureMin_)
{
SetFieldValue(14, 0, temperatureMin_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the TemperatureMax field
/// Units: C
/// Comment: Max temperature during the logging interval ended at timestamp</summary>
/// <returns>Returns nullable float representing the TemperatureMax field</returns>
public float? GetTemperatureMax()
{
return (float?)GetFieldValue(15, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set TemperatureMax field
/// Units: C
/// Comment: Max temperature during the logging interval ended at timestamp</summary>
/// <param name="temperatureMax_">Nullable field value to be set</param>
public void SetTemperatureMax(float? temperatureMax_)
{
SetFieldValue(15, 0, temperatureMax_, Fit.SubfieldIndexMainField);
}
/// <summary>
///
/// </summary>
/// <returns>returns number of elements in field ActivityTime</returns>
public int GetNumActivityTime()
{
return GetNumFieldValues(16, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the ActivityTime field
/// Units: minutes
/// Comment: Indexed using minute_activity_level enum</summary>
/// <param name="index">0 based index of ActivityTime element to retrieve</param>
/// <returns>Returns nullable ushort representing the ActivityTime field</returns>
public ushort? GetActivityTime(int index)
{
return (ushort?)GetFieldValue(16, index, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set ActivityTime field
/// Units: minutes
/// Comment: Indexed using minute_activity_level enum</summary>
/// <param name="index">0 based index of activity_time</param>
/// <param name="activityTime_">Nullable field value to be set</param>
public void SetActivityTime(int index, ushort? activityTime_)
{
SetFieldValue(16, index, activityTime_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the ActiveCalories field
/// Units: kcal</summary>
/// <returns>Returns nullable ushort representing the ActiveCalories field</returns>
public ushort? GetActiveCalories()
{
return (ushort?)GetFieldValue(19, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set ActiveCalories field
/// Units: kcal</summary>
/// <param name="activeCalories_">Nullable field value to be set</param>
public void SetActiveCalories(ushort? activeCalories_)
{
SetFieldValue(19, 0, activeCalories_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the CurrentActivityTypeIntensity field
/// Comment: Indicates single type / intensity for duration since last monitoring message.</summary>
/// <returns>Returns nullable byte representing the CurrentActivityTypeIntensity field</returns>
public byte? GetCurrentActivityTypeIntensity()
{
return (byte?)GetFieldValue(24, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set CurrentActivityTypeIntensity field
/// Comment: Indicates single type / intensity for duration since last monitoring message.</summary>
/// <param name="currentActivityTypeIntensity_">Nullable field value to be set</param>
public void SetCurrentActivityTypeIntensity(byte? currentActivityTypeIntensity_)
{
SetFieldValue(24, 0, currentActivityTypeIntensity_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the TimestampMin8 field
/// Units: min</summary>
/// <returns>Returns nullable byte representing the TimestampMin8 field</returns>
public byte? GetTimestampMin8()
{
return (byte?)GetFieldValue(25, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set TimestampMin8 field
/// Units: min</summary>
/// <param name="timestampMin8_">Nullable field value to be set</param>
public void SetTimestampMin8(byte? timestampMin8_)
{
SetFieldValue(25, 0, timestampMin8_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Timestamp16 field
/// Units: s</summary>
/// <returns>Returns nullable ushort representing the Timestamp16 field</returns>
public ushort? GetTimestamp16()
{
return (ushort?)GetFieldValue(26, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Timestamp16 field
/// Units: s</summary>
/// <param name="timestamp16_">Nullable field value to be set</param>
public void SetTimestamp16(ushort? timestamp16_)
{
SetFieldValue(26, 0, timestamp16_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the HeartRate field
/// Units: bpm</summary>
/// <returns>Returns nullable byte representing the HeartRate field</returns>
public byte? GetHeartRate()
{
return (byte?)GetFieldValue(27, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set HeartRate field
/// Units: bpm</summary>
/// <param name="heartRate_">Nullable field value to be set</param>
public void SetHeartRate(byte? heartRate_)
{
SetFieldValue(27, 0, heartRate_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Intensity field</summary>
/// <returns>Returns nullable float representing the Intensity field</returns>
public float? GetIntensity()
{
return (float?)GetFieldValue(28, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Intensity field</summary>
/// <param name="intensity_">Nullable field value to be set</param>
public void SetIntensity(float? intensity_)
{
SetFieldValue(28, 0, intensity_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the DurationMin field
/// Units: min</summary>
/// <returns>Returns nullable ushort representing the DurationMin field</returns>
public ushort? GetDurationMin()
{
return (ushort?)GetFieldValue(29, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set DurationMin field
/// Units: min</summary>
/// <param name="durationMin_">Nullable field value to be set</param>
public void SetDurationMin(ushort? durationMin_)
{
SetFieldValue(29, 0, durationMin_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Duration field
/// Units: s</summary>
/// <returns>Returns nullable uint representing the Duration field</returns>
public uint? GetDuration()
{
return (uint?)GetFieldValue(30, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Duration field
/// Units: s</summary>
/// <param name="duration_">Nullable field value to be set</param>
public void SetDuration(uint? duration_)
{
SetFieldValue(30, 0, duration_, Fit.SubfieldIndexMainField);
}
#endregion // Methods
} // Class
} // namespace
| |
namespace java.lang
{
[global::MonoJavaBridge.JavaClass()]
public partial class Thread : java.lang.Object, Runnable
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected Thread(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass()]
public sealed partial class State : java.lang.Enum
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal State(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public static global::java.lang.Thread.State[] values()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Thread.State._m0.native == global::System.IntPtr.Zero)
global::java.lang.Thread.State._m0 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Thread.State.staticClass, "values", "()[Ljava/lang/Thread/State;");
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.Thread.State>(@__env.CallStaticObjectMethod(java.lang.Thread.State.staticClass, global::java.lang.Thread.State._m0)) as java.lang.Thread.State[];
}
private static global::MonoJavaBridge.MethodId _m1;
public static global::java.lang.Thread.State valueOf(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Thread.State._m1.native == global::System.IntPtr.Zero)
global::java.lang.Thread.State._m1 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Thread.State.staticClass, "valueOf", "(Ljava/lang/String;)Ljava/lang/Thread$State;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.Thread.State>(@__env.CallStaticObjectMethod(java.lang.Thread.State.staticClass, global::java.lang.Thread.State._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Thread.State;
}
internal static global::MonoJavaBridge.FieldId _NEW6390;
public static global::java.lang.Thread.State NEW
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.Thread.State>(@__env.GetStaticObjectField(global::java.lang.Thread.State.staticClass, _NEW6390)) as java.lang.Thread.State;
}
}
internal static global::MonoJavaBridge.FieldId _RUNNABLE6391;
public static global::java.lang.Thread.State RUNNABLE
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.Thread.State>(@__env.GetStaticObjectField(global::java.lang.Thread.State.staticClass, _RUNNABLE6391)) as java.lang.Thread.State;
}
}
internal static global::MonoJavaBridge.FieldId _BLOCKED6392;
public static global::java.lang.Thread.State BLOCKED
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.Thread.State>(@__env.GetStaticObjectField(global::java.lang.Thread.State.staticClass, _BLOCKED6392)) as java.lang.Thread.State;
}
}
internal static global::MonoJavaBridge.FieldId _WAITING6393;
public static global::java.lang.Thread.State WAITING
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.Thread.State>(@__env.GetStaticObjectField(global::java.lang.Thread.State.staticClass, _WAITING6393)) as java.lang.Thread.State;
}
}
internal static global::MonoJavaBridge.FieldId _TIMED_WAITING6394;
public static global::java.lang.Thread.State TIMED_WAITING
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.Thread.State>(@__env.GetStaticObjectField(global::java.lang.Thread.State.staticClass, _TIMED_WAITING6394)) as java.lang.Thread.State;
}
}
internal static global::MonoJavaBridge.FieldId _TERMINATED6395;
public static global::java.lang.Thread.State TERMINATED
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.Thread.State>(@__env.GetStaticObjectField(global::java.lang.Thread.State.staticClass, _TERMINATED6395)) as java.lang.Thread.State;
}
}
static State()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.lang.Thread.State.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/lang/Thread$State"));
global::java.lang.Thread.State._NEW6390 = @__env.GetStaticFieldIDNoThrow(global::java.lang.Thread.State.staticClass, "NEW", "Ljava/lang/Thread$State;");
global::java.lang.Thread.State._RUNNABLE6391 = @__env.GetStaticFieldIDNoThrow(global::java.lang.Thread.State.staticClass, "RUNNABLE", "Ljava/lang/Thread$State;");
global::java.lang.Thread.State._BLOCKED6392 = @__env.GetStaticFieldIDNoThrow(global::java.lang.Thread.State.staticClass, "BLOCKED", "Ljava/lang/Thread$State;");
global::java.lang.Thread.State._WAITING6393 = @__env.GetStaticFieldIDNoThrow(global::java.lang.Thread.State.staticClass, "WAITING", "Ljava/lang/Thread$State;");
global::java.lang.Thread.State._TIMED_WAITING6394 = @__env.GetStaticFieldIDNoThrow(global::java.lang.Thread.State.staticClass, "TIMED_WAITING", "Ljava/lang/Thread$State;");
global::java.lang.Thread.State._TERMINATED6395 = @__env.GetStaticFieldIDNoThrow(global::java.lang.Thread.State.staticClass, "TERMINATED", "Ljava/lang/Thread$State;");
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::java.lang.Thread.UncaughtExceptionHandler_))]
public partial interface UncaughtExceptionHandler : global::MonoJavaBridge.IJavaObject
{
void uncaughtException(java.lang.Thread arg0, java.lang.Throwable arg1);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::java.lang.Thread.UncaughtExceptionHandler))]
internal sealed partial class UncaughtExceptionHandler_ : java.lang.Object, UncaughtExceptionHandler
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal UncaughtExceptionHandler_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
void java.lang.Thread.UncaughtExceptionHandler.uncaughtException(java.lang.Thread arg0, java.lang.Throwable arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.lang.Thread.UncaughtExceptionHandler_.staticClass, "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V", ref global::java.lang.Thread.UncaughtExceptionHandler_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
static UncaughtExceptionHandler_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.lang.Thread.UncaughtExceptionHandler_.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/lang/Thread$UncaughtExceptionHandler"));
}
}
private static global::MonoJavaBridge.MethodId _m0;
public virtual void run()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.lang.Thread.staticClass, "run", "()V", ref global::java.lang.Thread._m0);
}
private static global::MonoJavaBridge.MethodId _m1;
public override global::java.lang.String toString()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.lang.Thread.staticClass, "toString", "()Ljava/lang/String;", ref global::java.lang.Thread._m1) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m2;
public virtual bool isInterrupted()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.lang.Thread.staticClass, "isInterrupted", "()Z", ref global::java.lang.Thread._m2);
}
private static global::MonoJavaBridge.MethodId _m3;
public static global::java.lang.Thread currentThread()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Thread._m3.native == global::System.IntPtr.Zero)
global::java.lang.Thread._m3 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Thread.staticClass, "currentThread", "()Ljava/lang/Thread;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Thread.staticClass, global::java.lang.Thread._m3)) as java.lang.Thread;
}
public new global::java.lang.String Name
{
get
{
return getName();
}
set
{
setName(value);
}
}
private static global::MonoJavaBridge.MethodId _m4;
public virtual global::java.lang.String getName()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.lang.Thread.staticClass, "getName", "()Ljava/lang/String;", ref global::java.lang.Thread._m4) as java.lang.String;
}
public new global::java.lang.ThreadGroup ThreadGroup
{
get
{
return getThreadGroup();
}
}
private static global::MonoJavaBridge.MethodId _m5;
public virtual global::java.lang.ThreadGroup getThreadGroup()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.Thread.staticClass, "getThreadGroup", "()Ljava/lang/ThreadGroup;", ref global::java.lang.Thread._m5) as java.lang.ThreadGroup;
}
public new global::java.lang.StackTraceElement[] StackTrace
{
get
{
return getStackTrace();
}
}
private static global::MonoJavaBridge.MethodId _m6;
public virtual global::java.lang.StackTraceElement[] getStackTrace()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.StackTraceElement>(this, global::java.lang.Thread.staticClass, "getStackTrace", "()[Ljava/lang/StackTraceElement;", ref global::java.lang.Thread._m6) as java.lang.StackTraceElement[];
}
private static global::MonoJavaBridge.MethodId _m7;
public static void dumpStack()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Thread._m7.native == global::System.IntPtr.Zero)
global::java.lang.Thread._m7 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Thread.staticClass, "dumpStack", "()V");
@__env.CallStaticVoidMethod(java.lang.Thread.staticClass, global::java.lang.Thread._m7);
}
private static global::MonoJavaBridge.MethodId _m8;
public virtual void setPriority(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.lang.Thread.staticClass, "setPriority", "(I)V", ref global::java.lang.Thread._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new bool Daemon
{
set
{
setDaemon(value);
}
}
private static global::MonoJavaBridge.MethodId _m9;
public virtual void setDaemon(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.lang.Thread.staticClass, "setDaemon", "(Z)V", ref global::java.lang.Thread._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m10;
public virtual void start()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.lang.Thread.staticClass, "start", "()V", ref global::java.lang.Thread._m10);
}
private static global::MonoJavaBridge.MethodId _m11;
public static void yield()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Thread._m11.native == global::System.IntPtr.Zero)
global::java.lang.Thread._m11 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Thread.staticClass, "yield", "()V");
@__env.CallStaticVoidMethod(java.lang.Thread.staticClass, global::java.lang.Thread._m11);
}
private static global::MonoJavaBridge.MethodId _m12;
public static void sleep(long arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Thread._m12.native == global::System.IntPtr.Zero)
global::java.lang.Thread._m12 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Thread.staticClass, "sleep", "(J)V");
@__env.CallStaticVoidMethod(java.lang.Thread.staticClass, global::java.lang.Thread._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m13;
public static void sleep(long arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Thread._m13.native == global::System.IntPtr.Zero)
global::java.lang.Thread._m13 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Thread.staticClass, "sleep", "(JI)V");
@__env.CallStaticVoidMethod(java.lang.Thread.staticClass, global::java.lang.Thread._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m14;
public virtual void stop()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.lang.Thread.staticClass, "stop", "()V", ref global::java.lang.Thread._m14);
}
private static global::MonoJavaBridge.MethodId _m15;
public virtual void stop(java.lang.Throwable arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.lang.Thread.staticClass, "stop", "(Ljava/lang/Throwable;)V", ref global::java.lang.Thread._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m16;
public virtual void interrupt()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.lang.Thread.staticClass, "interrupt", "()V", ref global::java.lang.Thread._m16);
}
private static global::MonoJavaBridge.MethodId _m17;
public static bool interrupted()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Thread._m17.native == global::System.IntPtr.Zero)
global::java.lang.Thread._m17 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Thread.staticClass, "interrupted", "()Z");
return @__env.CallStaticBooleanMethod(java.lang.Thread.staticClass, global::java.lang.Thread._m17);
}
private static global::MonoJavaBridge.MethodId _m18;
public virtual void destroy()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.lang.Thread.staticClass, "destroy", "()V", ref global::java.lang.Thread._m18);
}
private static global::MonoJavaBridge.MethodId _m19;
public virtual bool isAlive()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.lang.Thread.staticClass, "isAlive", "()Z", ref global::java.lang.Thread._m19);
}
private static global::MonoJavaBridge.MethodId _m20;
public virtual void suspend()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.lang.Thread.staticClass, "suspend", "()V", ref global::java.lang.Thread._m20);
}
private static global::MonoJavaBridge.MethodId _m21;
public virtual void resume()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.lang.Thread.staticClass, "resume", "()V", ref global::java.lang.Thread._m21);
}
public new int Priority
{
get
{
return getPriority();
}
set
{
setPriority(value);
}
}
private static global::MonoJavaBridge.MethodId _m22;
public virtual int getPriority()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.lang.Thread.staticClass, "getPriority", "()I", ref global::java.lang.Thread._m22);
}
private static global::MonoJavaBridge.MethodId _m23;
public virtual void setName(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.lang.Thread.staticClass, "setName", "(Ljava/lang/String;)V", ref global::java.lang.Thread._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m24;
public static int activeCount()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Thread._m24.native == global::System.IntPtr.Zero)
global::java.lang.Thread._m24 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Thread.staticClass, "activeCount", "()I");
return @__env.CallStaticIntMethod(java.lang.Thread.staticClass, global::java.lang.Thread._m24);
}
private static global::MonoJavaBridge.MethodId _m25;
public static int enumerate(java.lang.Thread[] arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Thread._m25.native == global::System.IntPtr.Zero)
global::java.lang.Thread._m25 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Thread.staticClass, "enumerate", "([Ljava/lang/Thread;)I");
return @__env.CallStaticIntMethod(java.lang.Thread.staticClass, global::java.lang.Thread._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m26;
public virtual int countStackFrames()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.lang.Thread.staticClass, "countStackFrames", "()I", ref global::java.lang.Thread._m26);
}
private static global::MonoJavaBridge.MethodId _m27;
public virtual void join()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.lang.Thread.staticClass, "join", "()V", ref global::java.lang.Thread._m27);
}
private static global::MonoJavaBridge.MethodId _m28;
public virtual void join(long arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.lang.Thread.staticClass, "join", "(JI)V", ref global::java.lang.Thread._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m29;
public virtual void join(long arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.lang.Thread.staticClass, "join", "(J)V", ref global::java.lang.Thread._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m30;
public virtual bool isDaemon()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.lang.Thread.staticClass, "isDaemon", "()Z", ref global::java.lang.Thread._m30);
}
private static global::MonoJavaBridge.MethodId _m31;
public virtual void checkAccess()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.lang.Thread.staticClass, "checkAccess", "()V", ref global::java.lang.Thread._m31);
}
public new global::java.lang.ClassLoader ContextClassLoader
{
get
{
return getContextClassLoader();
}
set
{
setContextClassLoader(value);
}
}
private static global::MonoJavaBridge.MethodId _m32;
public virtual global::java.lang.ClassLoader getContextClassLoader()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.Thread.staticClass, "getContextClassLoader", "()Ljava/lang/ClassLoader;", ref global::java.lang.Thread._m32) as java.lang.ClassLoader;
}
private static global::MonoJavaBridge.MethodId _m33;
public virtual void setContextClassLoader(java.lang.ClassLoader arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.lang.Thread.staticClass, "setContextClassLoader", "(Ljava/lang/ClassLoader;)V", ref global::java.lang.Thread._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m34;
public static bool holdsLock(java.lang.Object arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Thread._m34.native == global::System.IntPtr.Zero)
global::java.lang.Thread._m34 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Thread.staticClass, "holdsLock", "(Ljava/lang/Object;)Z");
return @__env.CallStaticBooleanMethod(java.lang.Thread.staticClass, global::java.lang.Thread._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public static global::java.util.Map AllStackTraces
{
get
{
return getAllStackTraces();
}
}
private static global::MonoJavaBridge.MethodId _m35;
public static global::java.util.Map getAllStackTraces()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Thread._m35.native == global::System.IntPtr.Zero)
global::java.lang.Thread._m35 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Thread.staticClass, "getAllStackTraces", "()Ljava/util/Map;");
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Map>(@__env.CallStaticObjectMethod(java.lang.Thread.staticClass, global::java.lang.Thread._m35)) as java.util.Map;
}
public new long Id
{
get
{
return getId();
}
}
private static global::MonoJavaBridge.MethodId _m36;
public virtual long getId()
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.lang.Thread.staticClass, "getId", "()J", ref global::java.lang.Thread._m36);
}
private static global::MonoJavaBridge.MethodId _m37;
public virtual global::java.lang.Thread.State getState()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.Thread.State>(this, global::java.lang.Thread.staticClass, "getState", "()Ljava/lang/Thread$State;", ref global::java.lang.Thread._m37) as java.lang.Thread.State;
}
private static global::MonoJavaBridge.MethodId _m38;
public static void setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Thread._m38.native == global::System.IntPtr.Zero)
global::java.lang.Thread._m38 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Thread.staticClass, "setDefaultUncaughtExceptionHandler", "(Ljava/lang/Thread$UncaughtExceptionHandler;)V");
@__env.CallStaticVoidMethod(java.lang.Thread.staticClass, global::java.lang.Thread._m38, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public static global::java.lang.Thread.UncaughtExceptionHandler DefaultUncaughtExceptionHandler
{
get
{
return getDefaultUncaughtExceptionHandler();
}
set
{
setDefaultUncaughtExceptionHandler(value);
}
}
private static global::MonoJavaBridge.MethodId _m39;
public static global::java.lang.Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Thread._m39.native == global::System.IntPtr.Zero)
global::java.lang.Thread._m39 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Thread.staticClass, "getDefaultUncaughtExceptionHandler", "()Ljava/lang/Thread$UncaughtExceptionHandler;");
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.Thread.UncaughtExceptionHandler>(@__env.CallStaticObjectMethod(java.lang.Thread.staticClass, global::java.lang.Thread._m39)) as java.lang.Thread.UncaughtExceptionHandler;
}
private static global::MonoJavaBridge.MethodId _m40;
public virtual global::java.lang.Thread.UncaughtExceptionHandler getUncaughtExceptionHandler()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.lang.Thread.UncaughtExceptionHandler>(this, global::java.lang.Thread.staticClass, "getUncaughtExceptionHandler", "()Ljava/lang/Thread$UncaughtExceptionHandler;", ref global::java.lang.Thread._m40) as java.lang.Thread.UncaughtExceptionHandler;
}
private static global::MonoJavaBridge.MethodId _m41;
public virtual void setUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.lang.Thread.staticClass, "setUncaughtExceptionHandler", "(Ljava/lang/Thread$UncaughtExceptionHandler;)V", ref global::java.lang.Thread._m41, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m42;
public Thread(java.lang.ThreadGroup arg0, java.lang.Runnable arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Thread._m42.native == global::System.IntPtr.Zero)
global::java.lang.Thread._m42 = @__env.GetMethodIDNoThrow(global::java.lang.Thread.staticClass, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/Runnable;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.Thread.staticClass, global::java.lang.Thread._m42, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m43;
public Thread(java.lang.ThreadGroup arg0, java.lang.Runnable arg1, java.lang.String arg2, long arg3) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Thread._m43.native == global::System.IntPtr.Zero)
global::java.lang.Thread._m43 = @__env.GetMethodIDNoThrow(global::java.lang.Thread.staticClass, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/Runnable;Ljava/lang/String;J)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.Thread.staticClass, global::java.lang.Thread._m43, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m44;
public Thread(java.lang.ThreadGroup arg0, java.lang.Runnable arg1, java.lang.String arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Thread._m44.native == global::System.IntPtr.Zero)
global::java.lang.Thread._m44 = @__env.GetMethodIDNoThrow(global::java.lang.Thread.staticClass, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/Runnable;Ljava/lang/String;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.Thread.staticClass, global::java.lang.Thread._m44, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m45;
public Thread(java.lang.Runnable arg0, java.lang.String arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Thread._m45.native == global::System.IntPtr.Zero)
global::java.lang.Thread._m45 = @__env.GetMethodIDNoThrow(global::java.lang.Thread.staticClass, "<init>", "(Ljava/lang/Runnable;Ljava/lang/String;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.Thread.staticClass, global::java.lang.Thread._m45, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m46;
public Thread(java.lang.Runnable arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Thread._m46.native == global::System.IntPtr.Zero)
global::java.lang.Thread._m46 = @__env.GetMethodIDNoThrow(global::java.lang.Thread.staticClass, "<init>", "(Ljava/lang/Runnable;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.Thread.staticClass, global::java.lang.Thread._m46, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m47;
public Thread(java.lang.ThreadGroup arg0, java.lang.String arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Thread._m47.native == global::System.IntPtr.Zero)
global::java.lang.Thread._m47 = @__env.GetMethodIDNoThrow(global::java.lang.Thread.staticClass, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.Thread.staticClass, global::java.lang.Thread._m47, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m48;
public Thread(java.lang.String arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Thread._m48.native == global::System.IntPtr.Zero)
global::java.lang.Thread._m48 = @__env.GetMethodIDNoThrow(global::java.lang.Thread.staticClass, "<init>", "(Ljava/lang/String;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.Thread.staticClass, global::java.lang.Thread._m48, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m49;
public Thread() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Thread._m49.native == global::System.IntPtr.Zero)
global::java.lang.Thread._m49 = @__env.GetMethodIDNoThrow(global::java.lang.Thread.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.Thread.staticClass, global::java.lang.Thread._m49);
Init(@__env, handle);
}
public static int MIN_PRIORITY
{
get
{
return 1;
}
}
public static int NORM_PRIORITY
{
get
{
return 5;
}
}
public static int MAX_PRIORITY
{
get
{
return 10;
}
}
static Thread()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.lang.Thread.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/lang/Thread"));
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Controls.dll
// Description: The Windows Forms user interface controls like the map, legend, toolbox, ribbon and others.
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 4/4/2009 11:52:50 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using DotSpatial.Data;
using DotSpatial.Serialization;
using DotSpatial.Symbology;
namespace DotSpatial.Controls
{
public class MapGroup : Group, IMapGroup
{
/// <summary>
/// Overrides the base CreateGroup method to ensure that new groups are GeoGroups.
/// </summary>
protected override void OnCreateGroup()
{
new MapGroup(Layers, ParentMapFrame, ProgressHandler) {LegendText = "New Group"};
}
#region Nested type: MapLayerEnumerator
/// <summary>
/// Transforms an IMapLayer enumerator into an ILayer Enumerator
/// </summary>
public class MapLayerEnumerator : IEnumerator<ILayer>
{
private readonly IEnumerator<IMapLayer> _enumerator;
/// <summary>
/// Creates a new instance of the MapLayerEnumerator
/// </summary>
/// <param name="subEnumerator"></param>
public MapLayerEnumerator(IEnumerator<IMapLayer> subEnumerator)
{
_enumerator = subEnumerator;
}
#region IEnumerator<ILayer> Members
/// <inheritdoc />
public ILayer Current
{
get { return _enumerator.Current; }
}
/// <inheritdoc />
public void Dispose()
{
_enumerator.Dispose();
}
object IEnumerator.Current
{
get { return _enumerator.Current; }
}
/// <inheritdoc />
public bool MoveNext()
{
return _enumerator.MoveNext();
}
/// <inheritdoc />
public void Reset()
{
_enumerator.Reset();
}
#endregion
}
#endregion
#region Private Variables
private IMapLayerCollection _layers;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of GeoGroup
/// </summary>
public MapGroup()
{
Layers = new MapLayerCollection();
}
/// <summary>
/// Creates a new group for the specified map. This will place the group at the root level on the MapFrame.
/// </summary>
/// <param name="map">The map to add this group to.</param>
/// <param name="name">The name to appear in the legend text.</param>
public MapGroup(IMap map, string name)
: base(map.MapFrame, map.ProgressHandler)
{
Layers = new MapLayerCollection(map.MapFrame, this, map.ProgressHandler);
base.LegendText = name;
map.Layers.Add(this);
}
/// <summary>
/// Creates a group that sits in a layer list and uses the specified progress handler
/// </summary>
/// <param name="container">the layer list</param>
/// <param name="frame"></param>
/// <param name="progressHandler">the progress handler</param>
public MapGroup(ICollection<IMapLayer> container, IMapFrame frame, IProgressHandler progressHandler)
: base(frame, progressHandler)
{
Layers = new MapLayerCollection(frame, this, progressHandler);
container.Add(this);
}
#endregion
#region Methods
/// <inheritdoc />
public override int IndexOf(ILayer item)
{
IMapLayer ml = item as IMapLayer;
if (ml != null)
{
return _layers.IndexOf(ml);
}
return -1;
}
/// <inheritdoc />
public override void Add(ILayer layer)
{
IMapLayer ml = layer as IMapLayer;
if (ml != null)
{
_layers.Add(ml);
}
}
/// <inheritdoc />
public override bool Remove(ILayer layer)
{
IMapLayer ml = layer as IMapLayer;
return ml != null && _layers.Remove(ml);
}
/// <inheritdoc />
public override void RemoveAt(int index)
{
_layers.RemoveAt(index);
}
/// <inheritdoc />
public override void Insert(int index, ILayer layer)
{
IMapLayer ml = layer as IMapLayer;
if (ml != null)
{
_layers.Insert(index, ml);
}
}
/// <inheritdoc />
public override ILayer this[int index]
{
get
{
return _layers[index];
}
set
{
IMapLayer ml = value as IMapLayer;
_layers[index] = ml;
}
}
/// <inheritdoc />
public override void Clear()
{
_layers.Clear();
}
/// <inheritdoc />
public override bool Contains(ILayer item)
{
IMapLayer ml = item as IMapLayer;
return ml != null && _layers.Contains(ml);
}
/// <inheritdoc />
public override void CopyTo(ILayer[] array, int arrayIndex)
{
for (int i = 0; i < Layers.Count; i++)
{
array[i + arrayIndex] = _layers[i];
}
}
/// <inheritdoc />
public override int Count
{
get { return _layers.Count; }
}
/// <inheritdoc />
public override bool IsReadOnly
{
get { return _layers.IsReadOnly; }
}
/// <inheritdoc />
public override void SuspendEvents()
{
_layers.SuspendEvents();
}
/// <inheritdoc />
public override void ResumeEvents()
{
_layers.ResumeEvents();
}
/// <inheritdoc />
public override bool EventsSuspended
{
get { return _layers.EventsSuspended; }
}
/// <inheritdoc />
public override IEnumerator<ILayer> GetEnumerator()
{
return new MapLayerEnumerator(_layers.GetEnumerator());
}
/// <inheritdoc />
IEnumerator IEnumerable.GetEnumerator()
{
return _layers.GetEnumerator();
}
/// <summary>
/// This draws content from the specified geographic regions onto the specified graphics
/// object specified by MapArgs.
/// </summary>
public void DrawRegions(MapArgs args, List<Extent> regions)
{
if (Layers == null) return;
foreach (IMapLayer layer in Layers)
{
if (!layer.IsVisible) continue;
if (layer.UseDynamicVisibility)
{
if (layer.DynamicVisibilityMode == DynamicVisibilityMode.ZoomedIn)
{
if (MapFrame.ViewExtents.Width > layer.DynamicVisibilityWidth)
{
continue; // skip the geoLayer if we are zoomed out too far.
}
}
else
{
if (MapFrame.ViewExtents.Width < layer.DynamicVisibilityWidth)
{
continue; // skip the geoLayer if we are zoomed in too far.
}
}
}
layer.DrawRegions(args, regions);
}
}
#endregion
#region Properties
/// <summary>
/// Gets the collection of Geographic drawing layers.
/// </summary>
/// <summary>
/// Gets or sets the layers
/// </summary>
[Serialize("Layers")]
public new IMapLayerCollection Layers
{
get { return _layers; }
set
{
if (Layers != null)
{
Ignore_Layer_Events(_layers);
}
Handle_Layer_Events(value);
_layers = value;
//set the MapFrame property
if (ParentMapFrame != null)
{
_layers.MapFrame = ParentMapFrame;
}
}
}
/// <inheritdoc />
public override IFrame MapFrame
{
get { return base.MapFrame; }
set
{
base.MapFrame = value;
if (_layers != null)
{
IMapFrame newValue = value as IMapFrame;
if (newValue != null && _layers.MapFrame == null)
{
_layers.MapFrame = newValue;
}
}
}
}
/// <summary>
/// Gets the layers cast as ILayer without any information about the actual drawing methods.
/// This is useful for handling methods that my come from various types of maps.
/// </summary>
/// <returns>An enumerable collection of ILayer</returns>
public override IList<ILayer> GetLayers()
{
return _layers.Cast<ILayer>().ToList();
}
/// <summary>
/// Gets the MapFrame that this group ultimately belongs to. This may not
/// be the immediate parent of this group.
/// </summary>
public IMapFrame ParentMapFrame
{
get { return MapFrame as IMapFrame; }
set { MapFrame = value; }
}
/// <summary>
/// This is a different view of the layers cast as legend items. This allows
/// easier cycling in recursive legend code.
/// </summary>
public override IEnumerable<ILegendItem> LegendItems
{
get
{
// Keep cast for 3.5 framework
return _layers.Cast<ILegendItem>();
}
}
#endregion
}
}
| |
/*
* Qa full api
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: all
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace HostMe.Sdk.Model
{
/// <summary>
/// RedeemRequest
/// </summary>
[DataContract]
public partial class RedeemRequest : IEquatable<RedeemRequest>, IValidatableObject
{
/// <summary>
/// Gets or Sets Status
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum StatusEnum
{
/// <summary>
/// Enum Submited for "Submited"
/// </summary>
[EnumMember(Value = "Submited")]
Submited,
/// <summary>
/// Enum Approved for "Approved"
/// </summary>
[EnumMember(Value = "Approved")]
Approved,
/// <summary>
/// Enum Rejected for "Rejected"
/// </summary>
[EnumMember(Value = "Rejected")]
Rejected
}
/// <summary>
/// Gets or Sets Status
/// </summary>
[DataMember(Name="status", EmitDefaultValue=true)]
public StatusEnum? Status { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="RedeemRequest" /> class.
/// </summary>
/// <param name="Id">Id.</param>
/// <param name="Submited">Submited.</param>
/// <param name="Status">Status.</param>
/// <param name="StatusComment">StatusComment.</param>
/// <param name="Closed">Closed.</param>
/// <param name="RewardId">RewardId.</param>
/// <param name="TableNumber">TableNumber.</param>
/// <param name="MemberInfo">MemberInfo.</param>
/// <param name="RewardDetails">RewardDetails.</param>
public RedeemRequest(string Id = null, DateTimeOffset? Submited = null, StatusEnum? Status = null, string StatusComment = null, DateTimeOffset? Closed = null, string RewardId = null, string TableNumber = null, Member MemberInfo = null, RewardInfo RewardDetails = null)
{
this.Id = Id;
this.Submited = Submited;
this.Status = Status;
this.StatusComment = StatusComment;
this.Closed = Closed;
this.RewardId = RewardId;
this.TableNumber = TableNumber;
this.MemberInfo = MemberInfo;
this.RewardDetails = RewardDetails;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=true)]
public string Id { get; set; }
/// <summary>
/// Gets or Sets Submited
/// </summary>
[DataMember(Name="submited", EmitDefaultValue=true)]
public DateTimeOffset? Submited { get; set; }
/// <summary>
/// Gets or Sets StatusComment
/// </summary>
[DataMember(Name="statusComment", EmitDefaultValue=true)]
public string StatusComment { get; set; }
/// <summary>
/// Gets or Sets Closed
/// </summary>
[DataMember(Name="closed", EmitDefaultValue=true)]
public DateTimeOffset? Closed { get; set; }
/// <summary>
/// Gets or Sets RewardId
/// </summary>
[DataMember(Name="rewardId", EmitDefaultValue=true)]
public string RewardId { get; set; }
/// <summary>
/// Gets or Sets TableNumber
/// </summary>
[DataMember(Name="tableNumber", EmitDefaultValue=true)]
public string TableNumber { get; set; }
/// <summary>
/// Gets or Sets MemberInfo
/// </summary>
[DataMember(Name="memberInfo", EmitDefaultValue=true)]
public Member MemberInfo { get; set; }
/// <summary>
/// Gets or Sets RewardDetails
/// </summary>
[DataMember(Name="rewardDetails", EmitDefaultValue=true)]
public RewardInfo RewardDetails { 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 RedeemRequest {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Submited: ").Append(Submited).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" StatusComment: ").Append(StatusComment).Append("\n");
sb.Append(" Closed: ").Append(Closed).Append("\n");
sb.Append(" RewardId: ").Append(RewardId).Append("\n");
sb.Append(" TableNumber: ").Append(TableNumber).Append("\n");
sb.Append(" MemberInfo: ").Append(MemberInfo).Append("\n");
sb.Append(" RewardDetails: ").Append(RewardDetails).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as RedeemRequest);
}
/// <summary>
/// Returns true if RedeemRequest instances are equal
/// </summary>
/// <param name="other">Instance of RedeemRequest to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(RedeemRequest other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.Submited == other.Submited ||
this.Submited != null &&
this.Submited.Equals(other.Submited)
) &&
(
this.Status == other.Status ||
this.Status != null &&
this.Status.Equals(other.Status)
) &&
(
this.StatusComment == other.StatusComment ||
this.StatusComment != null &&
this.StatusComment.Equals(other.StatusComment)
) &&
(
this.Closed == other.Closed ||
this.Closed != null &&
this.Closed.Equals(other.Closed)
) &&
(
this.RewardId == other.RewardId ||
this.RewardId != null &&
this.RewardId.Equals(other.RewardId)
) &&
(
this.TableNumber == other.TableNumber ||
this.TableNumber != null &&
this.TableNumber.Equals(other.TableNumber)
) &&
(
this.MemberInfo == other.MemberInfo ||
this.MemberInfo != null &&
this.MemberInfo.Equals(other.MemberInfo)
) &&
(
this.RewardDetails == other.RewardDetails ||
this.RewardDetails != null &&
this.RewardDetails.Equals(other.RewardDetails)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.Submited != null)
hash = hash * 59 + this.Submited.GetHashCode();
if (this.Status != null)
hash = hash * 59 + this.Status.GetHashCode();
if (this.StatusComment != null)
hash = hash * 59 + this.StatusComment.GetHashCode();
if (this.Closed != null)
hash = hash * 59 + this.Closed.GetHashCode();
if (this.RewardId != null)
hash = hash * 59 + this.RewardId.GetHashCode();
if (this.TableNumber != null)
hash = hash * 59 + this.TableNumber.GetHashCode();
if (this.MemberInfo != null)
hash = hash * 59 + this.MemberInfo.GetHashCode();
if (this.RewardDetails != null)
hash = hash * 59 + this.RewardDetails.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
[CustomEditor(typeof(LevelAsset))]
public class LevelAssetEditor : UnityEditor.Editor {
GUISkin skin;
bool showGrid = true, showHex = true, showPathPreset = true, showBasePreset = true;
Vector2 gridSelection = new Vector2(-1, -1);
float pathHeight = 1, baseHeight = 0;
int pathColor = 1, baseColor = 0;
Texture2D hexBackTex;
Texture2D hexInnerTex;
Texture2D[] hexSegmentTexs = new Texture2D[6];
Rect gridShowRect;
Rect gridRect;
int hexSize = 50;
int nextPathPoint = 0;
[MenuItem("Assets/Create/LevelAsset")]
public static void CreateAsset ()
{
ScriptableObjectUtility.CreateAsset<LevelAsset> ();
}
public override void OnInspectorGUI() {
if(skin == null)
skin = EditorGUIUtility.Load("LevelEditorSkin.guiskin") as GUISkin;
if(hexBackTex == null)
hexBackTex = EditorGUIUtility.Load("Textures/hexagon_back.png") as Texture2D;
if(hexInnerTex == null)
hexInnerTex = EditorGUIUtility.Load("Textures/hexagon_inner.png") as Texture2D;
for(int i = 0; i < 6; i++)
{
if(hexSegmentTexs[i] == null)
hexSegmentTexs[i] = EditorGUIUtility.Load("Textures/hexagon_" + i + ".png") as Texture2D;
}
//let the default inspector handle the easy stuff
DrawDefaultInspector();
LevelAsset level = target as LevelAsset;
//make sure that the grid is the correct size, also initiallizes any nulls
if(level.grid == null || level.grid.Count != level.gridHeight || (level.grid.Count != 0 && level.grid[0].Count != level.gridWidth))
{
level.grid = createGrid(level.gridWidth, level.gridHeight, level.grid);
}
//grid editor
showGrid = EditorGUILayout.Foldout(showGrid, "Grid");
if( Event.current.type == EventType.Repaint )
gridShowRect = GUILayoutUtility.GetLastRect();
if(showGrid)
{
if(level.grid != null && level.grid.Count == level.gridHeight && level.grid.Count > 0 && level.grid[0].Count == level.gridWidth)
{
gridRect = new Rect(gridShowRect.x, gridShowRect.yMax, hexSize * level.gridHeight, hexSize * level.gridWidth);
gridSelection = hexGrid(gridSelection, level, hexSize, gridRect);
//GUILayout.Space(level.gridHeight * hexSize);
}
else
{
GUILayout.Label("Grid size changed, recreate grid");
}
}
//next path point
GUILayout.BeginHorizontal();
GUILayout.Label("Next Path ID");
nextPathPoint = EditorGUILayout.IntField(nextPathPoint);
GUILayout.EndHorizontal();
//grid selection editor, changes HexInfo values for selected cell
if(gridSelection.x != -1 && level.grid.Count != 0 && level.grid[0].Count != 0)
{
showHex = EditorGUILayout.Foldout(showHex, "Hex " + gridSelection.ToString());
if(showHex && gridSelection.y < level.grid.Count && gridSelection.x < level.grid[0].Count)
{
hexEditor(level.grid[(int)gridSelection.y][(int)gridSelection.x]);
}
}
//preset menu for base cells
showBasePreset = EditorGUILayout.Foldout(showBasePreset, "Base Preset");
if(showBasePreset)
{
GUILayout.BeginHorizontal();
GUILayout.Space(15);
GUILayout.BeginVertical();
GUILayout.Label("Color");
GUILayout.Label("Height");
GUILayout.EndVertical();
GUILayout.BeginVertical();
baseColor = EditorGUILayout.IntField(baseColor);
baseHeight = EditorGUILayout.FloatField(baseHeight);
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
//preset menu for path cells
showPathPreset = EditorGUILayout.Foldout(showPathPreset, "Path Preset");
if(showPathPreset)
{
GUILayout.BeginHorizontal();
GUILayout.Space(15);
GUILayout.BeginVertical();
GUILayout.Label("Color");
GUILayout.Label("Height");
GUILayout.EndVertical();
GUILayout.BeginVertical();
pathColor = EditorGUILayout.IntField(pathColor);
pathHeight = EditorGUILayout.FloatField(pathHeight);
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
//tells the editor to save the changes to disk
EditorUtility.SetDirty(level);
}
//custom element to display the hex grid as toggle buttons and return the selection
Vector2 hexGrid (Vector2 selection, LevelAsset level, int hexSize, Rect gridRect)
{
GUILayout.BeginVertical();
for(int y = 0; y < level.gridHeight; y++)
{
GUILayout.BeginHorizontal();
if(y % 2 == 1)
GUILayout.Space(hexSize / 2);
for(int x = 0; x < level.gridWidth; x++)
{
Rect hexRect = new Rect(gridRect.x + x * hexSize + (y%2 == 1 ? hexSize / 2 : 0), gridRect.y + y * hexSize, hexSize, hexSize);
if(level.grid[y][x] == null)
level.grid[y][x] = new HexInfo(x,y);
if(level.grid[y][x].pathId >= nextPathPoint)
nextPathPoint = level.grid[y][x].pathId + 1;
if(hexDisplay((x == selection.x && y == selection.y), level, level.grid[y][x], hexSize, hexRect))
selection = new Vector2(x,y);
}
if(y % 2 == 0)
GUILayout.Space(hexSize / 2);
GUILayout.EndHorizontal();
}
GUILayout.EndVertical();
return selection;
}
//custom element to display the hex in the grid
//provides more buttons for the selected cell
bool hexDisplay(bool toggle, LevelAsset level, HexInfo hex, int hexSize, Rect hexRect)
{
//if not toggled, display empty hex with info
if(!toggle)
{
Color tempColor = GUI.backgroundColor;
Color color;
if(level.colors != null && hex.color < level.colors.Length)
color = level.colors[hex.color];
else
color = Color.white;
color.a = 1;
GUI.backgroundColor = color;
string content = "" + hex.pathId;
toggle = GUILayout.Toggle(toggle, content, skin.customStyles[0], GUILayout.Height(hexSize), GUILayout.Width(hexSize));
GUI.backgroundColor = tempColor;
}
//if it is toggled, display the more complex button
else
{
GUILayout.Space(hexSize);
//path gui contains the toggle in the center and toggles for next positions on each edge
if(hex.path)
{
Color tempColor = GUI.color;
Color color;
if(level.colors != null && hex.color < level.colors.Length)
color = level.colors[hex.color];
else
color = Color.white;
color.a = 1;
GUI.color = color;
GUI.DrawTexture(hexRect, hexBackTex);
//bool result = GUI.Button(hexRect, hexBack, skin.customStyles[0]);
if( alphaButton(hexRect, hexInnerTex))
{
setBase(hex);
}
Vector2[] pathPoints = (((int)hex.position.y) % 2) == 0 ? HexInfo.pathPointsEven : HexInfo.pathPointsOdd;
//draw each segment button
for(int i = 0; i < 6; i++)
{
bool active = ((hex.nextPositions & (1 << i)) != 0);
bool result = alphaToggle(active, hexRect, hexSegmentTexs[i]);
if(active && !result)
{
hex.nextPositions = (byte)(hex.nextPositions & (~ (1 <<i)));
}
else if(!active && result)
{
hex.nextPositions = (byte)(hex.nextPositions | (byte)(1 << i));
Vector2 next = hex.position + pathPoints[i];
if(next.x >= 0 && next.y >=0 && next.x < level.gridWidth && next.y < level.gridHeight && !level.grid[(int)next.y][(int)next.x].path)
setPath(level.grid[(int)next.y][(int)next.x]);
}
}
GUI.color = tempColor;
GUI.Label(hexRect, "" + hex.pathId, skin.label);
}
//base gui only contains the toggle in the center
else
{
Color tempColor = GUI.color;
Color color;
if(level.colors != null && hex.color < level.colors.Length)
color = level.colors[hex.color];
else
color = Color.white;
color.a = 1;
GUI.color = color;
GUI.DrawTexture(hexRect, hexBackTex);
//bool result = GUI.Button(hexRect, hexBack, skin.customStyles[0]);
if( alphaButton(hexRect, hexInnerTex))
{
setPath(hex);
}
GUI.color = tempColor;
GUI.Label(hexRect, "" + hex.pathId, skin.label);
}
}
return toggle;
}
public bool alphaButton(Rect rect, Texture2D image)
{
Vector2 relativeClick;
bool result = false;
if( Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition) )
{
//relativeClick = new Vector2( Event.current.mousePosition.x - backRect.x, Event.current.mousePosition.y - backRect.y );
relativeClick = new Vector2(Event.current.mousePosition.x - rect.x, (rect.y + rect.height) - Event.current.mousePosition.y);
relativeClick *= image.width / rect.width;
result = (image.GetPixel((int)relativeClick.x, (int)relativeClick.y).a > .5f);
//Debug.Log(relativeClick);
}
GUI.DrawTexture(rect, image);
return result;
}
public bool alphaToggle(bool toggle, Rect rect, Texture2D image)
{
Color oldColor = GUI.color;
if(toggle)
{
Color newColor = new Color(oldColor.r - .2f, oldColor.g - .2f, oldColor.b - .2f, oldColor.a);
GUI.color = newColor;
}
if(alphaButton(rect, image))
toggle = !toggle;
GUI.color = oldColor;
return toggle;
}
//custom editor for HexInfo values
void hexEditor(HexInfo hex)
{
if(hex != null)
{
GUILayout.BeginHorizontal();
GUILayout.Space(15);
GUILayout.BeginVertical();
GUILayout.Label("Color");
GUILayout.Label("Height");
GUILayout.Label("Path");
GUILayout.Label("Path ID");
GUILayout.Label("Start");
GUILayout.Label("End");
GUILayout.EndVertical();
GUILayout.BeginVertical();
hex.color = EditorGUILayout.IntField(hex.color);
hex.height = EditorGUILayout.FloatField(hex.height);
hex.path = EditorGUILayout.Toggle(hex.path);
hex.pathId = EditorGUILayout.IntField(hex.pathId);
hex.start = EditorGUILayout.Toggle(hex.start);
hex.end = EditorGUILayout.Toggle(hex.end);
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
}
//updates the grid to reflect changes in size, fills in new spaces
List<GridRow> createGrid(int w, int h, List<GridRow> oldGrid)
{
List<GridRow> newGrid = new List<GridRow>();
for(int y = 0; y < h; y++)
{
//newGrid.Add(CreateInstance<GridRow>());
newGrid.Add(new GridRow());
for(int x = 0; x < w; x++)
{
if(oldGrid != null && y < oldGrid.Count && x < oldGrid[y].Count)
newGrid[y].Add(oldGrid[y][x]);
else
//newGrid[y].Add(CreateInstance<HexInfo>());
newGrid[y].Add(new HexInfo(x,y));
}
}
return newGrid;
}
void setBase(HexInfo hex)
{
hex.color = hex.path ? baseColor : pathColor;
hex.height = hex.path ? baseHeight : pathHeight;
hex.path = !hex.path;
hex.pathId = 0;
nextPathPoint--;
hex.nextPositions = 0; //new List<Vector2>();
}
void setPath(HexInfo hex)
{
hex.color = hex.path ? baseColor : pathColor;
hex.height = hex.path ? baseHeight : pathHeight;
hex.path = !hex.path;
hex.pathId = nextPathPoint;
nextPathPoint++;
}
}
| |
// 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<
Roslyn.Diagnostics.Analyzers.DoNotMixAttributesFromDifferentVersionsOfMEFAnalyzer,
Roslyn.Diagnostics.CSharp.Analyzers.CSharpDoNotMixAttributesFromDifferentVersionsOfMEFFixer>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Roslyn.Diagnostics.Analyzers.DoNotMixAttributesFromDifferentVersionsOfMEFAnalyzer,
Roslyn.Diagnostics.VisualBasic.Analyzers.BasicDoNotMixAttributesFromDifferentVersionsOfMEFFixer>;
namespace Roslyn.Diagnostics.Analyzers.UnitTests
{
public class DoNotMixAttributesFromDifferentVersionsOfMEFTests
{
private const string CSharpWellKnownAttributesDefinition = @"
namespace System.Composition
{
public class ExportAttribute : System.Attribute
{
public ExportAttribute(System.Type contractType){ }
}
public class MetadataAttributeAttribute : System.Attribute
{
public MetadataAttributeAttribute() { }
}
public class ImportAttribute : System.Attribute
{
public ImportAttribute() { }
}
public class ImportingConstructorAttribute : System.Attribute
{
public ImportingConstructorAttribute() { }
}
}
[System.Composition.MetadataAttribute]
public class SystemCompositionMetadataAttribute : System.Attribute
{
public class ExportAttribute : System.Attribute
{
public ExportAttribute(System.Type contractType){ }
}
public class MetadataAttributeAttribute : System.Attribute
{
public MetadataAttributeAttribute() { }
}
public class ImportAttribute : System.Attribute
{
public ImportAttribute() { }
}
public class ImportingConstructorAttribute : System.Attribute
{
public ImportingConstructorAttribute() { }
}
}
namespace System.ComponentModel.Composition
{
public class ExportAttribute : System.Attribute
{
public ExportAttribute(System.Type contractType){ }
}
public class MetadataAttributeAttribute : System.Attribute
{
public MetadataAttributeAttribute() { }
}
public class ImportAttribute : System.Attribute
{
public ImportAttribute() { }
}
public class ImportingConstructorAttribute : System.Attribute
{
public ImportingConstructorAttribute() { }
}
}
[System.ComponentModel.Composition.MetadataAttribute]
public class SystemComponentModelCompositionMetadataAttribute : System.Attribute
{
}
";
private const string BasicWellKnownAttributesDefinition = @"
Namespace System.Composition
Public Class ExportAttribute
Inherits System.Attribute
Public Sub New(contractType As System.Type)
End Sub
End Class
Public Class MetadataAttributeAttribute
Inherits System.Attribute
Public Sub New()
End Sub
End Class
Public Class ImportAttribute
Inherits System.Attribute
Public Sub New()
End Sub
End Class
Public Class ImportingConstructorAttribute
Inherits System.Attribute
Public Sub New()
End Sub
End Class
End Namespace
<System.Composition.MetadataAttribute> _
Public Class SystemCompositionMetadataAttribute
Inherits System.Attribute
End Class
Namespace System.ComponentModel.Composition
Public Class ExportAttribute
Inherits System.Attribute
Public Sub New(contractType As System.Type)
End Sub
End Class
Public Class MetadataAttributeAttribute
Inherits System.Attribute
Public Sub New()
End Sub
End Class
Public Class ImportAttribute
Inherits System.Attribute
Public Sub New()
End Sub
End Class
Public Class ImportingConstructorAttribute
Inherits System.Attribute
Public Sub New()
End Sub
End Class
End Namespace
<System.ComponentModel.Composition.MetadataAttribute> _
Public Class SystemComponentModelCompositionMetadataAttribute
Inherits System.Attribute
End Class
";
#region No Diagnostic Tests
[Fact]
public async Task NoDiagnosticCases_SingleMefAttribute()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
[System.Composition.Export(typeof(C))]
public class C
{
}
[System.ComponentModel.Composition.Export(typeof(C2))]
public class C2
{
}
" + CSharpWellKnownAttributesDefinition);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
<System.Composition.Export(GetType(C))> _
Public Class C
End Class
<System.ComponentModel.Composition.Export(GetType(C2))> _
Public Class C2
End Class
" + BasicWellKnownAttributesDefinition);
}
[Fact]
public async Task NoDiagnosticCases_SingleMefAttributeAndValidMetadataAttribute()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
[System.Composition.Export(typeof(C))]
[SystemCompositionMetadataAttribute]
public class C
{
}
[System.ComponentModel.Composition.Export(typeof(C2))]
[SystemComponentModelCompositionMetadataAttribute]
public class C2
{
}
" + CSharpWellKnownAttributesDefinition);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
<System.Composition.Export(GetType(C))> _
<SystemCompositionMetadataAttribute> _
Public Class C
End Class
<System.ComponentModel.Composition.Export(GetType(C2))> _
<SystemComponentModelCompositionMetadataAttribute> _
Public Class C2
End Class
" + BasicWellKnownAttributesDefinition);
}
[Fact]
public async Task NoDiagnosticCases_SingleMefAttributeAndAnotherExportAttribute()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
[System.Composition.Export(typeof(C)), MyNamespace.Export(typeof(C))]
public class C
{
}
[System.ComponentModel.Composition.Export(typeof(C2)), MyNamespace.Export(typeof(C2))]
public class C2
{
}
namespace MyNamespace
{
public class ExportAttribute : System.Attribute
{
public ExportAttribute(System.Type contractType){ }
}
}
" + CSharpWellKnownAttributesDefinition);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
<System.Composition.Export(GetType(C)), MyNamespace.Export(GetType(C))> _
Public Class C
End Class
<System.ComponentModel.Composition.Export(GetType(C2)), MyNamespace.Export(GetType(C2))> _
Public Class C2
End Class
Namespace MyNamespace
Public Class ExportAttribute
Inherits System.Attribute
Public Sub New(contractType As System.Type)
End Sub
End Class
End Namespace
" + BasicWellKnownAttributesDefinition);
}
[Fact]
public async Task NoDiagnosticCases_SingleMefAttributeOnTypeAndValidMefAttributeOnMember()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
public class B { }
[System.Composition.Export(typeof(C))]
public class C
{
[System.Composition.ImportingConstructor]
public C([System.Composition.Import]B b) { }
[System.Composition.Import]
public B PropertyB { get; }
}
[System.ComponentModel.Composition.Export(typeof(C2))]
public class C2
{
[System.ComponentModel.Composition.ImportingConstructor]
public C2([System.ComponentModel.Composition.Import]B b) { }
[System.ComponentModel.Composition.Import]
public B PropertyB { get; }
}
" + CSharpWellKnownAttributesDefinition);
await VerifyVB.VerifyAnalyzerAsync(@"
Public Class B
End Class
<System.Composition.Export(GetType(C))> _
Public Class C
<System.Composition.ImportingConstructor> _
Public Sub New(<System.Composition.Import> b As B)
End Sub
<System.Composition.Import> _
Public ReadOnly Property PropertyB() As B
End Class
<System.ComponentModel.Composition.Export(GetType(C2))> _
Public Class C2
<System.ComponentModel.Composition.ImportingConstructor> _
Public Sub New(<System.ComponentModel.Composition.Import> b As B)
End Sub
<System.ComponentModel.Composition.Import> _
Public ReadOnly Property PropertyB() As B
End Class
" + BasicWellKnownAttributesDefinition);
}
[Fact]
public async Task NoDiagnosticCases_UnresolvedTypes()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
@"
using System;
public class B { }
[System.{|CS0234:Composition|}.Export(typeof(C))]
public class C
{
[System.ComponentModel.{|CS0234:Composition|}.Import]
public B PropertyB { get; }
}
"
},
},
ReferenceAssemblies = ReferenceAssemblies.Default,
}.RunAsync();
await new VerifyVB.Test
{
TestState =
{
Sources =
{
@"
Public Class B
End Class
<{|BC30002:System.Composition.Export|}(GetType(C))> _
Public Class C
<{|BC30002:System.ComponentModel.Composition.Import|}> _
Public ReadOnly Property PropertyB() As B
End Class
"
},
},
ReferenceAssemblies = ReferenceAssemblies.Default,
}.RunAsync();
}
[Fact]
public async Task NoDiagnosticCases_MultiMefMetadataAttribute()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
[System.ComponentModel.Composition.Export(typeof(C)), MyNamespace.MultiMefMetadataAttribute]
public class C
{
}
namespace MyNamespace
{
[System.ComponentModel.Composition.MetadataAttribute, System.Composition.MetadataAttribute]
public class MultiMefMetadataAttribute : System.Attribute
{
}
}
" + CSharpWellKnownAttributesDefinition);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
<System.ComponentModel.Composition.Export(GetType(C)), MyNamespace.MultiMefMetadataAttribute> _
Public Class C
End Class
Namespace MyNamespace
<System.ComponentModel.Composition.MetadataAttribute, System.Composition.MetadataAttribute> _
Public Class MultiMefMetadataAttribute
Inherits System.Attribute
End Class
End Namespace
" + BasicWellKnownAttributesDefinition);
}
#endregion
#region Diagnostic Tests
[Fact]
public async Task DiagnosticCases_BadMetadataAttribute()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
[System.Composition.Export(typeof(C))]
[SystemComponentModelCompositionMetadataAttribute]
public class C
{
}
[System.ComponentModel.Composition.Export(typeof(C2))]
[SystemCompositionMetadataAttribute]
public class C2
{
}
" + CSharpWellKnownAttributesDefinition,
// Test0.cs(5,2): warning RS0006: Attribute 'SystemComponentModelCompositionMetadataAttribute' comes from a different version of MEF than the export attribute on 'C'
GetCSharpResultAt(5, 2, "SystemComponentModelCompositionMetadataAttribute", "C"),
// Test0.cs(11,2): warning RS0006: Attribute 'SystemCompositionMetadataAttribute' comes from a different version of MEF than the export attribute on 'C2'
GetCSharpResultAt(11, 2, "SystemCompositionMetadataAttribute", "C2"));
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
<System.Composition.Export(GetType(C))> _
<SystemComponentModelCompositionMetadataAttribute> _
Public Class C
End Class
<System.ComponentModel.Composition.Export(GetType(C2))> _
<SystemCompositionMetadataAttribute> _
Public Class C2
End Class
" + BasicWellKnownAttributesDefinition,
// Test0.vb(5,2): warning RS0006: Attribute 'SystemComponentModelCompositionMetadataAttribute' comes from a different version of MEF than the export attribute on 'C'
GetBasicResultAt(5, 2, "SystemComponentModelCompositionMetadataAttribute", "C"),
// Test0.vb(10,2): warning RS0006: Attribute 'SystemCompositionMetadataAttribute' comes from a different version of MEF than the export attribute on 'C2'
GetBasicResultAt(10, 2, "SystemCompositionMetadataAttribute", "C2"));
}
[Fact]
public async Task DiagnosticCases_BadMefAttributeOnMember()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
public class B { }
[System.Composition.Export(typeof(C))]
public class C
{
[System.ComponentModel.Composition.ImportingConstructor]
public C([System.Composition.Import]B b) { }
[System.ComponentModel.Composition.Import]
public B PropertyB { get; }
}
[System.ComponentModel.Composition.Export(typeof(C2))]
public class C2
{
[System.Composition.ImportingConstructor]
public C2([System.ComponentModel.Composition.Import]B b) { }
[System.Composition.Import]
public B PropertyB { get; }
}
" + CSharpWellKnownAttributesDefinition,
// Test0.cs(9,6): warning RS0006: Attribute 'ImportingConstructorAttribute' comes from a different version of MEF than the export attribute on 'C'
GetCSharpResultAt(9, 6, "ImportingConstructorAttribute", "C"),
// Test0.cs(12,6): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C'
GetCSharpResultAt(12, 6, "ImportAttribute", "C"),
// Test0.cs(19,6): warning RS0006: Attribute 'ImportingConstructorAttribute' comes from a different version of MEF than the export attribute on 'C2'
GetCSharpResultAt(19, 6, "ImportingConstructorAttribute", "C2"),
// Test0.cs(22,6): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C2'
GetCSharpResultAt(22, 6, "ImportAttribute", "C2")
);
await VerifyVB.VerifyAnalyzerAsync(@"
Public Class B
End Class
<System.Composition.Export(GetType(C))> _
Public Class C
<System.ComponentModel.Composition.ImportingConstructor> _
Public Sub New(<System.Composition.Import> b As B)
End Sub
<System.ComponentModel.Composition.Import> _
Public ReadOnly Property PropertyB() As B
End Class
<System.ComponentModel.Composition.Export(GetType(C2))> _
Public Class C2
<System.Composition.ImportingConstructor> _
Public Sub New(<System.ComponentModel.Composition.Import> b As B)
End Sub
<System.Composition.Import> _
Public ReadOnly Property PropertyB() As B
End Class
" + BasicWellKnownAttributesDefinition,
// Test0.vb(7,3): warning RS0006: Attribute 'ImportingConstructorAttribute' comes from a different version of MEF than the export attribute on 'C'
GetBasicResultAt(7, 3, "ImportingConstructorAttribute", "C"),
// Test0.vb(11,3): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C'
GetBasicResultAt(11, 3, "ImportAttribute", "C"),
// Test0.vb(17,3): warning RS0006: Attribute 'ImportingConstructorAttribute' comes from a different version of MEF than the export attribute on 'C2'
GetBasicResultAt(17, 3, "ImportingConstructorAttribute", "C2"),
// Test0.vb(21,3): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C2'
GetBasicResultAt(21, 3, "ImportAttribute", "C2")
);
}
[Fact]
public async Task DiagnosticCases_BadMefAttributeOnParameter()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
public class B { }
[System.Composition.Export(typeof(C))]
public class C
{
[System.Composition.ImportingConstructor]
public C([System.ComponentModel.Composition.Import]B b) { }
[System.Composition.Import]
public B PropertyB { get; }
}
[System.ComponentModel.Composition.Export(typeof(C2))]
public class C2
{
[System.ComponentModel.Composition.ImportingConstructor]
public C2([System.Composition.Import]B b) { }
[System.ComponentModel.Composition.Import]
public B PropertyB { get; }
}
" + CSharpWellKnownAttributesDefinition,
// Test0.cs(10,15): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C'
GetCSharpResultAt(10, 15, "ImportAttribute", "C"),
// Test0.cs(20,16): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C2'
GetCSharpResultAt(20, 16, "ImportAttribute", "C2"));
await VerifyVB.VerifyAnalyzerAsync(@"
Public Class B
End Class
<System.Composition.Export(GetType(C))> _
Public Class C
<System.Composition.ImportingConstructor> _
Public Sub New(<System.ComponentModel.Composition.Import> b As B)
End Sub
<System.Composition.Import> _
Public ReadOnly Property PropertyB() As B
End Class
<System.ComponentModel.Composition.Export(GetType(C2))> _
Public Class C2
<System.ComponentModel.Composition.ImportingConstructor> _
Public Sub New(<System.Composition.Import> b As B)
End Sub
<System.ComponentModel.Composition.Import> _
Public ReadOnly Property PropertyB() As B
End Class
" + BasicWellKnownAttributesDefinition,
// Test0.vb(8,18): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C'
GetBasicResultAt(8, 18, "ImportAttribute", "C"),
// Test0.vb(18,18): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C2'
GetBasicResultAt(18, 18, "ImportAttribute", "C2"));
}
#endregion
private static DiagnosticResult GetCSharpResultAt(int line, int column, string attributeName, string typeName) =>
VerifyCS.Diagnostic()
.WithLocation(line, column)
.WithArguments(attributeName, typeName);
private static DiagnosticResult GetBasicResultAt(int line, int column, string attributeName, string typeName) =>
VerifyVB.Diagnostic()
.WithLocation(line, column)
.WithArguments(attributeName, typeName);
}
}
| |
// 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.
// Generated code. DO NOT EDIT!
using gagvc = Google.Ads.GoogleAds.V8.Common;
using gagve = Google.Ads.GoogleAds.V8.Enums;
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using gr = Google.Rpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V8.Services;
namespace Google.Ads.GoogleAds.Tests.V8.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedCampaignCriterionServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetCampaignCriterionRequestObject()
{
moq::Mock<CampaignCriterionService.CampaignCriterionServiceClient> mockGrpcClient = new moq::Mock<CampaignCriterionService.CampaignCriterionServiceClient>(moq::MockBehavior.Strict);
GetCampaignCriterionRequest request = new GetCampaignCriterionRequest
{
ResourceNameAsCampaignCriterionName = gagvr::CampaignCriterionName.FromCustomerCampaignCriterion("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[CRITERION_ID]"),
};
gagvr::CampaignCriterion expectedResponse = new gagvr::CampaignCriterion
{
ResourceNameAsCampaignCriterionName = gagvr::CampaignCriterionName.FromCustomerCampaignCriterion("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[CRITERION_ID]"),
Type = gagve::CriterionTypeEnum.Types.CriterionType.Webpage,
Keyword = new gagvc::KeywordInfo(),
Placement = new gagvc::PlacementInfo(),
MobileAppCategory = new gagvc::MobileAppCategoryInfo(),
MobileApplication = new gagvc::MobileApplicationInfo(),
Location = new gagvc::LocationInfo(),
Device = new gagvc::DeviceInfo(),
AdSchedule = new gagvc::AdScheduleInfo(),
AgeRange = new gagvc::AgeRangeInfo(),
Gender = new gagvc::GenderInfo(),
IncomeRange = new gagvc::IncomeRangeInfo(),
ParentalStatus = new gagvc::ParentalStatusInfo(),
YoutubeVideo = new gagvc::YouTubeVideoInfo(),
YoutubeChannel = new gagvc::YouTubeChannelInfo(),
UserList = new gagvc::UserListInfo(),
Proximity = new gagvc::ProximityInfo(),
Topic = new gagvc::TopicInfo(),
ListingScope = new gagvc::ListingScopeInfo(),
Language = new gagvc::LanguageInfo(),
IpBlock = new gagvc::IpBlockInfo(),
ContentLabel = new gagvc::ContentLabelInfo(),
Carrier = new gagvc::CarrierInfo(),
UserInterest = new gagvc::UserInterestInfo(),
Webpage = new gagvc::WebpageInfo(),
OperatingSystemVersion = new gagvc::OperatingSystemVersionInfo(),
MobileDevice = new gagvc::MobileDeviceInfo(),
LocationGroup = new gagvc::LocationGroupInfo(),
Status = gagve::CampaignCriterionStatusEnum.Types.CampaignCriterionStatus.Removed,
CustomAffinity = new gagvc::CustomAffinityInfo(),
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
CriterionId = 8584655242409302840L,
BidModifier = 1.6595195E+17F,
Negative = false,
CustomAudience = new gagvc::CustomAudienceInfo(),
CombinedAudience = new gagvc::CombinedAudienceInfo(),
DisplayName = "display_name137f65c2",
KeywordTheme = new gagvc::KeywordThemeInfo(),
};
mockGrpcClient.Setup(x => x.GetCampaignCriterion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignCriterionServiceClient client = new CampaignCriterionServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignCriterion response = client.GetCampaignCriterion(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCampaignCriterionRequestObjectAsync()
{
moq::Mock<CampaignCriterionService.CampaignCriterionServiceClient> mockGrpcClient = new moq::Mock<CampaignCriterionService.CampaignCriterionServiceClient>(moq::MockBehavior.Strict);
GetCampaignCriterionRequest request = new GetCampaignCriterionRequest
{
ResourceNameAsCampaignCriterionName = gagvr::CampaignCriterionName.FromCustomerCampaignCriterion("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[CRITERION_ID]"),
};
gagvr::CampaignCriterion expectedResponse = new gagvr::CampaignCriterion
{
ResourceNameAsCampaignCriterionName = gagvr::CampaignCriterionName.FromCustomerCampaignCriterion("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[CRITERION_ID]"),
Type = gagve::CriterionTypeEnum.Types.CriterionType.Webpage,
Keyword = new gagvc::KeywordInfo(),
Placement = new gagvc::PlacementInfo(),
MobileAppCategory = new gagvc::MobileAppCategoryInfo(),
MobileApplication = new gagvc::MobileApplicationInfo(),
Location = new gagvc::LocationInfo(),
Device = new gagvc::DeviceInfo(),
AdSchedule = new gagvc::AdScheduleInfo(),
AgeRange = new gagvc::AgeRangeInfo(),
Gender = new gagvc::GenderInfo(),
IncomeRange = new gagvc::IncomeRangeInfo(),
ParentalStatus = new gagvc::ParentalStatusInfo(),
YoutubeVideo = new gagvc::YouTubeVideoInfo(),
YoutubeChannel = new gagvc::YouTubeChannelInfo(),
UserList = new gagvc::UserListInfo(),
Proximity = new gagvc::ProximityInfo(),
Topic = new gagvc::TopicInfo(),
ListingScope = new gagvc::ListingScopeInfo(),
Language = new gagvc::LanguageInfo(),
IpBlock = new gagvc::IpBlockInfo(),
ContentLabel = new gagvc::ContentLabelInfo(),
Carrier = new gagvc::CarrierInfo(),
UserInterest = new gagvc::UserInterestInfo(),
Webpage = new gagvc::WebpageInfo(),
OperatingSystemVersion = new gagvc::OperatingSystemVersionInfo(),
MobileDevice = new gagvc::MobileDeviceInfo(),
LocationGroup = new gagvc::LocationGroupInfo(),
Status = gagve::CampaignCriterionStatusEnum.Types.CampaignCriterionStatus.Removed,
CustomAffinity = new gagvc::CustomAffinityInfo(),
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
CriterionId = 8584655242409302840L,
BidModifier = 1.6595195E+17F,
Negative = false,
CustomAudience = new gagvc::CustomAudienceInfo(),
CombinedAudience = new gagvc::CombinedAudienceInfo(),
DisplayName = "display_name137f65c2",
KeywordTheme = new gagvc::KeywordThemeInfo(),
};
mockGrpcClient.Setup(x => x.GetCampaignCriterionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignCriterion>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignCriterionServiceClient client = new CampaignCriterionServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignCriterion responseCallSettings = await client.GetCampaignCriterionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CampaignCriterion responseCancellationToken = await client.GetCampaignCriterionAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetCampaignCriterion()
{
moq::Mock<CampaignCriterionService.CampaignCriterionServiceClient> mockGrpcClient = new moq::Mock<CampaignCriterionService.CampaignCriterionServiceClient>(moq::MockBehavior.Strict);
GetCampaignCriterionRequest request = new GetCampaignCriterionRequest
{
ResourceNameAsCampaignCriterionName = gagvr::CampaignCriterionName.FromCustomerCampaignCriterion("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[CRITERION_ID]"),
};
gagvr::CampaignCriterion expectedResponse = new gagvr::CampaignCriterion
{
ResourceNameAsCampaignCriterionName = gagvr::CampaignCriterionName.FromCustomerCampaignCriterion("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[CRITERION_ID]"),
Type = gagve::CriterionTypeEnum.Types.CriterionType.Webpage,
Keyword = new gagvc::KeywordInfo(),
Placement = new gagvc::PlacementInfo(),
MobileAppCategory = new gagvc::MobileAppCategoryInfo(),
MobileApplication = new gagvc::MobileApplicationInfo(),
Location = new gagvc::LocationInfo(),
Device = new gagvc::DeviceInfo(),
AdSchedule = new gagvc::AdScheduleInfo(),
AgeRange = new gagvc::AgeRangeInfo(),
Gender = new gagvc::GenderInfo(),
IncomeRange = new gagvc::IncomeRangeInfo(),
ParentalStatus = new gagvc::ParentalStatusInfo(),
YoutubeVideo = new gagvc::YouTubeVideoInfo(),
YoutubeChannel = new gagvc::YouTubeChannelInfo(),
UserList = new gagvc::UserListInfo(),
Proximity = new gagvc::ProximityInfo(),
Topic = new gagvc::TopicInfo(),
ListingScope = new gagvc::ListingScopeInfo(),
Language = new gagvc::LanguageInfo(),
IpBlock = new gagvc::IpBlockInfo(),
ContentLabel = new gagvc::ContentLabelInfo(),
Carrier = new gagvc::CarrierInfo(),
UserInterest = new gagvc::UserInterestInfo(),
Webpage = new gagvc::WebpageInfo(),
OperatingSystemVersion = new gagvc::OperatingSystemVersionInfo(),
MobileDevice = new gagvc::MobileDeviceInfo(),
LocationGroup = new gagvc::LocationGroupInfo(),
Status = gagve::CampaignCriterionStatusEnum.Types.CampaignCriterionStatus.Removed,
CustomAffinity = new gagvc::CustomAffinityInfo(),
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
CriterionId = 8584655242409302840L,
BidModifier = 1.6595195E+17F,
Negative = false,
CustomAudience = new gagvc::CustomAudienceInfo(),
CombinedAudience = new gagvc::CombinedAudienceInfo(),
DisplayName = "display_name137f65c2",
KeywordTheme = new gagvc::KeywordThemeInfo(),
};
mockGrpcClient.Setup(x => x.GetCampaignCriterion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignCriterionServiceClient client = new CampaignCriterionServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignCriterion response = client.GetCampaignCriterion(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCampaignCriterionAsync()
{
moq::Mock<CampaignCriterionService.CampaignCriterionServiceClient> mockGrpcClient = new moq::Mock<CampaignCriterionService.CampaignCriterionServiceClient>(moq::MockBehavior.Strict);
GetCampaignCriterionRequest request = new GetCampaignCriterionRequest
{
ResourceNameAsCampaignCriterionName = gagvr::CampaignCriterionName.FromCustomerCampaignCriterion("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[CRITERION_ID]"),
};
gagvr::CampaignCriterion expectedResponse = new gagvr::CampaignCriterion
{
ResourceNameAsCampaignCriterionName = gagvr::CampaignCriterionName.FromCustomerCampaignCriterion("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[CRITERION_ID]"),
Type = gagve::CriterionTypeEnum.Types.CriterionType.Webpage,
Keyword = new gagvc::KeywordInfo(),
Placement = new gagvc::PlacementInfo(),
MobileAppCategory = new gagvc::MobileAppCategoryInfo(),
MobileApplication = new gagvc::MobileApplicationInfo(),
Location = new gagvc::LocationInfo(),
Device = new gagvc::DeviceInfo(),
AdSchedule = new gagvc::AdScheduleInfo(),
AgeRange = new gagvc::AgeRangeInfo(),
Gender = new gagvc::GenderInfo(),
IncomeRange = new gagvc::IncomeRangeInfo(),
ParentalStatus = new gagvc::ParentalStatusInfo(),
YoutubeVideo = new gagvc::YouTubeVideoInfo(),
YoutubeChannel = new gagvc::YouTubeChannelInfo(),
UserList = new gagvc::UserListInfo(),
Proximity = new gagvc::ProximityInfo(),
Topic = new gagvc::TopicInfo(),
ListingScope = new gagvc::ListingScopeInfo(),
Language = new gagvc::LanguageInfo(),
IpBlock = new gagvc::IpBlockInfo(),
ContentLabel = new gagvc::ContentLabelInfo(),
Carrier = new gagvc::CarrierInfo(),
UserInterest = new gagvc::UserInterestInfo(),
Webpage = new gagvc::WebpageInfo(),
OperatingSystemVersion = new gagvc::OperatingSystemVersionInfo(),
MobileDevice = new gagvc::MobileDeviceInfo(),
LocationGroup = new gagvc::LocationGroupInfo(),
Status = gagve::CampaignCriterionStatusEnum.Types.CampaignCriterionStatus.Removed,
CustomAffinity = new gagvc::CustomAffinityInfo(),
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
CriterionId = 8584655242409302840L,
BidModifier = 1.6595195E+17F,
Negative = false,
CustomAudience = new gagvc::CustomAudienceInfo(),
CombinedAudience = new gagvc::CombinedAudienceInfo(),
DisplayName = "display_name137f65c2",
KeywordTheme = new gagvc::KeywordThemeInfo(),
};
mockGrpcClient.Setup(x => x.GetCampaignCriterionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignCriterion>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignCriterionServiceClient client = new CampaignCriterionServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignCriterion responseCallSettings = await client.GetCampaignCriterionAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CampaignCriterion responseCancellationToken = await client.GetCampaignCriterionAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetCampaignCriterionResourceNames()
{
moq::Mock<CampaignCriterionService.CampaignCriterionServiceClient> mockGrpcClient = new moq::Mock<CampaignCriterionService.CampaignCriterionServiceClient>(moq::MockBehavior.Strict);
GetCampaignCriterionRequest request = new GetCampaignCriterionRequest
{
ResourceNameAsCampaignCriterionName = gagvr::CampaignCriterionName.FromCustomerCampaignCriterion("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[CRITERION_ID]"),
};
gagvr::CampaignCriterion expectedResponse = new gagvr::CampaignCriterion
{
ResourceNameAsCampaignCriterionName = gagvr::CampaignCriterionName.FromCustomerCampaignCriterion("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[CRITERION_ID]"),
Type = gagve::CriterionTypeEnum.Types.CriterionType.Webpage,
Keyword = new gagvc::KeywordInfo(),
Placement = new gagvc::PlacementInfo(),
MobileAppCategory = new gagvc::MobileAppCategoryInfo(),
MobileApplication = new gagvc::MobileApplicationInfo(),
Location = new gagvc::LocationInfo(),
Device = new gagvc::DeviceInfo(),
AdSchedule = new gagvc::AdScheduleInfo(),
AgeRange = new gagvc::AgeRangeInfo(),
Gender = new gagvc::GenderInfo(),
IncomeRange = new gagvc::IncomeRangeInfo(),
ParentalStatus = new gagvc::ParentalStatusInfo(),
YoutubeVideo = new gagvc::YouTubeVideoInfo(),
YoutubeChannel = new gagvc::YouTubeChannelInfo(),
UserList = new gagvc::UserListInfo(),
Proximity = new gagvc::ProximityInfo(),
Topic = new gagvc::TopicInfo(),
ListingScope = new gagvc::ListingScopeInfo(),
Language = new gagvc::LanguageInfo(),
IpBlock = new gagvc::IpBlockInfo(),
ContentLabel = new gagvc::ContentLabelInfo(),
Carrier = new gagvc::CarrierInfo(),
UserInterest = new gagvc::UserInterestInfo(),
Webpage = new gagvc::WebpageInfo(),
OperatingSystemVersion = new gagvc::OperatingSystemVersionInfo(),
MobileDevice = new gagvc::MobileDeviceInfo(),
LocationGroup = new gagvc::LocationGroupInfo(),
Status = gagve::CampaignCriterionStatusEnum.Types.CampaignCriterionStatus.Removed,
CustomAffinity = new gagvc::CustomAffinityInfo(),
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
CriterionId = 8584655242409302840L,
BidModifier = 1.6595195E+17F,
Negative = false,
CustomAudience = new gagvc::CustomAudienceInfo(),
CombinedAudience = new gagvc::CombinedAudienceInfo(),
DisplayName = "display_name137f65c2",
KeywordTheme = new gagvc::KeywordThemeInfo(),
};
mockGrpcClient.Setup(x => x.GetCampaignCriterion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignCriterionServiceClient client = new CampaignCriterionServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignCriterion response = client.GetCampaignCriterion(request.ResourceNameAsCampaignCriterionName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCampaignCriterionResourceNamesAsync()
{
moq::Mock<CampaignCriterionService.CampaignCriterionServiceClient> mockGrpcClient = new moq::Mock<CampaignCriterionService.CampaignCriterionServiceClient>(moq::MockBehavior.Strict);
GetCampaignCriterionRequest request = new GetCampaignCriterionRequest
{
ResourceNameAsCampaignCriterionName = gagvr::CampaignCriterionName.FromCustomerCampaignCriterion("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[CRITERION_ID]"),
};
gagvr::CampaignCriterion expectedResponse = new gagvr::CampaignCriterion
{
ResourceNameAsCampaignCriterionName = gagvr::CampaignCriterionName.FromCustomerCampaignCriterion("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[CRITERION_ID]"),
Type = gagve::CriterionTypeEnum.Types.CriterionType.Webpage,
Keyword = new gagvc::KeywordInfo(),
Placement = new gagvc::PlacementInfo(),
MobileAppCategory = new gagvc::MobileAppCategoryInfo(),
MobileApplication = new gagvc::MobileApplicationInfo(),
Location = new gagvc::LocationInfo(),
Device = new gagvc::DeviceInfo(),
AdSchedule = new gagvc::AdScheduleInfo(),
AgeRange = new gagvc::AgeRangeInfo(),
Gender = new gagvc::GenderInfo(),
IncomeRange = new gagvc::IncomeRangeInfo(),
ParentalStatus = new gagvc::ParentalStatusInfo(),
YoutubeVideo = new gagvc::YouTubeVideoInfo(),
YoutubeChannel = new gagvc::YouTubeChannelInfo(),
UserList = new gagvc::UserListInfo(),
Proximity = new gagvc::ProximityInfo(),
Topic = new gagvc::TopicInfo(),
ListingScope = new gagvc::ListingScopeInfo(),
Language = new gagvc::LanguageInfo(),
IpBlock = new gagvc::IpBlockInfo(),
ContentLabel = new gagvc::ContentLabelInfo(),
Carrier = new gagvc::CarrierInfo(),
UserInterest = new gagvc::UserInterestInfo(),
Webpage = new gagvc::WebpageInfo(),
OperatingSystemVersion = new gagvc::OperatingSystemVersionInfo(),
MobileDevice = new gagvc::MobileDeviceInfo(),
LocationGroup = new gagvc::LocationGroupInfo(),
Status = gagve::CampaignCriterionStatusEnum.Types.CampaignCriterionStatus.Removed,
CustomAffinity = new gagvc::CustomAffinityInfo(),
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
CriterionId = 8584655242409302840L,
BidModifier = 1.6595195E+17F,
Negative = false,
CustomAudience = new gagvc::CustomAudienceInfo(),
CombinedAudience = new gagvc::CombinedAudienceInfo(),
DisplayName = "display_name137f65c2",
KeywordTheme = new gagvc::KeywordThemeInfo(),
};
mockGrpcClient.Setup(x => x.GetCampaignCriterionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignCriterion>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignCriterionServiceClient client = new CampaignCriterionServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignCriterion responseCallSettings = await client.GetCampaignCriterionAsync(request.ResourceNameAsCampaignCriterionName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CampaignCriterion responseCancellationToken = await client.GetCampaignCriterionAsync(request.ResourceNameAsCampaignCriterionName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateCampaignCriteriaRequestObject()
{
moq::Mock<CampaignCriterionService.CampaignCriterionServiceClient> mockGrpcClient = new moq::Mock<CampaignCriterionService.CampaignCriterionServiceClient>(moq::MockBehavior.Strict);
MutateCampaignCriteriaRequest request = new MutateCampaignCriteriaRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CampaignCriterionOperation(),
},
PartialFailure = false,
ValidateOnly = true,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateCampaignCriteriaResponse expectedResponse = new MutateCampaignCriteriaResponse
{
Results =
{
new MutateCampaignCriterionResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateCampaignCriteria(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignCriterionServiceClient client = new CampaignCriterionServiceClientImpl(mockGrpcClient.Object, null);
MutateCampaignCriteriaResponse response = client.MutateCampaignCriteria(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateCampaignCriteriaRequestObjectAsync()
{
moq::Mock<CampaignCriterionService.CampaignCriterionServiceClient> mockGrpcClient = new moq::Mock<CampaignCriterionService.CampaignCriterionServiceClient>(moq::MockBehavior.Strict);
MutateCampaignCriteriaRequest request = new MutateCampaignCriteriaRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CampaignCriterionOperation(),
},
PartialFailure = false,
ValidateOnly = true,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateCampaignCriteriaResponse expectedResponse = new MutateCampaignCriteriaResponse
{
Results =
{
new MutateCampaignCriterionResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateCampaignCriteriaAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCampaignCriteriaResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignCriterionServiceClient client = new CampaignCriterionServiceClientImpl(mockGrpcClient.Object, null);
MutateCampaignCriteriaResponse responseCallSettings = await client.MutateCampaignCriteriaAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateCampaignCriteriaResponse responseCancellationToken = await client.MutateCampaignCriteriaAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateCampaignCriteria()
{
moq::Mock<CampaignCriterionService.CampaignCriterionServiceClient> mockGrpcClient = new moq::Mock<CampaignCriterionService.CampaignCriterionServiceClient>(moq::MockBehavior.Strict);
MutateCampaignCriteriaRequest request = new MutateCampaignCriteriaRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CampaignCriterionOperation(),
},
};
MutateCampaignCriteriaResponse expectedResponse = new MutateCampaignCriteriaResponse
{
Results =
{
new MutateCampaignCriterionResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateCampaignCriteria(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignCriterionServiceClient client = new CampaignCriterionServiceClientImpl(mockGrpcClient.Object, null);
MutateCampaignCriteriaResponse response = client.MutateCampaignCriteria(request.CustomerId, request.Operations);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateCampaignCriteriaAsync()
{
moq::Mock<CampaignCriterionService.CampaignCriterionServiceClient> mockGrpcClient = new moq::Mock<CampaignCriterionService.CampaignCriterionServiceClient>(moq::MockBehavior.Strict);
MutateCampaignCriteriaRequest request = new MutateCampaignCriteriaRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CampaignCriterionOperation(),
},
};
MutateCampaignCriteriaResponse expectedResponse = new MutateCampaignCriteriaResponse
{
Results =
{
new MutateCampaignCriterionResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateCampaignCriteriaAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCampaignCriteriaResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignCriterionServiceClient client = new CampaignCriterionServiceClientImpl(mockGrpcClient.Object, null);
MutateCampaignCriteriaResponse responseCallSettings = await client.MutateCampaignCriteriaAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateCampaignCriteriaResponse responseCancellationToken = await client.MutateCampaignCriteriaAsync(request.CustomerId, request.Operations, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/*============================================================
**
**
**
**
** Purpose: Implements a generic, dynamically sized list as an
** array.
**
**
===========================================================*/
namespace System.Collections.Generic {
using System;
using System.Runtime;
using System.Runtime.Versioning;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Collections.ObjectModel;
using System.Security.Permissions;
// Implements a variable-size List that uses an array of objects to store the
// elements. A List has a capacity, which is the allocated length
// of the internal array. As elements are added to a List, the capacity
// of the List is automatically increased as required by reallocating the
// internal array.
//
[DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public class List<T> : IList<T>, System.Collections.IList, IReadOnlyList<T>
{
private const int _defaultCapacity = 4;
private T[] _items;
[ContractPublicPropertyName("Count")]
private int _size;
private int _version;
[NonSerialized]
private Object _syncRoot;
static readonly T[] _emptyArray = new T[0];
// Constructs a List. The list is initially empty and has a capacity
// of zero. Upon adding the first element to the list the capacity is
// increased to 16, and then increased in multiples of two as required.
public List() {
_items = _emptyArray;
}
// Constructs a List with a given initial capacity. The list is
// initially empty, but will have room for the given number of elements
// before any reallocations are required.
//
public List(int capacity) {
if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
if (capacity == 0)
_items = _emptyArray;
else
_items = new T[capacity];
}
// Constructs a List, copying the contents of the given collection. The
// size and capacity of the new list will both be equal to the size of the
// given collection.
//
public List(IEnumerable<T> collection) {
if (collection==null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
Contract.EndContractBlock();
ICollection<T> c = collection as ICollection<T>;
if( c != null) {
int count = c.Count;
if (count == 0)
{
_items = _emptyArray;
}
else {
_items = new T[count];
c.CopyTo(_items, 0);
_size = count;
}
}
else {
_size = 0;
_items = _emptyArray;
// This enumerable could be empty. Let Add allocate a new array, if needed.
// Note it will also go to _defaultCapacity first, not 1, then 2, etc.
using(IEnumerator<T> en = collection.GetEnumerator()) {
while(en.MoveNext()) {
Add(en.Current);
}
}
}
}
// Gets and sets the capacity of this list. The capacity is the size of
// the internal array used to hold items. When set, the internal
// array of the list is reallocated to the given capacity.
//
public int Capacity {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
return _items.Length;
}
set {
if (value < _size) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value, ExceptionResource.ArgumentOutOfRange_SmallCapacity);
}
Contract.EndContractBlock();
if (value != _items.Length) {
if (value > 0) {
T[] newItems = new T[value];
if (_size > 0) {
Array.Copy(_items, 0, newItems, 0, _size);
}
_items = newItems;
}
else {
_items = _emptyArray;
}
}
}
}
// Read-only property describing how many elements are in the List.
public int Count {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
return _size;
}
}
bool System.Collections.IList.IsFixedSize {
get { return false; }
}
// Is this List read-only?
bool ICollection<T>.IsReadOnly {
get { return false; }
}
bool System.Collections.IList.IsReadOnly {
get { return false; }
}
// Is this List synchronized (thread-safe)?
bool System.Collections.ICollection.IsSynchronized {
get { return false; }
}
// Synchronization root for this object.
Object System.Collections.ICollection.SyncRoot {
get {
if( _syncRoot == null) {
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
// Sets or Gets the element at the given index.
//
public T this[int index] {
get {
// Following trick can reduce the range check by one
if ((uint) index >= (uint)_size) {
ThrowHelper.ThrowArgumentOutOfRangeException();
}
Contract.EndContractBlock();
return _items[index];
}
set {
if ((uint) index >= (uint)_size) {
ThrowHelper.ThrowArgumentOutOfRangeException();
}
Contract.EndContractBlock();
_items[index] = value;
_version++;
}
}
private static bool IsCompatibleObject(object value) {
// Non-null values are fine. Only accept nulls if T is a class or Nullable<U>.
// Note that default(T) is not equal to null for value types except when T is Nullable<U>.
return ((value is T) || (value == null && default(T) == null));
}
Object System.Collections.IList.this[int index] {
get {
return this[index];
}
set {
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value);
try {
this[index] = (T)value;
}
catch (InvalidCastException) {
ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T));
}
}
}
// Adds the given object to the end of this list. The size of the list is
// increased by one. If required, the capacity of the list is doubled
// before adding the new element.
//
public void Add(T item) {
if (_size == _items.Length) EnsureCapacity(_size + 1);
_items[_size++] = item;
_version++;
}
int System.Collections.IList.Add(Object item)
{
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(item, ExceptionArgument.item);
try {
Add((T) item);
}
catch (InvalidCastException) {
ThrowHelper.ThrowWrongValueTypeArgumentException(item, typeof(T));
}
return Count - 1;
}
// Adds the elements of the given collection to the end of this list. If
// required, the capacity of the list is increased to twice the previous
// capacity or the new size, whichever is larger.
//
public void AddRange(IEnumerable<T> collection) {
Contract.Ensures(Count >= Contract.OldValue(Count));
InsertRange(_size, collection);
}
public ReadOnlyCollection<T> AsReadOnly() {
Contract.Ensures(Contract.Result<ReadOnlyCollection<T>>() != null);
return new ReadOnlyCollection<T>(this);
}
// Searches a section of the list for a given element using a binary search
// algorithm. Elements of the list are compared to the search value using
// the given IComparer interface. If comparer is null, elements of
// the list are compared to the search value using the IComparable
// interface, which in that case must be implemented by all elements of the
// list and the given search value. This method assumes that the given
// section of the list is already sorted; if this is not the case, the
// result will be incorrect.
//
// The method returns the index of the given value in the list. If the
// list does not contain the given value, the method returns a negative
// integer. The bitwise complement operator (~) can be applied to a
// negative result to produce the index of the first element (if any) that
// is larger than the given search value. This is also the index at which
// the search value should be inserted into the list in order for the list
// to remain sorted.
//
// The method uses the Array.BinarySearch method to perform the
// search.
//
public int BinarySearch(int index, int count, T item, IComparer<T> comparer) {
if (index < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
if (_size - index < count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
Contract.Ensures(Contract.Result<int>() <= index + count);
Contract.EndContractBlock();
return Array.BinarySearch<T>(_items, index, count, item, comparer);
}
public int BinarySearch(T item)
{
Contract.Ensures(Contract.Result<int>() <= Count);
return BinarySearch(0, Count, item, null);
}
public int BinarySearch(T item, IComparer<T> comparer)
{
Contract.Ensures(Contract.Result<int>() <= Count);
return BinarySearch(0, Count, item, comparer);
}
// Clears the contents of List.
public void Clear() {
if (_size > 0)
{
Array.Clear(_items, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
_size = 0;
}
_version++;
}
// Contains returns true if the specified element is in the List.
// It does a linear, O(n) search. Equality is determined by calling
// item.Equals().
//
public bool Contains(T item) {
if ((Object) item == null) {
for(int i=0; i<_size; i++)
if ((Object) _items[i] == null)
return true;
return false;
}
else {
EqualityComparer<T> c = EqualityComparer<T>.Default;
for(int i=0; i<_size; i++) {
if (c.Equals(_items[i], item)) return true;
}
return false;
}
}
bool System.Collections.IList.Contains(Object item)
{
if(IsCompatibleObject(item)) {
return Contains((T) item);
}
return false;
}
public List<TOutput> ConvertAll<TOutput>(Converter<T,TOutput> converter) {
if( converter == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.converter);
}
Contract.EndContractBlock();
List<TOutput> list = new List<TOutput>(_size);
for( int i = 0; i< _size; i++) {
list._items[i] = converter(_items[i]);
}
list._size = _size;
return list;
}
// Copies this List into array, which must be of a
// compatible array type.
//
public void CopyTo(T[] array) {
CopyTo(array, 0);
}
// Copies this List into array, which must be of a
// compatible array type.
//
void System.Collections.ICollection.CopyTo(Array array, int arrayIndex) {
if ((array != null) && (array.Rank != 1)) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
Contract.EndContractBlock();
try {
// Array.Copy will check for NULL.
Array.Copy(_items, 0, array, arrayIndex, _size);
}
catch(ArrayTypeMismatchException){
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
}
}
// Copies a section of this list to the given array at the given index.
//
// The method uses the Array.Copy method to copy the elements.
//
public void CopyTo(int index, T[] array, int arrayIndex, int count) {
if (_size - index < count) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
}
Contract.EndContractBlock();
// Delegate rest of error checking to Array.Copy.
Array.Copy(_items, index, array, arrayIndex, count);
}
public void CopyTo(T[] array, int arrayIndex) {
// Delegate rest of error checking to Array.Copy.
Array.Copy(_items, 0, array, arrayIndex, _size);
}
// Ensures that the capacity of this list is at least the given minimum
// value. If the currect capacity of the list is less than min, the
// capacity is increased to twice the current capacity or to min,
// whichever is larger.
private void EnsureCapacity(int min) {
if (_items.Length < min) {
int newCapacity = _items.Length == 0? _defaultCapacity : _items.Length * 2;
// Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow.
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast
if ((uint)newCapacity > Array.MaxArrayLength) newCapacity = Array.MaxArrayLength;
if (newCapacity < min) newCapacity = min;
Capacity = newCapacity;
}
}
public bool Exists(Predicate<T> match) {
return FindIndex(match) != -1;
}
public T Find(Predicate<T> match) {
if( match == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.EndContractBlock();
for(int i = 0 ; i < _size; i++) {
if(match(_items[i])) {
return _items[i];
}
}
return default(T);
}
public List<T> FindAll(Predicate<T> match) {
if( match == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.EndContractBlock();
List<T> list = new List<T>();
for(int i = 0 ; i < _size; i++) {
if(match(_items[i])) {
list.Add(_items[i]);
}
}
return list;
}
public int FindIndex(Predicate<T> match) {
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
return FindIndex(0, _size, match);
}
public int FindIndex(int startIndex, Predicate<T> match) {
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < startIndex + Count);
return FindIndex(startIndex, _size - startIndex, match);
}
public int FindIndex(int startIndex, int count, Predicate<T> match) {
if( (uint)startIndex > (uint)_size ) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
}
if (count < 0 || startIndex > _size - count) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count);
}
if( match == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < startIndex + count);
Contract.EndContractBlock();
int endIndex = startIndex + count;
for( int i = startIndex; i < endIndex; i++) {
if( match(_items[i])) return i;
}
return -1;
}
public T FindLast(Predicate<T> match) {
if( match == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.EndContractBlock();
for(int i = _size - 1 ; i >= 0; i--) {
if(match(_items[i])) {
return _items[i];
}
}
return default(T);
}
public int FindLastIndex(Predicate<T> match) {
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
return FindLastIndex(_size - 1, _size, match);
}
public int FindLastIndex(int startIndex, Predicate<T> match) {
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() <= startIndex);
return FindLastIndex(startIndex, startIndex + 1, match);
}
public int FindLastIndex(int startIndex, int count, Predicate<T> match) {
if( match == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() <= startIndex);
Contract.EndContractBlock();
if(_size == 0) {
// Special case for 0 length List
if( startIndex != -1) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
}
}
else {
// Make sure we're not out of range
if ( (uint)startIndex >= (uint)_size) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
}
}
// 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count);
}
int endIndex = startIndex - count;
for( int i = startIndex; i > endIndex; i--) {
if( match(_items[i])) {
return i;
}
}
return -1;
}
public void ForEach(Action<T> action) {
if( action == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.EndContractBlock();
int version = _version;
for(int i = 0 ; i < _size; i++) {
if (version != _version && BinaryCompatibility.TargetsAtLeast_Desktop_V4_5) {
break;
}
action(_items[i]);
}
if (version != _version && BinaryCompatibility.TargetsAtLeast_Desktop_V4_5)
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
}
// Returns an enumerator for this list with the given
// permission for removal of elements. If modifications made to the list
// while an enumeration is in progress, the MoveNext and
// GetObject methods of the enumerator will throw an exception.
//
public Enumerator GetEnumerator() {
return new Enumerator(this);
}
/// <internalonly/>
IEnumerator<T> IEnumerable<T>.GetEnumerator() {
return new Enumerator(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
return new Enumerator(this);
}
public List<T> GetRange(int index, int count) {
if (index < 0) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (_size - index < count) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
}
Contract.Ensures(Contract.Result<List<T>>() != null);
Contract.EndContractBlock();
List<T> list = new List<T>(count);
Array.Copy(_items, index, list._items, 0, count);
list._size = count;
return list;
}
// Returns the index of the first occurrence of a given value in a range of
// this list. The list is searched forwards from beginning to end.
// The elements of the list are compared to the given value using the
// Object.Equals method.
//
// This method uses the Array.IndexOf method to perform the
// search.
//
public int IndexOf(T item) {
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
return Array.IndexOf(_items, item, 0, _size);
}
int System.Collections.IList.IndexOf(Object item)
{
if(IsCompatibleObject(item)) {
return IndexOf((T)item);
}
return -1;
}
// Returns the index of the first occurrence of a given value in a range of
// this list. The list is searched forwards, starting at index
// index and ending at count number of elements. The
// elements of the list are compared to the given value using the
// Object.Equals method.
//
// This method uses the Array.IndexOf method to perform the
// search.
//
public int IndexOf(T item, int index) {
if (index > _size)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index);
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
Contract.EndContractBlock();
return Array.IndexOf(_items, item, index, _size - index);
}
// Returns the index of the first occurrence of a given value in a range of
// this list. The list is searched forwards, starting at index
// index and upto count number of elements. The
// elements of the list are compared to the given value using the
// Object.Equals method.
//
// This method uses the Array.IndexOf method to perform the
// search.
//
public int IndexOf(T item, int index, int count) {
if (index > _size)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index);
if (count <0 || index > _size - count) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count);
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
Contract.EndContractBlock();
return Array.IndexOf(_items, item, index, count);
}
// Inserts an element into this list at a given index. The size of the list
// is increased by one. If required, the capacity of the list is doubled
// before inserting the new element.
//
public void Insert(int index, T item) {
// Note that insertions at the end are legal.
if ((uint) index > (uint)_size) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_ListInsert);
}
Contract.EndContractBlock();
if (_size == _items.Length) EnsureCapacity(_size + 1);
if (index < _size) {
Array.Copy(_items, index, _items, index + 1, _size - index);
}
_items[index] = item;
_size++;
_version++;
}
void System.Collections.IList.Insert(int index, Object item)
{
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(item, ExceptionArgument.item);
try {
Insert(index, (T) item);
}
catch (InvalidCastException) {
ThrowHelper.ThrowWrongValueTypeArgumentException(item, typeof(T));
}
}
// Inserts the elements of the given collection at a given index. If
// required, the capacity of the list is increased to twice the previous
// capacity or the new size, whichever is larger. Ranges may be added
// to the end of the list by setting index to the List's size.
//
public void InsertRange(int index, IEnumerable<T> collection) {
if (collection==null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
}
if ((uint)index > (uint)_size) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index);
}
Contract.EndContractBlock();
ICollection<T> c = collection as ICollection<T>;
if( c != null ) { // if collection is ICollection<T>
int count = c.Count;
if (count > 0) {
EnsureCapacity(_size + count);
if (index < _size) {
Array.Copy(_items, index, _items, index + count, _size - index);
}
// If we're inserting a List into itself, we want to be able to deal with that.
if (this == c) {
// Copy first part of _items to insert location
Array.Copy(_items, 0, _items, index, index);
// Copy last part of _items back to inserted location
Array.Copy(_items, index+count, _items, index*2, _size-index);
}
else {
T[] itemsToInsert = new T[count];
c.CopyTo(itemsToInsert, 0);
itemsToInsert.CopyTo(_items, index);
}
_size += count;
}
}
else {
using(IEnumerator<T> en = collection.GetEnumerator()) {
while(en.MoveNext()) {
Insert(index++, en.Current);
}
}
}
_version++;
}
// Returns the index of the last occurrence of a given value in a range of
// this list. The list is searched backwards, starting at the end
// and ending at the first element in the list. The elements of the list
// are compared to the given value using the Object.Equals method.
//
// This method uses the Array.LastIndexOf method to perform the
// search.
//
public int LastIndexOf(T item)
{
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
if (_size == 0) { // Special case for empty list
return -1;
}
else {
return LastIndexOf(item, _size - 1, _size);
}
}
// Returns the index of the last occurrence of a given value in a range of
// this list. The list is searched backwards, starting at index
// index and ending at the first element in the list. The
// elements of the list are compared to the given value using the
// Object.Equals method.
//
// This method uses the Array.LastIndexOf method to perform the
// search.
//
public int LastIndexOf(T item, int index)
{
if (index >= _size)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index);
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(((Count == 0) && (Contract.Result<int>() == -1)) || ((Count > 0) && (Contract.Result<int>() <= index)));
Contract.EndContractBlock();
return LastIndexOf(item, index, index + 1);
}
// Returns the index of the last occurrence of a given value in a range of
// this list. The list is searched backwards, starting at index
// index and upto count elements. The elements of
// the list are compared to the given value using the Object.Equals
// method.
//
// This method uses the Array.LastIndexOf method to perform the
// search.
//
public int LastIndexOf(T item, int index, int count) {
if ((Count != 0) && (index < 0)) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if ((Count !=0) && (count < 0)) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(((Count == 0) && (Contract.Result<int>() == -1)) || ((Count > 0) && (Contract.Result<int>() <= index)));
Contract.EndContractBlock();
if (_size == 0) { // Special case for empty list
return -1;
}
if (index >= _size) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_BiggerThanCollection);
}
if (count > index + 1) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_BiggerThanCollection);
}
return Array.LastIndexOf(_items, item, index, count);
}
// Removes the element at the given index. The size of the list is
// decreased by one.
//
public bool Remove(T item) {
int index = IndexOf(item);
if (index >= 0) {
RemoveAt(index);
return true;
}
return false;
}
void System.Collections.IList.Remove(Object item)
{
if(IsCompatibleObject(item)) {
Remove((T) item);
}
}
// This method removes all items which matches the predicate.
// The complexity is O(n).
public int RemoveAll(Predicate<T> match) {
if( match == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() <= Contract.OldValue(Count));
Contract.EndContractBlock();
int freeIndex = 0; // the first free slot in items array
// Find the first item which needs to be removed.
while( freeIndex < _size && !match(_items[freeIndex])) freeIndex++;
if( freeIndex >= _size) return 0;
int current = freeIndex + 1;
while( current < _size) {
// Find the first item which needs to be kept.
while( current < _size && match(_items[current])) current++;
if( current < _size) {
// copy item to the free slot.
_items[freeIndex++] = _items[current++];
}
}
Array.Clear(_items, freeIndex, _size - freeIndex);
int result = _size - freeIndex;
_size = freeIndex;
_version++;
return result;
}
// Removes the element at the given index. The size of the list is
// decreased by one.
//
public void RemoveAt(int index) {
if ((uint)index >= (uint)_size) {
ThrowHelper.ThrowArgumentOutOfRangeException();
}
Contract.EndContractBlock();
_size--;
if (index < _size) {
Array.Copy(_items, index + 1, _items, index, _size - index);
}
_items[_size] = default(T);
_version++;
}
// Removes a range of elements from this list.
//
public void RemoveRange(int index, int count) {
if (index < 0) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (_size - index < count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
Contract.EndContractBlock();
if (count > 0) {
int i = _size;
_size -= count;
if (index < _size) {
Array.Copy(_items, index + count, _items, index, _size - index);
}
Array.Clear(_items, _size, count);
_version++;
}
}
// Reverses the elements in this list.
public void Reverse() {
Reverse(0, Count);
}
// Reverses the elements in a range of this list. Following a call to this
// method, an element in the range given by index and count
// which was previously located at index i will now be located at
// index index + (index + count - i - 1).
//
// This method uses the Array.Reverse method to reverse the
// elements.
//
public void Reverse(int index, int count) {
if (index < 0) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (_size - index < count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
Contract.EndContractBlock();
Array.Reverse(_items, index, count);
_version++;
}
// Sorts the elements in this list. Uses the default comparer and
// Array.Sort.
public void Sort()
{
Sort(0, Count, null);
}
// Sorts the elements in this list. Uses Array.Sort with the
// provided comparer.
public void Sort(IComparer<T> comparer)
{
Sort(0, Count, comparer);
}
// Sorts the elements in a section of this list. The sort compares the
// elements to each other using the given IComparer interface. If
// comparer is null, the elements are compared to each other using
// the IComparable interface, which in that case must be implemented by all
// elements of the list.
//
// This method uses the Array.Sort method to sort the elements.
//
public void Sort(int index, int count, IComparer<T> comparer) {
if (index < 0) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (_size - index < count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
Contract.EndContractBlock();
Array.Sort<T>(_items, index, count, comparer);
_version++;
}
public void Sort(Comparison<T> comparison) {
if( comparison == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.EndContractBlock();
if( _size > 0) {
IComparer<T> comparer = new Array.FunctorComparer<T>(comparison);
Array.Sort(_items, 0, _size, comparer);
}
}
// ToArray returns a new Object array containing the contents of the List.
// This requires copying the List, which is an O(n) operation.
public T[] ToArray() {
Contract.Ensures(Contract.Result<T[]>() != null);
Contract.Ensures(Contract.Result<T[]>().Length == Count);
T[] array = new T[_size];
Array.Copy(_items, 0, array, 0, _size);
return array;
}
// Sets the capacity of this list to the size of the list. This method can
// be used to minimize a list's memory overhead once it is known that no
// new elements will be added to the list. To completely clear a list and
// release all memory referenced by the list, execute the following
// statements:
//
// list.Clear();
// list.TrimExcess();
//
public void TrimExcess() {
int threshold = (int)(((double)_items.Length) * 0.9);
if( _size < threshold ) {
Capacity = _size;
}
}
public bool TrueForAll(Predicate<T> match) {
if( match == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.EndContractBlock();
for(int i = 0 ; i < _size; i++) {
if( !match(_items[i])) {
return false;
}
}
return true;
}
internal static IList<T> Synchronized(List<T> list) {
return new SynchronizedList(list);
}
[Serializable()]
internal class SynchronizedList : IList<T> {
private List<T> _list;
private Object _root;
internal SynchronizedList(List<T> list) {
_list = list;
_root = ((System.Collections.ICollection)list).SyncRoot;
}
public int Count {
get {
lock (_root) {
return _list.Count;
}
}
}
public bool IsReadOnly {
get {
return ((ICollection<T>)_list).IsReadOnly;
}
}
public void Add(T item) {
lock (_root) {
_list.Add(item);
}
}
public void Clear() {
lock (_root) {
_list.Clear();
}
}
public bool Contains(T item) {
lock (_root) {
return _list.Contains(item);
}
}
public void CopyTo(T[] array, int arrayIndex) {
lock (_root) {
_list.CopyTo(array, arrayIndex);
}
}
public bool Remove(T item) {
lock (_root) {
return _list.Remove(item);
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
lock (_root) {
return _list.GetEnumerator();
}
}
IEnumerator<T> IEnumerable<T>.GetEnumerator() {
lock (_root) {
return ((IEnumerable<T>)_list).GetEnumerator();
}
}
public T this[int index] {
get {
lock(_root) {
return _list[index];
}
}
set {
lock(_root) {
_list[index] = value;
}
}
}
public int IndexOf(T item) {
lock (_root) {
return _list.IndexOf(item);
}
}
public void Insert(int index, T item) {
lock (_root) {
_list.Insert(index, item);
}
}
public void RemoveAt(int index) {
lock (_root) {
_list.RemoveAt(index);
}
}
}
[Serializable]
public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator
{
private List<T> list;
private int index;
private int version;
private T current;
internal Enumerator(List<T> list) {
this.list = list;
index = 0;
version = list._version;
current = default(T);
}
public void Dispose() {
}
public bool MoveNext() {
List<T> localList = list;
if (version == localList._version && ((uint)index < (uint)localList._size))
{
current = localList._items[index];
index++;
return true;
}
return MoveNextRare();
}
private bool MoveNextRare()
{
if (version != list._version) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
}
index = list._size + 1;
current = default(T);
return false;
}
public T Current {
get {
return current;
}
}
Object System.Collections.IEnumerator.Current {
get {
if( index == 0 || index == list._size + 1) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
}
return Current;
}
}
void System.Collections.IEnumerator.Reset() {
if (version != list._version) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
}
index = 0;
current = default(T);
}
}
}
}
| |
/*
* Copyright (c) 2010-2012, Achim 'ahzf' Friedland <achim@graph-database.org>
* This file is part of Styx <http://www.github.com/Vanaheimr/Styx>
*
* 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.
*/
#region Usings
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
#endregion
namespace de.ahzf.Styx
{
#region Delegate PipelineDefinition
/// <summary>
/// A definition delegate for pipelines.
/// </summary>
/// <typeparam name="S">The type of the consuming objects.</typeparam>
/// <typeparam name="E">The type of the emitting objects.</typeparam>
/// <param name="Element">A source element.</param>
public delegate IEndPipe<E> PipelineDefinition<S, E>(S Element);
#endregion
/// <summary>
/// A Pipeline is a linear composite of Pipes.
/// Pipeline takes a List of Pipes and joins them according to their order as specified by their location in the List.
/// It is important to ensure that the provided ordered Pipes can connect together.
/// That is, that the output of the n-1 Pipe is the same as the input to n Pipe.
/// Once all provided Pipes are composed, a Pipeline can be treated like any other Pipe.
/// </summary>
/// <typeparam name="S">The type of the consuming objects.</typeparam>
/// <typeparam name="E">The type of the emitting objects.</typeparam>
public class Pipeline<S, E> : IPipe<S, E>
{
#region Data
private IPipe[] _Pipes;
private IStartPipe<S> _StartPipe;
private IEndPipe<E> _EndPipe;
private String _PipelineString;
private readonly PipelineDefinition<S, E> _PipelineDefinition;
private IEndPipe<E> _TmpIterator;
private IEnumerator<S> _InternalEnumerator;
private E _CurrentElement;
#endregion
#region Constructor(s)
#region Pipeline()
/// <summary>
/// Constructs a pipeline from the provided pipes.
/// </summary>
public Pipeline()
{
_PipelineString = null;
}
#endregion
#region Pipeline(PipelineDefinition)
/// <summary>
/// Constructs a pipeline based on the given PipelineDefinition<S, E>.
/// </summary>
public Pipeline(PipelineDefinition<S, E> PipelineDefinition)
{
_PipelineDefinition = PipelineDefinition;
}
#endregion
#region Pipeline(IPipes)
/// <summary>
/// Constructs a pipeline from the provided pipes.
/// The ordered list determines how the pipes will be chained together.
/// When the pipes are chained together, the start of pipe n is the end of pipe n-1.
/// </summary>
/// <param name="IPipes">The ordered list of pipes to chain together into a pipeline</param>
public Pipeline(IEnumerable<IPipe> IPipes)
: this()
{
SetPipes(IPipes);
}
#endregion
#region Pipeline(IPipes)
/// <summary>
/// Constructs a pipeline from the provided pipes.
/// The ordered array determines how the pipes will be chained together.
/// When the pipes are chained together, the start of pipe n is the end of pipe n-1.
/// </summary>
/// <param name="IPipes">the ordered array of pipes to chain together into a pipeline</param>
public Pipeline(params IPipe[] IPipes)
: this()
{
SetPipes(IPipes);
}
#endregion
#endregion
#region SetPipes(IPipes)
/// <summary>
/// Use when extending Pipeline and setting the pipeline chain without making use of the constructor.
/// </summary>
/// <param name="IPipes">the ordered list of pipes to chain together into a pipeline.</param>
protected IPipe<S, E> SetPipes(IEnumerable<IPipe> IPipes)
{
SetPipes(IPipes.ToArray());
return this;
}
#endregion
#region SetPipes(IPipes)
/// <summary>
/// Use when extending Pipeline and setting the pipeline chain without making use of the constructor.
/// </summary>
/// <param name="IPipes">the ordered array of pipes to chain together into a pipeline.</param>
protected void SetPipes(params IPipe[] IPipes)
{
_Pipes = IPipes;
var _PipeNames = new List<String>();
var _Length = IPipes.Length;
_StartPipe = IPipes[0] as IStartPipe<S>;
if (_StartPipe == null)
throw new ArgumentException("The first Pipe must implement 'IStartPipe<" + typeof(S) + ">', but '" + IPipes[0].GetType() + "' was provided!");
_EndPipe = IPipes[_Length - 1] as IEndPipe<E>;
if (_EndPipe == null)
throw new ArgumentException("The last Pipe must implement 'IEndPipe<" + typeof(E) + ">', but '" + IPipes[_Length - 1].GetType() + "' was provided!");
_PipeNames.Add(_StartPipe.ToString());
Type[] _GenericArguments = null;
Type _Consumes;
Type _Emitts;
#if SILVERLIGHT
Type _GenericIPipeInterface = _StartPipe.GetType().GetInterface("IPipe`2", false);
#else
Type _GenericIPipeInterface = _StartPipe.GetType().GetInterface("IPipe`2");
#endif
if (_GenericIPipeInterface == null)
throw new ArgumentException("IPipe<?,?> expected!");
_Emitts = _GenericIPipeInterface.GetGenericArguments()[1];
for (var i = 1; i < _Length; i++)
{
#if SILVERLIGHT
_GenericArguments = IPipes[i].GetType().GetInterface("IPipe`2", false).GetGenericArguments();
#else
_GenericArguments = IPipes[i].GetType().GetInterface("IPipe`2").GetGenericArguments();
#endif
_Consumes = _GenericArguments[0];
if (_Consumes != _Emitts)
throw new ArgumentException(IPipes[i - 1].GetType() + " emitts other objects than " + IPipes[i].GetType() + " consumes!");
_Emitts = _GenericArguments[1];
IPipes[i].SetSource(IPipes[i - 1]);
_PipeNames.Add(IPipes[i].ToString());
}
if (_InternalEnumerator != null)
IPipes[0].SetSource(_InternalEnumerator);
_PipelineString = _PipeNames.ToString();
}
#endregion
#region SetSource(SourceElement)
/// <summary>
/// Set the given element as source.
/// </summary>
/// <param name="SourceElement">A single source element.</param>
public virtual IPipe<S, E> SetSource(S SourceElement)
{
_InternalEnumerator = new HistoryEnumerator<S>(new List<S>() { SourceElement }.GetEnumerator());
if (_Pipes != null && _Pipes.Length > 0)
_Pipes[0].SetSource(_InternalEnumerator);
return this;
}
#endregion
#region SetSource(IEnumerator)
/// <summary>
/// Set the elements emitted by the given IEnumerator<S> as input.
/// </summary>
/// <param name="IEnumerator">An IEnumerator<S> as element source.</param>
public virtual IPipe<S, E> SetSource(IEnumerator<S> IEnumerator)
{
if (IEnumerator == null)
throw new ArgumentNullException("myIEnumerator must not be null!");
_InternalEnumerator = IEnumerator;
if (_Pipes != null && _Pipes.Length > 0)
_Pipes[0].SetSource(_InternalEnumerator);
return this;
}
/// <summary>
/// Set the elements emitted by the given IEnumerator as input.
/// </summary>
/// <param name="myIEnumerator">An IEnumerator as element source.</param>
void IStartPipe.SetSource(IEnumerator myIEnumerator)
{
if (myIEnumerator == null)
throw new ArgumentNullException("myIEnumerator must not be null!");
_InternalEnumerator = myIEnumerator as IEnumerator<S>;
if (_InternalEnumerator == null)
throw new ArgumentNullException("myIEnumerator must implement 'IEnumerator<" + typeof(S) + ">'!");
if (_Pipes != null && _Pipes.Length > 0)
_Pipes[0].SetSource(_InternalEnumerator);
}
#endregion
#region SetSourceCollection(IEnumerable)
/// <summary>
/// Set the elements emitted by the given IEnumerable<S> as input.
/// </summary>
/// <param name="IEnumerable">An IEnumerable<S> as element source.</param>
public virtual IPipe<S, E> SetSourceCollection(IEnumerable<S> IEnumerable)
{
if (IEnumerable == null)
throw new ArgumentNullException("myIEnumerator must not be null!");
_InternalEnumerator = IEnumerable.GetEnumerator();
if (_Pipes != null && _Pipes.Length > 0)
_Pipes[0].SetSource(_InternalEnumerator);
return this;
}
/// <summary>
/// Set the elements emitted from the given IEnumerable as input.
/// </summary>
/// <param name="myIEnumerable">An IEnumerable as element source.</param>
void IStartPipe.SetSourceCollection(IEnumerable myIEnumerable)
{
if (myIEnumerable == null)
throw new ArgumentNullException("myIEnumerable must not be null!");
_InternalEnumerator = myIEnumerable.GetEnumerator() as IEnumerator<S>;
if (_InternalEnumerator == null)
throw new ArgumentNullException("myIEnumerable must implement 'IEnumerable<" + typeof(S) + ">'!");
if (_Pipes != null && _Pipes.Length > 0)
_Pipes[0].SetSource(_InternalEnumerator);
}
#endregion
#region GetEnumerator()
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A IEnumerator<E> that can be used to iterate through the collection.
/// </returns>
public IEnumerator<E> GetEnumerator()
{
return this;
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A IEnumerator that can be used to iterate through the collection.
/// </returns>
IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this;
}
#endregion
#region Current
/// <summary>
/// Gets the current element in the collection.
/// </summary>
public E Current
{
get
{
return _CurrentElement;
}
}
/// <summary>
/// Gets the current element in the collection.
/// </summary>
Object System.Collections.IEnumerator.Current
{
get
{
return _CurrentElement;
}
}
#endregion
#region MoveNext()
/// <summary>
/// Advances the enumerator to the next element of the collection.
/// </summary>
/// <returns>
/// True if the enumerator was successfully advanced to the next
/// element; false if the enumerator has passed the end of the
/// collection.
/// </returns>
public Boolean MoveNext()
{
if (_InternalEnumerator == null)
return false;
if (_EndPipe == null && _PipelineDefinition == null)
return false;
if (_EndPipe != null)
{
if (_EndPipe.MoveNext())
{
_CurrentElement = _EndPipe.Current;
return true;
}
}
else if (_PipelineDefinition != null)
{
while (true)
{
if (_TmpIterator != null && _TmpIterator.MoveNext())
{
_CurrentElement = _TmpIterator.Current;
return true;
}
else if (_InternalEnumerator.MoveNext())
_TmpIterator = _PipelineDefinition(_InternalEnumerator.Current);
else
return false;
}
}
return false;
}
#endregion
#region Reset()
/// <summary>
/// Sets the enumerator to its initial position, which is
/// before the first element in the collection.
/// </summary>
public void Reset()
{
foreach (var _Pipe in _Pipes)
_Pipe.Reset();
}
#endregion
#region Dispose()
/// <summary>
/// Disposes this pipeline.
/// </summary>
public void Dispose()
{
if (_Pipes != null)
foreach (var _Pipe in _Pipes)
_Pipe.Dispose();
}
#endregion
#region Path
/// <summary>
/// Returns the transformation path to arrive at the current object
/// of the pipe. This is a list of all of the objects traversed for
/// the current iterator position of the pipe.
/// </summary>
public List<Object> Path
{
get
{
return _EndPipe.Path;
}
}
#endregion
#region ToString()
/// <summary>
/// A string representation of this pipe.
/// </summary>
public override String ToString()
{
return _PipelineString;
}
#endregion
void IStartPipe<S>.SetSource(S SourceElement)
{
throw new NotImplementedException();
}
void IStartPipe<S>.SetSource(IEnumerator<S> IEnumerator)
{
throw new NotImplementedException();
}
void IStartPipe<S>.SetSourceCollection(IEnumerable<S> IEnumerable)
{
throw new NotImplementedException();
}
public void SetSource(object SourceElement)
{
throw new NotImplementedException();
}
}
}
| |
// 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 GetValuesListDictionaryTests
{
public const int MAX_LEN = 50; // max length of random strings
[Fact]
public void Test01()
{
IntlStrings intl;
ListDictionary ld;
// simple string values
string[] values =
{
"",
" ",
"a",
"aa",
"tExt",
" spAces",
"1",
"$%^#",
"2222222222222222222222222",
System.DateTime.Today.ToString(),
Int32.MaxValue.ToString()
};
// keys for simple string values
string[] keys =
{
"zero",
"one",
" ",
"",
"aa",
"1",
System.DateTime.Today.ToString(),
"$%^#",
Int32.MaxValue.ToString(),
" spaces",
"2222222222222222222222222"
};
Array arr;
ICollection vs; // Values collection
int ind;
// initialize IntStrings
intl = new IntlStrings();
// [] ListDictionary is constructed as expected
//-----------------------------------------------------------------
ld = new ListDictionary();
// [] get Values for empty dictionary
//
if (ld.Count > 0)
ld.Clear();
if (ld.Values.Count != 0)
{
Assert.False(true, string.Format("Error, returned Values.Count = {0}", ld.Values.Count));
}
// [] get Values for filled dictionary
//
int len = values.Length;
ld.Clear();
for (int i = 0; i < len; i++)
{
ld.Add(keys[i], values[i]);
}
if (ld.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, len));
}
vs = ld.Values;
if (vs.Count != len)
{
Assert.False(true, string.Format("Error, returned Values.Count = {0}", vs.Count));
}
arr = Array.CreateInstance(typeof(Object), len);
vs.CopyTo(arr, 0);
for (int i = 0; i < len; i++)
{
ind = Array.IndexOf(arr, values[i]);
if (ind < 0)
{
Assert.False(true, string.Format("Error, Values doesn't contain \"{1}\" value. Search result: {2}", i, values[i], ind));
}
}
//
// [] get Values on dictionary with identical values
//
ld.Clear();
string intlStr = intl.GetRandomString(MAX_LEN);
ld.Add("keykey", intlStr); // 1st key
for (int i = 0; i < len; i++)
{
ld.Add(keys[i], values[i]);
}
ld.Add("keyKey", intlStr); // 2nd key
if (ld.Count != len + 2)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, len + 2));
}
// get Values
//
vs = ld.Values;
if (vs.Count != ld.Count)
{
Assert.False(true, string.Format("Error, returned Values.Count = {0}", vs.Count));
}
arr = Array.CreateInstance(typeof(Object), len + 2);
vs.CopyTo(arr, 0);
for (int i = 0; i < len; i++)
{
ind = Array.IndexOf(arr, values[i]);
if (ind < 0)
{
Assert.False(true, string.Format("Error, Values doesn't contain \"{1}\" value", i, values[i]));
}
}
ind = Array.IndexOf(arr, intlStr);
if (ind < 0)
{
Assert.False(true, string.Format("Error, Values doesn't contain {0} value", intlStr));
}
//
// Intl strings
// [] get Values for dictionary filled with Intl strings
//
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;
}
//
// will use first half of array as values and second half as keys
//
ld.Clear();
for (int i = 0; i < len; i++)
{
ld.Add(intlValues[i + len], intlValues[i]);
}
if (ld.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, len));
}
vs = ld.Values;
if (vs.Count != len)
{
Assert.False(true, string.Format("Error, returned Values.Count = {0}", vs.Count));
}
arr = Array.CreateInstance(typeof(Object), len);
vs.CopyTo(arr, 0);
for (int i = 0; i < arr.Length; i++)
{
ind = Array.IndexOf(arr, intlValues[i]);
if (ind < 0)
{
Assert.False(true, string.Format("Error, Values doesn't contain \"{1}\" value", i, intlValues[i]));
}
}
//
// [] Change dictionary and check Values
//
ld.Clear();
for (int i = 0; i < len; i++)
{
ld.Add(keys[i], values[i]);
}
if (ld.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, len));
}
vs = ld.Values;
if (vs.Count != len)
{
Assert.False(true, string.Format("Error, returned Values.Count = {0}", vs.Count));
}
ld.Remove(keys[0]);
if (ld.Count != len - 1)
{
Assert.False(true, string.Format("Error, didn't remove element"));
}
if (vs.Count != len - 1)
{
Assert.False(true, string.Format("Error, Values were not updated after removal"));
}
arr = Array.CreateInstance(typeof(Object), ld.Count);
vs.CopyTo(arr, 0);
ind = Array.IndexOf(arr, values[0]);
if (ind >= 0)
{
Assert.False(true, string.Format("Error, Values still contains removed value " + ind));
}
ld.Add(keys[0], "new item");
if (ld.Count != len)
{
Assert.False(true, string.Format("Error, didn't add element"));
}
if (vs.Count != len)
{
Assert.False(true, string.Format("Error, Values were not updated after addition"));
}
arr = Array.CreateInstance(typeof(Object), ld.Count);
vs.CopyTo(arr, 0);
ind = Array.IndexOf(arr, "new item");
if (ind < 0)
{
Assert.False(true, string.Format("Error, Values doesn't contain added value "));
}
// [] Run IEnumerable tests
ListDictionary Ld = new ListDictionary();
String[] expectedValues = new String[10];
for (int i = 0; i < 10; i++)
{
Ld.Add("key_" + i, "val_" + i);
expectedValues[i] = "val_" + i;
}
TestSupport.Collections.IEnumerable_Test iEnumerableTest;
iEnumerableTest = new TestSupport.Collections.IEnumerable_Test(Ld.Values, expectedValues);
if (!iEnumerableTest.RunAllTests())
{
Assert.False(true, string.Format("Err_98382apeuie System.Collections.IEnumerable tests FAILED"));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
namespace Ripper
{
partial class Login
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region 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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Login));
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.RegisterLink = new System.Windows.Forms.LinkLabel();
this.checkBox1 = new System.Windows.Forms.CheckBox();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.LoginBtn = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.textBox2 = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.comboBox2 = new System.Windows.Forms.ComboBox();
this.timer1 = new System.Timers.Timer();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.GuestLoginButton = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.timer1)).BeginInit();
this.groupBox2.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.RegisterLink);
this.groupBox1.Controls.Add(this.checkBox1);
this.groupBox1.Controls.Add(this.label4);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.LoginBtn);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.textBox2);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.textBox1);
this.groupBox1.Location = new System.Drawing.Point(8, 16);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(359, 241);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Provide Login Credentials for the ViperGirls Forums";
this.groupBox1.UseCompatibleTextRendering = true;
//
// RegisterLink
//
this.RegisterLink.AutoSize = true;
this.RegisterLink.Location = new System.Drawing.Point(99, 183);
this.RegisterLink.Name = "RegisterLink";
this.RegisterLink.Size = new System.Drawing.Size(177, 13);
this.RegisterLink.TabIndex = 7;
this.RegisterLink.TabStop = true;
this.RegisterLink.Text = "Not a Member yet? Click to Register";
this.RegisterLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.RegisterLink_LinkClicked);
//
// checkBox1
//
this.checkBox1.Checked = true;
this.checkBox1.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBox1.Enabled = false;
this.checkBox1.Location = new System.Drawing.Point(102, 152);
this.checkBox1.MaximumSize = new System.Drawing.Size(144, 24);
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new System.Drawing.Size(120, 23);
this.checkBox1.TabIndex = 2;
this.checkBox1.Text = "Remember Me";
this.checkBox1.UseCompatibleTextRendering = true;
//
// label4
//
this.label4.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.ForeColor = System.Drawing.Color.Red;
this.label4.Location = new System.Drawing.Point(16, 24);
this.label4.MaximumSize = new System.Drawing.Size(352, 48);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(293, 45);
this.label4.TabIndex = 6;
this.label4.Text = "WARNING! More than 3 failed tries will result in your Forum Account being locked!" +
" You have been warned!";
this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.label4.UseCompatibleTextRendering = true;
//
// label3
//
this.label3.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.ForeColor = System.Drawing.Color.Red;
this.label3.Location = new System.Drawing.Point(13, 207);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(335, 24);
this.label3.TabIndex = 5;
this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// LoginBtn
//
this.LoginBtn.Image = ((System.Drawing.Image)(resources.GetObject("LoginBtn.Image")));
this.LoginBtn.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.LoginBtn.Location = new System.Drawing.Point(252, 152);
this.LoginBtn.MaximumSize = new System.Drawing.Size(96, 24);
this.LoginBtn.Name = "LoginBtn";
this.LoginBtn.Size = new System.Drawing.Size(80, 23);
this.LoginBtn.TabIndex = 3;
this.LoginBtn.Text = "Login";
this.LoginBtn.UseCompatibleTextRendering = true;
this.LoginBtn.Click += new System.EventHandler(this.LoginBtnClick);
//
// label2
//
this.label2.Location = new System.Drawing.Point(9, 123);
this.label2.MaximumSize = new System.Drawing.Size(87, 16);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(73, 14);
this.label2.TabIndex = 3;
this.label2.Text = "Password :";
this.label2.UseCompatibleTextRendering = true;
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(102, 120);
this.textBox2.MaximumSize = new System.Drawing.Size(246, 20);
this.textBox2.Name = "textBox2";
this.textBox2.PasswordChar = '*';
this.textBox2.Size = new System.Drawing.Size(205, 20);
this.textBox2.TabIndex = 1;
//
// label1
//
this.label1.Location = new System.Drawing.Point(9, 88);
this.label1.MaximumSize = new System.Drawing.Size(87, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(73, 15);
this.label1.TabIndex = 1;
this.label1.Text = "User Name :";
this.label1.UseCompatibleTextRendering = true;
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(102, 88);
this.textBox1.MaximumSize = new System.Drawing.Size(246, 20);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(205, 20);
this.textBox1.TabIndex = 0;
//
// label5
//
this.label5.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.label5.Location = new System.Drawing.Point(76, 363);
this.label5.MaximumSize = new System.Drawing.Size(0, 13);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(184, 12);
this.label5.TabIndex = 13;
this.label5.Text = "label5";
this.label5.TextAlign = System.Drawing.ContentAlignment.TopRight;
this.label5.UseCompatibleTextRendering = true;
//
// comboBox2
//
this.comboBox2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.comboBox2.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox2.Items.AddRange(new object[] { "German", "French", "English" });
this.comboBox2.Location = new System.Drawing.Point(266, 359);
this.comboBox2.MaximumSize = new System.Drawing.Size(121, 0);
this.comboBox2.Name = "comboBox2";
this.comboBox2.Size = new System.Drawing.Size(101, 21);
this.comboBox2.TabIndex = 4;
this.comboBox2.SelectedIndexChanged += new System.EventHandler(this.ComboBox2SelectedIndexChanged);
//
// timer1
//
this.timer1.Interval = 400D;
this.timer1.SynchronizingObject = this;
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.Timer1Elapsed);
//
// groupBox2
//
this.groupBox2.Controls.Add(this.GuestLoginButton);
this.groupBox2.Location = new System.Drawing.Point(8, 264);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(359, 81);
this.groupBox2.TabIndex = 14;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Or Login as Guest ...";
//
// GuestLoginButton
//
this.GuestLoginButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.GuestLoginButton.Location = new System.Drawing.Point(102, 19);
this.GuestLoginButton.Name = "GuestLoginButton";
this.GuestLoginButton.Size = new System.Drawing.Size(244, 47);
this.GuestLoginButton.TabIndex = 4;
this.GuestLoginButton.Text = "Guest Login";
this.GuestLoginButton.UseCompatibleTextRendering = true;
this.GuestLoginButton.Click += new System.EventHandler(this.GuestLoginButton_Click);
//
// Login
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(375, 395);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.label5);
this.Controls.Add(this.comboBox2);
this.Controls.Add(this.groupBox1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "Login";
this.Text = "Login";
this.Load += new System.EventHandler(this.LoginLoad);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.timer1)).EndInit();
this.groupBox2.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBox1;
private TextBox textBox1;
private Label label1;
private Label label2;
private TextBox textBox2;
private Button LoginBtn;
private Label label3;
private System.Timers.Timer timer1;
private Label label4;
private CheckBox checkBox1;
private ComboBox comboBox2;
private Label label5;
private GroupBox groupBox2;
private Button GuestLoginButton;
private LinkLabel RegisterLink;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace System
{
internal sealed class ArrayEnumerator : IEnumerator, ICloneable
{
private Array array;
private int index;
private int endIndex;
private int startIndex; // Save for Reset.
private int[] _indices; // The current position in a multidim array
private bool _complete;
internal ArrayEnumerator(Array array, int index, int count)
{
this.array = array;
this.index = index - 1;
startIndex = index;
endIndex = index + count;
_indices = new int[array.Rank];
int checkForZero = 1; // Check for dimensions of size 0.
for (int i = 0; i < array.Rank; i++)
{
_indices[i] = array.GetLowerBound(i);
checkForZero *= array.GetLength(i);
}
// To make MoveNext simpler, decrement least significant index.
_indices[_indices.Length - 1]--;
_complete = (checkForZero == 0);
}
private void IncArray()
{
// This method advances us to the next valid array index,
// handling all the multiple dimension & bounds correctly.
// Think of it like an odometer in your car - we start with
// the last digit, increment it, and check for rollover. If
// it rolls over, we set all digits to the right and including
// the current to the appropriate lower bound. Do these overflow
// checks for each dimension, and if the most significant digit
// has rolled over it's upper bound, we're done.
//
int rank = array.Rank;
_indices[rank - 1]++;
for (int dim = rank - 1; dim >= 0; dim--)
{
if (_indices[dim] > array.GetUpperBound(dim))
{
if (dim == 0)
{
_complete = true;
break;
}
for (int j = dim; j < rank; j++)
_indices[j] = array.GetLowerBound(j);
_indices[dim - 1]++;
}
}
}
public object Clone()
{
return MemberwiseClone();
}
public bool MoveNext()
{
if (_complete)
{
index = endIndex;
return false;
}
index++;
IncArray();
return !_complete;
}
public object Current
{
get
{
if (index < startIndex) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted();
if (_complete) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded();
return array.GetValue(_indices);
}
}
public void Reset()
{
index = startIndex - 1;
int checkForZero = 1;
for (int i = 0; i < array.Rank; i++)
{
_indices[i] = array.GetLowerBound(i);
checkForZero *= array.GetLength(i);
}
_complete = (checkForZero == 0);
// To make MoveNext simpler, decrement least significant index.
_indices[_indices.Length - 1]--;
}
}
internal sealed class SZArrayEnumerator : IEnumerator, ICloneable
{
private readonly Array _array;
private int _index;
private int _endIndex; // Cache Array.Length, since it's a little slow.
internal SZArrayEnumerator(Array array)
{
Debug.Assert(array.Rank == 1 && array.GetLowerBound(0) == 0, "SZArrayEnumerator only works on single dimension arrays w/ a lower bound of zero.");
_array = array;
_index = -1;
_endIndex = array.Length;
}
public object Clone()
{
return MemberwiseClone();
}
public bool MoveNext()
{
if (_index < _endIndex)
{
_index++;
return (_index < _endIndex);
}
return false;
}
public object Current
{
get
{
if (_index < 0)
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted();
if (_index >= _endIndex)
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded();
return _array.GetValue(_index);
}
}
public void Reset()
{
_index = -1;
}
}
internal sealed class SZGenericArrayEnumerator<T> : IEnumerator<T>
{
private readonly T[] _array;
private int _index;
// Array.Empty is intentionally omitted here, since we don't want to pay for generic instantiations that
// wouldn't have otherwise been used.
internal static readonly SZGenericArrayEnumerator<T> Empty = new SZGenericArrayEnumerator<T>(new T[0]);
internal SZGenericArrayEnumerator(T[] array)
{
Debug.Assert(array != null);
_array = array;
_index = -1;
}
public bool MoveNext()
{
int index = _index + 1;
if ((uint)index >= (uint)_array.Length)
{
_index = _array.Length;
return false;
}
_index = index;
return true;
}
public T Current
{
get
{
int index = _index;
T[] array = _array;
if ((uint)index >= (uint)array.Length)
{
ThrowHelper.ThrowInvalidOperationException_EnumCurrent(index);
}
return array[index];
}
}
object IEnumerator.Current => Current;
void IEnumerator.Reset() => _index = -1;
public void Dispose()
{
}
}
}
| |
using System.Linq;
using NakedObjects.Boot;
using NakedObjects.Core.NakedObjectsSystem;
using NakedObjects.EntityObjectStore;
using NakedObjects.Services;
using NakedObjects.Xat;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Cluster.Batch.Impl;
using System.Data.Entity;
using Cluster.System.Mock;
using System;
using Cluster.Users.Mock;
using Helpers;
namespace Cluster.Batch.Test
{
[TestClass()]
public class BatchTests : ClusterXAT<BatchTestDbContext, BatchFixture>
{
#region Run configuration
//Set up the properties in this region exactly the same way as in your Run class
protected override IServicesInstaller MenuServices
{
get
{
return new ServicesInstaller(
new BatchRepository(),
new FixedClock(new DateTime(2000, 1, 1)),
new MockUserService());
}
}
protected override IFixturesInstaller Fixtures
{
get
{
return new FixturesInstaller(
new BatchFixture(),
new MockUsersFixture());
}
}
#endregion
#region Initialize and Cleanup
[TestInitialize()]
public void Initialize()
{
InitializeNakedObjectsFramework();
// Use e.g. DatabaseUtils.RestoreDatabase to revert database before each test (or within a [ClassInitialize()] method).
}
[TestCleanup()]
public void Cleanup()
{
CleanupNakedObjectsFramework();
}
#endregion
[TestMethod()]
public void CreateNewProcess()
{
var proc = GetTestService("Batch").GetAction("Create New Process Definition").InvokeReturnObject();
proc.AssertIsTransient().AssertIsType(typeof(BatchProcessDefinition));
var name = proc.GetPropertyByName("Name").AssertIsEmpty().AssertIsMandatory();
var desc = proc.GetPropertyByName("Description").AssertIsEmpty().AssertIsOptional();
var status = proc.GetPropertyByName("Status").AssertTitleIsEqual("Active").AssertIsMandatory().AssertIsUnmodifiable();
var className = proc.GetPropertyByName("Class To Invoke").AssertIsEmpty().AssertIsMandatory();
var instance = proc.GetPropertyByName("Process Instance Id").AssertIsOptional().AssertIsEmpty();
var priority = proc.GetPropertyByName("Priority").AssertIsMandatory().AssertValueIsEqual("1");
var attempts = proc.GetPropertyByName("Number Of Attempts Each Run").AssertIsMandatory().AssertValueIsEqual("1");
var firstRun = proc.GetPropertyByName("First Run").AssertIsMandatory().AssertValueIsEqual("01/01/2000 00:00:00");
var frequency = proc.GetPropertyByName("Frequency").AssertIsMandatory().AssertValueIsEqual("Manual Runs Only");
var nextRun = proc.GetPropertyByName("Next Run").AssertIsUnmodifiable().AssertIsEmpty();
var lastRun = proc.GetPropertyByName("Last Run").AssertIsOptional().AssertIsEmpty();
}
[TestMethod()]
public void ValidateClassToInvokeAndInstance()
{
var proc = GetTestService("Batch").GetAction("Create New Process Definition").InvokeReturnObject();
var name = proc.GetPropertyByName("Name").SetValue("Foo");
var className = proc.GetPropertyByName("Class To Invoke");
var instance = proc.GetPropertyByName("Process Instance Id").AssertIsOptional().AssertIsEmpty();
className.SetValue("Cluster.Batch.Test.MockSP");
proc.AssertCanBeSaved();
instance.SetValue("1");
proc.AssertCannotBeSaved();
className.SetValue("Cluster.Batch.Test.MockPersistentSP");
proc.AssertCanBeSaved();
instance.ClearValue();
proc.AssertCannotBeSaved();
className.SetValue("Cluster.Batch.Test.MockNotAnSP");
proc.AssertCannotBeSaved();
instance.SetValue("1");
proc.AssertCannotBeSaved();
}
[TestMethod()]
public void RetrievePersistentProcessInstance()
{
var find = GetTestService("Batch").GetAction("Find Process Definitions");
var proc = find.InvokeReturnCollection("Process5", null).ElementAt(0);
proc.AssertTitleEquals("Process5");
var mock = proc.GetAction("Retrieve Persistent Process Object").InvokeReturnObject();
mock.AssertIsPersistent().AssertIsType(typeof(MockPersistentSP));
mock.GetPropertyByName("Id").AssertValueIsEqual("1");
}
[TestMethod()]
public void RetrievePersistentProcessInstanceNotVisibleWhenProcessNotPersistent()
{
var find = GetTestService("Batch").GetAction("Find Process Definitions");
var proc = find.InvokeReturnCollection("Process4", null).ElementAt(0);
proc.AssertTitleEquals("Process4");
proc.GetAction("Retrieve Persistent Process Object").AssertIsInvisible() ;
}
[TestMethod]
public void ValidatePriority()
{
var proc = GetTestService("Batch").GetAction("Create New Process Definition").InvokeReturnObject();
var priority = proc.GetPropertyByName("Priority").AssertIsMandatory().AssertValueIsEqual("1");
priority.AssertFieldEntryIsValid("999");
priority.AssertFieldEntryInvalid("1000");
priority.AssertFieldEntryInvalid("0");
priority.AssertFieldEntryInvalid("-1");
priority.AssertFieldEntryInvalid("1.1");
}
[TestMethod]
public void ValidateNumberOfAttempts()
{
var proc = GetTestService("Batch").GetAction("Create New Process Definition").InvokeReturnObject();
var name = proc.GetPropertyByName("Name").SetValue("Foo");
var priority = proc.GetPropertyByName("Number Of Attempts Each Run").AssertIsMandatory().AssertValueIsEqual("1");
priority.AssertFieldEntryIsValid("1");
priority.AssertFieldEntryIsValid("9");
priority.AssertFieldEntryInvalid("10");
priority.AssertFieldEntryInvalid("0");
priority.AssertFieldEntryInvalid("-1");
priority.AssertFieldEntryInvalid("1.1");
}
//Minimal test that validation is being picked up as there is separate unit test for the validate method
[TestMethod()]
public void ValidateDates()
{
var proc = GetTestService("Batch").GetAction("Create New Process Definition").InvokeReturnObject();
proc.GetPropertyByName("Name").SetValue("Foo");
proc.GetPropertyByName("Class To Invoke").SetValue("Cluster.Batch.Test.MockSP");
var firstRun = proc.GetPropertyByName("First Run").AssertIsMandatory().AssertValueIsEqual("01/01/2000 00:00:00");
var lastRun = proc.GetPropertyByName("Last Run").AssertIsOptional().AssertIsEmpty();
firstRun.SetValue("03/01/2000");
lastRun.SetValue("02/01/2000");
proc.AssertCannotBeSaved();
firstRun.SetValue("01/01/2000");
proc.AssertCanBeSaved();
}
[TestMethod()]
public void SaveNewProcessAndTestNextRunDate()
{
var proc = GetTestService("Batch").GetAction("Create New Process Definition").InvokeReturnObject();
proc.GetPropertyByName("Name").SetValue("Foo");
var className = proc.GetPropertyByName("Class To Invoke").SetValue("Cluster.Batch.Test.MockSP");
var firstRun = proc.GetPropertyByName("First Run").SetValue("01/02/2000 00:00:00");
var frequency = proc.GetPropertyByName("Frequency").SetValue(Frequency.MonthlyOn1stOfMonth.ToString());
proc.Save();
proc.AssertIsPersistent();
proc.GetPropertyByName("Next Run").AssertValueIsEqual("01/02/2000 00:00:00");
}
[TestMethod()]
public void StatusChanges()
{
var proc = GetTestService("Batch").GetAction("Find Process Definitions").InvokeReturnCollection("Process1", null).ElementAt(0);
proc.AssertTitleEquals("Process1");
var status = proc.GetPropertyByName("Status").AssertIsMandatory().AssertIsUnmodifiable();
var firstRun = proc.GetPropertyByName("First Run").AssertIsNotEmpty();
var frequency = proc.GetPropertyByName("Frequency").AssertIsNotEmpty();
var nextRun = proc.GetPropertyByName("Next Run").AssertIsNotEmpty();
var lastRun = proc.GetPropertyByName("Last Run").AssertIsNotEmpty();
var suspend = proc.GetAction("Suspend");
var resume = proc.GetAction("Resume");
var archive = proc.GetAction("Archive");
status.AssertTitleIsEqual("Active");
suspend.AssertIsVisible().AssertIsEnabled();
resume.AssertIsInvisible();
archive.AssertIsVisible().AssertIsEnabled();
suspend.InvokeReturnObject();
status.AssertTitleIsEqual("Suspended");
suspend.AssertIsInvisible();
resume.AssertIsVisible().AssertIsEnabled();
archive.AssertIsVisible().AssertIsEnabled();
firstRun.AssertIsNotEmpty();
nextRun.AssertIsEmpty();
lastRun.AssertIsNotEmpty();
resume.InvokeReturnObject();
status.AssertTitleIsEqual("Active");
firstRun.AssertIsNotEmpty();
nextRun.AssertIsNotEmpty();
lastRun.AssertIsNotEmpty();
archive.InvokeReturnObject();
status.AssertTitleIsEqual("Archived");
suspend.AssertIsInvisible();
resume.AssertIsInvisible();
archive.AssertIsInvisible();
firstRun.AssertIsNotEmpty();
nextRun.AssertIsEmpty();
lastRun.AssertIsEmpty();
}
[TestMethod()]
public void RunProcessManually()
{
var proc = GetTestService("Batch").GetAction("Find Process Definitions").InvokeReturnCollection("Process2", null).ElementAt(0);
proc.AssertTitleEquals("Process2");
var className = proc.GetPropertyByName("Class To Invoke").AssertValueIsEqual("Cluster.Batch.Test.MockSP");
var instance = proc.GetPropertyByName("Process Instance Id").AssertIsEmpty();
var run = proc.GetAction("Run Process Manually");
var processRun = run.InvokeReturnObject();
processRun.AssertIsType(typeof(BatchLog)).AssertIsPersistent().AssertTitleEquals("01/01/2000 00:00:00");
processRun.GetPropertyByName("Process Definition").AssertObjectIsEqual(proc);
processRun.GetPropertyByName("When Run").AssertValueIsEqual("01/01/2000 00:00:00");
processRun.GetPropertyByName("Run Mode").AssertValueIsEqual("Manual");
processRun.GetPropertyByName("Successful").AssertValueIsEqual("True");
processRun.GetPropertyByName("Attempt Number").AssertValueIsEqual("1");
processRun.GetPropertyByName("Outcome").AssertValueIsEqual("MockSP run OK");
processRun.GetPropertyByName("User").AssertTitleIsEqual("Test");
}
[TestMethod()]
public void RunProcessManuallyThrowsException()
{
var proc = GetTestService("Batch").GetAction("Find Process Definitions").InvokeReturnCollection("Process3", null).ElementAt(0);
proc.AssertTitleEquals("Process3");
var className = proc.GetPropertyByName("Class To Invoke").AssertValueIsEqual("Cluster.Batch.Test.MockSPThrowsException");
var instance = proc.GetPropertyByName("Process Instance Id").AssertIsEmpty();
var run = proc.GetAction("Run Process Manually");
var processRun = run.InvokeReturnObject();
processRun.AssertIsType(typeof(BatchLog)).AssertIsPersistent().AssertTitleEquals("01/01/2000 00:00:00");
processRun.GetPropertyByName("Process Definition").AssertObjectIsEqual(proc);
processRun.GetPropertyByName("When Run").AssertValueIsEqual("01/01/2000 00:00:00");
processRun.GetPropertyByName("Run Mode").AssertValueIsEqual("Manual");
processRun.GetPropertyByName("Successful").AssertValueIsEqual("False");
processRun.GetPropertyByName("Attempt Number").AssertValueIsEqual("1");
processRun.GetPropertyByName("Outcome").AssertValueIsEqual("Test Exception");
processRun.GetPropertyByName("User").AssertTitleIsEqual("Test");
}
[TestMethod()]
public void RunProcessManuallyNotVisibleOnArchivedProcess()
{
var proc = GetTestService("Batch").GetAction("Find Process Definitions").InvokeReturnCollection("Process4", null).ElementAt(0);
proc.AssertTitleEquals("Process4");
proc.GetPropertyByName("Status").AssertValueIsEqual("Archived");
var run = proc.GetAction("Run Process Manually").AssertIsInvisible();
}
[TestMethod()]
public void RunPersistentProcessManually()
{
var find = GetTestService("Batch").GetAction("Find Process Definitions");
var proc = find.InvokeReturnCollection("Process5", null).ElementAt(0);
proc.AssertTitleEquals("Process5");
var className = proc.GetPropertyByName("Class To Invoke").AssertValueIsEqual("Cluster.Batch.Test.MockPersistentSP");
var instance = proc.GetPropertyByName("Process Instance Id").AssertValueIsEqual("1");
var run = proc.GetAction("Run Process Manually");
var processRun = run.InvokeReturnObject();
processRun.AssertIsType(typeof(BatchLog)).AssertIsPersistent().AssertTitleEquals("01/01/2000 00:00:00");
processRun.GetPropertyByName("Process Definition").AssertObjectIsEqual(proc);
processRun.GetPropertyByName("When Run").AssertValueIsEqual("01/01/2000 00:00:00");
processRun.GetPropertyByName("Run Mode").AssertValueIsEqual("Manual");
processRun.GetPropertyByName("Outcome").AssertValueIsEqual("Outcome1");
processRun.GetPropertyByName("Successful").AssertValueIsEqual("True");
processRun.GetPropertyByName("Attempt Number").AssertValueIsEqual("1");
processRun.GetPropertyByName("User").AssertTitleIsEqual("Test");
//second test
proc = find.InvokeReturnCollection("Process6", null).ElementAt(0);
proc.AssertTitleEquals("Process6");
proc.GetPropertyByName("Class To Invoke").AssertValueIsEqual("Cluster.Batch.Test.MockPersistentSP");
proc.GetPropertyByName("Process Instance Id").AssertValueIsEqual("2");
run = proc.GetAction("Run Process Manually");
processRun = run.InvokeReturnObject();
processRun.AssertIsType(typeof(BatchLog)).AssertIsPersistent();
processRun.GetPropertyByName("Outcome").AssertValueIsEqual("Outcome2");
}
[TestMethod()]
public void RunPersistentProcessManuallyWithInvalidId()
{
var find = GetTestService("Batch").GetAction("Find Process Definitions");
var proc = find.InvokeReturnCollection("Process7", null).ElementAt(0);
proc.AssertTitleEquals("Process7");
var className = proc.GetPropertyByName("Class To Invoke").AssertValueIsEqual("Cluster.Batch.Test.MockPersistentSP");
var instance = proc.GetPropertyByName("Process Instance Id").AssertValueIsEqual("100");
var run = proc.GetAction("Run Process Manually");
var processRun = run.InvokeReturnObject();
processRun.AssertIsType(typeof(BatchLog)).AssertIsPersistent();
processRun.GetPropertyByName("Outcome").AssertValueIsEqual("No instance of type Cluster.Batch.Test.MockPersistentSP with Id =100");
processRun.GetPropertyByName("Successful").AssertValueIsEqual("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.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Principal;
namespace System.Net.Security
{
/*
An authenticated stream based on NEGO SSP.
The class that can be used by client and server side applications
- to transfer Identities across the stream
- to encrypt data based on NEGO SSP package
In most cases the innerStream will be of type NetworkStream.
On Win9x data encryption is not available and both sides have
to explicitly drop SecurityLevel and MuatualAuth requirements.
This is a simple wrapper class.
All real work is done by internal NegoState class and the other partial implementation files.
*/
public partial class NegotiateStream : AuthenticatedStream
{
private NegoState _negoState;
private string _package;
private IIdentity _remoteIdentity;
public NegotiateStream(Stream innerStream) : this(innerStream, false)
{
}
public NegotiateStream(Stream innerStream, bool leaveInnerStreamOpen) : base(innerStream, leaveInnerStreamOpen)
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User))
{
#endif
_negoState = new NegoState(innerStream, leaveInnerStreamOpen);
_package = NegoState.DefaultPackage;
InitializeStreamPart();
#if DEBUG
}
#endif
}
private IAsyncResult BeginAuthenticateAsClient(AsyncCallback asyncCallback, object asyncState)
{
return BeginAuthenticateAsClient((NetworkCredential)CredentialCache.DefaultCredentials, null, string.Empty,
ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification,
asyncCallback, asyncState);
}
private IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential, string targetName, AsyncCallback asyncCallback, object asyncState)
{
return BeginAuthenticateAsClient(credential, null, targetName,
ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification,
asyncCallback, asyncState);
}
private IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential, ChannelBinding binding, string targetName, AsyncCallback asyncCallback, object asyncState)
{
return BeginAuthenticateAsClient(credential, binding, targetName,
ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification,
asyncCallback, asyncState);
}
private IAsyncResult BeginAuthenticateAsClient(
NetworkCredential credential,
string targetName,
ProtectionLevel requiredProtectionLevel,
TokenImpersonationLevel allowedImpersonationLevel,
AsyncCallback asyncCallback,
object asyncState)
{
return BeginAuthenticateAsClient(credential, null, targetName,
requiredProtectionLevel, allowedImpersonationLevel,
asyncCallback, asyncState);
}
private IAsyncResult BeginAuthenticateAsClient(
NetworkCredential credential,
ChannelBinding binding,
string targetName,
ProtectionLevel requiredProtectionLevel,
TokenImpersonationLevel allowedImpersonationLevel,
AsyncCallback asyncCallback,
object asyncState)
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
_negoState.ValidateCreateContext(_package, false, credential, targetName, binding, requiredProtectionLevel, allowedImpersonationLevel);
LazyAsyncResult result = new LazyAsyncResult(_negoState, asyncState, asyncCallback);
_negoState.ProcessAuthentication(result);
return result;
#if DEBUG
}
#endif
}
private void EndAuthenticateAsClient(IAsyncResult asyncResult)
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User))
{
#endif
_negoState.EndProcessAuthentication(asyncResult);
#if DEBUG
}
#endif
}
private IAsyncResult BeginAuthenticateAsServer(AsyncCallback asyncCallback, object asyncState)
{
return BeginAuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, null, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState);
}
private IAsyncResult BeginAuthenticateAsServer(ExtendedProtectionPolicy policy, AsyncCallback asyncCallback, object asyncState)
{
return BeginAuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, policy, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState);
}
private IAsyncResult BeginAuthenticateAsServer(
NetworkCredential credential,
ProtectionLevel requiredProtectionLevel,
TokenImpersonationLevel requiredImpersonationLevel,
AsyncCallback asyncCallback,
object asyncState)
{
return BeginAuthenticateAsServer(credential, null, requiredProtectionLevel, requiredImpersonationLevel, asyncCallback, asyncState);
}
private IAsyncResult BeginAuthenticateAsServer(
NetworkCredential credential,
ExtendedProtectionPolicy policy,
ProtectionLevel requiredProtectionLevel,
TokenImpersonationLevel requiredImpersonationLevel,
AsyncCallback asyncCallback,
object asyncState)
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
_negoState.ValidateCreateContext(_package, credential, string.Empty, policy, requiredProtectionLevel, requiredImpersonationLevel);
LazyAsyncResult result = new LazyAsyncResult(_negoState, asyncState, asyncCallback);
_negoState.ProcessAuthentication(result);
return result;
#if DEBUG
}
#endif
}
//
private void EndAuthenticateAsServer(IAsyncResult asyncResult)
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User))
{
#endif
_negoState.EndProcessAuthentication(asyncResult);
#if DEBUG
}
#endif
}
public virtual Task AuthenticateAsClientAsync()
{
return Task.Factory.FromAsync(BeginAuthenticateAsClient, EndAuthenticateAsClient, null);
}
public virtual Task AuthenticateAsClientAsync(NetworkCredential credential, string targetName)
{
return Task.Factory.FromAsync(BeginAuthenticateAsClient, EndAuthenticateAsClient, credential, targetName, null);
}
public virtual Task AuthenticateAsClientAsync(
NetworkCredential credential, string targetName,
ProtectionLevel requiredProtectionLevel,
TokenImpersonationLevel allowedImpersonationLevel)
{
return Task.Factory.FromAsync((callback, state) => BeginAuthenticateAsClient(credential, targetName, requiredProtectionLevel, allowedImpersonationLevel, callback, state), EndAuthenticateAsClient, null);
}
public virtual Task AuthenticateAsClientAsync(NetworkCredential credential, ChannelBinding binding, string targetName)
{
return Task.Factory.FromAsync(BeginAuthenticateAsClient, EndAuthenticateAsClient, credential, binding, targetName, null);
}
public virtual Task AuthenticateAsClientAsync(
NetworkCredential credential, ChannelBinding binding,
string targetName, ProtectionLevel requiredProtectionLevel,
TokenImpersonationLevel allowedImpersonationLevel)
{
return Task.Factory.FromAsync((callback, state) => BeginAuthenticateAsClient(credential, binding, targetName, requiredProtectionLevel, allowedImpersonationLevel, callback, state), EndAuthenticateAsClient, null);
}
public virtual Task AuthenticateAsServerAsync()
{
return Task.Factory.FromAsync(BeginAuthenticateAsServer, EndAuthenticateAsServer, null);
}
public virtual Task AuthenticateAsServerAsync(ExtendedProtectionPolicy policy)
{
return Task.Factory.FromAsync(BeginAuthenticateAsServer, EndAuthenticateAsServer, policy, null);
}
public virtual Task AuthenticateAsServerAsync(NetworkCredential credential, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel)
{
return Task.Factory.FromAsync(BeginAuthenticateAsServer, EndAuthenticateAsServer, credential, requiredProtectionLevel, requiredImpersonationLevel, null);
}
public virtual Task AuthenticateAsServerAsync(
NetworkCredential credential, ExtendedProtectionPolicy policy,
ProtectionLevel requiredProtectionLevel,
TokenImpersonationLevel requiredImpersonationLevel)
{
return Task.Factory.FromAsync((callback, state) => BeginAuthenticateAsServer(credential, policy, requiredProtectionLevel, requiredImpersonationLevel, callback, state), EndAuthenticateAsClient, null);
}
public override bool IsAuthenticated
{
get
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
return _negoState.IsAuthenticated;
#if DEBUG
}
#endif
}
}
public override bool IsMutuallyAuthenticated
{
get
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
return _negoState.IsMutuallyAuthenticated;
#if DEBUG
}
#endif
}
}
public override bool IsEncrypted
{
get
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
return _negoState.IsEncrypted;
#if DEBUG
}
#endif
}
}
public override bool IsSigned
{
get
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
return _negoState.IsSigned;
#if DEBUG
}
#endif
}
}
public override bool IsServer
{
get
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
return _negoState.IsServer;
#if DEBUG
}
#endif
}
}
public virtual TokenImpersonationLevel ImpersonationLevel
{
get
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
return _negoState.AllowedImpersonation;
#if DEBUG
}
#endif
}
}
public virtual IIdentity RemoteIdentity
{
get
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
if (_remoteIdentity == null)
{
_remoteIdentity = _negoState.GetIdentity();
}
return _remoteIdentity;
#if DEBUG
}
#endif
}
}
//
// Stream contract implementation
//
public override bool CanSeek
{
get
{
return false;
}
}
public override bool CanRead
{
get
{
return IsAuthenticated && InnerStream.CanRead;
}
}
public override bool CanTimeout
{
get
{
return InnerStream.CanTimeout;
}
}
public override bool CanWrite
{
get
{
return IsAuthenticated && InnerStream.CanWrite;
}
}
public override int ReadTimeout
{
get
{
return InnerStream.ReadTimeout;
}
set
{
InnerStream.ReadTimeout = value;
}
}
public override int WriteTimeout
{
get
{
return InnerStream.WriteTimeout;
}
set
{
InnerStream.WriteTimeout = value;
}
}
public override long Length
{
get
{
return InnerStream.Length;
}
}
public override long Position
{
get
{
return InnerStream.Position;
}
set
{
throw new NotSupportedException(SR.net_noseek);
}
}
public override void SetLength(long value)
{
InnerStream.SetLength(value);
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException(SR.net_noseek);
}
public override void Flush()
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
{
#endif
InnerStream.Flush();
#if DEBUG
}
#endif
}
protected override void Dispose(bool disposing)
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User))
{
#endif
try
{
_negoState.Close();
}
finally
{
base.Dispose(disposing);
}
#if DEBUG
}
#endif
}
public override int Read(byte[] buffer, int offset, int count)
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
{
#endif
_negoState.CheckThrow(true);
if (!_negoState.CanGetSecureStream)
{
return InnerStream.Read(buffer, offset, count);
}
return ProcessRead(buffer, offset, count, null);
#if DEBUG
}
#endif
}
public override void Write(byte[] buffer, int offset, int count)
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
{
#endif
_negoState.CheckThrow(true);
if (!_negoState.CanGetSecureStream)
{
InnerStream.Write(buffer, offset, count);
return;
}
ProcessWrite(buffer, offset, count, null);
#if DEBUG
}
#endif
}
private IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
_negoState.CheckThrow(true);
if (!_negoState.CanGetSecureStream)
{
return InnerStreamAPM.BeginRead(buffer, offset, count, asyncCallback, asyncState);
}
BufferAsyncResult bufferResult = new BufferAsyncResult(this, buffer, offset, count, asyncState, asyncCallback);
AsyncProtocolRequest asyncRequest = new AsyncProtocolRequest(bufferResult);
ProcessRead(buffer, offset, count, asyncRequest);
return bufferResult;
#if DEBUG
}
#endif
}
private int EndRead(IAsyncResult asyncResult)
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User))
{
#endif
_negoState.CheckThrow(true);
if (!_negoState.CanGetSecureStream)
{
return InnerStreamAPM.EndRead(asyncResult);
}
if (asyncResult == null)
{
throw new ArgumentNullException("asyncResult");
}
BufferAsyncResult bufferResult = asyncResult as BufferAsyncResult;
if (bufferResult == null)
{
throw new ArgumentException(SR.Format(SR.net_io_async_result, asyncResult.GetType().FullName), "asyncResult");
}
if (Interlocked.Exchange(ref _NestedRead, 0) == 0)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndRead"));
}
// No "artificial" timeouts implemented so far, InnerStream controls timeout.
bufferResult.InternalWaitForCompletion();
if (bufferResult.Result is Exception)
{
if (bufferResult.Result is IOException)
{
throw (Exception)bufferResult.Result;
}
throw new IOException(SR.net_io_read, (Exception)bufferResult.Result);
}
return (int)bufferResult.Result;
#if DEBUG
}
#endif
}
//
//
private IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
_negoState.CheckThrow(true);
if (!_negoState.CanGetSecureStream)
{
return InnerStreamAPM.BeginWrite(buffer, offset, count, asyncCallback, asyncState);
}
BufferAsyncResult bufferResult = new BufferAsyncResult(this, buffer, offset, count, true, asyncState, asyncCallback);
AsyncProtocolRequest asyncRequest = new AsyncProtocolRequest(bufferResult);
ProcessWrite(buffer, offset, count, asyncRequest);
return bufferResult;
#if DEBUG
}
#endif
}
private void EndWrite(IAsyncResult asyncResult)
{
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User))
{
#endif
_negoState.CheckThrow(true);
if (!_negoState.CanGetSecureStream)
{
InnerStreamAPM.EndWrite(asyncResult);
return;
}
if (asyncResult == null)
{
throw new ArgumentNullException("asyncResult");
}
BufferAsyncResult bufferResult = asyncResult as BufferAsyncResult;
if (bufferResult == null)
{
throw new ArgumentException(SR.Format(SR.net_io_async_result, asyncResult.GetType().FullName), "asyncResult");
}
if (Interlocked.Exchange(ref _NestedWrite, 0) == 0)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndWrite"));
}
// No "artificial" timeouts implemented so far, InnerStream controls timeout.
bufferResult.InternalWaitForCompletion();
if (bufferResult.Result is Exception)
{
if (bufferResult.Result is IOException)
{
throw (Exception)bufferResult.Result;
}
throw new IOException(SR.net_io_write, (Exception)bufferResult.Result);
}
#if DEBUG
}
#endif
}
// ReadAsync - provide async read functionality.
//
// This method provides async read functionality. All we do is
// call through to the Begin/EndRead methods.
//
// Input:
//
// buffer - Buffer to read into.
// offset - Offset into the buffer where we're to read.
// size - Number of bytes to read.
// cancellationtoken - Token used to request cancellation of the operation
//
// Returns:
//
// A Task<int> representing the read.
public override Task<int> ReadAsync(byte[] buffer, int offset, int size, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<int>(cancellationToken);
}
return Task.Factory.FromAsync(
(bufferArg, offsetArg, sizeArg, callback, state) => ((NegotiateStream)state).BeginRead(bufferArg, offsetArg, sizeArg, callback, state),
iar => ((NegotiateStream)iar.AsyncState).EndRead(iar),
buffer,
offset,
size,
this);
}
// WriteAsync - provide async write functionality.
//
// This method provides async write functionality. All we do is
// call through to the Begin/EndWrite methods.
//
// Input:
//
// buffer - Buffer to write into.
// offset - Offset into the buffer where we're to write.
// size - Number of bytes to write.
// cancellationtoken - Token used to request cancellation of the operation
//
// Returns:
//
// A Task representing the write.
public override Task WriteAsync(byte[] buffer, int offset, int size, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<int>(cancellationToken);
}
return Task.Factory.FromAsync(
(bufferArg, offsetArg, sizeArg, callback, state) => ((NegotiateStream)state).BeginWrite(bufferArg, offsetArg, sizeArg, callback, state),
iar => ((NegotiateStream)iar.AsyncState).EndWrite(iar),
buffer,
offset,
size,
this);
}
}
}
| |
using SevenZip.Compression.LZ;
using SevenZip.Compression.RangeCoder;
using System;
using System.IO;
namespace SevenZip.Compression.LZMA
{
public class Decoder : ICoder, ISetDecoderProperties
{
private class LenDecoder
{
private BitDecoder m_Choice = default(BitDecoder);
private BitDecoder m_Choice2 = default(BitDecoder);
private BitTreeDecoder[] m_LowCoder = new BitTreeDecoder[16];
private BitTreeDecoder[] m_MidCoder = new BitTreeDecoder[16];
private BitTreeDecoder m_HighCoder = new BitTreeDecoder(8);
private uint m_NumPosStates;
public void Create(uint numPosStates)
{
for (uint num = this.m_NumPosStates; num < numPosStates; num += 1u)
{
this.m_LowCoder[(int)((UIntPtr)num)] = new BitTreeDecoder(3);
this.m_MidCoder[(int)((UIntPtr)num)] = new BitTreeDecoder(3);
}
this.m_NumPosStates = numPosStates;
}
public void Init()
{
this.m_Choice.Init();
for (uint num = 0u; num < this.m_NumPosStates; num += 1u)
{
this.m_LowCoder[(int)((UIntPtr)num)].Init();
this.m_MidCoder[(int)((UIntPtr)num)].Init();
}
this.m_Choice2.Init();
this.m_HighCoder.Init();
}
public uint Decode(SevenZip.Compression.RangeCoder.Decoder rangeDecoder, uint posState)
{
if (this.m_Choice.Decode(rangeDecoder) == 0u)
{
return this.m_LowCoder[(int)((UIntPtr)posState)].Decode(rangeDecoder);
}
uint num = 8u;
if (this.m_Choice2.Decode(rangeDecoder) == 0u)
{
num += this.m_MidCoder[(int)((UIntPtr)posState)].Decode(rangeDecoder);
}
else
{
num += 8u;
num += this.m_HighCoder.Decode(rangeDecoder);
}
return num;
}
}
private class LiteralDecoder
{
private struct Decoder2
{
private BitDecoder[] m_Decoders;
public void Create()
{
this.m_Decoders = new BitDecoder[768];
}
public void Init()
{
for (int i = 0; i < 768; i++)
{
this.m_Decoders[i].Init();
}
}
public byte DecodeNormal(SevenZip.Compression.RangeCoder.Decoder rangeDecoder)
{
uint num = 1u;
do
{
num = (num << 1 | this.m_Decoders[(int)((UIntPtr)num)].Decode(rangeDecoder));
}
while (num < 256u);
return (byte)num;
}
public byte DecodeWithMatchByte(SevenZip.Compression.RangeCoder.Decoder rangeDecoder, byte matchByte)
{
uint num = 1u;
while (true)
{
uint num2 = (uint)(matchByte >> 7 & 1);
matchByte = (byte)(matchByte << 1);
uint num3 = this.m_Decoders[(int)((UIntPtr)((1u + num2 << 8) + num))].Decode(rangeDecoder);
num = (num << 1 | num3);
if (num2 != num3)
{
break;
}
if (num >= 256u)
{
goto IL_6D;
}
}
while (num < 256u)
{
num = (num << 1 | this.m_Decoders[(int)((UIntPtr)num)].Decode(rangeDecoder));
}
IL_6D:
return (byte)num;
}
}
private Decoder.LiteralDecoder.Decoder2[] m_Coders;
private int m_NumPrevBits;
private int m_NumPosBits;
private uint m_PosMask;
public void Create(int numPosBits, int numPrevBits)
{
if (this.m_Coders != null && this.m_NumPrevBits == numPrevBits && this.m_NumPosBits == numPosBits)
{
return;
}
this.m_NumPosBits = numPosBits;
this.m_PosMask = (1u << numPosBits) - 1u;
this.m_NumPrevBits = numPrevBits;
uint num = 1u << this.m_NumPrevBits + this.m_NumPosBits;
this.m_Coders = new Decoder.LiteralDecoder.Decoder2[num];
for (uint num2 = 0u; num2 < num; num2 += 1u)
{
this.m_Coders[(int)((UIntPtr)num2)].Create();
}
}
public void Init()
{
uint num = 1u << this.m_NumPrevBits + this.m_NumPosBits;
for (uint num2 = 0u; num2 < num; num2 += 1u)
{
this.m_Coders[(int)((UIntPtr)num2)].Init();
}
}
private uint GetState(uint pos, byte prevByte)
{
return ((pos & this.m_PosMask) << this.m_NumPrevBits) + (uint)(prevByte >> 8 - this.m_NumPrevBits);
}
public byte DecodeNormal(SevenZip.Compression.RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte)
{
return this.m_Coders[(int)((UIntPtr)this.GetState(pos, prevByte))].DecodeNormal(rangeDecoder);
}
public byte DecodeWithMatchByte(SevenZip.Compression.RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte, byte matchByte)
{
return this.m_Coders[(int)((UIntPtr)this.GetState(pos, prevByte))].DecodeWithMatchByte(rangeDecoder, matchByte);
}
}
private OutWindow m_OutWindow = new OutWindow();
private SevenZip.Compression.RangeCoder.Decoder m_RangeDecoder = new SevenZip.Compression.RangeCoder.Decoder();
private BitDecoder[] m_IsMatchDecoders = new BitDecoder[192];
private BitDecoder[] m_IsRepDecoders = new BitDecoder[12];
private BitDecoder[] m_IsRepG0Decoders = new BitDecoder[12];
private BitDecoder[] m_IsRepG1Decoders = new BitDecoder[12];
private BitDecoder[] m_IsRepG2Decoders = new BitDecoder[12];
private BitDecoder[] m_IsRep0LongDecoders = new BitDecoder[192];
private BitTreeDecoder[] m_PosSlotDecoder = new BitTreeDecoder[4];
private BitDecoder[] m_PosDecoders = new BitDecoder[114];
private BitTreeDecoder m_PosAlignDecoder = new BitTreeDecoder(4);
private Decoder.LenDecoder m_LenDecoder = new Decoder.LenDecoder();
private Decoder.LenDecoder m_RepLenDecoder = new Decoder.LenDecoder();
private Decoder.LiteralDecoder m_LiteralDecoder = new Decoder.LiteralDecoder();
private uint m_DictionarySize;
private uint m_DictionarySizeCheck;
private uint m_PosStateMask;
private bool _solid;
public Decoder()
{
this.m_DictionarySize = 4294967295u;
int num = 0;
while ((long)num < 4L)
{
this.m_PosSlotDecoder[num] = new BitTreeDecoder(6);
num++;
}
}
private void SetDictionarySize(uint dictionarySize)
{
if (this.m_DictionarySize != dictionarySize)
{
this.m_DictionarySize = dictionarySize;
this.m_DictionarySizeCheck = Math.Max(this.m_DictionarySize, 1u);
uint windowSize = Math.Max(this.m_DictionarySizeCheck, 4096u);
this.m_OutWindow.Create(windowSize);
}
}
private void SetLiteralProperties(int lp, int lc)
{
if (lp > 8)
{
throw new InvalidParamException();
}
if (lc > 8)
{
throw new InvalidParamException();
}
this.m_LiteralDecoder.Create(lp, lc);
}
private void SetPosBitsProperties(int pb)
{
if (pb > 4)
{
throw new InvalidParamException();
}
uint num = 1u << pb;
this.m_LenDecoder.Create(num);
this.m_RepLenDecoder.Create(num);
this.m_PosStateMask = num - 1u;
}
private void Init(Stream inStream, Stream outStream)
{
this.m_RangeDecoder.Init(inStream);
this.m_OutWindow.Init(outStream, this._solid);
for (uint num = 0u; num < 12u; num += 1u)
{
for (uint num2 = 0u; num2 <= this.m_PosStateMask; num2 += 1u)
{
uint num3 = (num << 4) + num2;
this.m_IsMatchDecoders[(int)((UIntPtr)num3)].Init();
this.m_IsRep0LongDecoders[(int)((UIntPtr)num3)].Init();
}
this.m_IsRepDecoders[(int)((UIntPtr)num)].Init();
this.m_IsRepG0Decoders[(int)((UIntPtr)num)].Init();
this.m_IsRepG1Decoders[(int)((UIntPtr)num)].Init();
this.m_IsRepG2Decoders[(int)((UIntPtr)num)].Init();
}
this.m_LiteralDecoder.Init();
for (uint num = 0u; num < 4u; num += 1u)
{
this.m_PosSlotDecoder[(int)((UIntPtr)num)].Init();
}
for (uint num = 0u; num < 114u; num += 1u)
{
this.m_PosDecoders[(int)((UIntPtr)num)].Init();
}
this.m_LenDecoder.Init();
this.m_RepLenDecoder.Init();
this.m_PosAlignDecoder.Init();
}
public void Code(Stream inStream, Stream outStream, long inSize, long outSize, ICodeProgress progress)
{
this.Init(inStream, outStream);
Base.State state = default(Base.State);
state.Init();
uint num = 0u;
uint num2 = 0u;
uint num3 = 0u;
uint num4 = 0u;
ulong num5 = 0uL;
if (num5 < (ulong)outSize)
{
if (this.m_IsMatchDecoders[(int)((UIntPtr)(state.Index << 4))].Decode(this.m_RangeDecoder) != 0u)
{
throw new DataErrorException();
}
state.UpdateChar();
byte b = this.m_LiteralDecoder.DecodeNormal(this.m_RangeDecoder, 0u, 0);
this.m_OutWindow.PutByte(b);
num5 += 1uL;
}
while (num5 < (ulong)outSize)
{
uint num6 = (uint)num5 & this.m_PosStateMask;
if (this.m_IsMatchDecoders[(int)((UIntPtr)((state.Index << 4) + num6))].Decode(this.m_RangeDecoder) == 0u)
{
byte @byte = this.m_OutWindow.GetByte(0u);
byte b2;
if (!state.IsCharState())
{
b2 = this.m_LiteralDecoder.DecodeWithMatchByte(this.m_RangeDecoder, (uint)num5, @byte, this.m_OutWindow.GetByte(num));
}
else
{
b2 = this.m_LiteralDecoder.DecodeNormal(this.m_RangeDecoder, (uint)num5, @byte);
}
this.m_OutWindow.PutByte(b2);
state.UpdateChar();
num5 += 1uL;
}
else
{
uint num8;
if (this.m_IsRepDecoders[(int)((UIntPtr)state.Index)].Decode(this.m_RangeDecoder) == 1u)
{
if (this.m_IsRepG0Decoders[(int)((UIntPtr)state.Index)].Decode(this.m_RangeDecoder) == 0u)
{
if (this.m_IsRep0LongDecoders[(int)((UIntPtr)((state.Index << 4) + num6))].Decode(this.m_RangeDecoder) == 0u)
{
state.UpdateShortRep();
this.m_OutWindow.PutByte(this.m_OutWindow.GetByte(num));
num5 += 1uL;
continue;
}
}
else
{
uint num7;
if (this.m_IsRepG1Decoders[(int)((UIntPtr)state.Index)].Decode(this.m_RangeDecoder) == 0u)
{
num7 = num2;
}
else
{
if (this.m_IsRepG2Decoders[(int)((UIntPtr)state.Index)].Decode(this.m_RangeDecoder) == 0u)
{
num7 = num3;
}
else
{
num7 = num4;
num4 = num3;
}
num3 = num2;
}
num2 = num;
num = num7;
}
num8 = this.m_RepLenDecoder.Decode(this.m_RangeDecoder, num6) + 2u;
state.UpdateRep();
}
else
{
num4 = num3;
num3 = num2;
num2 = num;
num8 = 2u + this.m_LenDecoder.Decode(this.m_RangeDecoder, num6);
state.UpdateMatch();
uint num9 = this.m_PosSlotDecoder[(int)((UIntPtr)Base.GetLenToPosState(num8))].Decode(this.m_RangeDecoder);
if (num9 >= 4u)
{
int num10 = (int)((num9 >> 1) - 1u);
num = (2u | (num9 & 1u)) << num10;
if (num9 < 14u)
{
num += BitTreeDecoder.ReverseDecode(this.m_PosDecoders, num - num9 - 1u, this.m_RangeDecoder, num10);
}
else
{
num += this.m_RangeDecoder.DecodeDirectBits(num10 - 4) << 4;
num += this.m_PosAlignDecoder.ReverseDecode(this.m_RangeDecoder);
}
}
else
{
num = num9;
}
}
if ((ulong)num >= (ulong)this.m_OutWindow.TrainSize + num5 || num >= this.m_DictionarySizeCheck)
{
if (num == 4294967295u)
{
break;
}
throw new DataErrorException();
}
else
{
this.m_OutWindow.CopyBlock(num, num8);
num5 += (ulong)num8;
}
}
}
this.m_OutWindow.Flush();
this.m_OutWindow.ReleaseStream();
this.m_RangeDecoder.ReleaseStream();
}
public void SetDecoderProperties(byte[] properties)
{
if (properties.Length < 5)
{
throw new InvalidParamException();
}
int lc = (int)(properties[0] % 9);
int num = (int)(properties[0] / 9);
int lp = num % 5;
int num2 = num / 5;
if (num2 > 4)
{
throw new InvalidParamException();
}
uint num3 = 0u;
for (int i = 0; i < 4; i++)
{
num3 += (uint)((uint)properties[1 + i] << i * 8);
}
this.SetDictionarySize(num3);
this.SetLiteralProperties(lp, lc);
this.SetPosBitsProperties(num2);
}
public bool Train(Stream stream)
{
this._solid = true;
return this.m_OutWindow.Train(stream);
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <peter@majorsilence.com>
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using fyiReporting.RDL;
using ScintillaNET;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Linq;
using fyiReporting.RdlDesign.Syntax;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// DialogListOfStrings: puts up a dialog that lets a user enter a list of strings
/// </summary>
public partial class DialogExprEditor
{
Type[] BASE_TYPES = new Type[]
{
typeof(string),
typeof(double),
typeof(Single),
typeof(decimal),
typeof(DateTime),
typeof(char),
typeof(bool),
typeof(int),
typeof(short),
typeof(long),
typeof(byte),
typeof(UInt16),
typeof(UInt32),
typeof(UInt64)
};
// design draw
private bool _Color; // true if color list should be displayed
RdlScriptLexer rdlLexer = new RdlScriptLexer();
string resultExpression = null; //It workaround System.AccessViolationException geting from Scintilla after form closed
internal DialogExprEditor(DesignXmlDraw dxDraw, string expr, XmlNode node) :
this(dxDraw, expr, node, false)
{
}
internal DialogExprEditor(DesignXmlDraw dxDraw, string expr, XmlNode node, bool bColor)
{
_Draw = dxDraw;
_Color = bColor;
//
// Required for Windows Form Designer support
//
InitializeComponent();
var styling = new ScintillaExprStyle(rdlLexer, scintilla1);
styling.ConfigureScintillaStyle();
// Fill out the fields list
string[] fields = null;
// Find the dataregion that contains the item (if any)
for (XmlNode pNode = node; pNode != null; pNode = pNode.ParentNode)
{
if (pNode.Name == "List" ||
pNode.Name == "Table" ||
pNode.Name == "Matrix" ||
pNode.Name == "Chart")
{
string dsname = _Draw.GetDataSetNameValue(pNode);
if (dsname != null) // found it
{
fields = _Draw.GetFields(dsname, true);
}
}
}
BuildTree(fields);
FillLexerByFields(_Draw);
if (expr != null)
scintilla1.Text = expr.Replace("\r\n", "\n").Replace("\n", Environment.NewLine);
return;
}
void FillLexerByFields(DesignXmlDraw dxDraw)
{
var fields = new List<string>();
foreach (var dataSet in dxDraw.DataSetNames)
{
var datasetFields = dxDraw.GetFields((string)dataSet, false);
if(datasetFields != null)
fields.AddRange(datasetFields);
}
rdlLexer.SetFields(fields);
}
void BuildTree(string[] flds)
{
// suppress redraw until tree view is complete
tvOp.BeginUpdate();
//AJM GJL Adding Missing 'User' Menu
// Handle the user
InitUsers();
// Handle the globals
InitGlobals();
// Fields - only when a dataset is specified
InitFields(flds);
// Fields - is missing
InitFieldsIsMissing(flds);
// Report parameters
InitReportParameters();
// Handle the functions
InitFunctions();
// Aggregate functions
InitAggrFunctions();
// Operators
InitOperators();
// Colors (if requested)
InitColors();
// Modules and class (if any)
// EBN 30/03/2014
InitReportModulesAndClass();
tvOp.EndUpdate();
}
// Josh: 6:22:10 Added as a uniform method of addind nodes to the TreeView.
void InitTreeNodes(string node, IEnumerable<string> list)
{
TreeNode ndRoot = new TreeNode(node);
tvOp.Nodes.Add(ndRoot);
foreach (string item in list)
{
TreeNode aRoot = new TreeNode(item);
ndRoot.Nodes.Add(aRoot);
}
}
// Josh: 6:22:10 Begin Init Methods.
// Methods have been changed to use InitTreeNodes
// and ArrayToFormattedList methods
// Initializes the user functions
void InitUsers()
{
List<string> users = StaticLists.ArrayToFormattedList(StaticLists.UserList, "{!", "}");
InitTreeNodes("User", users);
}
// Initializes the Globals
void InitGlobals()
{
List<string> globals = StaticLists.ArrayToFormattedList(StaticLists.GlobalList, "{@", "}");
InitTreeNodes("Globals", globals);
}
// Initializes the database fields
void InitFields(string[] flds)
{
if (flds != null && flds.Length > 0)
{
List<string> fields = StaticLists.ArrayToFormattedList(flds, "{", "}");
InitTreeNodes("Fields", fields);
}
}
// Initializes the database fields is missing
void InitFieldsIsMissing(string[] flds)
{
if (flds != null && flds.Length > 0)
{
List<string> fields = StaticLists.ArrayToFormattedList(flds, "Fields!", ".IsMissing");
InitTreeNodes("Check for null", fields);
//fieldsKeys.AddRange(fields);
}
}
// Initializes the aggregate functions
void InitAggrFunctions()
{
InitTreeNodes("Aggregate Functions", StaticLists.AggrFunctionList);
}
// Initializes the operators
void InitOperators()
{
InitTreeNodes("Operators", StaticLists.OperatorList);
}
// Initializes the colors
void InitColors()
{
if (_Color)
{
InitTreeNodes("Colors", StaticLists.ColorList);
}
}
/// <summary>
/// Populate tree view with the report parameters (if any)
/// </summary>
void InitReportParameters()
{
string[] ps = _Draw.GetReportParameters(true);
if (ps != null && ps.Length != 0)
{
List<string> parameters = StaticLists.ArrayToFormattedList(ps, "{?", "}");
InitTreeNodes("Parameters", parameters);
rdlLexer.SetParameters(StaticLists.ArrayToFormattedList(ps, "", ""));
}
}
/// <summary>
/// Populate tree view with the Module and Class parameters (if any)
/// EBN 30/03/2014
/// </summary>
void InitReportModulesAndClass()
{
string[] ms = _Draw.GetReportModules(false);
string[] qs = _Draw.GetReportClasses(false);
List<string> mc = new List<string>();
if (ms == null) return;
if (qs == null) return;
// Try to load the assembly if not already loaded
foreach (string s in ms)
{
try
{
Assembly a = Assembly.LoadFrom(s);
foreach (string c in qs)
{
Type t = a.GetType(c);
if (t != null)
{
// Class is found in this assembly
BuildMethods(mc, t, c + ".");
}
}
}
catch
{
// Nothing to do, we can not load the assembly...
}
}
if (qs != null && qs.Length != 0)
{
InitTreeNodes("Modules", mc);
}
}
//Done: Look at grouping items, such as Math, Financial, etc
// Josh: 6:21:10 added grouping for common items.
void InitFunctions()
{
List<string> ar = new List<string>();
ar.AddRange(StaticLists.FunctionList);
// Build list of methods in the VBFunctions class
fyiReporting.RDL.FontStyleEnum fsi = FontStyleEnum.Italic; // just want a class from RdlEngine.dll assembly
Assembly a = Assembly.GetAssembly(fsi.GetType());
if (a == null)
return;
Type ft = a.GetType("fyiReporting.RDL.VBFunctions");
BuildMethods(ar, ft, "");
// build list of financial methods in Financial class
ft = a.GetType("fyiReporting.RDL.Financial");
BuildMethods(ar, ft, "Financial.");
a = Assembly.GetAssembly("".GetType());
ft = a.GetType("System.Math");
BuildMethods(ar, ft, "Math.");
ft = a.GetType("System.Convert");
BuildMethods(ar, ft, "Convert.");
ft = a.GetType("System.String");
BuildMethods(ar, ft, "String.");
ar.Sort();
TreeNode ndRoot = new TreeNode("Functions");
tvOp.Nodes.Add(ndRoot);
foreach (TreeNode node in GroupMethods(RemoveDuplicates(ar)))
{
ndRoot.Nodes.Add(node);
}
}
// Josh: 6:22:10 End Init Methods
List<string> RemoveDuplicates(IEnumerable<string> ar)
{
List<string> newAr = new List<string>();
string previous = "";
foreach (string str in ar)
{
if (str != previous)
newAr.Add(str);
previous = str;
}
return newAr;
}
List<TreeNode> GroupMethods(List<string> ar)
{
List<TreeNode> nodeList = new List<TreeNode>();
string group = " ";
foreach (string str in ar)
{
if (!str.StartsWith(group))
{
if (str.Contains("."))
{
if (str.IndexOf("(") > str.IndexOf("."))
{
group = str.Split('.')[0];
TreeNode aRoot = new TreeNode(group);
List<string> groupList = ar.FindAll(
delegate(string methodName)
{
return methodName.StartsWith(group);
}
);
if (groupList != null)
{
foreach (string method in groupList)
{
aRoot.Nodes.Add(new TreeNode(
method.Replace(group, string.Empty)
.Replace(".", string.Empty)));
}
}
nodeList.Add(aRoot);
}
else
{
nodeList.Add(new TreeNode(str));
}
}
else
{
nodeList.Add(new TreeNode(str));
}
}
}
return nodeList;
}
void InitFunctions(TreeNode ndRoot)
{
List<string> ar = new List<string>();
ar.AddRange(StaticLists.FunctionList);
// Build list of methods in the VBFunctions class
fyiReporting.RDL.FontStyleEnum fsi = FontStyleEnum.Italic; // just want a class from RdlEngine.dll assembly
Assembly a = Assembly.GetAssembly(fsi.GetType());
if (a == null)
return;
Type ft = a.GetType("fyiReporting.RDL.VBFunctions");
BuildMethods(ar, ft, "");
// build list of financial methods in Financial class
ft = a.GetType("fyiReporting.RDL.Financial");
BuildMethods(ar, ft, "Financial.");
a = Assembly.GetAssembly("".GetType());
ft = a.GetType("System.Math");
BuildMethods(ar, ft, "Math.");
ft = a.GetType("System.Convert");
BuildMethods(ar, ft, "Convert.");
ft = a.GetType("System.String");
BuildMethods(ar, ft, "String.");
ar.Sort();
string previous = "";
foreach (string item in ar)
{
if (item != previous) // don't add duplicates
{
// Add the node to the tree
TreeNode aRoot = new TreeNode(item);
ndRoot.Nodes.Add(aRoot);
}
previous = item;
}
}
void BuildMethods(List<string> ar, Type ft, string prefix)
{
if (ft == null)
return;
MethodInfo[] mis = ft.GetMethods(BindingFlags.Static | BindingFlags.Public);
foreach (MethodInfo mi in mis)
{
// Add the node to the tree
string name = BuildMethodName(mi);
if (name != null)
ar.Add(prefix + name);
}
}
string BuildMethodName(MethodInfo mi)
{
StringBuilder sb = new StringBuilder(mi.Name);
sb.Append("(");
ParameterInfo[] pis = mi.GetParameters();
bool bFirst = true;
foreach (ParameterInfo pi in pis)
{
if (!IsBaseType(pi.ParameterType))
return null;
if (bFirst)
bFirst = false;
else
sb.Append(", ");
sb.Append(pi.Name);
}
sb.Append(")");
return sb.ToString();
}
// Determines if underlying type is a primitive
bool IsBaseType(Type t)
{
foreach (Type bt in BASE_TYPES)
{
if (bt == t)
return true;
}
return false;
}
public string Expression
{
get { return resultExpression != null ? resultExpression : scintilla1.Text; }
}
private void bCopy_Click(object sender, System.EventArgs e)
{
if (tvOp.SelectedNode == null ||
tvOp.SelectedNode.Parent == null ||
tvOp.SelectedNode.Nodes.Count > 0)
return; // this is the top level nodes (Fields, Parameters, ...)
TreeNode node = tvOp.SelectedNode;
string t = string.Empty;
// Josh: 6:21:10 Changed to add parent node name for grouped nodes (eg: Convert.ToByte(value))
// and not to add it for the root functions (the non grouped).
if (tvOp.Nodes.Contains(node.Parent))
t = node.Text;
else
t = node.Parent.Text + "." + node.Text;
if (scintilla1.TextLength == 0)
t = "=" + t;
scintilla1.ReplaceSelection(t);
}
private void tvOp_DoubleClick(object sender, EventArgs e)
{
bCopy.PerformClick();
}
private void bOK_Click(object sender, EventArgs e)
{
resultExpression = scintilla1.Text;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using static System.Diagnostics.Trace;
namespace Alluvial
{
/// <summary>
/// Methods for working with distributors.
/// </summary>
public static class Distributor
{
/// <summary>
/// Creates an anonymous distributor.
/// </summary>
/// <typeparam name="T">The type of the distributed resource.</typeparam>
/// <param name="start">A delegate that when called starts the distributor.</param>
/// <param name="onReceive">A delegate to be called when a lease becomes available.</param>
/// <param name="onException">A delegate to be called when the distributor catches an exception while acquiring, distributing, or releasing a lease.</param>
/// <param name="stop">A delegate that when called stops the distributor.</param>
/// <param name="distribute">A delegate that when called distributes the specified number of leases.</param>
/// <returns>An anonymous distributor instance.</returns>
public static IDistributor<T> Create<T>(
Func<Task> start,
Action<DistributorPipeAsync<T>> onReceive,
Func<Task> stop,
Func<int, Task<IEnumerable<T>>> distribute,
Action<Action<Exception, Lease<T>>> onException) =>
new AnonymousDistributor<T>(start, onReceive, stop, distribute, onException);
/// <summary>
/// Creates an in-memory distributor.
/// </summary>
/// <typeparam name="TPartition">The type of the partitions.</typeparam>
/// <param name="partitions">The partitions to be leased out.</param>
/// <param name="maxDegreesOfParallelism">The maximum degrees of parallelism.</param>
/// <param name="pool">The pool.</param>
/// <param name="defaultLeaseDuration">Default duration of the lease. If not specified, the default is 1 minute.</param>
/// <returns></returns>
/// <exception cref="System.ArgumentNullException"></exception>
public static IDistributor<IStreamQueryPartition<TPartition>> CreateInMemoryDistributor<TPartition>(
this IEnumerable<IStreamQueryPartition<TPartition>> partitions,
int maxDegreesOfParallelism = 5,
string pool = "default",
TimeSpan? defaultLeaseDuration = null)
{
if (partitions == null)
{
throw new ArgumentNullException(nameof(partitions));
}
var leasables = partitions.CreateLeasables();
return new InMemoryDistributor<IStreamQueryPartition<TPartition>>(
leasables,
pool,
maxDegreesOfParallelism,
defaultLeaseDuration);
}
/// <summary>
/// Creates leasables from the specified partitions.
/// </summary>
/// <typeparam name="TPartition">The type of the partition.</typeparam>
/// <param name="partitions">The partitions.</param>
/// <exception cref="System.ArgumentNullException"></exception>
public static Leasable<IStreamQueryPartition<TPartition>>[] CreateLeasables<TPartition>(
this IEnumerable<IStreamQueryPartition<TPartition>> partitions)
{
if (partitions == null)
{
throw new ArgumentNullException(nameof(partitions));
}
return partitions.Select(p => new Leasable<IStreamQueryPartition<TPartition>>(p, p.ToString()))
.ToArray();
}
/// <summary>
/// Distributes all available leases.
/// </summary>
/// <param name="distributor">The distributor.</param>
public static async Task<IEnumerable<T>> DistributeAll<T>(this IDistributor<T> distributor) =>
await distributor.Distribute(int.MaxValue);
/// <summary>
/// Continuously extends leases while work in progress.
/// </summary>
/// <param name="distributor">The distributor.</param>
/// <param name="frequency">The frequency with which to refresh the lease.</param>
/// <returns></returns>
public static IDistributor<T> KeepExtendingLeasesWhileWorking<T>(
this IDistributor<T> distributor,
TimeSpan frequency)
{
distributor.OnReceive(async (lease, next) =>
{
using (lease.KeepAlive(frequency))
{
await next(lease);
}
});
return distributor;
}
/// <summary>
/// Specifies a delegate to be called when a lease is available.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="distributor">The distributor.</param>
/// <param name="receive">The delegate called when work is available to be done.</param>
/// <exception cref="System.ArgumentNullException">
/// </exception>
/// <remarks>
/// For the duration of the lease, the leased resource will not be available to any other instance.
/// </remarks>
public static void OnReceive<T>(
this IDistributor<T> distributor,
Func<Lease<T>, Task> receive)
{
if (distributor == null)
{
throw new ArgumentNullException(nameof(distributor));
}
if (receive == null)
{
throw new ArgumentNullException(nameof(receive));
}
distributor.OnReceive(async (lease, next) =>
{
await receive(lease);
await next(lease);
});
}
/// <summary>
/// Configures the distributor to release leases as soon as the work on the lease is completed.
/// </summary>
/// <typeparam name="T">The type of the distributed resource.</typeparam>
/// <param name="distributor">The distributor.</param>
public static IDistributor<T> ReleaseLeasesWhenWorkIsDone<T>(
this IDistributor<T> distributor)
{
distributor.OnReceive(async (lease, next) =>
{
await next(lease);
await lease.Release();
});
return distributor;
}
/// <summary>
/// Wraps a distributor with tracing behaviors when leases are acquired and released.
/// </summary>
/// <exception cref="System.ArgumentNullException"></exception>
public static IDistributor<T> Trace<T>(
this IDistributor<T> distributor,
Action<Lease<T>> onLeaseAcquired = null,
Action<Lease<T>> onLeaseWorkDone = null,
Action<Exception, Lease<T>> onException = null)
{
if (distributor == null)
{
throw new ArgumentNullException(nameof(distributor));
}
if (onLeaseAcquired == null &&
onLeaseWorkDone == null &&
onException == null)
{
onLeaseAcquired = lease => TraceOnLeaseAcquired(distributor, lease);
onLeaseWorkDone = lease => TraceOnLeaseWorkDone(distributor, lease);
onException = (exception, lease) => TraceOnException(distributor, exception, lease);
}
else
{
onLeaseAcquired = onLeaseAcquired ?? (l => { });
onLeaseWorkDone = onLeaseWorkDone ?? (l => { });
onException = onException ?? ((exception, lease) => { });
}
var newDistributor = Create(
start: () =>
{
WriteLine($"[Distribute] {distributor}: Start");
return distributor.Start();
},
stop: () =>
{
WriteLine($"[Distribute] {distributor}: Stop");
return distributor.Stop();
},
distribute: distributor.Distribute,
onReceive: distributor.OnReceive,
onException: distributor.OnException);
distributor.OnReceive(async (lease, next) =>
{
onLeaseAcquired(lease);
await next(lease);
onLeaseWorkDone(lease);
});
distributor.OnException(onException);
return newDistributor;
}
private static void TraceOnException<T>(
IDistributor<T> distributor,
Exception exception,
Lease<T> lease)
{
if (lease != null)
{
WriteLine($"[Distribute] {distributor}: Exception: {lease.Exception}");
}
else if (exception != null)
{
WriteLine($"[Distribute] {distributor}: Exception: {exception}");
}
}
private static void TraceOnLeaseAcquired<T>(IDistributor<T> distributor, Lease<T> lease) =>
WriteLine($"[Distribute] {distributor}: OnReceive " + lease);
private static void TraceOnLeaseWorkDone<T>(IDistributor<T> distributor, Lease<T> lease) =>
WriteLine($"[Distribute] {distributor}: OnReceive (done) " + lease);
internal static DistributorPipeAsync<T> PipeInto<T>(
this DistributorPipeAsync<T> first,
DistributorPipeAsync<T> next) => (lease, _ignored_) =>
first(lease,
l => next(l, _ => Unit.Default.CompletedTask()));
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace petstore
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
public partial class SwaggerPetstoreClient : ServiceClient<SwaggerPetstoreClient>, ISwaggerPetstoreClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Initializes a new instance of the SwaggerPetstoreClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected SwaggerPetstoreClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the SwaggerPetstoreClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected SwaggerPetstoreClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the SwaggerPetstoreClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected SwaggerPetstoreClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the SwaggerPetstoreClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected SwaggerPetstoreClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the SwaggerPetstoreClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SwaggerPetstoreClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SwaggerPetstoreClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SwaggerPetstoreClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SwaggerPetstoreClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SwaggerPetstoreClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SwaggerPetstoreClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SwaggerPetstoreClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
BaseUri = new System.Uri("http://petstore.swagger.io/v1");
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
/// <summary>
/// List all pets
/// </summary>
/// <param name='limit'>
/// How many items to return at one time (max 100)
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IList<Pet>,ListPetsHeaders>> ListPetsWithHttpMessagesAsync(int? limit = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("limit", limit);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListPets", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pets").ToString();
List<string> _queryParameters = new List<string>();
if (limit != null)
{
_queryParameters.Add(string.Format("limit={0}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(limit, SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (GenerateClientRequestId != null && GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", 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 (Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IList<Pet>,ListPetsHeaders>();
_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 = SafeJsonConvert.DeserializeObject<IList<Pet>>(_responseContent, DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<ListPetsHeaders>(JsonSerializer.Create(DeserializationSettings));
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Create a pet
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> CreatePetsWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreatePets", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pets").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (GenerateClientRequestId != null && GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", 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 (Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 201)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Info for a specific pet
/// </summary>
/// <param name='petId'>
/// The id of the pet to retrieve
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IList<Pet>>> ShowPetByIdWithHttpMessagesAsync(string petId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (petId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "petId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("petId", petId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ShowPetById", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pets/{petId}").ToString();
_url = _url.Replace("{petId}", System.Uri.EscapeDataString(petId));
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (GenerateClientRequestId != null && GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", 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 (Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IList<Pet>>();
_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 = SafeJsonConvert.DeserializeObject<IList<Pet>>(_responseContent, DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Threading;
using System.Collections.Generic;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.Rfcomm;
using Windows.Devices.Enumeration;
using Windows.Foundation;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Navigation;
using System.ComponentModel;
using Windows.UI.Xaml.Media.Imaging;
using System.Collections.ObjectModel;
namespace SDKTemplate
{
public sealed partial class Scenario1_ChatClient : Page
{
// A pointer back to the main page is required to display status messages.
private MainPage rootPage = MainPage.Current;
// Used to display list of available devices to chat with
public ObservableCollection<RfcommChatDeviceDisplay> ResultCollection
{
get;
private set;
}
private DeviceWatcher deviceWatcher = null;
private StreamSocket chatSocket = null;
private DataWriter chatWriter = null;
private RfcommDeviceService chatService = null;
private BluetoothDevice bluetoothDevice;
public Scenario1_ChatClient()
{
this.InitializeComponent();
App.Current.Suspending += App_Suspending;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
rootPage = MainPage.Current;
ResultCollection = new ObservableCollection<RfcommChatDeviceDisplay>();
DataContext = this;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
StopWatcher();
}
private void StopWatcher()
{
if (null != deviceWatcher && (DeviceWatcherStatus.Started == deviceWatcher.Status ||
DeviceWatcherStatus.EnumerationCompleted == deviceWatcher.Status))
{
deviceWatcher.Stop();
}
}
void App_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e)
{
// Make sure we clean up resources on suspend.
Disconnect("App Suspension disconnects");
}
/// <summary>
/// When the user presses the run button, query for all nearby unpaired devices
/// Note that in this case, the other device must be running the Rfcomm Chat Server before being paired.
/// </summary>
/// <param name="sender">Instance that triggered the event.</param>
/// <param name="e">Event data describing the conditions that led to the event.</param>
private void RunButton_Click(object sender, RoutedEventArgs e)
{
SetDeviceWatcherUI();
StartUnpairedDeviceWatcher();
}
private void SetDeviceWatcherUI()
{
// Disable the button while we do async operations so the user can't Run twice.
RunButton.IsEnabled = false;
// Clear any previous messages
rootPage.NotifyUser("", NotifyType.StatusMessage);
resultsListView.Visibility = Visibility.Visible;
resultsListView.IsEnabled = true;
}
private void StartUnpairedDeviceWatcher()
{
// Request additional properties
string[] requestedProperties = new string[] { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" };
deviceWatcher = DeviceInformation.CreateWatcher("(System.Devices.Aep.ProtocolId:=\"{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}\")",
requestedProperties,
DeviceInformationKind.AssociationEndpoint);
// Hook up handlers for the watcher events before starting the watcher
deviceWatcher.Added += new TypedEventHandler<DeviceWatcher, DeviceInformation>(async (watcher, deviceInfo) =>
{
// Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
// Make sure device name isn't blank
if(deviceInfo.Name != "")
{
ResultCollection.Add(new RfcommChatDeviceDisplay(deviceInfo));
rootPage.NotifyUser(
String.Format("{0} devices found.", ResultCollection.Count),
NotifyType.StatusMessage);
}
});
});
deviceWatcher.Updated += new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>(async (watcher, deviceInfoUpdate) =>
{
await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
{
foreach (RfcommChatDeviceDisplay rfcommInfoDisp in ResultCollection)
{
if (rfcommInfoDisp.Id == deviceInfoUpdate.Id)
{
rfcommInfoDisp.Update(deviceInfoUpdate);
break;
}
}
});
});
deviceWatcher.EnumerationCompleted += new TypedEventHandler<DeviceWatcher, Object>(async (watcher, obj) =>
{
await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
{
rootPage.NotifyUser(
String.Format("{0} devices found. Enumeration completed. Watching for updates...", ResultCollection.Count),
NotifyType.StatusMessage);
});
});
deviceWatcher.Removed += new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>(async (watcher, deviceInfoUpdate) =>
{
// Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
{
// Find the corresponding DeviceInformation in the collection and remove it
foreach (RfcommChatDeviceDisplay rfcommInfoDisp in ResultCollection)
{
if (rfcommInfoDisp.Id == deviceInfoUpdate.Id)
{
ResultCollection.Remove(rfcommInfoDisp);
break;
}
}
rootPage.NotifyUser(
String.Format("{0} devices found.", ResultCollection.Count),
NotifyType.StatusMessage);
});
});
deviceWatcher.Stopped += new TypedEventHandler<DeviceWatcher, Object>(async (watcher, obj) =>
{
await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
{
rootPage.NotifyUser(
String.Format("{0} devices found. Watcher {1}.",
ResultCollection.Count,
DeviceWatcherStatus.Aborted == watcher.Status ? "aborted" : "stopped"),
NotifyType.StatusMessage);
ResultCollection.Clear();
RunButton.IsEnabled = true;
});
});
deviceWatcher.Start();
}
/// <summary>
/// Invoked once the user has selected the device to connect to.
/// Once the user has selected the device,
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void ConnectButton_Click(object sender, RoutedEventArgs e)
{
// Make sure user has selected a device first
if (resultsListView.SelectedItem != null)
{
rootPage.NotifyUser("Connecting to remote device. Please wait...", NotifyType.StatusMessage);
}
else
{
rootPage.NotifyUser("Please select an item to connect to", NotifyType.ErrorMessage);
return;
}
RfcommChatDeviceDisplay deviceInfoDisp = resultsListView.SelectedItem as RfcommChatDeviceDisplay;
// Perform device access checks before trying to get the device.
// First, we check if consent has been explicitly denied by the user.
DeviceAccessStatus accessStatus = DeviceAccessInformation.CreateFromId(deviceInfoDisp.Id).CurrentStatus;
if (accessStatus == DeviceAccessStatus.DeniedByUser)
{
rootPage.NotifyUser("This app does not have access to connect to the remote device (please grant access in Settings > Privacy > Other Devices", NotifyType.ErrorMessage);
return;
}
// If not, try to get the Bluetooth device
try
{
bluetoothDevice = await BluetoothDevice.FromIdAsync(deviceInfoDisp.Id);
}
catch (Exception ex)
{
rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
return;
}
// If we were unable to get a valid Bluetooth device object,
// it's most likely because the user has specified that all unpaired devices
// should not be interacted with.
if (bluetoothDevice == null)
{
rootPage.NotifyUser("Bluetooth Device returned null. Access Status = " + accessStatus.ToString(), NotifyType.ErrorMessage);
}
// This should return a list of uncached Bluetooth services (so if the server was not active when paired, it will still be detected by this call
var rfcommServices = await bluetoothDevice.GetRfcommServicesForIdAsync(
RfcommServiceId.FromUuid(Constants.RfcommChatServiceUuid), BluetoothCacheMode.Uncached);
if (rfcommServices.Services.Count > 0)
{
chatService = rfcommServices.Services[0];
}
else
{
rootPage.NotifyUser(
"Could not discover the chat service on the remote device",
NotifyType.StatusMessage);
return;
}
// Do various checks of the SDP record to make sure you are talking to a device that actually supports the Bluetooth Rfcomm Chat Service
var attributes = await chatService.GetSdpRawAttributesAsync();
if (!attributes.ContainsKey(Constants.SdpServiceNameAttributeId))
{
rootPage.NotifyUser(
"The Chat service is not advertising the Service Name attribute (attribute id=0x100). " +
"Please verify that you are running the BluetoothRfcommChat server.",
NotifyType.ErrorMessage);
RunButton.IsEnabled = true;
return;
}
var attributeReader = DataReader.FromBuffer(attributes[Constants.SdpServiceNameAttributeId]);
var attributeType = attributeReader.ReadByte();
if (attributeType != Constants.SdpServiceNameAttributeType)
{
rootPage.NotifyUser(
"The Chat service is using an unexpected format for the Service Name attribute. " +
"Please verify that you are running the BluetoothRfcommChat server.",
NotifyType.ErrorMessage);
RunButton.IsEnabled = true;
return;
}
var serviceNameLength = attributeReader.ReadByte();
// The Service Name attribute requires UTF-8 encoding.
attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8;
deviceWatcher.Stop();
lock (this)
{
chatSocket = new StreamSocket();
}
try
{
await chatSocket.ConnectAsync(chatService.ConnectionHostName, chatService.ConnectionServiceName);
SetChatUI(attributeReader.ReadString(serviceNameLength), bluetoothDevice.Name);
chatWriter = new DataWriter(chatSocket.OutputStream);
DataReader chatReader = new DataReader(chatSocket.InputStream);
ReceiveStringLoop(chatReader);
}
catch (Exception ex)
{
switch ((uint)ex.HResult)
{
case (0x80070490): // ERROR_ELEMENT_NOT_FOUND
rootPage.NotifyUser("Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage);
RunButton.IsEnabled = true;
break;
default:
throw;
}
}
}
/// <summary>
/// If you believe the Bluetooth device will eventually be paired with Windows,
/// you might want to pre-emptively get consent to access the device.
/// An explicit call to RequestAccessAsync() prompts the user for consent.
/// If this is not done, a device that's working before being paired,
/// will no longer work after being paired.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void RequestAccessButton_Click(object sender, RoutedEventArgs e)
{
// Make sure user has given consent to access device
DeviceAccessStatus accessStatus = await bluetoothDevice.RequestAccessAsync();
if (accessStatus != DeviceAccessStatus.Allowed)
{
rootPage.NotifyUser(
"Access to the device is denied because the application was not granted access",
NotifyType.StatusMessage);
}
else
{
rootPage.NotifyUser(
"Access granted, you are free to pair devices",
NotifyType.StatusMessage);
}
}
private void SendButton_Click(object sender, RoutedEventArgs e)
{
SendMessage();
}
public void KeyboardKey_Pressed(object sender, KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.Enter)
{
SendMessage();
}
}
/// <summary>
/// Takes the contents of the MessageTextBox and writes it to the outgoing chatWriter
/// </summary>
private async void SendMessage()
{
try
{
if (MessageTextBox.Text.Length != 0)
{
chatWriter.WriteUInt32((uint)MessageTextBox.Text.Length);
chatWriter.WriteString(MessageTextBox.Text);
ConversationList.Items.Add("Sent: " + MessageTextBox.Text);
MessageTextBox.Text = "";
await chatWriter.StoreAsync();
}
}
catch (Exception ex) when ((uint)ex.HResult == 0x80072745)
{
// The remote device has disconnected the connection
rootPage.NotifyUser("Remote side disconnect: " + ex.HResult.ToString() + " - " + ex.Message,
NotifyType.StatusMessage);
}
}
private async void ReceiveStringLoop(DataReader chatReader)
{
try
{
uint size = await chatReader.LoadAsync(sizeof(uint));
if (size < sizeof(uint))
{
Disconnect("Remote device terminated connection - make sure only one instance of server is running on remote device");
return;
}
uint stringLength = chatReader.ReadUInt32();
uint actualStringLength = await chatReader.LoadAsync(stringLength);
if (actualStringLength != stringLength)
{
// The underlying socket was closed before we were able to read the whole data
return;
}
ConversationList.Items.Add("Received: " + chatReader.ReadString(stringLength));
ReceiveStringLoop(chatReader);
}
catch (Exception ex)
{
lock (this)
{
if (chatSocket == null)
{
// Do not print anything here - the user closed the socket.
// HResult = 0x80072745 - catch this (remote device disconnect) ex = {"An established connection was aborted by the software in your host machine. (Exception from HRESULT: 0x80072745)"}
}
else
{
Disconnect("Read stream failed with error: " + ex.Message);
}
}
}
}
private void DisconnectButton_Click(object sender, RoutedEventArgs e)
{
Disconnect("Disconnected");
}
/// <summary>
/// Cleans up the socket and DataWriter and reset the UI
/// </summary>
/// <param name="disconnectReason"></param>
private void Disconnect(string disconnectReason)
{
if (chatWriter != null)
{
chatWriter.DetachStream();
chatWriter = null;
}
if (chatService != null)
{
chatService.Dispose();
chatService = null;
}
lock (this)
{
if (chatSocket != null)
{
chatSocket.Dispose();
chatSocket = null;
}
}
rootPage.NotifyUser(disconnectReason, NotifyType.StatusMessage);
ResetUI();
}
private void ResetUI()
{
RunButton.IsEnabled = true;
ConnectButton.Visibility = Visibility.Visible;
ChatBox.Visibility = Visibility.Collapsed;
RequestAccessButton.Visibility = Visibility.Collapsed;
ConversationList.Items.Clear();
}
private void SetChatUI(string serviceName, string deviceName)
{
ServiceName.Text = "Service Name: " + serviceName;
DeviceName.Text = "Connected to: " + deviceName;
RunButton.IsEnabled = false;
ConnectButton.Visibility = Visibility.Collapsed;
RequestAccessButton.Visibility = Visibility.Visible;
resultsListView.IsEnabled = false;
resultsListView.Visibility = Visibility.Collapsed;
ChatBox.Visibility = Visibility.Visible;
}
private void ResultsListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
UpdatePairingButtons();
}
private void UpdatePairingButtons()
{
RfcommChatDeviceDisplay deviceDisp = (RfcommChatDeviceDisplay)resultsListView.SelectedItem;
if (null != deviceDisp)
{
ConnectButton.IsEnabled = true;
}
else
{
ConnectButton.IsEnabled = false;
}
}
}
public class RfcommChatDeviceDisplay : INotifyPropertyChanged
{
private DeviceInformation deviceInfo;
public RfcommChatDeviceDisplay(DeviceInformation deviceInfoIn)
{
deviceInfo = deviceInfoIn;
UpdateGlyphBitmapImage();
}
public DeviceInformation DeviceInformation
{
get
{
return deviceInfo;
}
private set
{
deviceInfo = value;
}
}
public string Id
{
get
{
return deviceInfo.Id;
}
}
public string Name
{
get
{
return deviceInfo.Name;
}
}
public BitmapImage GlyphBitmapImage
{
get;
private set;
}
public void Update(DeviceInformationUpdate deviceInfoUpdate)
{
deviceInfo.Update(deviceInfoUpdate);
UpdateGlyphBitmapImage();
}
private async void UpdateGlyphBitmapImage()
{
DeviceThumbnail deviceThumbnail = await deviceInfo.GetGlyphThumbnailAsync();
BitmapImage glyphBitmapImage = new BitmapImage();
await glyphBitmapImage.SetSourceAsync(deviceThumbnail);
GlyphBitmapImage = glyphBitmapImage;
OnPropertyChanged("GlyphBitmapImage");
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Portions derived from React Native:
// Copyright (c) 2015-present, Facebook, Inc.
// Licensed under the MIT License.
using ReactNative.Bridge;
using ReactNative.Collections;
using System;
using System.Collections.Generic;
using System.Reactive.Disposables;
using System.Threading;
using System.Threading.Tasks;
namespace ReactNative.Modules.Core
{
/// <summary>
/// Native module for JavaScript timer execution.
/// </summary>
public class Timing : ReactContextNativeModuleBase, ILifecycleEventListener
{
private const string IdleChoreographerKey = nameof(Timing) + "_Idle";
private static readonly TimeSpan s_frameDuration = TimeSpan.FromTicks(166666);
private static readonly TimeSpan s_idleCallbackFrameDeadline = TimeSpan.FromMilliseconds(1);
private readonly object _gate = new object();
private readonly object _idleGate = new object();
private readonly HeapBasedPriorityQueue<TimerData> _timers;
private readonly SerialDisposable _idleCancellationDisposable = new SerialDisposable();
private readonly Lazy<JSTimers> _jsTimersModule;
private bool _suspended;
private bool _sendIdleEvents;
/// <summary>
/// Instantiates the <see cref="Timing"/> module.
/// </summary>
/// <param name="reactContext">The React context.</param>
public Timing(ReactContext reactContext)
#if WINDOWS_UWP
: base(reactContext)
#else
: base(reactContext, CompiledReactDelegateFactory.Instance)
#endif
{
_timers = new HeapBasedPriorityQueue<TimerData>(
Comparer<TimerData>.Create((x, y) =>
x.TargetTime.CompareTo(y.TargetTime)));
_jsTimersModule = new Lazy<JSTimers>(() => Context.GetJavaScriptModule<JSTimers>());
}
/// <summary>
/// The name of the module.
/// </summary>
public override string Name
{
get
{
return "Timing";
}
}
/// <summary>
/// Initializes the module.
/// </summary>
public override void Initialize()
{
Context.AddLifecycleEventListener(this);
}
/// <summary>
/// Called when the host application suspends.
/// </summary>
public void OnSuspend()
{
_suspended = true;
ReactChoreographer.Instance.JavaScriptEventsCallback -= DoFrameSafe;
lock (_idleGate)
{
if (_sendIdleEvents)
{
ReactChoreographer.Instance.IdleCallback -= DoFrameIdleCallbackSafe;
}
}
}
/// <summary>
/// Called when the host application resumes.
/// </summary>
public void OnResume()
{
_suspended = false;
ReactChoreographer.Instance.JavaScriptEventsCallback += DoFrameSafe;
lock (_idleGate)
{
if (_sendIdleEvents)
{
ReactChoreographer.Instance.IdleCallback += DoFrameIdleCallbackSafe;
}
}
}
/// <summary>
/// Called when the host application is destroyed.
/// </summary>
public void OnDestroy()
{
ReactChoreographer.Instance.JavaScriptEventsCallback -= DoFrameSafe;
lock (_idleGate)
{
if (_sendIdleEvents)
{
ReactChoreographer.Instance.IdleCallback -= DoFrameIdleCallbackSafe;
}
}
}
/// <summary>
/// Creates a timer with the given properties.
/// </summary>
/// <param name="callbackId">The timer identifier.</param>
/// <param name="duration">The duration in milliseconds.</param>
/// <param name="jsSchedulingTime">
/// The Unix timestamp when the timer was created.
/// </param>
/// <param name="repeat">
/// A flag signaling if the timer should fire at intervals.
/// </param>
[ReactMethod]
public void createTimer(
int callbackId,
int duration,
double jsSchedulingTime,
bool repeat)
{
if (duration == 0 && !repeat)
{
_jsTimersModule.Value.callTimers(new[] { callbackId });
return;
}
var period = TimeSpan.FromMilliseconds(duration);
var unixEpoch = DateTimeOffset.Parse("1970-01-01T00:00:00Z");
var scheduledTime = unixEpoch.AddMilliseconds((long)jsSchedulingTime);
var initialTargetTime = (scheduledTime + period);
var timer = new TimerData(callbackId, initialTargetTime, period, repeat);
lock (_gate)
{
_timers.Enqueue(timer);
}
ReactChoreographer.Instance.ActivateCallback(nameof(Timing));
}
/// <summary>
/// Removes a timer.
/// </summary>
/// <param name="timerId">The timer identifier.</param>
[ReactMethod]
public void deleteTimer(int timerId)
{
lock (_gate)
{
_timers.Remove(new TimerData(timerId));
if (_timers.Count == 0)
{
ReactChoreographer.Instance.DeactivateCallback(nameof(Timing));
}
}
}
/// <summary>
/// Enable or disable idle events.
/// </summary>
/// <param name="sendIdleEvents">
/// <code>true</code> if idle events should be enabled, otherwise
/// <code>false</code>.
/// </param>
[ReactMethod]
public void setSendIdleEvents(bool sendIdleEvents)
{
lock (_idleGate)
{
_sendIdleEvents = sendIdleEvents;
if (_sendIdleEvents)
{
ReactChoreographer.Instance.IdleCallback += DoFrameIdleCallbackSafe;
ReactChoreographer.Instance.ActivateCallback(IdleChoreographerKey);
}
else
{
ReactChoreographer.Instance.IdleCallback -= DoFrameIdleCallbackSafe;
ReactChoreographer.Instance.DeactivateCallback(IdleChoreographerKey);
}
}
}
/// <summary>
/// Called before a <see cref="IReactInstance"/> is disposed.
/// </summary>
public override Task OnReactInstanceDisposeAsync()
{
_idleCancellationDisposable.Dispose();
//return Task.CompletedTask;
return Net46.Net45.Task.CompletedTask;
}
private void DoFrameSafe(object sender, object e)
{
try
{
DoFrame(sender, e);
}
catch (Exception ex)
{
Context.HandleException(ex);
}
}
private void DoFrame(object sender, object e)
{
if (Volatile.Read(ref _suspended))
{
return;
}
var ready = new List<int>();
var now = DateTimeOffset.Now;
lock (_gate)
{
while (_timers.Count > 0 && _timers.Peek().TargetTime < now)
{
var next = _timers.Dequeue();
ready.Add(next.CallbackId);
var nextInterval = next.Increment(now);
if (nextInterval.CanExecute)
{
_timers.Enqueue(nextInterval);
}
}
if (_timers.Count == 0)
{
ReactChoreographer.Instance.DeactivateCallback(nameof(Timing));
}
}
if (ready.Count > 0)
{
_jsTimersModule.Value.callTimers(ready);
}
}
private void DoFrameIdleCallbackSafe(object sender, FrameEventArgs e)
{
try
{
DoFrameIdleCallback(sender, e);
}
catch (Exception ex)
{
Context.HandleException(ex);
}
}
private void DoFrameIdleCallback(object sender, FrameEventArgs e)
{
if (Volatile.Read(ref _suspended))
{
return;
}
var cancellationDisposable = new CancellationDisposable();
_idleCancellationDisposable.Disposable = cancellationDisposable;
Context.RunOnJavaScriptQueueThread(() => DoIdleCallback(e.FrameTime, cancellationDisposable.Token));
}
private void DoIdleCallback(DateTimeOffset frameTime, CancellationToken token)
{
if (token.IsCancellationRequested)
{
return;
}
var remainingFrameTime = frameTime - DateTimeOffset.UtcNow;
if (remainingFrameTime < s_idleCallbackFrameDeadline)
{
return;
}
bool sendIdleEvents;
lock (_idleGate)
{
sendIdleEvents = _sendIdleEvents;
}
if (sendIdleEvents)
{
var frameStartTime = frameTime - s_frameDuration;
Context.GetJavaScriptModule<JSTimers>()
.callIdleCallbacks(Net46.Net45.Time.ToUnixTimeMilliseconds(frameStartTime));
}
}
struct TimerData : IEquatable<TimerData>
{
private readonly bool _repeat;
public TimerData(int callbackId)
{
CallbackId = callbackId;
TargetTime = DateTimeOffset.MaxValue;
Period = default(TimeSpan);
_repeat = false;
CanExecute = false;
}
public TimerData(int callbackId, DateTimeOffset initialTargetTime, TimeSpan period, bool repeat)
{
CallbackId = callbackId;
TargetTime = initialTargetTime;
Period = period;
_repeat = repeat;
CanExecute = true;
}
public int CallbackId { get; }
public DateTimeOffset TargetTime { get; private set; }
public TimeSpan Period { get; }
public bool CanExecute { get; private set; }
public TimerData Increment(DateTimeOffset now)
{
return new TimerData(CallbackId, now + Period, Period, _repeat)
{
CanExecute = _repeat,
};
}
public bool Equals(TimerData other)
{
return CallbackId == other.CallbackId &&
(TargetTime == other.TargetTime ||
TargetTime == DateTimeOffset.MaxValue ||
other.TargetTime == DateTimeOffset.MaxValue);
}
public override bool Equals(object obj)
{
if (obj is TimerData)
{
return Equals((TimerData)obj);
}
return false;
}
public override int GetHashCode()
{
return CallbackId.GetHashCode();
}
}
}
}
| |
namespace UnitTest
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;
using NUnit.Framework;
using Bond;
using Bond.Protocols;
using Bond.IO.Unsafe;
public static class Util
{
public static IEnumerable<MethodInfo> GetDeclaredMethods(this Type type, string name)
{
return type.GetMethods().Where(m => m.Name == name);
}
public static MethodInfo GetMethod(this Type type, string name, params Type[] paramTypes)
{
var methods = type.GetDeclaredMethods(name);
return (
from method in methods
let parameters = method.GetParameters()
where parameters != null
where parameters.Select(p => p.ParameterType).Where(t => !t.IsGenericParameter).SequenceEqual(paramTypes)
select method).FirstOrDefault();
}
public static void TranscodeCBCB(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new CompactBinaryReader<InputStream>(input);
var output = new OutputStream(to, 19);
var writer = new CompactBinaryWriter<OutputStream>(output);
Transcode.FromTo(reader, writer);
output.Flush();
}
public static void TranscodeCBFB(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new CompactBinaryReader<InputStream>(input);
var output = new OutputStream(to, 19);
var writer = new FastBinaryWriter<OutputStream>(output);
Transcode.FromTo(reader, writer);
output.Flush();
}
public static void TranscodeCBSP<From>(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new CompactBinaryReader<InputStream>(input);
var output = new OutputStream(to, 19);
var writer = new SimpleBinaryWriter<OutputStream>(output);
Transcode<From>.FromTo(reader, writer);
output.Flush();
}
public static void TranscodeCBXml<From>(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new CompactBinaryReader<InputStream>(input);
var hasBase = Schema<From>.RuntimeSchema.HasBase;
var writer = new SimpleXmlWriter(to, new SimpleXmlWriter.Settings { UseNamespaces = hasBase });
Transcode<From>.FromTo(reader, writer);
writer.Flush();
}
public static void TranscodeCBJson<From>(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new CompactBinaryReader<InputStream>(input);
var writer = new SimpleJsonWriter(to);
Transcode<From>.FromTo(reader, writer);
writer.Flush();
}
public static void TranscodeFBCB(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new FastBinaryReader<InputStream>(input);
var output = new OutputStream(to, 19);
var writer = new CompactBinaryWriter<OutputStream>(output);
Transcode.FromTo(reader, writer);
output.Flush();
}
public static void TranscodeFBFB(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new FastBinaryReader<InputStream>(input);
var output = new OutputStream(to, 19);
var writer = new FastBinaryWriter<OutputStream>(output);
Transcode.FromTo(reader, writer);
output.Flush();
}
public static void TranscodeFBSP<From>(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new FastBinaryReader<InputStream>(input);
var output = new OutputStream(to, 19);
var writer = new SimpleBinaryWriter<OutputStream>(output);
Transcode<From>.FromTo(reader, writer);
output.Flush();
}
public static void TranscodeFBXml<From>(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new FastBinaryReader<InputStream>(input);
var hasBase = Schema<From>.RuntimeSchema.HasBase;
var writer = new SimpleXmlWriter(to, new SimpleXmlWriter.Settings { UseNamespaces = hasBase });
Transcode<From>.FromTo(reader, writer);
writer.Flush();
}
public static void TranscodeFBJson<From>(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new FastBinaryReader<InputStream>(input);
var writer = new SimpleJsonWriter(to);
Transcode<From>.FromTo(reader, writer);
writer.Flush();
}
public static void TranscodeSPSP<From>(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new SimpleBinaryReader<InputStream>(input);
var output = new OutputStream(to, 19);
var writer = new SimpleBinaryWriter<OutputStream>(output);
Transcode<From>.FromTo(reader, writer);
output.Flush();
}
public static void TranscodeSPCB<From>(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new SimpleBinaryReader<InputStream>(input);
var output = new OutputStream(to, 19);
var writer = new CompactBinaryWriter<OutputStream>(output);
Transcode<From>.FromTo(reader, writer);
output.Flush();
}
public static void TranscodeSPFB<From>(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new SimpleBinaryReader<InputStream>(input);
var output = new OutputStream(to, 19);
var writer = new FastBinaryWriter<OutputStream>(output);
Transcode<From>.FromTo(reader, writer);
output.Flush();
}
public static void TranscodeSPXml<From>(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new SimpleBinaryReader<InputStream>(input);
var hasBase = Schema<From>.RuntimeSchema.HasBase;
var writer = new SimpleXmlWriter(to, new SimpleXmlWriter.Settings { UseNamespaces = hasBase });
Transcode<From>.FromTo(reader, writer);
writer.Flush();
}
public static void TranscodeSPJson<From>(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new SimpleBinaryReader<InputStream>(input);
var writer = new SimpleJsonWriter(to);
Transcode<From>.FromTo(reader, writer);
writer.Flush();
}
public static void SerializeCB<T>(T obj, Stream stream)
{
var output = new OutputStream(stream, 11);
var writer = new CompactBinaryWriter<OutputStream>(output);
Serialize.To(writer, obj);
output.Flush();
}
public static void MarshalCB<T>(T obj, Stream stream)
{
var output = new OutputStream(stream, 11);
var writer = new CompactBinaryWriter<OutputStream>(output);
Marshal.To(writer, obj);
output.Flush();
}
public static void SerializerMarshalCB<T>(T obj, Stream stream)
{
var output = new OutputStream(stream, 11);
var writer = new CompactBinaryWriter<OutputStream>(output);
var serializer = new Serializer<CompactBinaryWriter<OutputStream>>(typeof(T));
serializer.Marshal(obj, writer);
output.Flush();
}
public static ArraySegment<byte> MarshalCB<T>(T obj)
{
var output = new OutputBuffer(new byte[11]);
var writer = new CompactBinaryWriter<OutputBuffer>(output);
Marshal.To(writer, obj);
return output.Data;
}
public static void SerializeCB<T>(IBonded<T> obj, Stream stream)
{
var output = new OutputStream(stream, 11);
var writer = new CompactBinaryWriter<OutputStream>(output);
Serialize.To(writer, obj);
output.Flush();
}
public static void SerializeCB(IBonded obj, Stream stream)
{
var output = new OutputStream(stream, 11);
var writer = new CompactBinaryWriter<OutputStream>(output);
Serialize.To(writer, obj);
output.Flush();
}
public static ArraySegment<byte> SerializeUnsafeCB<T>(T obj)
{
var output = new OutputBuffer();
var writer = new CompactBinaryWriter<OutputBuffer>(output);
Serialize.To(writer, obj);
return output.Data;
}
public static ArraySegment<byte> SerializeSafeCB<T>(T obj)
{
var output = new Bond.IO.Safe.OutputBuffer(new byte[11]);
var writer = new CompactBinaryWriter<Bond.IO.Safe.OutputBuffer>(output);
Serialize.To(writer, obj);
return output.Data;
}
public static T DeserializeCB<T>(Stream stream)
{
var input = new InputStream(stream);
var reader = new CompactBinaryReader<InputStream>(input);
return Deserialize<T>.From(reader);
}
public static T DeserializeSafeCB<T>(ArraySegment<byte> data)
{
var input = new Bond.IO.Safe.InputBuffer(data);
var reader = new CompactBinaryReader<Bond.IO.Safe.InputBuffer>(input);
return Deserialize<T>.From(reader);
}
public static T DeserializeUnsafeCB<T>(ArraySegment<byte> data)
{
var input = new InputBuffer(data);
var reader = new CompactBinaryReader<InputBuffer>(input);
return Deserialize<T>.From(reader);
}
public static void SerializeFB<T>(T obj, Stream stream)
{
var output = new OutputStream(stream, 11);
var writer = new FastBinaryWriter<OutputStream>(output);
Serialize.To(writer, obj);
output.Flush();
}
public static void MarshalFB<T>(T obj, Stream stream)
{
var output = new OutputStream(stream, 11);
var writer = new FastBinaryWriter<OutputStream>(output);
Marshal.To(writer, obj);
output.Flush();
}
public static void SerializerMarshalFB<T>(T obj, Stream stream)
{
var output = new OutputStream(stream, 11);
var writer = new FastBinaryWriter<OutputStream>(output);
var serializer = new Serializer<FastBinaryWriter<OutputStream>>(typeof(T));
serializer.Marshal(obj, writer);
output.Flush();
}
public static ArraySegment<byte> MarshalFB<T>(T obj)
{
var output = new OutputBuffer();
var writer = new FastBinaryWriter<OutputBuffer>(output);
Marshal.To(writer, obj);
return output.Data;
}
public static void SerializeFB<T>(IBonded<T> obj, Stream stream)
{
var output = new OutputStream(stream, 11);
var writer = new FastBinaryWriter<OutputStream>(output);
Serialize.To(writer, obj);
output.Flush();
}
public static void SerializeFB(IBonded obj, Stream stream)
{
var output = new OutputStream(stream, 11);
var writer = new FastBinaryWriter<OutputStream>(output);
Serialize.To(writer, obj);
output.Flush();
}
public static ArraySegment<byte> SerializeFB<T>(T obj)
{
var output = new OutputBuffer();
var writer = new FastBinaryWriter<OutputBuffer>(output);
Serialize.To(writer, obj);
return output.Data;
}
public static T DeserializeFB<T>(Stream stream)
{
var input = new InputStream(stream);
var reader = new FastBinaryReader<InputStream>(input);
return Deserialize<T>.From(reader);
}
public static T DeserializeSafeFB<T>(ArraySegment<byte> data)
{
var input = new Bond.IO.Safe.InputBuffer(data);
var reader = new FastBinaryReader<Bond.IO.Safe.InputBuffer>(input);
return Deserialize<T>.From(reader);
}
public static T DeserializeUnsafeFB<T>(ArraySegment<byte> data)
{
var input = new InputBuffer(data);
var reader = new FastBinaryReader<InputBuffer>(input);
return Deserialize<T>.From(reader);
}
public static void SerializeSP<T>(T obj, Stream stream)
{
var output = new OutputStream(stream, 11);
var writer = new SimpleBinaryWriter<OutputStream>(output);
Serialize.To(writer, obj);
output.Flush();
}
public static void SerializeSP<T>(IBonded<T> obj, Stream stream)
{
var output = new OutputStream(stream, 11);
var writer = new SimpleBinaryWriter<OutputStream>(output);
Serialize.To(writer, obj);
output.Flush();
}
public static ArraySegment<byte> SerializeSP<T>(T obj)
{
var output = new OutputBuffer();
var writer = new SimpleBinaryWriter<OutputBuffer>(output);
Serialize.To(writer, obj);
return output.Data;
}
public static void SerializeJson<T>(T obj, Stream stream)
{
var writer = new SimpleJsonWriter(stream);
Serialize.To(writer, obj);
writer.Flush();
}
public static void MarshalSP<T>(T obj, Stream stream)
{
var output = new OutputStream(stream, 11);
var writer = new SimpleBinaryWriter<OutputStream>(output);
Marshal.To(writer, obj);
output.Flush();
}
public static To DeserializeSP<From, To>(Stream stream)
{
var input = new InputStream(stream);
var reader = new SimpleBinaryReader<InputStream>(input);
var deserializer = new Deserializer<SimpleBinaryReader<InputStream>>(typeof(To), Schema<From>.RuntimeSchema);
return deserializer.Deserialize<To>(reader);
}
public static To DeserializeSafeSP<From, To>(ArraySegment<byte> data)
{
var input = new Bond.IO.Safe.InputBuffer(data.Array, data.Offset, data.Count);
var reader = new SimpleBinaryReader<Bond.IO.Safe.InputBuffer>(input);
var deserializer = new Deserializer<SimpleBinaryReader<Bond.IO.Safe.InputBuffer>>(typeof(To), Schema<From>.RuntimeSchema);
return deserializer.Deserialize<To>(reader);
}
public static To DeserializeUnsafeSP<From, To>(ArraySegment<byte> data)
{
var input = new InputBuffer(data);
var reader = new SimpleBinaryReader<InputBuffer>(input);
var deserializer = new Deserializer<SimpleBinaryReader<InputBuffer>>(typeof(To), Schema<From>.RuntimeSchema);
return deserializer.Deserialize<To>(reader);
}
public static void SerializeXml<T>(T obj, Stream stream)
{
var hasBase = Schema<T>.RuntimeSchema.HasBase;
var writer = new SimpleXmlWriter(stream, new SimpleXmlWriter.Settings { UseNamespaces = hasBase });
Serialize.To(writer, obj);
writer.Flush();
}
public static void SerializeXmlWithNamespaces<T>(T obj, Stream stream)
{
var writer = new SimpleXmlWriter(stream, new SimpleXmlWriter.Settings { UseNamespaces = true });
Serialize.To(writer, obj);
writer.Flush();
}
public static void SerializeXml<T>(IBonded<T> obj, Stream stream)
{
var writer = new SimpleXmlWriter(stream, new SimpleXmlWriter.Settings { UseNamespaces = true });
Serialize.To(writer, obj);
writer.Flush();
}
public static T DeserializeXml<T>(Stream stream)
{
var reader = new SimpleXmlReader(stream);
return Deserialize<T>.From(reader);
}
public static T DeserializeJson<T>(Stream stream)
{
var reader = new SimpleJsonReader(stream);
return Deserialize<T>.From(reader);
}
public static T DeserializeTagged<T>(ITaggedProtocolReader reader)
{
return Deserialize<T>.From(reader);
}
public static To DeserializeUntagged<From, To>(IUntaggedProtocolReader reader)
{
var deserializer = new Deserializer<IUntaggedProtocolReader>(typeof(To), Schema<From>.RuntimeSchema);
return deserializer.Deserialize<To>(reader);
}
public static string SerializeXmlString<T>(T obj)
{
var builder = new StringBuilder();
var writer = new SimpleXmlWriter(XmlWriter.Create(builder, new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true }));
Serialize.To(writer, obj);
writer.Flush();
return builder.ToString();
}
public static IBonded<T> MakeBondedCB<T>(T obj)
{
var stream = new MemoryStream();
SerializeCB(obj, stream);
stream.Position = 0;
// Create new MemoryStream at non-zero offset in a buffer
var buffer = new byte[stream.Length + 2];
stream.Read(buffer, 1, buffer.Length - 2);
var input = new InputStream(new MemoryStream(buffer, 1, buffer.Length - 2, false, true));
var reader = new CompactBinaryReader<InputStream>(input);
return new Bonded<T, CompactBinaryReader<InputStream>>(reader);
}
public static IBonded<T> MakeBondedSP<T>(T obj)
{
var stream = new MemoryStream();
SerializeSP(obj, stream);
stream.Position = 0;
// Create new MemoryStream at non-zero offset in a buffer
var buffer = new byte[stream.Length + 2];
stream.Read(buffer, 1, buffer.Length - 2);
var input = new InputStream(new MemoryStream(buffer, 1, buffer.Length - 2, false, true));
var reader = new SimpleBinaryReader<InputStream>(input);
return new Bonded<T, SimpleBinaryReader<InputStream>>(reader);
}
public delegate void RoundtripStream<From, To>(Action<From, Stream> serialize, Func<Stream, To> deserialize);
public delegate void MarshalStream<From>(Action<From, Stream> serialize);
public delegate void MarshalMemory<From>(Func<From, ArraySegment<byte>> serialize);
public delegate void TranscodeStream<From, To>(Action<From, Stream> serialize, Action<Stream, Stream> transcode, Func<Stream, To> deserialize);
public delegate void RoundtripMemory<From, To>(Func<From, ArraySegment<byte>> serialize, Func<ArraySegment<byte>, To> deserialize);
public static void AllSerializeDeserialize<From, To>(From from, bool noTranscoding = false)
where From : class
where To : class
{
RoundtripMemory<From, To> memoryRoundtrip = (serialize, deserialize) =>
{
var data = serialize(from);
var to = deserialize(data);
Assert.IsTrue(from.IsEqual(to));
};
RoundtripStream<From, To> streamRoundtrip = (serialize, deserialize) =>
{
var stream = new MemoryStream();
serialize(from, stream);
stream.Position = 0;
var to = deserialize(stream);
Assert.IsTrue(from.IsEqual(to));
};
MarshalStream<From> streamMarshal = serialize => streamRoundtrip(serialize, stream =>
{
stream.Position = 0;
return Unmarshal<To>.From(new InputStream(stream));
});
MarshalStream<From> streamMarshalSchema = serialize => streamRoundtrip(serialize, stream =>
{
stream.Position = 0;
return Unmarshal.From(new InputStream(stream), Schema<From>.RuntimeSchema).Deserialize<To>();
});
MarshalStream<From> streamMarshalNoSchema = serialize => streamRoundtrip(serialize, stream =>
{
stream.Position = 0;
return Unmarshal.From(new InputStream(stream)).Deserialize<To>();
});
MarshalMemory<From> memoryMarshal = serialize => memoryRoundtrip(serialize, Unmarshal<To>.From);
TranscodeStream<From, To> streamTranscode = (serialize, transcode, deserialize) =>
streamRoundtrip((obj, stream) =>
{
using (var tmp = new MemoryStream())
{
serialize(obj, tmp);
tmp.Position = 0;
transcode(tmp, stream);
}
}, deserialize);
if (noTranscoding)
streamTranscode = (serialize, transcode, deserialize) => { };
// Compact Binary
streamRoundtrip(SerializeCB, DeserializeCB<To>);
memoryRoundtrip(SerializeUnsafeCB, DeserializeSafeCB<To>);
memoryRoundtrip(SerializeUnsafeCB, DeserializeUnsafeCB<To>);
memoryRoundtrip(SerializeSafeCB, DeserializeSafeCB<To>);
memoryRoundtrip(SerializeSafeCB, DeserializeUnsafeCB<To>);
streamMarshal(MarshalCB);
streamMarshal(SerializerMarshalCB);
streamMarshalSchema(MarshalCB);
streamMarshalNoSchema(MarshalCB);
memoryMarshal(MarshalCB);
streamTranscode(SerializeCB, TranscodeCBCB, DeserializeCB<To>);
streamTranscode(SerializeCB, TranscodeCBFB, DeserializeFB<To>);
streamRoundtrip(SerializeCB, stream =>
{
var input = new InputStream(stream);
var reader = new CompactBinaryReader<InputStream>(input);
return DeserializeTagged<To>(reader);
});
// Fast Binary
streamRoundtrip(SerializeFB, DeserializeFB<To>);
memoryRoundtrip(SerializeFB, DeserializeSafeFB<To>);
memoryRoundtrip(SerializeFB, DeserializeUnsafeFB<To>);
streamMarshal(MarshalFB);
streamMarshal(SerializerMarshalFB);
streamMarshalSchema(MarshalFB);
streamMarshalNoSchema(MarshalFB);
memoryMarshal(MarshalFB);
streamTranscode(SerializeFB, TranscodeFBFB, DeserializeFB<To>);
streamTranscode(SerializeFB, TranscodeFBCB, DeserializeCB<To>);
streamRoundtrip(SerializeFB, stream =>
{
var input = new InputStream(stream);
var reader = new FastBinaryReader<InputStream>(input);
return DeserializeTagged<To>(reader);
});
// Simple doesn't support omitting fields
if (typeof(From) != typeof(Nothing) && typeof(From) != typeof(GenericsWithNothing))
{
streamRoundtrip(SerializeSP, DeserializeSP<From, To>);
memoryRoundtrip(SerializeSP, DeserializeSafeSP<From, To>);
memoryRoundtrip(SerializeSP, DeserializeUnsafeSP<From, To>);
streamTranscode(SerializeCB, TranscodeCBSP<From>, DeserializeSP<From, To>);
streamTranscode(SerializeFB, TranscodeFBSP<From>, DeserializeSP<From, To>);
streamTranscode(SerializeSP, TranscodeSPSP<From>, DeserializeSP<From, To>);
streamTranscode(SerializeSP, TranscodeSPCB<From>, DeserializeCB<To>);
streamTranscode(SerializeSP, TranscodeSPFB<From>, DeserializeFB<To>);
streamTranscode(SerializeSP, TranscodeSPXml<From>, DeserializeXml<To>);
streamTranscode(SerializeSP, TranscodeSPJson<From>, DeserializeJson<To>);
streamRoundtrip(SerializeSP, stream =>
{
var input = new InputStream(stream);
var reader = new SimpleBinaryReader<InputStream>(input);
return DeserializeUntagged<From, To>(reader);
});
streamMarshalSchema(MarshalSP);
}
streamRoundtrip(SerializeXml, DeserializeXml<To>);
streamRoundtrip(SerializeJson, DeserializeJson<To>);
streamTranscode(SerializeCB, TranscodeCBXml<From>, DeserializeXml<To>);
streamTranscode(SerializeCB, TranscodeCBJson<From>, DeserializeJson<To>);
streamTranscode(SerializeFB, TranscodeFBXml<From>, DeserializeXml<To>);
streamTranscode(SerializeFB, TranscodeFBJson<From>, DeserializeJson<To>);
}
}
}
| |
#pragma warning disable 0168
using nHydrate.Generator.Common;
using nHydrate.Generator.Common.Models;
using nHydrate.Generator.Common.Util;
using System;
using System.Linq;
using System.Text;
namespace nHydrate.Generator.EFCodeFirstNetCore.Generators.Contexts
{
public class ContextGeneratedTemplate : EFCodeFirstNetCoreBaseTemplate
{
private readonly ModelConfiguration _modelConfiguration = null;
public ContextGeneratedTemplate(ModelRoot model)
: base(model)
{
if (model.ModelConfigurations.ContainsKey(typeof(EFCodeFirstNetCoreProjectGenerator).Name))
_modelConfiguration = model.ModelConfigurations[typeof(EFCodeFirstNetCoreProjectGenerator).Name] as ModelConfiguration;
if (_modelConfiguration == null)
_modelConfiguration = new ModelConfiguration();
}
#region BaseClassTemplate overrides
public override string FileName => _model.ProjectName + "Entities.Generated.cs";
public string ParentItemName => _model.ProjectName + "Entities.cs";
public override string FileContent { get => Generate(); }
#endregion
#region GenerateContent
public override string Generate()
{
var sb = new StringBuilder();
GenerationHelper.AppendFileGeneatedMessageInCode(sb);
sb.AppendLine("#pragma warning disable 612");
this.AppendUsingStatements(sb);
sb.AppendLine("namespace " + this.GetLocalNamespace());
sb.AppendLine("{");
this.AppendTypeTableEnums(sb);
this.AppendTableMapping(sb);
this.AppendClass(sb);
this.AppendExtensions(sb);
sb.AppendLine("}");
sb.AppendLine();
sb.AppendLine($"namespace {this.GetLocalNamespace()}.Entity");
sb.AppendLine("{");
sb.AppendLine("}");
sb.AppendLine("#pragma warning restore 612");
return sb.ToString();
}
private void AppendTableMapping(StringBuilder sb)
{
sb.AppendLine(" #region EntityMappingConstants Enumeration");
sb.AppendLine();
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// A map for all entity types in this library");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" public enum EntityMappingConstants");
sb.AppendLine(" {");
foreach (var table in _model.Database.Tables.Where(x => !x.IsEnumOnly()).OrderBy(x => x.PascalName))
{
sb.AppendLine(" /// <summary>");
sb.AppendLine($" /// A mapping for the the {table.PascalName} entity");
sb.AppendLine(" /// </summary>");
sb.AppendLine($" {table.PascalName},");
}
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" #endregion");
sb.AppendLine();
}
private void AppendUsingStatements(StringBuilder sb)
{
sb.AppendLine("using System;");
sb.AppendLine("using System.Linq;");
sb.AppendLine("using System.Collections.Generic;");
sb.AppendLine("using Microsoft.EntityFrameworkCore;");
sb.AppendLine("using System.Configuration;");
sb.AppendLine("using Microsoft.EntityFrameworkCore.ChangeTracking;");
sb.AppendLine("using System.Threading.Tasks;");
sb.AppendLine("using System.Threading;");
sb.AppendLine("using System.Reflection;");
sb.AppendLine("using System.ComponentModel.DataAnnotations;");
sb.AppendLine();
}
private void AppendClass(StringBuilder sb)
{
sb.AppendLine(" #region Entity Context");
sb.AppendLine();
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// The entity context for the defined model schema");
sb.AppendLine(" /// </summary>");
sb.AppendLine($" public partial class {_model.ProjectName}Entities : Microsoft.EntityFrameworkCore.DbContext, IContext");
sb.AppendLine(" {");
sb.AppendLine(" private static Dictionary<string, bool> _mapAuditDateFields = new Dictionary<string, bool>();");
sb.AppendLine();
sb.AppendLine(" /// <summary />");
sb.AppendLine($" public static Action<string> QueryLogger {GetSetSuffix}");
sb.AppendLine();
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// A unique key for this object instance");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" public Guid InstanceKey { get; private set; }");
sb.AppendLine();
sb.AppendLine(" private string _tenantId = null;");
//Create the modifier property
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// The audit modifier used to mark database edits");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" protected IContextStartup _contextStartup = new ContextStartup(null);");
sb.AppendLine();
sb.AppendLine(" private static object _seqCacheLock = new object();");
sb.AppendLine();
// Create consts for version and modelKey
sb.AppendLine($" private const string _version = \"{_model.Version}.{_model.GeneratedVersion}\";");
sb.AppendLine($" private const string _modelKey = \"{_model.Key}\";");
sb.AppendLine(" protected string _connectionString = null;");
sb.AppendLine();
#region Constructors
sb.AppendLine(" #region Constructors");
sb.AppendLine();
sb.AppendLine(" /// <summary>");
sb.AppendLine($" /// Initializes a new {_model.ProjectName}Entities object using the connection string found in the '{_model.ProjectName}Entities' section of the application configuration file.");
sb.AppendLine(" /// </summary>");
sb.AppendLine($" public {_model.ProjectName}Entities() :");
sb.AppendLine(" base()");
sb.AppendLine(" {");
sb.AppendLine($" _connectionString = ConfigurationManager.ConnectionStrings[\"{_model.ProjectName}Entities\"]?.ConnectionString;");
sb.AppendLine(" InstanceKey = Guid.NewGuid();");
sb.AppendLine(" _contextStartup = new ContextStartup(null, true);");
sb.AppendLine(" this.CommandTimeout = _contextStartup.CommandTimeout;");
sb.AppendLine(" this.OnContextCreated();");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" /// <summary>");
sb.AppendLine($" /// Initialize a new {_model.ProjectName}Entities object with an audit modifier.");
sb.AppendLine(" /// </summary>");
sb.AppendLine($" public {_model.ProjectName}Entities(IContextStartup contextStartup) :");
sb.AppendLine(" base()");
sb.AppendLine(" {");
sb.AppendLine(" _contextStartup = contextStartup;");
sb.AppendLine(" _tenantId = (this.ContextStartup as TenantContextStartup)?.TenantId;");
sb.AppendLine($" _connectionString = ConfigurationManager.ConnectionStrings[\"{_model.ProjectName}Entities\"]?.ConnectionString;");
sb.AppendLine(" InstanceKey = Guid.NewGuid();");
sb.AppendLine(" this.CommandTimeout = _contextStartup.CommandTimeout;");
sb.AppendLine(" this.OnContextCreated();");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" /// <summary>");
sb.AppendLine($" /// Initialize a new {_model.ProjectName}Entities object with an audit modifier.");
sb.AppendLine(" /// </summary>");
sb.AppendLine($" public {_model.ProjectName}Entities(IContextStartup contextStartup, string connectionString) :");
sb.AppendLine(" base()");
sb.AppendLine(" {");
sb.AppendLine(" _contextStartup = contextStartup;");
sb.AppendLine(" _tenantId = (this.ContextStartup as TenantContextStartup)?.TenantId;");
sb.AppendLine(" _connectionString = connectionString;");
sb.AppendLine(" InstanceKey = Guid.NewGuid();");
sb.AppendLine(" this.CommandTimeout = _contextStartup.CommandTimeout;");
sb.AppendLine(" this.OnContextCreated();");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" /// <summary>");
sb.AppendLine($" /// Initialize a new {_model.ProjectName}Entities object with an audit modifier.");
sb.AppendLine(" /// </summary>");
sb.AppendLine($" public {_model.ProjectName}Entities(string connectionString) :");
sb.AppendLine(" base()");
sb.AppendLine(" {");
sb.AppendLine(" _connectionString = connectionString;");
sb.AppendLine(" InstanceKey = Guid.NewGuid();");
sb.AppendLine(" _contextStartup = new ContextStartup(null, true);");
sb.AppendLine(" this.CommandTimeout = _contextStartup.CommandTimeout;");
sb.AppendLine(" this.OnContextCreated();");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" #endregion");
sb.AppendLine();
#endregion
sb.AppendLine(" partial void OnContextCreated();");
sb.AppendLine(" partial void OnModelCreated(ModelBuilder modelBuilder);");
sb.AppendLine();
#region OnModelCreating
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// Model creation event");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" protected override void OnModelCreating(ModelBuilder modelBuilder)");
sb.AppendLine(" {");
sb.AppendLine(" base.OnModelCreating(modelBuilder);");
sb.AppendLine();
#region Map Tables
sb.AppendLine(" #region Map Tables");
//Tables
foreach (var item in _model.Database.Tables.Where(x => !x.AssociativeTable && !x.IsEnumOnly()).OrderBy(x => x.PascalName))
{
if (item.DBSchema.IsEmpty())
sb.AppendLine($" modelBuilder.Entity<{this.GetLocalNamespace()}.Entity.{item.PascalName}>().ToTable(\"{item.DatabaseName}\");");
else
sb.AppendLine($" modelBuilder.Entity<{this.GetLocalNamespace()}.Entity.{item.PascalName}>().ToTable(\"{item.DatabaseName}\", \"{item.DBSchema}\");");
}
//Views
foreach (var item in _model.Database.CustomViews.OrderBy(x => x.DatabaseName))
{
if (item.DBSchema.IsEmpty())
sb.AppendLine($" modelBuilder.Entity<{this.GetLocalNamespace()}.Entity.{item.PascalName}>().ToTable(\"{item.DatabaseName}\");");
else
sb.AppendLine($" modelBuilder.Entity<{this.GetLocalNamespace()}.Entity.{item.PascalName}>().ToTable(\"{item.DatabaseName}\", \"{item.DBSchema}\");");
}
sb.AppendLine(" #endregion");
sb.AppendLine();
#endregion
#region Create annotations for properties
sb.AppendLine(" #region Setup Fields");
sb.AppendLine();
//Tables
foreach (var table in _model.Database.Tables.Where(x => !x.IsEnumOnly()).OrderBy(x => x.Name))
{
sb.AppendLine($" //Field setup for {table.PascalName} entity");
foreach (var column in table.GetColumns().OrderBy(x => x.Name))
{
#region Determine if this is a type table Value field and if so ignore
{
if (table.IsColumnRelatedToTypeTable(column, out string pascalRoleName) || (column.PrimaryKey && table.IsTypedTable()))
{
var typeTable = table.GetRelatedTypeTableByColumn(column, out pascalRoleName) ?? table;
if (typeTable != null)
sb.AppendLine($" modelBuilder.Entity<{this.GetLocalNamespace()}.Entity.{table.PascalName}>().Ignore(d => d.{pascalRoleName}{typeTable.PascalName}Value);");
}
}
#endregion
//If the column is not a PK then process it
//if (!column.PrimaryKey)
{
sb.Append($" modelBuilder.Entity<{this.GetLocalNamespace()}.Entity.{table.PascalName}>()");
sb.Append($".Property(d => d.{column.PascalName})");
if (column.AllowNull) sb.Append(".IsRequired(false)");
else sb.Append(".IsRequired(true)");
//Add the auto-gen value UNLESS it is a type table
if (!table.IsTypedTable() && column.IdentityDatabase() && column.DataType.IsIntegerType())
sb.Append(".ValueGeneratedOnAdd()");
if (column.DataType.IsTextType() && column.Length > 0 && column.DataType != System.Data.SqlDbType.Xml)
sb.Append($".HasMaxLength({column.GetAnnotationStringLength()})");
if (column.DatabaseName != column.PascalName)
sb.Append($".HasColumnName(\"{column.DatabaseName}\")");
sb.AppendLine(";");
}
}
if (table.IsTenant)
{
sb.AppendLine($" modelBuilder.Entity<{this.GetLocalNamespace()}.Entity.{table.PascalName}>().Property(\"{_model.TenantColumnName}\").IsRequired();");
}
if (table.AllowCreateAudit)
sb.AppendLine($" modelBuilder.Entity<{this.GetLocalNamespace()}.Entity.{table.PascalName}>().Property(d => d.{_model.Database.CreatedDateColumnName}).IsRequired();");
if (table.AllowModifiedAudit)
sb.AppendLine($" modelBuilder.Entity<{this.GetLocalNamespace()}.Entity.{table.PascalName}>().Property(d => d.{_model.Database.ModifiedDateColumnName}).IsRequired();");
if (table.AllowConcurrencyCheck)
{
if (!String.Equals(_model.Database.ConcurrencyCheckDatabaseName, _model.Database.ConcurrencyCheckPascalName, StringComparison.OrdinalIgnoreCase))
{
sb.Append($" modelBuilder.Entity<{this.GetLocalNamespace()}.Entity.{table.PascalName}>()");
sb.Append($".Property(d => d.{_model.Database.ConcurrencyCheckPascalName})");
sb.Append($".HasColumnName(\"{_model.Database.ConcurrencyCheckDatabaseName}\")");
sb.AppendLine(";");
}
sb.AppendLine($" modelBuilder.Entity<{this.GetLocalNamespace()}.Entity.{table.PascalName}>().Property(d => d.{_model.Database.ConcurrencyCheckPascalName}).IsRequired();");
}
sb.AppendLine();
}
//Views
foreach (var item in _model.Database.CustomViews.OrderBy(x => x.Name))
{
sb.AppendLine($" //Field setup for {item.PascalName} entity");
foreach (var column in item.GetColumns().OrderBy(x => x.Name))
{
sb.Append($" modelBuilder.Entity<{this.GetLocalNamespace()}.Entity.{item.PascalName}>()");
sb.Append($".Property(d => d.{column.PascalName})");
if (!column.AllowNull) sb.Append(".IsRequired()");
if (column.DataType.IsTextType() && column.Length > 0 && column.DataType != System.Data.SqlDbType.Xml) sb.Append($".HasMaxLength({column.GetAnnotationStringLength()})");
if (column.DatabaseName != column.PascalName) sb.Append($".HasColumnName(\"{column.DatabaseName}\")");
sb.AppendLine(";");
}
sb.AppendLine();
}
sb.AppendLine(" #endregion");
sb.AppendLine();
#endregion
#region Setup ignores for Enum properties
sb.AppendLine(" #region Ignore Enum Properties");
sb.AppendLine();
foreach (var table in _model.Database.Tables.Where(x => !x.IsEnumOnly()).OrderBy(x => x.Name))
{
foreach (var column in table.GetColumns().OrderBy(x => x.Name))
{
if (table.IsColumnRelatedToTypeTable(column, out var pascalRoleName) || (column.PrimaryKey && table.IsTypedTable()))
{
var typeTable = table.GetRelatedTypeTableByColumn(column, out pascalRoleName);
if (typeTable == null) typeTable = table;
if (typeTable != null)
{
sb.AppendLine($" modelBuilder.Entity<{this.GetLocalNamespace()}.Entity.{table.PascalName}>().Ignore(t => t.{pascalRoleName}{typeTable.PascalName}Value);");
}
}
}
}
sb.AppendLine();
sb.AppendLine(" #endregion");
sb.AppendLine();
#endregion
#region Primary Keys
sb.AppendLine(" #region Primary Keys");
sb.AppendLine();
foreach (var table in _model.Database.Tables.Where(x => !x.IsEnumOnly()).OrderBy(x => x.Name))
{
sb.Append($" modelBuilder.Entity<{this.GetLocalNamespace()}.Entity." + table.PascalName + ">().HasKey(x => new { ");
var columnList = table.GetColumns().Where(x => x.PrimaryKey).OrderBy(x => x.Name).ToList();
foreach (var c in columnList)
{
sb.Append($"x.{c.PascalName}");
if (columnList.IndexOf(c) < columnList.Count - 1)
sb.Append(", ");
}
sb.AppendLine(" });");
}
foreach (var table in _model.Database.CustomViews.OrderBy(x => x.Name))
{
sb.Append($" modelBuilder.Entity<{this.GetLocalNamespace()}.Entity." + table.PascalName + ">().HasKey(x => new { ");
var columnList = table.GetColumns().Where(x => x.IsPrimaryKey).OrderBy(x => x.Name).ToList();
sb.Append(string.Join(", ", columnList.Select(c => $"x.{c.PascalName}")));
sb.AppendLine(" });");
}
sb.AppendLine();
sb.AppendLine(" #endregion");
sb.AppendLine();
#endregion
#region Create annotations for relationships
sb.AppendLine(" #region Relations");
sb.AppendLine();
foreach (var table in _model.Database.Tables.Where(x => !x.AssociativeTable && !x.IsEnumOnly()).OrderBy(x => x.PascalName))
{
foreach (var relation in table.GetRelations())
{
var childTable = relation.ChildTable;
if (!childTable.IsInheritedFrom(table) && !childTable.AssociativeTable)
{
if (relation.IsOneToOne)
{
sb.AppendLine($" //Relation [{table.PascalName}] -> [{childTable.PascalName}] (Multiplicity 1:1)");
sb.AppendLine($" modelBuilder.Entity<{this.GetLocalNamespace()}.Entity.{table.PascalName}>()");
sb.AppendLine($" .HasOne(a => a.{relation.PascalRoleName}{childTable.PascalName})");
sb.AppendLine($" .WithOne(x => x.{relation.PascalRoleName}{table.PascalName})");
sb.AppendLine($" .HasForeignKey<{this.GetLocalNamespace()}.Entity." + childTable.PascalName + ">(q => new { " +
string.Join(",", relation.ColumnRelationships.Select(x => x.ChildColumn.PascalName).OrderBy(x => x).Select(c => "q." + c)) + " })");
sb.AppendLine($" .HasPrincipalKey<{this.GetLocalNamespace()}.Entity." + table.PascalName + ">(q => new { " +
string.Join(",", relation.ColumnRelationships.Select(x => x.ParentColumn.PascalName).OrderBy(x => x).Select(c => "q." + c)) + " })");
if (relation.IsRequired)
sb.AppendLine(" .IsRequired(true)");
else
sb.AppendLine(" .IsRequired(false)");
//Specify what to do on delete
if (relation.DeleteAction == DeleteActionConstants.Cascade)
sb.AppendLine(" .OnDelete(DeleteBehavior.Cascade);");
else if (relation.DeleteAction == DeleteActionConstants.SetNull)
sb.AppendLine(" .OnDelete(DeleteBehavior.SetNull);");
else if (relation.DeleteAction == DeleteActionConstants.NoAction)
sb.AppendLine(" .OnDelete(DeleteBehavior.Restrict);");
}
else
{
sb.AppendLine($" //Relation [{table.PascalName}] -> [{childTable.PascalName}] (Multiplicity 1:N)");
sb.AppendLine($" modelBuilder.Entity<{this.GetLocalNamespace()}.Entity.{childTable.PascalName}>()");
sb.AppendLine($" .HasOne(a => a.{relation.PascalRoleName}{table.PascalName})");
if (relation.IsOneToOne)
sb.AppendLine($" .WithOne(x => x.{relation.PascalRoleName}{childTable.PascalName})");
else
sb.AppendLine($" .WithMany(b => b.{relation.PascalRoleName}{childTable.PascalName}List)");
if (relation.IsRequired)
sb.AppendLine(" .IsRequired(true)");
else
sb.AppendLine(" .IsRequired(false)");
sb.AppendLine(" .HasPrincipalKey(q => new { " + string.Join(", ", relation.ColumnRelationships.Select(x => x.ParentColumn.PascalName).OrderBy(x => x).Select(c => "q." + c)) + " })");
sb.Append(" .HasForeignKey(u => new { ");
var index = 0;
foreach (var columnPacket in relation.ColumnRelationships
.Select(x => new { Child = x.ChildColumn, Parent = x.ParentColumn })
.Where(x => x.Child != null && x.Parent != null)
.OrderBy(x => x.Parent.PascalName)
.ToList())
{
sb.Append($"u.{columnPacket.Child.PascalName}");
if (index < relation.ColumnRelationships.Count - 1)
sb.Append(", ");
index++;
}
sb.AppendLine(" })");
var indexName = $"FK_{relation.RoleName}_{relation.ChildTable.DatabaseName}_{relation.ParentTable.DatabaseName}".ToUpper();
sb.AppendLine($" .HasConstraintName(\"{indexName}\")");
//Specify what to do on delete
if (relation.DeleteAction == DeleteActionConstants.Cascade)
sb.AppendLine(" .OnDelete(DeleteBehavior.Cascade);");
else if (relation.DeleteAction == DeleteActionConstants.SetNull)
sb.AppendLine(" .OnDelete(DeleteBehavior.SetNull);");
else if (relation.DeleteAction == DeleteActionConstants.NoAction)
sb.AppendLine(" .OnDelete(DeleteBehavior.Restrict);");
}
sb.AppendLine();
}
}
}
//Associative tables
foreach (var table in _model.Database.Tables.Where(x => x.AssociativeTable && !x.IsEnumOnly()).OrderBy(x => x.PascalName))
{
var relations = table.GetRelationsWhereChild().ToList();
if (relations.Count == 2)
{
var relation1 = relations.First();
var relation2 = relations.Last();
var index1Name = $"FK_{relation1.RoleName}_{relation1.ChildTable.DatabaseName}_{relation1.ParentTable.DatabaseName}".ToUpper();
var index2Name = $"FK_{relation2.RoleName}_{relation2.ChildTable.DatabaseName}_{relation2.ParentTable.DatabaseName}".ToUpper();
sb.AppendLine($" //Relation for [{relation1.ParentTable.PascalName}] -> [{relation2.ParentTable.PascalName}] (Multiplicity N:M)");
sb.AppendLine($" modelBuilder.Entity<{this.GetLocalNamespace()}.Entity.{relation1.ParentTable.PascalName}>()");
sb.AppendLine($" .HasMany(q => q.{relation1.PascalRoleName}{table.PascalName}List)");
sb.AppendLine($" .WithOne(q => q.{relation1.PascalRoleName}{relation1.ParentTable.PascalName})");
sb.AppendLine($" .HasConstraintName(\"{index1Name}\")");
sb.AppendLine(" .HasPrincipalKey(q => new { " + string.Join(", ", relation1.ColumnRelationships.Select(x => x.ParentColumn.PascalName).OrderBy(x => x).Select(c => "q." + c)) + " })");
sb.AppendLine(" .HasForeignKey(q => new { " + string.Join(", ", relation1.ColumnRelationships.Select(x => x.ChildColumn.PascalName).OrderBy(x => x).Select(c => "q." + c)) + " })");
sb.AppendLine(" .OnDelete(DeleteBehavior.Restrict);");
sb.AppendLine();
sb.AppendLine($" //Relation for [{relation2.ParentTable.PascalName}] -> [{relation1.ParentTable.PascalName}] (Multiplicity N:M)");
sb.AppendLine($" modelBuilder.Entity<{this.GetLocalNamespace()}.Entity.{relation2.ParentTable.PascalName}>()");
sb.AppendLine($" .HasMany(q => q.{relation2.PascalRoleName}{table.PascalName}List)");
sb.AppendLine($" .WithOne(q => q.{relation2.PascalRoleName}{relation2.ParentTable.PascalName})");
sb.AppendLine($" .HasConstraintName(\"{index2Name}\")");
sb.AppendLine(" .HasPrincipalKey(q => new { " + string.Join(", ", relation2.ColumnRelationships.Select(x => x.ParentColumn.PascalName).OrderBy(x => x).Select(c => "q." + c)) + " })");
sb.AppendLine(" .HasForeignKey(q => new { " + string.Join(", ", relation2.ColumnRelationships.Select(x => x.ChildColumn.PascalName).OrderBy(x => x).Select(c => "q." + c)) + " })");
sb.AppendLine(" .OnDelete(DeleteBehavior.Restrict);");
sb.AppendLine();
}
}
sb.AppendLine(" #endregion");
sb.AppendLine();
#endregion
sb.AppendLine(" foreach (var eType in modelBuilder.Model.GetEntityTypes())");
sb.AppendLine(" {");
sb.AppendLine(" var tableType = eType.ClrType;");
sb.AppendLine(" var isTenant = tableType.GetInterfaces().Any(x => x == typeof(ITenantEntity));");
sb.AppendLine();
sb.AppendLine(" #region Audit Fields");
sb.AppendLine(" foreach (var prop in tableType.Props(false).Where(x => x.GetCustomAttributes(true).Any(z => z.GetType() != typeof(System.ComponentModel.DataAnnotations.Schema.NotMappedAttribute))))");
sb.AppendLine(" {");
sb.AppendLine(" //Created Date");
sb.AppendLine(" var attr2 = prop.GetAttr<AuditCreatedDateAttribute>();");
sb.AppendLine(" if (attr2 != null)");
sb.AppendLine(" {");
sb.AppendLine(" _mapAuditDateFields.Add($\"{tableType.FullName}:{typeof(AuditCreatedDateAttribute).Name}\", attr2.IsUTC);");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" //Modified Date");
sb.AppendLine(" var attr4 = prop.GetAttr<AuditModifiedDateAttribute>();");
sb.AppendLine(" if (attr4 != null)");
sb.AppendLine(" {");
sb.AppendLine(" _mapAuditDateFields.Add($\"{tableType.FullName}:{typeof(AuditModifiedDateAttribute).Name}\", attr4.IsUTC);");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" //Timestamp (default .NET attribute)");
sb.AppendLine(" var attr6 = prop.GetAttr<System.ComponentModel.DataAnnotations.TimestampAttribute>();");
sb.AppendLine(" if (attr6 != null)");
sb.AppendLine(" {");
sb.AppendLine(" throw new Exception($\"Error on '{tableType.FullName}.{prop.Name}'. The 'Timestamp' attribute has been replaced with the 'ConcurrencyCheck' attribute.\");");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine(" #endregion");
sb.AppendLine();
sb.AppendLine(" #region Handle the Tenant mappings");
sb.AppendLine(" if (isTenant)");
sb.AppendLine(" {");
sb.AppendLine(" //Verify ");
sb.AppendLine(" var startup = this.ContextStartup as TenantContextStartup;");
sb.AppendLine(" if (startup == null)");
sb.AppendLine(" throw new Exceptions.ContextConfigurationException(\"A tenant context must be created with a TenantContextStartup object.\");");
sb.AppendLine();
sb.AppendLine(" //https://haacked.com/archive/2019/07/29/query-filter-by-interface/");
sb.AppendLine(" modelBuilder.SetEntityQueryFilter<ITenantEntity>(tableType, p => EF.Property<string>(p, \"" + _model.TenantColumnName + "\") == _tenantId);");
sb.AppendLine(" }");
sb.AppendLine(" #endregion");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" // Override this event in the partial class to add any custom model changes or validation");
sb.AppendLine(" this.OnModelCreated(modelBuilder);");
sb.AppendLine();
sb.AppendLine(" }");
sb.AppendLine();
#endregion
#region SaveChanges
sb.AppendLine(" private bool _inSave = false;");
sb.AppendLine(" public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))");
sb.AppendLine(" {");
sb.AppendLine(" if (!_inSave)");
sb.AppendLine(" {");
sb.AppendLine(" _inSave = true;");
sb.AppendLine(" try");
sb.AppendLine(" {");
sb.AppendLine(" this.SetupSave();");
sb.AppendLine(" return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);");
sb.AppendLine(" }");
sb.AppendLine(" finally");
sb.AppendLine(" {");
sb.AppendLine(" _inSave = false;");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine(" else");
sb.AppendLine(" return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))");
sb.AppendLine(" {");
sb.AppendLine(" _inSave = true;");
sb.AppendLine(" try");
sb.AppendLine(" {");
sb.AppendLine(" this.SetupSave();");
sb.AppendLine(" return base.SaveChangesAsync(cancellationToken);");
sb.AppendLine(" }");
sb.AppendLine(" finally");
sb.AppendLine(" {");
sb.AppendLine(" _inSave = false;");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" public override int SaveChanges(bool acceptAllChangesOnSuccess)");
sb.AppendLine(" {");
sb.AppendLine(" if (!_inSave)");
sb.AppendLine(" {");
sb.AppendLine(" _inSave = true;");
sb.AppendLine(" try");
sb.AppendLine(" {");
sb.AppendLine(" this.SetupSave();");
sb.AppendLine(" return base.SaveChanges(acceptAllChangesOnSuccess);");
sb.AppendLine(" }");
sb.AppendLine(" finally");
sb.AppendLine(" {");
sb.AppendLine(" _inSave = false;");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine(" else");
sb.AppendLine(" return base.SaveChanges(acceptAllChangesOnSuccess);");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" public override int SaveChanges()");
sb.AppendLine(" {");
sb.AppendLine(" _inSave = true;");
sb.AppendLine(" try");
sb.AppendLine(" {");
sb.AppendLine(" this.SetupSave();");
sb.AppendLine(" return base.SaveChanges();");
sb.AppendLine(" }");
sb.AppendLine(" finally");
sb.AppendLine(" {");
sb.AppendLine(" _inSave = false;");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine();
#endregion
#region Auditing
sb.AppendLine(" protected virtual void SetupSave()");
sb.AppendLine(" {");
sb.AppendLine(" var markedTime = System.DateTime.Now;");
sb.AppendLine(" var markedTimeUtc = System.DateTime.UtcNow;");
//sb.AppendLine(" var cancel = false;");
//sb.AppendLine(" OnBeforeSaveChanges(ref cancel);");
//sb.AppendLine(" if (cancel) return 0;");
sb.AppendLine(" var tenantId = (this.ContextStartup as TenantContextStartup)?.TenantId;");
sb.AppendLine();
#region Added Items
sb.AppendLine(" //Get the added list");
sb.AppendLine(" var addedList = this.ChangeTracker.Entries().Where(x => x.State == EntityState.Added);");
sb.AppendLine(" //Process added list");
sb.AppendLine(" foreach (var item in addedList)");
sb.AppendLine(" {");
sb.AppendLine(" var isCreatedUtc = false;");
sb.AppendLine(" if (_mapAuditDateFields.ContainsKey($\"{item.Entity}:{typeof(AuditCreatedDateAttribute).Name}\"))");
sb.AppendLine(" isCreatedUtc = _mapAuditDateFields[$\"{item.Entity}:{typeof(AuditCreatedDateAttribute).Name}\"];");
sb.AppendLine();
sb.AppendLine(" var isModifiedUtc = false;");
sb.AppendLine(" if (_mapAuditDateFields.ContainsKey($\"{item.Entity}:{typeof(AuditModifiedDateAttribute).Name}\"))");
sb.AppendLine(" isModifiedUtc = _mapAuditDateFields[$\"{item.Entity}:{typeof(AuditModifiedDateAttribute).Name}\"];");
sb.AppendLine(" ReflectionHelpers.SetPropertyByAttribute(item.Entity, typeof(AuditCreatedByAttribute), this.ContextStartup.Modifier);");
sb.AppendLine(" ReflectionHelpers.SetPropertyByAttribute(item.Entity, typeof(AuditCreatedDateAttribute), isCreatedUtc ? markedTimeUtc : markedTime);");
sb.AppendLine(" ReflectionHelpers.SetPropertyByAttribute(item.Entity, typeof(AuditModifiedByAttribute), this.ContextStartup.Modifier);");
sb.AppendLine(" ReflectionHelpers.SetPropertyByAttribute(item.Entity, typeof(AuditModifiedDateAttribute), isModifiedUtc ? markedTimeUtc : markedTime);");
sb.AppendLine(" ReflectionHelpers.SetPropertyConcurrency(item, typeof(System.ComponentModel.DataAnnotations.ConcurrencyCheckAttribute));");
sb.AppendLine();
sb.AppendLine(" //Only set the TenantID on create. It never changes.");
sb.AppendLine(" if (item.Entity is ITenantEntity)");
sb.AppendLine(" {");
sb.AppendLine($" Util.SetPropertyByName(item.Entity, \"{_model.TenantColumnName}\", tenantId);");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" }");
sb.AppendLine();
#endregion
#region Modified Items
sb.AppendLine(" //Process modified list");
sb.AppendLine(" var modifiedList = this.ChangeTracker.Entries().Where(x => x.State == EntityState.Modified);");
sb.AppendLine(" foreach (var item in modifiedList)");
sb.AppendLine(" {");
sb.AppendLine(" var isModifiedUtc = false;");
sb.AppendLine(" if (_mapAuditDateFields.ContainsKey($\"{item.Entity}:{typeof(AuditModifiedDateAttribute).Name}\"))");
sb.AppendLine(" isModifiedUtc = _mapAuditDateFields[$\"{item.Entity}:{typeof(AuditModifiedDateAttribute).Name}\"];");
sb.AppendLine(" ReflectionHelpers.SetPropertyByAttribute(item.Entity, typeof(AuditModifiedByAttribute), this.ContextStartup.Modifier);");
sb.AppendLine(" ReflectionHelpers.SetPropertyByAttribute(item.Entity, typeof(AuditModifiedDateAttribute), isModifiedUtc ? markedTimeUtc : markedTime);");
sb.AppendLine(" ReflectionHelpers.SetPropertyConcurrency(item, typeof(System.ComponentModel.DataAnnotations.ConcurrencyCheckAttribute));");
sb.AppendLine(" }");
sb.AppendLine();
#endregion
//sb.AppendLine(" var retval = 0;");
//sb.AppendLine(" Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction customTrans = null;");
//sb.AppendLine(" try");
//sb.AppendLine(" {");
//sb.AppendLine(" if (base.Database.CurrentTransaction == null)");
//sb.AppendLine(" customTrans = base.Database.BeginTransaction();");
//sb.AppendLine(" retval += base.SaveChanges();");
//sb.AppendLine(" if (customTrans != null)");
//sb.AppendLine(" customTrans.Commit();");
//sb.AppendLine(" }");
//sb.AppendLine(" catch");
//sb.AppendLine(" {");
//sb.AppendLine(" throw;");
//sb.AppendLine(" }");
//sb.AppendLine(" finally");
//sb.AppendLine(" {");
//sb.AppendLine(" if (customTrans != null)");
//sb.AppendLine(" customTrans.Dispose();");
//sb.AppendLine(" }");
//sb.AppendLine(" this.OnAfterSaveAddedEntity(new EventArguments.EntityListEventArgs { List = addedList });");
//sb.AppendLine(" this.OnAfterSaveModifiedEntity(new EventArguments.EntityListEventArgs { List = modifiedList });");
//sb.AppendLine(" OnAfterSaveChanges();");
//sb.AppendLine(" return retval;");
sb.AppendLine(" }");
sb.AppendLine();
#endregion
#region Entity Sets
sb.AppendLine(" #region Entity Sets");
sb.AppendLine();
foreach (var item in _model.Database.Tables.Where(x => !x.IsEnumOnly()).OrderBy(x => x.PascalName))
{
var name = item.PascalName;
var scope = "public";
//if (item.AssociativeTable)
// scope = "protected";
var tenantInfo = item.IsTenant ? " (Tenant Table)" : string.Empty;
sb.AppendLine(" /// <summary>");
sb.AppendLine($" /// Entity set for {item.PascalName}{tenantInfo}");
sb.AppendLine(" /// </summary>");
sb.AppendLine($" {scope} virtual DbSet<{this.GetLocalNamespace()}.Entity.{item.PascalName}> {name} {GetSetSuffix}");
sb.AppendLine();
}
foreach (var item in _model.Database.CustomViews.OrderBy(x => x.PascalName))
{
sb.AppendLine(" /// <summary>");
sb.AppendLine($" /// Entity set for {item.PascalName}");
sb.AppendLine(" /// </summary>");
sb.AppendLine($" public virtual DbSet<{this.GetLocalNamespace()}.Entity.{item.PascalName}> {item.PascalName} {GetSetSuffix}");
sb.AppendLine();
}
sb.AppendLine(" #endregion");
sb.AppendLine();
#endregion
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// The global settings of this context");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" public virtual IContextStartup ContextStartup => _contextStartup;");
sb.AppendLine();
#region Configuration API/Database verification
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// Determines the version of the model that created this library.");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" public virtual string Version => _version;");
sb.AppendLine();
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// Determines the key of the model that created this library.");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" public virtual string ModelKey => _modelKey;");
sb.AppendLine();
#endregion
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// Back door add for immutable entities to be called for seed data");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" internal EntityEntry AddImmutable(object entity)");
sb.AppendLine(" {");
sb.AppendLine(" return base.Add(entity);");
sb.AppendLine(" }");
sb.AppendLine();
#region Add Functionality
//Add an strongly-typed extension for "AddItem" method
sb.AppendLine(" #region AddItem Methods");
sb.AppendLine();
sb.AppendLine(" public override EntityEntry Add( object entity)");
sb.AppendLine(" {");
sb.AppendLine(" //No model validation. You should use the AddItem method.");
sb.AppendLine(" return base.Add(entity);");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" public override EntityEntry<TEntity> Add<TEntity>( TEntity entity)");
sb.AppendLine(" {");
sb.AppendLine(" //No model validation. You should use the AddItem method.");
sb.AppendLine(" return base.Add(entity);");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" public override void AddRange(IEnumerable<object> entities)");
sb.AppendLine(" {");
sb.AppendLine(" if (entities == null) return;");
sb.AppendLine(" //This will enforce model validation.");
sb.AppendLine(" foreach (var item in entities)");
sb.AppendLine(" {");
sb.AppendLine(" var entity = item as IBusinessObject;");
sb.AppendLine(" if (entity == null)");
sb.AppendLine(" throw new Exception(\"Unknown entity type\");");
sb.AppendLine(" this.AddItem(entity);");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" public override void AddRange(params object[] entities)");
sb.AppendLine(" {");
sb.AppendLine(" this.AddRange(entities?.AsEnumerable());");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" public virtual void AddRange(IEnumerable<IBusinessObject> entities)");
sb.AppendLine(" {");
sb.AppendLine(" this.AddRange(entities?.AsEnumerable<object>());");
sb.AppendLine(" }");
sb.AppendLine();
#region Tables
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// Adds an entity of to the object context");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" /// <param name=\"entity\">The entity to add</param>");
sb.AppendLine($" public virtual T AddItem<T>(T entity) where T : class, IBusinessObject");
sb.AppendLine(" {");
sb.AppendLine(" if (entity == null) throw new NullReferenceException();");
sb.AppendLine(" ReflectionHelpers.SetPropertyByAttribute(entity, typeof(AuditCreatedByAttribute), this.ContextStartup.Modifier);");
sb.AppendLine(" ReflectionHelpers.SetPropertyByAttribute(entity, typeof(AuditModifiedByAttribute), this.ContextStartup.Modifier);");
sb.AppendLine(" if (false) { }");
foreach (var table in _model.Database.Tables.Where(x => !x.Immutable).OrderBy(x => x.PascalName))
{
sb.AppendLine($" else if (entity is {GetLocalNamespace()}.Entity.{table.PascalName})");
sb.AppendLine(" {");
sb.AppendLine($" this.Add(entity);");
sb.AppendLine(" }");
}
//If not an entity then throw exception
sb.AppendLine($" else");
sb.AppendLine(" {");
sb.AppendLine(" //If not an entity then throw exception");
sb.AppendLine(" throw new Exception(\"Unknown entity type\");");
sb.AppendLine(" }");
sb.AppendLine(" return entity;");
sb.AppendLine(" }");
sb.AppendLine();
#endregion
sb.AppendLine(" #endregion");
sb.AppendLine();
#endregion
#region Delete Functionality
//Add an strongly-typed extension for "RemoveItem" method
sb.AppendLine(" #region RemoveItem Methods");
sb.AppendLine();
sb.AppendLine(" public override EntityEntry Remove(object entity)");
sb.AppendLine(" {");
sb.AppendLine(" //No model validation. You should use the RemoveItem method.");
sb.AppendLine(" return base.Remove(entity);");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" public override EntityEntry<TEntity> Remove<TEntity>(TEntity entity)");
sb.AppendLine(" {");
sb.AppendLine(" //No model validation. You should use the RemoveItem method.");
sb.AppendLine(" return base.Remove(entity);");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" public override void RemoveRange(IEnumerable<object> entities)");
sb.AppendLine(" {");
sb.AppendLine(" if (entities == null) return;");
sb.AppendLine(" foreach (var item in entities)");
sb.AppendLine(" {");
sb.AppendLine(" var entity = item as IBusinessObject;");
sb.AppendLine(" if (entity == null)");
sb.AppendLine(" throw new Exception(\"Unknown entity type\");");
sb.AppendLine(" this.RemoveItem(entity);");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" public override void RemoveRange(params object[] entities)");
sb.AppendLine(" {");
sb.AppendLine(" this.RemoveRange(entities?.AsEnumerable());");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" public virtual void RemoveRange(IEnumerable<IBusinessObject> entities)");
sb.AppendLine(" {");
sb.AppendLine(" this.RemoveRange(entities?.AsEnumerable<object>());");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// Deletes an entity from the context");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" /// <param name=\"entity\">The entity to delete</param>");
sb.AppendLine(" public virtual void RemoveItem<T>(T entity) where T : class, IBusinessObject");
sb.AppendLine(" {");
sb.AppendLine(" if (entity == null) return;");
sb.AppendLine(" else this.Remove(entity);");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" #endregion");
sb.AppendLine();
#endregion
#region Connection String
sb.AppendLine(" #region Connection String");
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// Returns the connection string used for this context object");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" public string ConnectionString");
sb.AppendLine(" {");
sb.AppendLine(" get");
sb.AppendLine(" {");
sb.AppendLine(" try");
sb.AppendLine(" {");
sb.AppendLine(" if (this.Database.GetDbConnection() != null && !string.IsNullOrEmpty(this.Database.GetDbConnection().ConnectionString))");
sb.AppendLine(" return this.Database.GetDbConnection().ConnectionString;");
sb.AppendLine(" else return null;");
sb.AppendLine(" }");
sb.AppendLine(" catch (Exception) { return null; }");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine(" #endregion");
sb.AppendLine();
#endregion
#region IContext Interface
sb.AppendLine(" #region IContext Interface");
sb.AppendLine(" Enum IContext.GetEntityFromField(Enum field) => GetEntityFromField(field);");
sb.AppendLine(" #endregion");
sb.AppendLine();
#endregion
#region GetEntityFromField
sb.AppendLine(" #region GetEntityFromField");
sb.AppendLine();
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// Determines the entity from one of its fields");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" public static EntityMappingConstants GetEntityFromField(Enum field)");
sb.AppendLine(" {");
foreach (var table in _model.Database.Tables.Where(x => !x.AssociativeTable && !x.IsEnumOnly()).OrderBy(x => x.PascalName))
{
sb.AppendLine($" if (field is {this.GetLocalNamespace()}.Entity.{table.PascalName}.FieldNameConstants) return {this.GetLocalNamespace()}.EntityMappingConstants.{table.PascalName};");
}
sb.AppendLine(" throw new Exception(\"Unknown field type!\");");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" #endregion");
sb.AppendLine();
#endregion
#region Extra
sb.AppendLine(" #region Interface Extras");
sb.AppendLine();
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// Reloads the context object from database");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" public void ReloadItem(IBusinessObject entity)");
sb.AppendLine(" {");
sb.AppendLine(" this.Entry(entity).Reload();");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" #endregion");
sb.AppendLine();
#endregion
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// Determines the timeout of the database connection");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" public int? CommandTimeout");
sb.AppendLine(" {");
sb.AppendLine(" get { return this.Database.GetCommandTimeout(); }");
sb.AppendLine(" set { ");
sb.AppendLine(" try { this.Database.SetCommandTimeout(value); }");
sb.AppendLine(" catch (System.InvalidOperationException ex) { if (!ex.Message.Contains(\"relational database\")) throw; }");
sb.AppendLine(" catch { throw; }");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" }");
sb.AppendLine(" #endregion");
sb.AppendLine();
}
private void AppendExtensions(StringBuilder sb)
{
sb.AppendLine(" public static class ContextExtensions");
sb.AppendLine(" {");
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// Load all enum tables and insert data");
sb.AppendLine(" /// </summary>");
sb.AppendLine($" public static void EnsureSeedData(this {_model.ProjectName}Entities context)");
sb.AppendLine(" {");
sb.AppendLine(" //Get the assembly of the containing types");
sb.AppendLine(" var assembly = context.Model.GetEntityTypes().FirstOrDefault()?.ClrType?.Assembly;");
sb.AppendLine(" if (assembly == null) return;");
sb.AppendLine();
sb.AppendLine(" var allTypes = context.GetType()");
sb.AppendLine(" .GetProperties()");
sb.AppendLine(" .Where(pi => pi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>))");
sb.AppendLine(" .SelectMany(x => x.PropertyType.GenericTypeArguments)");
sb.AppendLine(" .ToList();");
sb.AppendLine();
sb.AppendLine(" foreach (var mytype in ReflectionHelpers.GetTypesWithAttribute(allTypes, typeof(StaticDataAttribute)))");
sb.AppendLine(" {");
sb.AppendLine(" var enumMap = mytype.GetAttr<StaticDataAttribute>();");
sb.AppendLine(" var key = mytype");
sb.AppendLine(" .GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)");
sb.AppendLine(" .FirstOrDefault(x => Enumerable.Any<object>(x.GetCustomAttributes(true), z => z.GetType() != typeof(KeyAttribute)));");
sb.AppendLine();
sb.AppendLine(" var entities = ReflectionHelpers.BuildEntityObjectsFromEnum(mytype, enumMap.ParentType);");
sb.AppendLine(" try");
sb.AppendLine(" {");
sb.AppendLine(" foreach (var entity in entities)");
sb.AppendLine(" {");
sb.AppendLine(" // attempt to load the existing item from the database");
sb.AppendLine(" var entry = context.Entry(entity);");
sb.AppendLine(" entry.Reload();");
sb.AppendLine();
sb.AppendLine(" if (entry.State == EntityState.Detached)");
sb.AppendLine(" {");
sb.AppendLine(" // if it doesn't yet exist, add it as normal");
sb.AppendLine(" context.AddImmutable(entity);");
sb.AppendLine(" }");
sb.AppendLine(" else");
sb.AppendLine(" {");
sb.AppendLine(" // otherwise update its values as the enum name may have changed etc");
sb.AppendLine(" entry.CurrentValues.SetValues(entity);");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine(" context.SaveChanges();");
sb.AppendLine(" }");
sb.AppendLine(" catch (Exception ex)");
sb.AppendLine(" {");
sb.AppendLine(" //TODO: Handle duplicates, second runs");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" }");
}
private void AppendTypeTableEnums(StringBuilder sb)
{
foreach (var table in _model.Database.Tables.Where(x => x.IsTypedTable()).OrderBy(x => x.PascalName))
{
if (table.PrimaryKeyColumns.Count == 1)
{
var pk = table.PrimaryKeyColumns.First();
sb.AppendLine($" #region StaticDataConstants Enumeration for '{table.PascalName}' entity");
sb.AppendLine(" /// <summary>");
sb.AppendLine($" /// Enumeration to define static data items and their ids '{table.PascalName}' table.");
sb.AppendLine(" /// </summary>");
sb.Append($" public enum {table.PascalName}Constants");
//Non-integer types must explicitly add the type
if (pk.DataType != System.Data.SqlDbType.Int)
sb.Append(" : " + pk.GetCodeType(false));
sb.AppendLine();
sb.AppendLine(" {");
foreach (var rowEntry in table.StaticData)
{
var idValue = rowEntry.GetCodeIdValue(table);
var identifier = rowEntry.GetCodeIdentifier(table);
var description = rowEntry.GetCodeDescription(table);
var raw = rowEntry.GetDataRaw(table);
var sort = rowEntry.GetDataSort(table);
if (!string.IsNullOrEmpty(description))
{
sb.AppendLine(" /// <summary>");
StringHelper.LineBreakCode(sb, description, " /// ");
sb.AppendLine(" /// </summary>");
sb.AppendLine($" [Description(\"{description}\")]");
}
else
{
sb.AppendLine(" /// <summary>");
sb.AppendLine($" /// Enumeration for the '{identifier}' item");
sb.AppendLine(" /// </summary>");
}
var key = ValidationHelper.MakeDatabaseIdentifier(identifier.Replace(" ", string.Empty));
if ((key.Length > 0) && ("0123456789".Contains(key[0])))
key = "_" + key;
//If there is a sort value then format as attribute
if (int.TryParse(sort, out var svalue))
{
sort = ", Order = " + svalue;
}
else
{
sort = string.Empty;
}
sb.AppendLine($" [System.ComponentModel.DataAnnotations.Display(Name = \"{raw}\"{sort})]");
sb.AppendLine($" {key} = {idValue},");
}
sb.AppendLine(" }");
sb.AppendLine(" #endregion");
sb.AppendLine();
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
namespace Eto
{
/// <summary>
/// Arguments for when a widget is created
/// </summary>
/// <copyright>(c) 2012-2015 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
public class WidgetCreatedEventArgs : EventArgs
{
/// <summary>
/// Gets the instance of the widget that was created
/// </summary>
public Widget Instance { get; private set; }
/// <summary>
/// Initializes a new instance of the WidgetCreatedArgs class
/// </summary>
/// <param name="instance">Instance of the widget that was created</param>
public WidgetCreatedEventArgs(Widget instance)
{
this.Instance = instance;
}
}
/// <summary>
/// Arguments for when a widget is cloned
/// </summary>
/// <copyright>(c) 2012-2015 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
public class WidgetClonedEventArgs : EventArgs
{
/// <summary>
/// Gets the instance of the widget that was created
/// </summary>
public Widget Instance { get; private set; }
/// <summary>
/// Gets the instance of the widget that was created
/// </summary>
public Widget Source { get; private set; }
/// <summary>
/// Initializes a new instance of the WidgetCreatedArgs class
/// </summary>
/// <param name="instance">Instance of the widget that was created</param>
/// <param name="source">Instance of the widget that was cloned</param>
public WidgetClonedEventArgs(Widget instance, Widget source)
{
this.Instance = instance;
this.Source = source;
}
}
/// <summary>
/// Arguments for when a widget is created
/// </summary>
/// <copyright>(c) 2012-2015 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
public class HandlerCreatedEventArgs : EventArgs
{
/// <summary>
/// Gets the instance of the widget that was created
/// </summary>
public object Instance { get; private set; }
/// <summary>
/// Initializes a new instance of the WidgetCreatedArgs class
/// </summary>
/// <param name="instance">Instance of the widget that was created</param>
public HandlerCreatedEventArgs(object instance)
{
this.Instance = instance;
}
}
class HandlerInfo
{
public bool Initialize { get; private set; }
public Func<object> Instantiator { get; private set; }
public HandlerInfo(bool initialize, Func<object> instantiator)
{
Initialize = initialize;
Instantiator = instantiator;
}
}
/// <summary>
/// Base platform class
/// </summary>
/// <remarks>
/// This class takes care of creating the platform-specific implementations of each control.
/// All controls the platform can handle should be added using <see cref="Platform.Add{T}"/>.
/// </remarks>
/// <copyright>(c) 2012-2015 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
public abstract class Platform
{
readonly Dictionary<Type, Func<object>> instantiatorMap = new Dictionary<Type, Func<object>>();
readonly Dictionary<Type, HandlerInfo> handlerMap = new Dictionary<Type, HandlerInfo>();
readonly Dictionary<Type, object> sharedInstances = new Dictionary<Type, object>();
readonly Dictionary<object, object> properties = new Dictionary<object, object>();
static Platform globalInstance;
static readonly ThreadLocal<Platform> instance = new ThreadLocal<Platform>(() => globalInstance);
internal T GetSharedProperty<T>(object key, Func<T> instantiator)
{
object value;
lock (properties)
{
if (!properties.TryGetValue(key, out value))
{
value = instantiator();
properties[key] = value;
}
}
return (T)value;
}
internal void SetSharedProperty(object key, object value)
{
lock (properties)
{
properties[key] = value;
}
}
#region Events
/// <summary>
/// Event to handle when widgets are created by this platform
/// </summary>
public event EventHandler<HandlerCreatedEventArgs> HandlerCreated;
/// <summary>
/// Handles the <see cref="WidgetCreated"/> event
/// </summary>
/// <param name="e">Arguments for the event</param>
protected virtual void OnHandlerCreated(HandlerCreatedEventArgs e)
{
if (HandlerCreated != null)
HandlerCreated(this, e);
}
/// <summary>
/// Event to handle when widgets are created by this platform
/// </summary>
public event EventHandler<WidgetCreatedEventArgs> WidgetCreated;
/// <summary>
/// Handles the <see cref="WidgetCreated"/> event
/// </summary>
/// <param name="e">Arguments for the event</param>
protected virtual void OnWidgetCreated(WidgetCreatedEventArgs e)
{
Eto.Style.OnStyleWidgetDefaults(e.Instance);
if (WidgetCreated != null)
WidgetCreated(this, e);
}
internal void TriggerWidgetCreated(WidgetCreatedEventArgs args)
{
OnWidgetCreated(args);
}
/// <summary>
/// Event to handle when widgets are cloned by this platform
/// </summary>
public event EventHandler<WidgetClonedEventArgs> WidgetCloned;
/// <summary>
/// Handles the <see cref="WidgetCloned"/> event
/// </summary>
/// <param name="e">Arguments for the event</param>
protected virtual void OnWWidgetCloned(WidgetClonedEventArgs e)
{
if (WidgetCloned != null)
WidgetCloned(this, e);
}
internal void TriggerWidgetCloned(WidgetClonedEventArgs args)
{
OnWWidgetCloned(args);
}
#endregion
/// <summary>
/// Gets the ID of this platform
/// </summary>
/// <remarks>
/// The platform ID can be used to determine which platform is currently in use. The platform
/// does not necessarily correspond to the OS that it is running on, as for example the GTK platform
/// can run on OS X and Windows.
/// </remarks>
public abstract string ID { get; }
/// <summary>
/// Gets a value indicating whether this platform is a mac based platform (MonoMac/XamMac)
/// </summary>
/// <value><c>true</c> if this platform is mac; otherwise, <c>false</c>.</value>
public virtual bool IsMac { get { return false; } }
/// <summary>
/// Gets a value indicating whether this platform is based on Windows Forms
/// </summary>
/// <value><c>true</c> if this platform is window forms; otherwise, <c>false</c>.</value>
public virtual bool IsWinForms { get { return false; } }
/// <summary>
/// Gets a value indicating whether this platform is based on WPF
/// </summary>
/// <value><c>true</c> if this platform is wpf; otherwise, <c>false</c>.</value>
public virtual bool IsWpf { get { return false; } }
/// <summary>
/// Gets a value indicating whether this platform is based on GTK# (2 or 3)
/// </summary>
/// <value><c>true</c> if this platform is gtk; otherwise, <c>false</c>.</value>
public virtual bool IsGtk { get { return false; } }
/// <summary>
/// Gets a value indicating whether this platform is based on Xamarin.iOS
/// </summary>
/// <value><c>true</c> if this platform is ios; otherwise, <c>false</c>.</value>
public virtual bool IsIos { get { return false; } }
/// <summary>
/// Gets a value indicating whether this platform is based on Xamarin.Android.
/// </summary>
/// <value><c>true</c> if this platform is android; otherwise, <c>false</c>.</value>
public virtual bool IsAndroid { get { return false; } }
/// <summary>
/// Gets a value indicating whether this is a desktop platform. This includes Mac, Gtk, WinForms, Wpf, Direct2D.
/// </summary>
/// <remarks>
/// A desktop platform is usually used via mouse & keyboard, and can have complex user interface elements.
/// </remarks>
/// <value><c>true</c> if this is a desktop platform; otherwise, <c>false</c>.</value>
public virtual bool IsDesktop { get { return false; } }
/// <summary>
/// Gets a value indicating whether this is a mobile platform. This includes iOS, Android, and WinRT.
/// </summary>
/// <remarks>
/// A mobile platform is usually touch friendly, and have a simpler interface.
/// </remarks>
/// <value><c>true</c> if this instance is mobile; otherwise, <c>false</c>.</value>
public virtual bool IsMobile { get { return false; } }
/// <summary>
/// Gets a value indicating that this platform is valid on the running device
/// </summary>
/// <remarks>
/// This is used in platform detection to ensure that the correct platform is loaded.
/// For example, the Mac platforms are only valid when run in an .app bundle.
/// </remarks>
/// <value><c>true</c> if this platform is valid and can be run; otherwise, <c>false</c>.</value>
public virtual bool IsValid { get { return true; } }
/// <summary>
/// Initializes a new instance of the Platform class
/// </summary>
protected Platform()
{
}
/// <summary>
/// Gets a value indicating that the specified type is supported by this platform
/// </summary>
/// <typeparam name="T">Type of the handler or class with HandlerAttribute to test for.</typeparam>
/// <returns>true if the specified type is supported, false otherwise</returns>
public bool Supports<T>()
where T: class
{
return Supports(typeof(T));
}
/// <summary>
/// Gets a value indicating that the specified <paramref name="type"/> is supported by this platform
/// </summary>
/// <param name="type">Type of the handler or class with HandlerAttribute to test for.</param>
/// <returns>true if the specified type is supported, false otherwise</returns>
public virtual bool Supports(Type type)
{
return Find(type) != null;
}
/// <summary>
/// Gets the platform for the current thread
/// </summary>
/// <remarks>
/// Typically you'd have only one platform active at a time, and this holds an instance to that value.
/// The current platform is set automatically by the <see cref="Forms.Application"/> class
/// when it is initially created.
///
/// This will return a different value for each thread, so if you have multiple platforms running
/// (e.g. GTK + Mac for OS X), then this will allow for that.
///
/// This will be used when creating controls. To create controls on a different platform outside of its own thread,
/// use the <see cref="Context"/> property.
/// </remarks>
public static Platform Instance
{
get
{
return instance.Value;
}
}
/// <summary>
/// Returns the current generator, or detects the generator to use if no current generator is set.
/// </summary>
/// <remarks>
/// This detects the platform to use based on the generator assemblies available and the current OS.
///
/// For windows, it will prefer WPF to Windows Forms.
/// Mac OS X will prefer the Mac platform.
/// Other unix-based platforms will prefer GTK.
/// </remarks>
public static Platform Detect
{
get
{
if (globalInstance != null)
return globalInstance;
Platform detected = null;
if (EtoEnvironment.Platform.IsMac)
{
if (EtoEnvironment.Is64BitProcess)
detected = Platform.Get(Platforms.Mac64, true);
if (detected == null)
detected = Platform.Get(Platforms.XamMac, true);
if (detected == null)
detected = Platform.Get(Platforms.Mac, true);
}
else if (EtoEnvironment.Platform.IsWindows)
{
detected = Platform.Get(Platforms.Wpf, true);
if (detected == null)
detected = Platform.Get(Platforms.WinForms, true);
}
if (detected == null && EtoEnvironment.Platform.IsUnix)
{
detected = Platform.Get(Platforms.Gtk3, true);
if (detected == null)
detected = Platform.Get(Platforms.Gtk2, true);
}
if (detected == null)
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Could not detect platform. Are you missing a platform assembly?"));
Initialize(detected);
return globalInstance;
}
}
/// <summary>
/// Initializes the specified <paramref name="platform"/> as the current generator, for the current thread
/// </summary>
/// <remarks>
/// This is called automatically by the <see cref="Forms.Application"/> when it is constructed
/// </remarks>
/// <param name="platform">Generator to set as the current generator</param>
public static void Initialize(Platform platform)
{
if (globalInstance == null)
globalInstance = platform;
instance.Value = platform;
}
/// <summary>
/// Initialize the generator with the specified <paramref name="platformType"/> as the current generator
/// </summary>
/// <param name="platformType">Type of the generator to set as the current generator</param>
public static void Initialize(string platformType)
{
Initialize(Get(platformType));
}
/// <summary>
/// Gets the generator of the specified type
/// </summary>
/// <param name="generatorType">Type of the generator to get</param>
/// <returns>An instance of a Generator of the specified type, or null if it cannot be loaded</returns>
public static Platform Get(string generatorType)
{
return Get(generatorType, true);
}
internal static Platform Get(string platformType, bool allowNull)
{
Type type = Type.GetType(platformType);
if (type == null)
{
if (allowNull)
return null;
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Platform not found. Are you missing the platform assembly?"));
}
try
{
var platform = (Platform)Activator.CreateInstance(type);
if (!platform.IsValid)
{
var message = string.Format("Platform type {0} was loaded but is not valid in the current context. E.g. Mac platforms require to be in an .app bundle to run", platformType);
if (allowNull)
Debug.WriteLine(message);
else
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, message));
return null;
}
return platform;
}
catch (Exception ex)
{
Debug.WriteLine(string.Format("Error creating instance of platform type '{0}'\n{1}", platformType, ex));
if (allowNull)
return null;
throw;
}
}
/// <summary>
/// Add the <paramref name="instantiator"/> for the specified handler type of <typeparamref name="T"/>
/// </summary>
/// <param name="instantiator">Instantiator to create an instance of the handler</param>
/// <typeparam name="T">The handler type to add the instantiator for (usually an interface derived from <see cref="Widget.IHandler"/>)</typeparam>
public void Add<T>(Func<T> instantiator)
where T: class
{
Add(typeof(T), instantiator);
}
/// <summary>
/// Add the specified type and instantiator.
/// </summary>
/// <param name="type">Type of the handler (usually an interface derived from <see cref="Widget.IHandler"/>)</param>
/// <param name="instantiator">Instantiator to create an instance of the handler</param>
public void Add(Type type, Func<object> instantiator)
{
var handler = type.GetCustomAttribute<HandlerAttribute>(true);
if (handler != null)
instantiatorMap[handler.Type] = instantiator; // for backward compatibility, for now
instantiatorMap[type] = instantiator;
}
/// <summary>
/// Find the delegate to create instances of the specified <paramref name="type"/>
/// </summary>
/// <param name="type">Type of the handler interface to get the instantiator for (usually derived from <see cref="Widget.IHandler"/> or another type)</param>
public Func<object> Find(Type type)
{
Func<object> activator;
if (instantiatorMap.TryGetValue(type, out activator))
return activator;
var handler = type.GetCustomAttribute<HandlerAttribute>(true);
if (handler != null && instantiatorMap.TryGetValue(handler.Type, out activator))
{
instantiatorMap.Add(type, activator);
return activator;
}
return null;
}
/// <summary>
/// Finds the delegate to create instances of the specified type
/// </summary>
/// <typeparam name="T">Type of the handler interface (usually derived from <see cref="Widget.IHandler"/> or another type)</typeparam>
/// <returns>The delegate to use to create instances of the specified type</returns>
public Func<T> Find<T>()
where T: class
{
return (Func<T>)Find(typeof(T));
}
internal HandlerInfo FindHandler(Type type)
{
HandlerInfo info;
if (handlerMap.TryGetValue(type, out info))
return info;
var handler = type.GetCustomAttribute<HandlerAttribute>(true);
Func<object> activator;
if (handler != null && instantiatorMap.TryGetValue(handler.Type, out activator))
{
var autoInit = handler.Type.GetCustomAttribute<AutoInitializeAttribute>(true);
info = new HandlerInfo(autoInit == null || autoInit.Initialize, activator);
handlerMap.Add(type, info);
return info;
}
return null;
}
/// <summary>
/// Creates a new instance of the handler of the specified type of <typeparamref name="T"/>
/// </summary>
/// <remarks>
/// This extension should be used when creating instances of a fixed type.
/// </remarks>
/// <typeparam name="T">Type of handler to create</typeparam>
/// <returns>A new instance of a handler</returns>
public T Create<T>()
{
return (T)Create(typeof(T));
}
/// <summary>
/// Creates a new instance of the handler of the specified type
/// </summary>
/// <param name="type">Type of handler to create</param>
/// <returns>A new instance of a handler</returns>
public object Create(Type type)
{
try
{
var instantiator = Find(type);
if (instantiator == null)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Type {0} could not be found in this generator", type.FullName));
var handler = instantiator();
OnHandlerCreated(new HandlerCreatedEventArgs(handler));
return handler;
}
catch (Exception e)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Could not create instance of type {0}", type), e);
}
}
/// <summary>
/// Creates a shared singleton instance of the specified type of <paramref name="type"/>
/// </summary>
/// <param name="type">The type of handler to get a shared instance for</param>
/// <returns>The shared instance of a handler of the given type, or a new instance if not already created</returns>
public object CreateShared(Type type)
{
object instance;
lock (sharedInstances)
{
if (!sharedInstances.TryGetValue(type, out instance))
{
instance = Create(type);
sharedInstances[type] = instance;
}
}
return instance;
}
/// <summary>
/// Creates a shared singleton instance of the specified type of <typeparamref name="T"/>
/// </summary>
/// <remarks>
/// This extension should be used when creating shared instances of a fixed type.
/// </remarks>
/// <typeparam name="T">The type of handler to get a shared instance for</typeparam>
/// <returns>The shared instance of a handler of the given type, or a new instance if not already created</returns>
public T CreateShared<T>()
{
return (T)CreateShared(typeof(T));
}
/// <summary>
/// Gets a shared cache dictionary
/// </summary>
/// <remarks>
/// This is used to cache things like brushes and pens, but can also be used to cache other things for your
/// application's use.
/// </remarks>
/// <param name="cacheKey">Unique cache key to load the cache instance</param>
/// <typeparam name="TKey">The type of the lookup key</typeparam>
/// <typeparam name="TValue">The type of the lookup value</typeparam>
public Dictionary<TKey, TValue> Cache<TKey, TValue>(object cacheKey)
{
return GetSharedProperty<Dictionary<TKey, TValue>>(cacheKey, () => new Dictionary<TKey, TValue>());
}
/// <summary>
/// Used at the start of your custom threads
/// </summary>
/// <returns></returns>
public virtual IDisposable ThreadStart()
{
return null;
}
/// <summary>
/// Gets an object to wrap in the platform's context, when using multiple platforms.
/// </summary>
/// <remarks>
/// This sets this platform as current, and reverts back to the previous platform when disposed.
///
/// This value may be null.
/// </remarks>
/// <example>
/// <code>
/// using (platform.Context)
/// {
/// // do some stuff with the specified platform
/// }
/// </code>
/// </example>
public IDisposable Context
{
get
{
return instance.Value != this ? new PlatformContext(this) : null;
}
}
/// <summary>
/// Invoke the specified action within the context of this platform
/// </summary>
/// <remarks>
/// This is useful when you are using multiple platforms at the same time, and gives you an easy
/// way to execute code within the context of this platform.
/// </remarks>
/// <param name="action">Action to execute.</param>
public void Invoke(Action action)
{
using (Context)
{
action();
}
}
/// <summary>
/// Invoke the specified function within the context of this platform, returning its value.
/// </summary>
/// <remarks>
/// This is useful when you are using multiple platforms at the same time, and gives you an easy
/// way to execute code within the context of this platform, and return its value.
/// </remarks>
/// <example>
/// <code>
/// var mycontrol = MyPlatform.Invoke(() => new MyControl());
/// </code>
/// </example>
/// <param name="action">Action to execute.</param>
/// <typeparam name="T">The type of value to return.</typeparam>
public T Invoke<T>(Func<T> action)
{
using (Context)
{
return action();
}
}
}
}
| |
// jskeyword.cs
//
// Copyright 2010 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Baker.Text
{
internal sealed class JsKeyword
{
private JsKeyword m_next;
private JsToken m_token;
private string m_name;
private int m_length;
private JsKeyword(JsToken token, string name)
: this(token, name, null)
{
}
private JsKeyword(JsToken token, string name, JsKeyword next)
{
m_name = name;
m_token = token;
m_length = m_name.Length;
m_next = next;
}
/*internal bool Exists(string target)
{
JSKeyword keyword = this;
while (keyword != null)
{
if (keyword.m_name == target)
{
return true;
}
keyword = keyword.m_next;
}
return false;
}*/
internal static string CanBeIdentifier(JsToken keyword)
{
switch (keyword)
{
// always allowed
case JsToken.Get: return "get";
case JsToken.Set: return "set";
// not in strict mode
case JsToken.Implements: return "implements";
case JsToken.Interface: return "interface";
case JsToken.Let: return "let";
case JsToken.Package: return "package";
case JsToken.Private: return "private";
case JsToken.Protected: return "protected";
case JsToken.Public: return "public";
case JsToken.Static: return "static";
case JsToken.Yield: return "yield";
// apparently never allowed for Chrome, so we want to treat it
// differently, too
case JsToken.Native: return "native";
// no other tokens can be identifiers
default: return null;
}
}
internal JsToken GetKeyword(JsContext context, int wordLength)
{
return GetKeyword(context.Document.Source, context.StartPosition, wordLength);
}
internal JsToken GetKeyword(string source, int startPosition, int wordLength)
{
JsKeyword keyword = this;
nextToken:
while (null != keyword)
{
if (wordLength == keyword.m_length)
{
// equal number of characters
// we know the first char has to match, so start with the second
for (int i = 1, j = startPosition + 1; i < wordLength; i++, j++)
{
char ch1 = keyword.m_name[i];
char ch2 = source[j];
if (ch1 == ch2)
{
// match -- continue
continue;
}
else if (ch2 < ch1)
{
// because the list is in order, if the character for the test
// is less than the character for the keyword we are testing against,
// then we know this isn't going to be in any other node
return JsToken.Identifier;
}
else
{
// must be greater than the current token -- try the next one
keyword = keyword.m_next;
goto nextToken;
}
}
// if we got this far, it was a complete match
return keyword.m_token;
}
else if (wordLength < keyword.m_length)
{
// in word-length order first of all, so if the length of the test string is
// less than the length of the keyword node, this is an identifier
return JsToken.Identifier;
}
keyword = keyword.m_next;
}
return JsToken.Identifier;
}
// each list must in order or length first, shortest to longest.
// for equal length words, in alphabetical order
internal static JsKeyword[] InitKeywords()
{
JsKeyword[] keywords = new JsKeyword[26];
// a
// b
keywords['b' - 'a'] = new JsKeyword(JsToken.Break, "break");
// c
keywords['c' - 'a'] = new JsKeyword(JsToken.Case, "case",
new JsKeyword(JsToken.Catch, "catch",
new JsKeyword(JsToken.Class, "class",
new JsKeyword(JsToken.Const, "const",
new JsKeyword(JsToken.Continue, "continue")))));
// d
keywords['d' - 'a'] = new JsKeyword(JsToken.Do, "do",
new JsKeyword(JsToken.Delete, "delete",
new JsKeyword(JsToken.Default, "default",
new JsKeyword(JsToken.Debugger, "debugger"))));
// e
keywords['e' - 'a'] = new JsKeyword(JsToken.Else, "else",
new JsKeyword(JsToken.Enum, "enum",
new JsKeyword(JsToken.Export, "export",
new JsKeyword(JsToken.Extends, "extends"))));
// f
keywords['f' - 'a'] = new JsKeyword(JsToken.For, "for",
new JsKeyword(JsToken.False, "false",
new JsKeyword(JsToken.Finally, "finally",
new JsKeyword(JsToken.Function, "function"))));
// g
keywords['g' - 'a'] = new JsKeyword(JsToken.Get, "get");
// i
keywords['i' - 'a'] = new JsKeyword(JsToken.If, "if",
new JsKeyword(JsToken.In, "in",
new JsKeyword(JsToken.Import, "import",
new JsKeyword(JsToken.Interface, "interface",
new JsKeyword(JsToken.Implements, "implements",
new JsKeyword(JsToken.InstanceOf, "instanceof"))))));
// l
keywords['l' - 'a'] = new JsKeyword(JsToken.Let, "let");
// n
keywords['n' - 'a'] = new JsKeyword(JsToken.New, "new",
new JsKeyword(JsToken.Null, "null",
new JsKeyword(JsToken.Native, "native")));
// p
keywords['p' - 'a'] = new JsKeyword(JsToken.Public, "public",
new JsKeyword(JsToken.Package, "package",
new JsKeyword(JsToken.Private, "private",
new JsKeyword(JsToken.Protected, "protected"))));
// r
keywords['r' - 'a'] = new JsKeyword(JsToken.Return, "return");
// s
keywords['s' - 'a'] = new JsKeyword(JsToken.Set, "set",
new JsKeyword(JsToken.Super, "super",
new JsKeyword(JsToken.Static, "static",
new JsKeyword(JsToken.Switch, "switch"))));
// t
keywords['t' - 'a'] = new JsKeyword(JsToken.Try, "try",
new JsKeyword(JsToken.This, "this",
new JsKeyword(JsToken.True, "true",
new JsKeyword(JsToken.Throw, "throw",
new JsKeyword(JsToken.TypeOf, "typeof")))));
// u
// v
keywords['v' - 'a'] = new JsKeyword(JsToken.Var, "var",
new JsKeyword(JsToken.Void, "void"));
// w
keywords['w' - 'a'] = new JsKeyword(JsToken.With, "with",
new JsKeyword(JsToken.While, "while"));
// y
keywords['y' - 'a'] = new JsKeyword(JsToken.Yield, "yield");
return keywords;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Nini.Config;
namespace LaunchSLClient
{
public partial class Form1 : Form
{
string gridUrl = "";
string sandboxUrl = "";
string runUrl = "";
string runLine = "";
string exeFlags = "";
string exePath = "";
private MachineConfig m_machineConfig;
private List<Grid> m_grids = new List<Grid>();
public Form1()
{
InitializeComponent();
m_machineConfig = getMachineConfig();
m_machineConfig.GetClient(ref exePath, ref runLine, ref exeFlags);
initializeGrids();
ArrayList menuItems = new ArrayList();
menuItems.Add(string.Empty);
addLocalSims(ref menuItems);
foreach (Grid grid in m_grids)
{
menuItems.Add(grid.Name + " - " + grid.URL);
}
comboBox1.DataSource = menuItems;
}
private MachineConfig getMachineConfig()
{
if (Environment.OSVersion.Platform == PlatformID.Unix)
{
if (File.Exists("/System/Library/Frameworks/Cocoa.framework/Cocoa"))
{
return new OSXConfig();
}
else
{
return new UnixConfig();
}
}
else
{
return new WindowsConfig();
}
}
private void initializeGrids()
{
string iniFile = "LaunchSLClient.ini";
if (!File.Exists(iniFile))
return;
IniConfigSource configSource = new IniConfigSource(iniFile);
foreach (IConfig config in configSource.Configs)
{
Grid grid = new Grid();
grid.Name = config.Name;
grid.LoginURI = config.GetString("loginURI", "");
grid.URL = config.GetString("URL", "");
m_grids.Add(grid);
}
}
private void addLocalSandbox(ref ArrayList menuItems)
{
// build sandbox URL from Regions/default.xml
// this is highly dependant on a standard default.xml
if (File.Exists("Regions/default.xml"))
{
string sandboxHostName = "";
string sandboxPort = "";
string text;
Regex myRegex = new Regex(".*internal_ip_port=\\\"(?<port>.*?)\\\".*external_host_name=\\\"(?<name>.*?)\\\".*");
FileInfo defaultFile = new FileInfo("Regions/default.xml");
StreamReader stream = defaultFile.OpenText();
do
{
text = stream.ReadLine();
if (text == null)
{
break;
}
MatchCollection theMatches = myRegex.Matches(text);
foreach (Match theMatch in theMatches)
{
if (theMatch.Length != 0)
{
sandboxHostName = theMatch.Groups["name"].ToString();
sandboxPort = theMatch.Groups["port"].ToString();
}
}
} while (text != null);
stream.Close();
sandboxUrl = "http:\\" + sandboxHostName + ":" + sandboxPort;
menuItems.Add("Local Sandbox");
}
}
private void addLocalGrid(ref ArrayList menuItems)
{
//build local grid URL from network_servers_information.xml
if (File.Exists("network_servers_information.xml"))
{
string text;
FileInfo defaultFile = new FileInfo("network_servers_information.xml");
Regex myRegex = new Regex(".*UserServerURL=\\\"(?<url>.*?)\\\".*");
StreamReader stream = defaultFile.OpenText();
do
{
text = stream.ReadLine();
if (text == null)
{
break;
}
foreach (Match theMatch in myRegex.Matches(text))
{
if (theMatch.Length != 0)
{
gridUrl = theMatch.Groups["url"].ToString();
}
}
} while (text != null);
stream.Close();
if (gridUrl != null)
{
menuItems.Add("Local Grid Server");
}
}
}
private void addLocalSims(ref ArrayList menuItems)
{
string configDir = m_machineConfig.GetConfigDir();
if (!string.IsNullOrEmpty(configDir))
{
Directory.SetCurrentDirectory(configDir);
addLocalSandbox(ref menuItems);
addLocalGrid(ref menuItems);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.Text == string.Empty)
{
return;
}
else if (comboBox1.Text == "Local Sandbox")
{
runUrl=" -loginuri " + sandboxUrl;
}
else if (comboBox1.Text == "Local Grid Server")
{
runUrl = " -loginuri " + gridUrl;
}
else
{
foreach (Grid grid in m_grids)
{
if (comboBox1.Text == grid.Name + " - " + grid.URL)
{
if (grid.LoginURI != string.Empty)
runUrl = " -loginuri " + grid.LoginURI;
else
runUrl = "";
break;
}
}
}
comboBox1.DroppedDown = false;
Hide();
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = runLine;
proc.StartInfo.Arguments = exeFlags + " " + runUrl;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = false;
proc.StartInfo.WorkingDirectory = exePath;
proc.Start();
proc.WaitForExit();
Application.Exit();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Cryptography.Asn1;
using System.Security.Cryptography.Pkcs.Asn1;
using System.Security.Cryptography.X509Certificates;
using Internal.Cryptography;
namespace System.Security.Cryptography.Pkcs
{
public sealed partial class SignedCms
{
private SignedDataAsn _signedData;
private bool _hasData;
// A defensive copy of the relevant portions of the data to Decode
private Memory<byte> _heldData;
// Due to the way the underlying Windows CMS API behaves a copy of the content
// bytes will be held separate once the content is "bound" (first signature or decode)
private ReadOnlyMemory<byte>? _heldContent;
// Similar to _heldContent, the Windows CMS API held this separate internally,
// and thus we need to be reslilient against modification.
private string _contentType;
public int Version { get; private set; }
public ContentInfo ContentInfo { get; private set; }
public bool Detached { get; private set; }
public SignedCms(SubjectIdentifierType signerIdentifierType, ContentInfo contentInfo, bool detached)
{
if (contentInfo == null)
throw new ArgumentNullException(nameof(contentInfo));
if (contentInfo.Content == null)
throw new ArgumentNullException("contentInfo.Content");
// signerIdentifierType is ignored.
// In .NET Framework it is used for the signer type of a prompt-for-certificate signer.
// In .NET Core we don't support prompting.
//
// .NET Framework turned any unknown value into IssuerAndSerialNumber, so no exceptions
// are required, either.
ContentInfo = contentInfo;
Detached = detached;
Version = 0;
}
public X509Certificate2Collection Certificates
{
get
{
var coll = new X509Certificate2Collection();
if (!_hasData)
{
return coll;
}
CertificateChoiceAsn[] certChoices = _signedData.CertificateSet;
if (certChoices == null)
{
return coll;
}
foreach (CertificateChoiceAsn choice in certChoices)
{
coll.Add(new X509Certificate2(choice.Certificate.Value.ToArray()));
}
return coll;
}
}
public SignerInfoCollection SignerInfos
{
get
{
if (!_hasData)
{
return new SignerInfoCollection();
}
return new SignerInfoCollection(_signedData.SignerInfos, this);
}
}
public byte[] Encode()
{
if (!_hasData)
{
throw new InvalidOperationException(SR.Cryptography_Cms_MessageNotSigned);
}
// Write as DER, so everyone can read it.
AsnWriter writer = AsnSerializer.Serialize(_signedData, AsnEncodingRules.DER);
byte[] signedData = writer.Encode();
ContentInfoAsn contentInfo = new ContentInfoAsn
{
Content = signedData,
ContentType = Oids.Pkcs7Signed,
};
// Write as DER, so everyone can read it.
writer = AsnSerializer.Serialize(contentInfo, AsnEncodingRules.DER);
return writer.Encode();
}
public void Decode(byte[] encodedMessage)
{
if (encodedMessage == null)
throw new ArgumentNullException(nameof(encodedMessage));
// Windows (and thus NetFx) reads the leading data and ignores extra.
// The deserializer will complain if too much data is given, so use the reader
// to ask how much we want to deserialize.
AsnReader reader = new AsnReader(encodedMessage, AsnEncodingRules.BER);
ReadOnlyMemory<byte> cmsSegment = reader.GetEncodedValue();
ContentInfoAsn contentInfo = AsnSerializer.Deserialize<ContentInfoAsn>(cmsSegment, AsnEncodingRules.BER);
if (contentInfo.ContentType != Oids.Pkcs7Signed)
{
throw new CryptographicException(SR.Cryptography_Cms_InvalidMessageType);
}
// Hold a copy of the SignedData memory so we are protected against memory reuse by the caller.
_heldData = contentInfo.Content.ToArray();
_signedData = AsnSerializer.Deserialize<SignedDataAsn>(_heldData, AsnEncodingRules.BER);
_contentType = _signedData.EncapContentInfo.ContentType;
if (!Detached)
{
ReadOnlyMemory<byte>? content = _signedData.EncapContentInfo.Content;
// This is in _heldData, so we don't need a defensive copy.
_heldContent = content ?? ReadOnlyMemory<byte>.Empty;
// The ContentInfo object/property DOES need a defensive copy, because
// a) it is mutable by the user, and
// b) it is no longer authoritative
//
// (and c: it takes a byte[] and we have a ReadOnlyMemory<byte>)
ContentInfo = new ContentInfo(new Oid(_contentType), _heldContent.Value.ToArray());
}
else
{
// Hold a defensive copy of the content bytes, (Windows/NetFx compat)
_heldContent = ContentInfo.Content.CloneByteArray();
}
Version = _signedData.Version;
_hasData = true;
}
public void ComputeSignature()
{
throw new PlatformNotSupportedException(SR.Cryptography_Cms_NoSignerCert);
}
public void ComputeSignature(CmsSigner signer) => ComputeSignature(signer, true);
public void ComputeSignature(CmsSigner signer, bool silent)
{
if (signer == null)
{
throw new ArgumentNullException(nameof(signer));
}
// While it shouldn't be possible to change the length of ContentInfo.Content
// after it's built, use the property at this stage, then use the saved value
// (if applicable) after this point.
if (ContentInfo.Content.Length == 0)
{
throw new CryptographicException(SR.Cryptography_Cms_Sign_Empty_Content);
}
// If we had content already, use that now.
// (The second signer doesn't inherit edits to signedCms.ContentInfo.Content)
ReadOnlyMemory<byte> content = _heldContent ?? ContentInfo.Content;
string contentType = _contentType ?? ContentInfo.ContentType.Value;
X509Certificate2Collection chainCerts;
SignerInfoAsn newSigner = signer.Sign(content, contentType, silent, out chainCerts);
bool firstSigner = false;
if (!_hasData)
{
firstSigner = true;
_signedData = new SignedDataAsn
{
DigestAlgorithms = Array.Empty<AlgorithmIdentifierAsn>(),
SignerInfos = Array.Empty<SignerInfoAsn>(),
EncapContentInfo = new EncapsulatedContentInfoAsn { ContentType = contentType },
};
// Since we're going to call Decode before this method exits we don't need to save
// the copy of _heldContent or _contentType here if we're attached.
if (!Detached)
{
_signedData.EncapContentInfo.Content = content;
}
_hasData = true;
}
int newIdx = _signedData.SignerInfos.Length;
Array.Resize(ref _signedData.SignerInfos, newIdx + 1);
_signedData.SignerInfos[newIdx] = newSigner;
UpdateCertificatesFromAddition(chainCerts);
ConsiderDigestAddition(newSigner.DigestAlgorithm);
UpdateMetadata();
if (firstSigner)
{
Reencode();
Debug.Assert(_heldContent != null);
Debug.Assert(_contentType == contentType);
}
}
public void RemoveSignature(int index)
{
if (!_hasData)
{
throw new InvalidOperationException(SR.Cryptography_Cms_MessageNotSigned);
}
if (index < 0 || index >= _signedData.SignerInfos.Length)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
}
AlgorithmIdentifierAsn signerAlgorithm = _signedData.SignerInfos[index].DigestAlgorithm;
Helpers.RemoveAt(ref _signedData.SignerInfos, index);
ConsiderDigestRemoval(signerAlgorithm);
UpdateMetadata();
}
public void RemoveSignature(SignerInfo signerInfo)
{
if (signerInfo == null)
throw new ArgumentNullException(nameof(signerInfo));
int idx = SignerInfos.FindIndexForSigner(signerInfo);
if (idx < 0)
{
throw new CryptographicException(SR.Cryptography_Cms_SignerNotFound);
}
RemoveSignature(idx);
}
internal ReadOnlySpan<byte> GetContentSpan() => _heldContent.Value.Span;
internal void Reencode()
{
// When NetFx re-encodes it just resets the CMS handle, the ContentInfo property
// does not get changed.
// See ReopenToDecode
ContentInfo save = ContentInfo;
try
{
byte[] encoded = Encode();
if (Detached)
{
// At this point the _heldContent becomes whatever ContentInfo says it should be.
_heldContent = null;
}
Decode(encoded);
Debug.Assert(_heldContent != null);
}
finally
{
ContentInfo = save;
}
}
private void UpdateMetadata()
{
// Version 5: any certificate of type Other or CRL of type Other. We don't support this.
// Version 4: any certificates are V2 attribute certificates. We don't support this.
// Version 3a: any certificates are V1 attribute certificates. We don't support this.
// Version 3b: any signerInfos are v3
// Version 3c: eContentType != data
// Version 2: does not exist for signed-data
// Version 1: default
// The versions 3 are OR conditions, so we need to check the content type and the signerinfos.
int version = 1;
if ((_contentType ?? ContentInfo.ContentType.Value) != Oids.Pkcs7Data)
{
version = 3;
}
else if (_signedData.SignerInfos.Any(si => si.Version == 3))
{
version = 3;
}
Version = version;
_signedData.Version = version;
}
private void ConsiderDigestAddition(AlgorithmIdentifierAsn candidate)
{
int curLength = _signedData.DigestAlgorithms.Length;
for (int i = 0; i < curLength; i++)
{
ref AlgorithmIdentifierAsn alg = ref _signedData.DigestAlgorithms[i];
if (candidate.Equals(ref alg))
{
return;
}
}
Array.Resize(ref _signedData.DigestAlgorithms, curLength + 1);
_signedData.DigestAlgorithms[curLength] = candidate;
}
private void ConsiderDigestRemoval(AlgorithmIdentifierAsn candidate)
{
bool remove = true;
for (int i = 0; i < _signedData.SignerInfos.Length; i++)
{
ref AlgorithmIdentifierAsn signerAlg = ref _signedData.SignerInfos[i].DigestAlgorithm;
if (candidate.Equals(ref signerAlg))
{
remove = false;
break;
}
}
if (!remove)
{
return;
}
for (int i = 0; i < _signedData.DigestAlgorithms.Length; i++)
{
ref AlgorithmIdentifierAsn alg = ref _signedData.DigestAlgorithms[i];
if (candidate.Equals(ref alg))
{
Helpers.RemoveAt(ref _signedData.DigestAlgorithms, i);
break;
}
}
}
internal void UpdateCertificatesFromAddition(X509Certificate2Collection newCerts)
{
if (newCerts.Count == 0)
{
return;
}
int existingLength = _signedData.CertificateSet?.Length ?? 0;
if (existingLength > 0 || newCerts.Count > 1)
{
var certs = new HashSet<X509Certificate2>(Certificates.OfType<X509Certificate2>());
for (int i = 0; i < newCerts.Count; i++)
{
X509Certificate2 candidate = newCerts[i];
if (!certs.Add(candidate))
{
newCerts.RemoveAt(i);
i--;
}
}
}
if (newCerts.Count == 0)
{
return;
}
if (_signedData.CertificateSet == null)
{
_signedData.CertificateSet = new CertificateChoiceAsn[newCerts.Count];
}
else
{
Array.Resize(ref _signedData.CertificateSet, existingLength + newCerts.Count);
}
for (int i = existingLength; i < _signedData.CertificateSet.Length; i++)
{
_signedData.CertificateSet[i] = new CertificateChoiceAsn
{
Certificate = newCerts[i - existingLength].RawData
};
}
}
public void CheckSignature(bool verifySignatureOnly) =>
CheckSignature(new X509Certificate2Collection(), verifySignatureOnly);
public void CheckSignature(X509Certificate2Collection extraStore, bool verifySignatureOnly)
{
if (!_hasData)
throw new InvalidOperationException(SR.Cryptography_Cms_MessageNotSigned);
if (extraStore == null)
throw new ArgumentNullException(nameof(extraStore));
CheckSignatures(SignerInfos, extraStore, verifySignatureOnly);
}
private static void CheckSignatures(
SignerInfoCollection signers,
X509Certificate2Collection extraStore,
bool verifySignatureOnly)
{
Debug.Assert(signers != null);
if (signers.Count < 1)
{
throw new CryptographicException(SR.Cryptography_Cms_NoSignerAtIndex);
}
foreach (SignerInfo signer in signers)
{
signer.CheckSignature(extraStore, verifySignatureOnly);
SignerInfoCollection counterSigners = signer.CounterSignerInfos;
if (counterSigners.Count > 0)
{
CheckSignatures(counterSigners, extraStore, verifySignatureOnly);
}
}
}
public void CheckHash()
{
if (!_hasData)
throw new InvalidOperationException(SR.Cryptography_Cms_MessageNotSigned);
SignerInfoCollection signers = SignerInfos;
Debug.Assert(signers != null);
if (signers.Count < 1)
{
throw new CryptographicException(SR.Cryptography_Cms_NoSignerAtIndex);
}
foreach (SignerInfo signer in signers)
{
if (signer.SignerIdentifier.Type == SubjectIdentifierType.NoSignature)
{
signer.CheckHash();
}
}
}
internal ref SignedDataAsn GetRawData()
{
return ref _signedData;
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
namespace DiscUtils.Raw
{
using System;
using System.IO;
using DiscUtils.Partitions;
/// <summary>
/// Represents a single raw disk image file.
/// </summary>
public sealed class DiskImageFile : VirtualDiskLayer
{
private SparseStream _content;
private Ownership _ownsContent;
private Geometry _geometry;
/// <summary>
/// Initializes a new instance of the DiskImageFile class.
/// </summary>
/// <param name="stream">The stream to interpret</param>
public DiskImageFile(Stream stream)
: this(stream, Ownership.None, null)
{
}
/// <summary>
/// Initializes a new instance of the DiskImageFile class.
/// </summary>
/// <param name="stream">The stream to interpret</param>
/// <param name="ownsStream">Indicates if the new instance should control the lifetime of the stream.</param>
/// <param name="geometry">The emulated geometry of the disk.</param>
public DiskImageFile(Stream stream, Ownership ownsStream, Geometry geometry)
{
_content = stream as SparseStream;
_ownsContent = ownsStream;
if (_content == null)
{
_content = SparseStream.FromStream(stream, ownsStream);
_ownsContent = Ownership.Dispose;
}
_geometry = geometry ?? DetectGeometry(_content);
}
/// <summary>
/// Gets the geometry of the file.
/// </summary>
public override Geometry Geometry
{
get { return _geometry; }
}
/// <summary>
/// Gets a value indicating if the layer only stores meaningful sectors.
/// </summary>
public override bool IsSparse
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether the file is a differencing disk.
/// </summary>
public override bool NeedsParent
{
get { return false; }
}
/// <summary>
/// Gets the type of disk represented by this object.
/// </summary>
public VirtualDiskClass DiskType
{
get { return DetectDiskType(Capacity); }
}
internal override long Capacity
{
get { return _content.Length; }
}
internal override FileLocator RelativeFileLocator
{
get { return null; }
}
internal SparseStream Content
{
get { return _content; }
}
/// <summary>
/// Initializes a stream as a raw disk image.
/// </summary>
/// <param name="stream">The stream to initialize.</param>
/// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param>
/// <param name="capacity">The desired capacity of the new disk</param>
/// <param name="geometry">The geometry of the new disk</param>
/// <returns>An object that accesses the stream as a raw disk image</returns>
public static DiskImageFile Initialize(Stream stream, Ownership ownsStream, long capacity, Geometry geometry)
{
stream.SetLength(Utilities.RoundUp(capacity, Sizes.Sector));
// Wipe any pre-existing master boot record / BPB
stream.Position = 0;
stream.Write(new byte[Sizes.Sector], 0, Sizes.Sector);
stream.Position = 0;
return new DiskImageFile(stream, ownsStream, geometry);
}
/// <summary>
/// Initializes a stream as an unformatted floppy disk.
/// </summary>
/// <param name="stream">The stream to initialize.</param>
/// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param>
/// <param name="type">The type of floppy disk image to create</param>
/// <returns>An object that accesses the stream as a disk</returns>
public static DiskImageFile Initialize(Stream stream, Ownership ownsStream, FloppyDiskType type)
{
return Initialize(stream, ownsStream, FloppyCapacity(type), null);
}
/// <summary>
/// Gets the content of this layer.
/// </summary>
/// <param name="parent">The parent stream (if any)</param>
/// <param name="ownsParent">Controls ownership of the parent stream</param>
/// <returns>The content as a stream</returns>
public override SparseStream OpenContent(SparseStream parent, Ownership ownsParent)
{
if (ownsParent == Ownership.Dispose && parent != null)
{
parent.Dispose();
}
return SparseStream.FromStream(Content, Ownership.None);
}
/// <summary>
/// Gets the possible locations of the parent file (if any).
/// </summary>
/// <returns>Array of strings, empty if no parent</returns>
public override string[] GetParentLocations()
{
return new string[0];
}
/// <summary>
/// Disposes of underlying resources.
/// </summary>
/// <param name="disposing">Set to <c>true</c> if called within Dispose(),
/// else <c>false</c>.</param>
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
if (_ownsContent == Ownership.Dispose && _content != null)
{
_content.Dispose();
}
_content = null;
}
}
finally
{
base.Dispose(disposing);
}
}
/// <summary>
/// Calculates the best guess geometry of a disk.
/// </summary>
/// <param name="disk">The disk to detect the geometry of</param>
/// <returns>The geometry of the disk</returns>
private static Geometry DetectGeometry(Stream disk)
{
long capacity = disk.Length;
// First, check for floppy disk capacities - these have well-defined geometries
if (capacity == Sizes.Sector * 1440)
{
return new Geometry(80, 2, 9);
}
else if (capacity == Sizes.Sector * 2880)
{
return new Geometry(80, 2, 18);
}
else if (capacity == Sizes.Sector * 5760)
{
return new Geometry(80, 2, 36);
}
// Failing that, try to detect the geometry from any partition table.
// Note: this call falls back to guessing the geometry from the capacity
return BiosPartitionTable.DetectGeometry(disk);
}
/// <summary>
/// Calculates the best guess disk type (i.e. floppy or hard disk)
/// </summary>
/// <param name="capacity">The capacity of the disk</param>
/// <returns>The disk type</returns>
private static VirtualDiskClass DetectDiskType(long capacity)
{
if (capacity == Sizes.Sector * 1440
|| capacity == Sizes.Sector * 2880
|| capacity == Sizes.Sector * 5760)
{
return VirtualDiskClass.FloppyDisk;
}
else
{
return VirtualDiskClass.HardDisk;
}
}
private static long FloppyCapacity(FloppyDiskType type)
{
switch (type)
{
case FloppyDiskType.DoubleDensity:
return Sizes.Sector * 1440;
case FloppyDiskType.HighDensity:
return Sizes.Sector * 2880;
case FloppyDiskType.Extended:
return Sizes.Sector * 5760;
default:
throw new ArgumentException("Invalid floppy disk type", "type");
}
}
}
}
| |
using System.Collections.Generic;
using Esprima.Ast;
using Jint.Runtime.Modules;
namespace Jint
{
internal readonly struct HoistingScope
{
internal readonly List<FunctionDeclaration> _functionDeclarations;
internal readonly List<VariableDeclaration> _variablesDeclarations;
internal readonly List<Key> _varNames;
internal readonly List<Declaration> _lexicalDeclarations;
internal readonly List<string> _lexicalNames;
private HoistingScope(
List<FunctionDeclaration> functionDeclarations,
List<Key> varNames,
List<VariableDeclaration> variableDeclarations,
List<Declaration> lexicalDeclarations,
List<string> lexicalNames)
{
_functionDeclarations = functionDeclarations;
_varNames = varNames;
_variablesDeclarations = variableDeclarations;
_lexicalDeclarations = lexicalDeclarations;
_lexicalNames = lexicalNames;
}
public static HoistingScope GetProgramLevelDeclarations(
Program script,
bool collectVarNames = false,
bool collectLexicalNames = false)
{
var treeWalker = new ScriptWalker(StrictModeScope.IsStrictModeCode, collectVarNames, collectLexicalNames);
treeWalker.Visit(script, null);
return new HoistingScope(
treeWalker._functions,
treeWalker._varNames,
treeWalker._variableDeclarations,
treeWalker._lexicalDeclarations,
treeWalker._lexicalNames);
}
public static HoistingScope GetFunctionLevelDeclarations(
IFunction node,
bool collectVarNames = false,
bool collectLexicalNames = false)
{
var treeWalker = new ScriptWalker(StrictModeScope.IsStrictModeCode, collectVarNames, collectLexicalNames);
treeWalker.Visit(node.Body, null);
return new HoistingScope(
treeWalker._functions,
treeWalker._varNames,
treeWalker._variableDeclarations,
treeWalker._lexicalDeclarations,
treeWalker._lexicalNames);
}
public static HoistingScope GetModuleLevelDeclarations(
Module module,
bool collectVarNames = false,
bool collectLexicalNames = false)
{
//Modules area always strict
var treeWalker = new ScriptWalker(true, collectVarNames, collectLexicalNames);
treeWalker.Visit(module, null);
return new HoistingScope(
treeWalker._functions,
treeWalker._varNames,
treeWalker._variableDeclarations,
treeWalker._lexicalDeclarations,
treeWalker._lexicalNames);
}
public static List<Declaration> GetLexicalDeclarations(BlockStatement statement)
{
List<Declaration> lexicalDeclarations = null;
ref readonly var statementListItems = ref statement.Body;
for (var i = 0; i < statementListItems.Count; i++)
{
var node = statementListItems[i];
if (node.Type != Nodes.VariableDeclaration && node.Type != Nodes.FunctionDeclaration)
{
continue;
}
if (node is VariableDeclaration { Kind: VariableDeclarationKind.Var })
{
continue;
}
lexicalDeclarations ??= new List<Declaration>();
lexicalDeclarations.Add((Declaration)node);
}
return lexicalDeclarations;
}
public static List<Declaration> GetLexicalDeclarations(SwitchCase statement)
{
List<Declaration> lexicalDeclarations = null;
ref readonly var statementListItems = ref statement.Consequent;
for (var i = 0; i < statementListItems.Count; i++)
{
var node = statementListItems[i];
if (node.Type != Nodes.VariableDeclaration)
{
continue;
}
var rootVariable = (VariableDeclaration)node;
if (rootVariable.Kind == VariableDeclarationKind.Var)
{
continue;
}
lexicalDeclarations ??= new List<Declaration>();
lexicalDeclarations.Add(rootVariable);
}
return lexicalDeclarations;
}
public static void GetImportsAndExports(
Module module,
out HashSet<string> requestedModules,
out List<ImportEntry> importEntries,
out List<ExportEntry> localExportEntries,
out List<ExportEntry> indirectExportEntries,
out List<ExportEntry> starExportEntries)
{
var treeWalker = new ModuleWalker();
treeWalker.Visit(module);
importEntries = treeWalker._importEntries;
requestedModules = treeWalker._requestedModules ?? new();
var importedBoundNames = new HashSet<string>();
if (importEntries != null)
{
for (var i = 0; i < importEntries.Count; i++)
{
var ie = importEntries[i];
if (ie.LocalName is not null)
{
importedBoundNames.Add(ie.LocalName);
}
}
}
var exportEntries = treeWalker._exportEntries;
localExportEntries = new();
indirectExportEntries = new();
starExportEntries = new();
if (exportEntries != null)
{
for (var i = 0; i < exportEntries.Count; i++)
{
var ee = exportEntries[i];
if (ee.ModuleRequest is null)
{
if (!importedBoundNames.Contains(ee.LocalName))
{
localExportEntries.Add(ee);
}
else
{
for (var j = 0; j < importEntries!.Count; j++)
{
var ie = importEntries[j];
if (ie.LocalName == ee.LocalName)
{
if (ie.ImportName == "*")
{
localExportEntries.Add(ee);
}
else
{
indirectExportEntries.Add(new(ee.ExportName, ie.ModuleRequest, ie.ImportName, null));
}
break;
}
}
}
}
else if (ee.ImportName == "*" && ee.ExportName is null)
{
starExportEntries.Add(ee);
}
else
{
indirectExportEntries.Add(ee);
}
}
}
}
private sealed class ScriptWalker
{
internal List<FunctionDeclaration> _functions;
private readonly bool _strict;
private readonly bool _collectVarNames;
internal List<VariableDeclaration> _variableDeclarations;
internal List<Key> _varNames;
private readonly bool _collectLexicalNames;
internal List<Declaration> _lexicalDeclarations;
internal List<string> _lexicalNames;
public ScriptWalker(bool strict, bool collectVarNames, bool collectLexicalNames)
{
_strict = strict;
_collectVarNames = collectVarNames;
_collectLexicalNames = collectLexicalNames;
}
public void Visit(Node node, Node parent)
{
foreach (var childNode in node.ChildNodes)
{
if (childNode is null)
{
// array expression can push null nodes in Esprima
continue;
}
if (childNode.Type == Nodes.VariableDeclaration)
{
var variableDeclaration = (VariableDeclaration)childNode;
if (variableDeclaration.Kind == VariableDeclarationKind.Var)
{
_variableDeclarations ??= new List<VariableDeclaration>();
_variableDeclarations.Add(variableDeclaration);
if (_collectVarNames)
{
_varNames ??= new List<Key>();
ref readonly var nodeList = ref variableDeclaration.Declarations;
foreach (var declaration in nodeList)
{
if (declaration.Id is Identifier identifier)
{
_varNames.Add(identifier.Name);
}
}
}
}
if ((parent is null or Module) && variableDeclaration.Kind != VariableDeclarationKind.Var)
{
_lexicalDeclarations ??= new List<Declaration>();
_lexicalDeclarations.Add(variableDeclaration);
if (_collectLexicalNames)
{
_lexicalNames ??= new List<string>();
ref readonly var nodeList = ref variableDeclaration.Declarations;
foreach (var declaration in nodeList)
{
if (declaration.Id is Identifier identifier)
{
_lexicalNames.Add(identifier.Name);
}
}
}
}
}
else if (childNode.Type == Nodes.FunctionDeclaration
// in strict mode cannot include function declarations directly under block or case clauses
&& (!_strict || parent is null || (node.Type != Nodes.BlockStatement && node.Type != Nodes.SwitchCase)))
{
_functions ??= new List<FunctionDeclaration>();
_functions.Add((FunctionDeclaration)childNode);
}
else if (childNode.Type == Nodes.ClassDeclaration)
{
_lexicalDeclarations ??= new List<Declaration>();
_lexicalDeclarations.Add((Declaration) childNode);
}
if (childNode.Type != Nodes.FunctionDeclaration
&& childNode.Type != Nodes.ArrowFunctionExpression
&& childNode.Type != Nodes.ArrowParameterPlaceHolder
&& childNode.Type != Nodes.FunctionExpression
&& childNode.ChildNodes.Count > 0)
{
Visit(childNode, node);
}
}
}
}
private sealed class ModuleWalker
{
internal List<ImportEntry> _importEntries;
internal List<ExportEntry> _exportEntries;
internal HashSet<string> _requestedModules;
internal void Visit(Node node)
{
foreach (var childNode in node.ChildNodes)
{
if (childNode is null)
{
continue;
}
if (childNode.Type == Nodes.ImportDeclaration)
{
_importEntries ??= new();
_requestedModules ??= new();
var import = childNode as ImportDeclaration;
import.GetImportEntries(_importEntries, _requestedModules);
}
else if (childNode.Type == Nodes.ExportAllDeclaration ||
childNode.Type == Nodes.ExportDefaultDeclaration ||
childNode.Type == Nodes.ExportNamedDeclaration)
{
_exportEntries ??= new();
_requestedModules ??= new();
var export = (ExportDeclaration) childNode;
export.GetExportEntries(_exportEntries, _requestedModules);
}
if (childNode.ChildNodes.Count > 0)
{
Visit(childNode);
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Msagl.Core.Geometry.Curves;
using Microsoft.Msagl.Core.Routing;
using Microsoft.Msagl.Drawing;
using Microsoft.Msagl.GraphViewerGdi;
using Microsoft.Msagl.Layout.Layered;
using Microsoft.Msagl.Layout.MDS;
using Color = Microsoft.Msagl.Drawing.Color;
using Label = Microsoft.Msagl.Drawing.Label;
using MouseButtons = System.Windows.Forms.MouseButtons;
using Node = Microsoft.Msagl.Core.Layout.Node;
using Point = Microsoft.Msagl.Core.Geometry.Point;
namespace WindowsApplicationSample {
public partial class Form1 : Form {
readonly ToolTip toolTip1 = new ToolTip();
object selectedObject;
AttributeBase selectedObjectAttr;
public Form1() {
Load += Form1Load;
InitializeComponent();
gViewer.MouseWheel += GViewerMouseWheel;
toolTip1.Active = true;
toolTip1.AutoPopDelay = 5000;
toolTip1.InitialDelay = 1000;
toolTip1.ReshowDelay = 500;
gViewer.LayoutEditor.DecorateObjectForDragging = SetDragDecorator;
gViewer.LayoutEditor.RemoveObjDraggingDecorations = RemoveDragDecorator;
gViewer.MouseDown += WaMouseDown;
gViewer.MouseUp += WaMouseUp;
gViewer.MouseMove += GViewerOnMouseMove;
}
void GViewerOnMouseMove(object sender, MouseEventArgs mouseEventArgs) {
if (labelToChange == null) return;
labelToChange.Text = MousePosition.ToString();
if (viewerEntityCorrespondingToLabelToChange == null) {
foreach (var e in gViewer.Entities) {
if (e.DrawingObject == labelToChange) {
viewerEntityCorrespondingToLabelToChange = e;
break;
}
}
}
if (viewerEntityCorrespondingToLabelToChange == null) return;
var rect = labelToChange.BoundingBox;
var font = new Font(labelToChange.FontName, (int) labelToChange.FontSize);
double width;
double height;
StringMeasure.MeasureWithFont(labelToChange.Text, font, out width, out height);
if (width <= 0)
//this is a temporary fix for win7 where Measure fonts return negative lenght for the string " "
StringMeasure.MeasureWithFont("a", font, out width, out height);
labelToChange.Width = width;
labelToChange.Height = height;
rect.Add(labelToChange.BoundingBox);
gViewer.Invalidate(gViewer.MapSourceRectangleToScreenRectangle(rect));
}
void WaMouseUp(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Left)
myMouseUpPoint = e.Location;
}
void WaMouseDown(object sender, MouseEventArgs e) {
if(e.Button==MouseButtons.Left)
myMouseDownPoint = e.Location;
}
readonly Dictionary<object, Color> draggedObjectOriginalColors=new Dictionary<object, Color>();
System.Drawing.Point myMouseDownPoint;
System.Drawing.Point myMouseUpPoint;
void SetDragDecorator(IViewerObject obj) {
var dNode = obj as DNode;
if (dNode != null) {
draggedObjectOriginalColors[dNode] = dNode.DrawingNode.Attr.Color;
dNode.DrawingNode.Attr.Color = Color.Magenta;
gViewer.Invalidate(obj);
}
}
void RemoveDragDecorator(IViewerObject obj) {
var dNode = obj as DNode;
if (dNode != null) {
dNode.DrawingNode.Attr.Color = draggedObjectOriginalColors[dNode];
draggedObjectOriginalColors.Remove(obj);
gViewer.Invalidate(obj);
}
}
void GViewerMouseWheel(object sender, MouseEventArgs e) {
int delta = e.Delta;
if (delta != 0)
gViewer.ZoomF *= delta < 0 ? 0.9 : 1.1;
}
void Form1Load(object sender, EventArgs e) {
gViewer.ObjectUnderMouseCursorChanged += GViewerObjectUnderMouseCursorChanged;
#if DEBUG
//DisplayGeometryGraph.SetShowFunctions();
#endif
///// CreateGraph();
}
void GViewerObjectUnderMouseCursorChanged(object sender, ObjectUnderMouseCursorChangedEventArgs e) {
selectedObject = e.OldObject != null ? e.OldObject.DrawingObject : null;
if (selectedObject != null) {
RestoreSelectedObjAttr();
gViewer.Invalidate(e.OldObject);
selectedObject = null;
}
if (gViewer.SelectedObject == null) {
label1.Text = "No object under the mouse";
gViewer.SetToolTip(toolTip1, "");
} else {
selectedObject = gViewer.SelectedObject;
var edge = selectedObject as Edge;
if (edge != null) {
selectedObjectAttr = edge.Attr.Clone();
edge.Attr.Color = Color.Blue;
gViewer.Invalidate(e.NewObject);
// here we can use e.Attr.Id or e.UserData to get back to the user data
gViewer.SetToolTip(toolTip1, String.Format("edge from {0} to {1}", edge.Source, edge.Target));
} else if (selectedObject is Microsoft.Msagl.Drawing.Node) {
selectedObjectAttr = (gViewer.SelectedObject as Microsoft.Msagl.Drawing.Node).Attr.Clone();
(selectedObject as Microsoft.Msagl.Drawing.Node).Attr.Color = Color.Green;
// // here you can use e.Attr.Id to get back to your data
gViewer.SetToolTip(toolTip1,
String.Format("node {0}",
(selectedObject as Microsoft.Msagl.Drawing.Node).Attr.Id));
gViewer.Invalidate(e.NewObject);
}
label1.Text = selectedObject.ToString();
}
}
void RestoreSelectedObjAttr() {
var edge = selectedObject as Edge;
if (edge != null) {
edge.Attr = (EdgeAttr) selectedObjectAttr;
}
else {
var node = selectedObject as Microsoft.Msagl.Drawing.Node;
if (node != null)
node.Attr = (NodeAttr)selectedObjectAttr;
}
}
void Button1Click(object sender, EventArgs e) {
CreateGraph();
}
Label labelToChange;
IViewerObject viewerEntityCorrespondingToLabelToChange;
void CreateGraph() {
#if DEBUG
DisplayGeometryGraph.SetShowFunctions();
#endif
Graph graph = new Graph();
graph.AddEdge("47", "58");
graph.AddEdge("70", "71");
var subgraph = new Subgraph("subgraph1");
graph.RootSubgraph.AddSubgraph(subgraph);
subgraph.AddNode(graph.FindNode("47"));
subgraph.AddNode(graph.FindNode("58"));
var subgraph2 = new Subgraph("subgraph2");
subgraph2.Attr.Color = Color.Black;
subgraph2.Attr.FillColor = Color.Yellow;
subgraph2.AddNode(graph.FindNode("70"));
subgraph2.AddNode(graph.FindNode("71"));
subgraph.AddSubgraph(subgraph2);
graph.AddEdge("58", subgraph2.Id);
graph.Attr.LayerDirection = LayerDirection.LR;
gViewer.Graph = graph;
// Graph graph = new Graph("graph");
// //graph.LayoutAlgorithmSettings=new MdsLayoutSettings();
// gViewer.BackColor = System.Drawing.Color.FromArgb(10, System.Drawing.Color.Red);
//
// /*
// 4->5
//5->7
//7->8
//8->22
//22->24
//*/
//
// //int wm = 80;
// graph.AddEdge("1", "2");
// graph.AddEdge("1", "3");
// var e = graph.AddEdge("4", "5");
// //e.Attr.Weight *= wm;
// e.Attr.Color = Color.Red;
// e.Attr.LineWidth *= 2;
//
// e = graph.AddEdge("4", "6");
// e.LabelText = "Changing label";
// this.labelToChange = e.Label;
// e=graph.AddEdge("7", "8");
// //e.Attr.Weight *= wm;
// e.Attr.LineWidth *= 2;
// e.Attr.Color = Color.Red;
//
// graph.AddEdge("7", "9");
// e=graph.AddEdge("5", "7");
// //e.Attr.Weight *= wm;
// e.Attr.Color = Color.Red;
// e.Attr.LineWidth *= 2;
//
// graph.AddEdge("2", "7");
// graph.AddEdge("10", "11");
// graph.AddEdge("10", "12");
// graph.AddEdge("2", "10");
// graph.AddEdge("8", "10");
// graph.AddEdge("5", "10");
// graph.AddEdge("13", "14");
// graph.AddEdge("13", "15");
// graph.AddEdge("8", "13");
// graph.AddEdge("2", "13");
// graph.AddEdge("5", "13");
// graph.AddEdge("16", "17");
// graph.AddEdge("16", "18");
// graph.AddEdge("19", "20");
// graph.AddEdge("19", "21");
// graph.AddEdge("17", "19");
// graph.AddEdge("2", "19");
// graph.AddEdge("22", "23");
//
// e=graph.AddEdge("22", "24");
// //e.Attr.Weight *= wm;
// e.Attr.Color = Color.Red;
// e.Attr.LineWidth *= 2;
//
// e = graph.AddEdge("8", "22");
// //e.Attr.Weight *= wm;
// e.Attr.Color = Color.Red;
// e.Attr.LineWidth *= 2;
//
// graph.AddEdge("20", "22");
// graph.AddEdge("25", "26");
// graph.AddEdge("25", "27");
// graph.AddEdge("20", "25");
// graph.AddEdge("28", "29");
// graph.AddEdge("28", "30");
// graph.AddEdge("31", "32");
// graph.AddEdge("31", "33");
// graph.AddEdge("5", "31");
// graph.AddEdge("8", "31");
// graph.AddEdge("2", "31");
// graph.AddEdge("20", "31");
// graph.AddEdge("17", "31");
// graph.AddEdge("29", "31");
// graph.AddEdge("34", "35");
// graph.AddEdge("34", "36");
// graph.AddEdge("20", "34");
// graph.AddEdge("29", "34");
// graph.AddEdge("5", "34");
// graph.AddEdge("2", "34");
// graph.AddEdge("8", "34");
// graph.AddEdge("17", "34");
// graph.AddEdge("37", "38");
// graph.AddEdge("37", "39");
// graph.AddEdge("29", "37");
// graph.AddEdge("5", "37");
// graph.AddEdge("20", "37");
// graph.AddEdge("8", "37");
// graph.AddEdge("2", "37");
// graph.AddEdge("40", "41");
// graph.AddEdge("40", "42");
// graph.AddEdge("17", "40");
// graph.AddEdge("2", "40");
// graph.AddEdge("8", "40");
// graph.AddEdge("5", "40");
// graph.AddEdge("20", "40");
// graph.AddEdge("29", "40");
// graph.AddEdge("43", "44");
// graph.AddEdge("43", "45");
// graph.AddEdge("8", "43");
// graph.AddEdge("2", "43");
// graph.AddEdge("20", "43");
// graph.AddEdge("17", "43");
// graph.AddEdge("5", "43");
// graph.AddEdge("29", "43");
// graph.AddEdge("46", "47");
// graph.AddEdge("46", "48");
// graph.AddEdge("29", "46");
// graph.AddEdge("5", "46");
// graph.AddEdge("17", "46");
// graph.AddEdge("49", "50");
// graph.AddEdge("49", "51");
// graph.AddEdge("5", "49");
// graph.AddEdge("2", "49");
// graph.AddEdge("52", "53");
// graph.AddEdge("52", "54");
// graph.AddEdge("17", "52");
// graph.AddEdge("20", "52");
// graph.AddEdge("2", "52");
// graph.AddEdge("50", "52");
// graph.AddEdge("55", "56");
// graph.AddEdge("55", "57");
// graph.AddEdge("58", "59");
// graph.AddEdge("58", "60");
// graph.AddEdge("20", "58");
// graph.AddEdge("29", "58");
// graph.AddEdge("5", "58");
// graph.AddEdge("47", "58");
//
// //ChangeNodeSizes(graph);
//
// //var sls = graph.LayoutAlgorithmSettings as SugiyamaLayoutSettings;
// //if (sls != null)
// //{
// // sls.GridSizeByX = 30;
// // // sls.GridSizeByY = 0;
// //}
// var subgraph = new Subgraph("subgraph label");
// graph.RootSubgraph.AddSubgraph(subgraph);
// subgraph.AddNode(graph.FindNode("47"));
// subgraph.AddNode(graph.FindNode("58"));
// //layout the graph and draw it
// gViewer.Graph = graph;
this.propertyGrid1.SelectedObject = graph;
}
void RecalculateLayoutButtonClick(object sender, EventArgs e) {
gViewer.Graph = propertyGrid1.SelectedObject as Graph;
}
bool MouseDownPointAndMouseUpPointsAreFarEnough()
{
double dx = myMouseDownPoint.X - myMouseUpPoint.X;
double dy = myMouseDownPoint.Y - myMouseUpPoint.Y;
return dx*dx + dy*dy >= 25; //so 5X5 pixels already give something
}
void ShowObjectsInTheLastRectClick(object sender, EventArgs e) {
string message;
if(gViewer.Graph==null) {
message = "there is no graph";
}else {
if (MouseDownPointAndMouseUpPointsAreFarEnough()) {
var p0 = gViewer.ScreenToSource(myMouseDownPoint);
var p1 = gViewer.ScreenToSource(myMouseUpPoint);
var rubberRect = new Microsoft.Msagl.Core.Geometry.Rectangle(p0, p1);
var stringB = new StringBuilder();
foreach (var node in gViewer.Graph.Nodes)
if (rubberRect.Contains(node.BoundingBox))
stringB.Append(node.LabelText + "\n");
foreach (var edge in gViewer.Graph.Edges)
if (rubberRect.Contains(edge.BoundingBox))
stringB.Append(String.Format("edge from {0} to {1}\n", edge.SourceNode.LabelText,
edge.TargetNode.LabelText));
message = stringB.ToString();
}
else
message = "the window is not defined";
}
MessageBox.Show(message);
}
}
}
| |
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// There are 3 #defines that have an impact on performance / features of this ByteBuffer implementation
//
// UNSAFE_BYTEBUFFER
// This will use unsafe code to manipulate the underlying byte array. This
// can yield a reasonable performance increase.
//
// BYTEBUFFER_NO_BOUNDS_CHECK
// This will disable the bounds check asserts to the byte array. This can
// yield a small performance gain in normal code..
//
// ENABLE_SPAN_T
// This will enable reading and writing blocks of memory with a Span<T> instead if just
// T[]. You can also enable writing directly to shared memory or other types of memory
// by providing a custom implementation of ByteBufferAllocator.
// ENABLE_SPAN_T also requires UNSAFE_BYTEBUFFER to be defined
//
// Using UNSAFE_BYTEBUFFER and BYTEBUFFER_NO_BOUNDS_CHECK together can yield a
// performance gain of ~15% for some operations, however doing so is potentially
// dangerous. Do so at your own risk!
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
#if ENABLE_SPAN_T
using System.Buffers.Binary;
#endif
#if ENABLE_SPAN_T && !UNSAFE_BYTEBUFFER
#error ENABLE_SPAN_T requires UNSAFE_BYTEBUFFER to also be defined
#endif
namespace FlatBuffers
{
public abstract class ByteBufferAllocator
{
#if ENABLE_SPAN_T
public abstract Span<byte> Span { get; }
public abstract ReadOnlySpan<byte> ReadOnlySpan { get; }
public abstract Memory<byte> Memory { get; }
public abstract ReadOnlyMemory<byte> ReadOnlyMemory { get; }
#else
public byte[] Buffer
{
get;
protected set;
}
#endif
public int Length
{
get;
protected set;
}
public abstract void GrowFront(int newSize);
}
public sealed class ByteArrayAllocator : ByteBufferAllocator
{
private byte[] _buffer;
public ByteArrayAllocator(byte[] buffer)
{
_buffer = buffer;
InitBuffer();
}
public override void GrowFront(int newSize)
{
if ((Length & 0xC0000000) != 0)
throw new Exception(
"ByteBuffer: cannot grow buffer beyond 2 gigabytes.");
if (newSize < Length)
throw new Exception("ByteBuffer: cannot truncate buffer.");
byte[] newBuffer = new byte[newSize];
System.Buffer.BlockCopy(_buffer, 0, newBuffer, newSize - Length, Length);
_buffer = newBuffer;
InitBuffer();
}
#if ENABLE_SPAN_T
public override Span<byte> Span => _buffer;
public override ReadOnlySpan<byte> ReadOnlySpan => _buffer;
public override Memory<byte> Memory => _buffer;
public override ReadOnlyMemory<byte> ReadOnlyMemory => _buffer;
#endif
private void InitBuffer()
{
Length = _buffer.Length;
#if !ENABLE_SPAN_T
Buffer = _buffer;
#endif
}
}
/// <summary>
/// Class to mimic Java's ByteBuffer which is used heavily in Flatbuffers.
/// </summary>
public class ByteBuffer
{
private ByteBufferAllocator _buffer;
private int _pos; // Must track start of the buffer.
public ByteBuffer(ByteBufferAllocator allocator, int position)
{
_buffer = allocator;
_pos = position;
}
public ByteBuffer(int size) : this(new byte[size]) { }
public ByteBuffer(byte[] buffer) : this(buffer, 0) { }
public ByteBuffer(byte[] buffer, int pos)
{
_buffer = new ByteArrayAllocator(buffer);
_pos = pos;
}
public int Position
{
get { return _pos; }
set { _pos = value; }
}
public int Length { get { return _buffer.Length; } }
public void Reset()
{
_pos = 0;
}
// Create a new ByteBuffer on the same underlying data.
// The new ByteBuffer's position will be same as this buffer's.
public ByteBuffer Duplicate()
{
return new ByteBuffer(_buffer, Position);
}
// Increases the size of the ByteBuffer, and copies the old data towards
// the end of the new buffer.
public void GrowFront(int newSize)
{
_buffer.GrowFront(newSize);
}
public byte[] ToArray(int pos, int len)
{
return ToArray<byte>(pos, len);
}
/// <summary>
/// A lookup of type sizes. Used instead of Marshal.SizeOf() which has additional
/// overhead, but also is compatible with generic functions for simplified code.
/// </summary>
private static Dictionary<Type, int> genericSizes = new Dictionary<Type, int>()
{
{ typeof(bool), sizeof(bool) },
{ typeof(float), sizeof(float) },
{ typeof(double), sizeof(double) },
{ typeof(sbyte), sizeof(sbyte) },
{ typeof(byte), sizeof(byte) },
{ typeof(short), sizeof(short) },
{ typeof(ushort), sizeof(ushort) },
{ typeof(int), sizeof(int) },
{ typeof(uint), sizeof(uint) },
{ typeof(ulong), sizeof(ulong) },
{ typeof(long), sizeof(long) },
};
/// <summary>
/// Get the wire-size (in bytes) of a type supported by flatbuffers.
/// </summary>
/// <param name="t">The type to get the wire size of</param>
/// <returns></returns>
public static int SizeOf<T>()
{
return genericSizes[typeof(T)];
}
/// <summary>
/// Checks if the Type provided is supported as scalar value
/// </summary>
/// <typeparam name="T">The Type to check</typeparam>
/// <returns>True if the type is a scalar type that is supported, falsed otherwise</returns>
public static bool IsSupportedType<T>()
{
return genericSizes.ContainsKey(typeof(T));
}
/// <summary>
/// Get the wire-size (in bytes) of an typed array
/// </summary>
/// <typeparam name="T">The type of the array</typeparam>
/// <param name="x">The array to get the size of</param>
/// <returns>The number of bytes the array takes on wire</returns>
public static int ArraySize<T>(T[] x)
{
return SizeOf<T>() * x.Length;
}
#if ENABLE_SPAN_T
public static int ArraySize<T>(Span<T> x)
{
return SizeOf<T>() * x.Length;
}
#endif
// Get a portion of the buffer casted into an array of type T, given
// the buffer position and length.
#if ENABLE_SPAN_T
public T[] ToArray<T>(int pos, int len)
where T : struct
{
AssertOffsetAndLength(pos, len);
return MemoryMarshal.Cast<byte, T>(_buffer.ReadOnlySpan.Slice(pos)).Slice(0, len).ToArray();
}
#else
public T[] ToArray<T>(int pos, int len)
where T : struct
{
AssertOffsetAndLength(pos, len);
T[] arr = new T[len];
Buffer.BlockCopy(_buffer.Buffer, pos, arr, 0, ArraySize(arr));
return arr;
}
#endif
public byte[] ToSizedArray()
{
return ToArray<byte>(Position, Length - Position);
}
public byte[] ToFullArray()
{
return ToArray<byte>(0, Length);
}
#if ENABLE_SPAN_T
public ReadOnlyMemory<byte> ToReadOnlyMemory(int pos, int len)
{
return _buffer.ReadOnlyMemory.Slice(pos, len);
}
public Memory<byte> ToMemory(int pos, int len)
{
return _buffer.Memory.Slice(pos, len);
}
public Span<byte> ToSpan(int pos, int len)
{
return _buffer.Span.Slice(pos, len);
}
#else
public ArraySegment<byte> ToArraySegment(int pos, int len)
{
return new ArraySegment<byte>(_buffer.Buffer, pos, len);
}
public MemoryStream ToMemoryStream(int pos, int len)
{
return new MemoryStream(_buffer.Buffer, pos, len);
}
#endif
#if !UNSAFE_BYTEBUFFER
// A conversion union where all the members are overlapping. This allows to reinterpret the bytes of one type
// as another, without additional copies.
[StructLayout(LayoutKind.Explicit)]
struct ConversionUnion
{
[FieldOffset(0)] public int intValue;
[FieldOffset(0)] public float floatValue;
}
#endif // !UNSAFE_BYTEBUFFER
// Helper functions for the unsafe version.
static public ushort ReverseBytes(ushort input)
{
return (ushort)(((input & 0x00FFU) << 8) |
((input & 0xFF00U) >> 8));
}
static public uint ReverseBytes(uint input)
{
return ((input & 0x000000FFU) << 24) |
((input & 0x0000FF00U) << 8) |
((input & 0x00FF0000U) >> 8) |
((input & 0xFF000000U) >> 24);
}
static public ulong ReverseBytes(ulong input)
{
return (((input & 0x00000000000000FFUL) << 56) |
((input & 0x000000000000FF00UL) << 40) |
((input & 0x0000000000FF0000UL) << 24) |
((input & 0x00000000FF000000UL) << 8) |
((input & 0x000000FF00000000UL) >> 8) |
((input & 0x0000FF0000000000UL) >> 24) |
((input & 0x00FF000000000000UL) >> 40) |
((input & 0xFF00000000000000UL) >> 56));
}
#if !UNSAFE_BYTEBUFFER
// Helper functions for the safe (but slower) version.
protected void WriteLittleEndian(int offset, int count, ulong data)
{
if (BitConverter.IsLittleEndian)
{
for (int i = 0; i < count; i++)
{
_buffer.Buffer[offset + i] = (byte)(data >> i * 8);
}
}
else
{
for (int i = 0; i < count; i++)
{
_buffer.Buffer[offset + count - 1 - i] = (byte)(data >> i * 8);
}
}
}
protected ulong ReadLittleEndian(int offset, int count)
{
AssertOffsetAndLength(offset, count);
ulong r = 0;
if (BitConverter.IsLittleEndian)
{
for (int i = 0; i < count; i++)
{
r |= (ulong)_buffer.Buffer[offset + i] << i * 8;
}
}
else
{
for (int i = 0; i < count; i++)
{
r |= (ulong)_buffer.Buffer[offset + count - 1 - i] << i * 8;
}
}
return r;
}
#endif // !UNSAFE_BYTEBUFFER
private void AssertOffsetAndLength(int offset, int length)
{
#if !BYTEBUFFER_NO_BOUNDS_CHECK
if (offset < 0 ||
offset > _buffer.Length - length)
throw new ArgumentOutOfRangeException();
#endif
}
#if ENABLE_SPAN_T
public void PutSbyte(int offset, sbyte value)
{
AssertOffsetAndLength(offset, sizeof(sbyte));
_buffer.Span[offset] = (byte)value;
}
public void PutByte(int offset, byte value)
{
AssertOffsetAndLength(offset, sizeof(byte));
_buffer.Span[offset] = value;
}
public void PutByte(int offset, byte value, int count)
{
AssertOffsetAndLength(offset, sizeof(byte) * count);
Span<byte> span = _buffer.Span.Slice(offset, count);
for (var i = 0; i < span.Length; ++i)
span[i] = value;
}
#else
public void PutSbyte(int offset, sbyte value)
{
AssertOffsetAndLength(offset, sizeof(sbyte));
_buffer.Buffer[offset] = (byte)value;
}
public void PutByte(int offset, byte value)
{
AssertOffsetAndLength(offset, sizeof(byte));
_buffer.Buffer[offset] = value;
}
public void PutByte(int offset, byte value, int count)
{
AssertOffsetAndLength(offset, sizeof(byte) * count);
for (var i = 0; i < count; ++i)
_buffer.Buffer[offset + i] = value;
}
#endif
// this method exists in order to conform with Java ByteBuffer standards
public void Put(int offset, byte value)
{
PutByte(offset, value);
}
#if ENABLE_SPAN_T
public unsafe void PutStringUTF8(int offset, string value)
{
AssertOffsetAndLength(offset, value.Length);
fixed (char* s = value)
{
fixed (byte* buffer = &MemoryMarshal.GetReference(_buffer.Span))
{
Encoding.UTF8.GetBytes(s, value.Length, buffer + offset, Length - offset);
}
}
}
#else
public void PutStringUTF8(int offset, string value)
{
AssertOffsetAndLength(offset, value.Length);
Encoding.UTF8.GetBytes(value, 0, value.Length,
_buffer.Buffer, offset);
}
#endif
#if UNSAFE_BYTEBUFFER
// Unsafe but more efficient versions of Put*.
public void PutShort(int offset, short value)
{
PutUshort(offset, (ushort)value);
}
public unsafe void PutUshort(int offset, ushort value)
{
AssertOffsetAndLength(offset, sizeof(ushort));
#if ENABLE_SPAN_T
Span<byte> span = _buffer.Span.Slice(offset);
BinaryPrimitives.WriteUInt16LittleEndian(span, value);
#else
fixed (byte* ptr = _buffer.Buffer)
{
*(ushort*)(ptr + offset) = BitConverter.IsLittleEndian
? value
: ReverseBytes(value);
}
#endif
}
public void PutInt(int offset, int value)
{
PutUint(offset, (uint)value);
}
public unsafe void PutUint(int offset, uint value)
{
AssertOffsetAndLength(offset, sizeof(uint));
#if ENABLE_SPAN_T
Span<byte> span = _buffer.Span.Slice(offset);
BinaryPrimitives.WriteUInt32LittleEndian(span, value);
#else
fixed (byte* ptr = _buffer.Buffer)
{
*(uint*)(ptr + offset) = BitConverter.IsLittleEndian
? value
: ReverseBytes(value);
}
#endif
}
public unsafe void PutLong(int offset, long value)
{
PutUlong(offset, (ulong)value);
}
public unsafe void PutUlong(int offset, ulong value)
{
AssertOffsetAndLength(offset, sizeof(ulong));
#if ENABLE_SPAN_T
Span<byte> span = _buffer.Span.Slice(offset);
BinaryPrimitives.WriteUInt64LittleEndian(span, value);
#else
fixed (byte* ptr = _buffer.Buffer)
{
*(ulong*)(ptr + offset) = BitConverter.IsLittleEndian
? value
: ReverseBytes(value);
}
#endif
}
public unsafe void PutFloat(int offset, float value)
{
AssertOffsetAndLength(offset, sizeof(float));
#if ENABLE_SPAN_T
fixed (byte* ptr = &MemoryMarshal.GetReference(_buffer.Span))
#else
fixed (byte* ptr = _buffer.Buffer)
#endif
{
if (BitConverter.IsLittleEndian)
{
*(float*)(ptr + offset) = value;
}
else
{
*(uint*)(ptr + offset) = ReverseBytes(*(uint*)(&value));
}
}
}
public unsafe void PutDouble(int offset, double value)
{
AssertOffsetAndLength(offset, sizeof(double));
#if ENABLE_SPAN_T
fixed (byte* ptr = &MemoryMarshal.GetReference(_buffer.Span))
#else
fixed (byte* ptr = _buffer.Buffer)
#endif
{
if (BitConverter.IsLittleEndian)
{
*(double*)(ptr + offset) = value;
}
else
{
*(ulong*)(ptr + offset) = ReverseBytes(*(ulong*)(&value));
}
}
}
#else // !UNSAFE_BYTEBUFFER
// Slower versions of Put* for when unsafe code is not allowed.
public void PutShort(int offset, short value)
{
AssertOffsetAndLength(offset, sizeof(short));
WriteLittleEndian(offset, sizeof(short), (ulong)value);
}
public void PutUshort(int offset, ushort value)
{
AssertOffsetAndLength(offset, sizeof(ushort));
WriteLittleEndian(offset, sizeof(ushort), (ulong)value);
}
public void PutInt(int offset, int value)
{
AssertOffsetAndLength(offset, sizeof(int));
WriteLittleEndian(offset, sizeof(int), (ulong)value);
}
public void PutUint(int offset, uint value)
{
AssertOffsetAndLength(offset, sizeof(uint));
WriteLittleEndian(offset, sizeof(uint), (ulong)value);
}
public void PutLong(int offset, long value)
{
AssertOffsetAndLength(offset, sizeof(long));
WriteLittleEndian(offset, sizeof(long), (ulong)value);
}
public void PutUlong(int offset, ulong value)
{
AssertOffsetAndLength(offset, sizeof(ulong));
WriteLittleEndian(offset, sizeof(ulong), value);
}
public void PutFloat(int offset, float value)
{
AssertOffsetAndLength(offset, sizeof(float));
// TODO(derekbailey): use BitConvert.SingleToInt32Bits() whenever flatbuffers upgrades to a .NET version
// that contains it.
ConversionUnion union;
union.intValue = 0;
union.floatValue = value;
WriteLittleEndian(offset, sizeof(float), (ulong)union.intValue);
}
public void PutDouble(int offset, double value)
{
AssertOffsetAndLength(offset, sizeof(double));
WriteLittleEndian(offset, sizeof(double), (ulong)BitConverter.DoubleToInt64Bits(value));
}
#endif // UNSAFE_BYTEBUFFER
#if ENABLE_SPAN_T
public sbyte GetSbyte(int index)
{
AssertOffsetAndLength(index, sizeof(sbyte));
return (sbyte)_buffer.ReadOnlySpan[index];
}
public byte Get(int index)
{
AssertOffsetAndLength(index, sizeof(byte));
return _buffer.ReadOnlySpan[index];
}
#else
public sbyte GetSbyte(int index)
{
AssertOffsetAndLength(index, sizeof(sbyte));
return (sbyte)_buffer.Buffer[index];
}
public byte Get(int index)
{
AssertOffsetAndLength(index, sizeof(byte));
return _buffer.Buffer[index];
}
#endif
#if ENABLE_SPAN_T
public unsafe string GetStringUTF8(int startPos, int len)
{
fixed (byte* buffer = &MemoryMarshal.GetReference(_buffer.ReadOnlySpan.Slice(startPos)))
{
return Encoding.UTF8.GetString(buffer, len);
}
}
#else
public string GetStringUTF8(int startPos, int len)
{
return Encoding.UTF8.GetString(_buffer.Buffer, startPos, len);
}
#endif
#if UNSAFE_BYTEBUFFER
// Unsafe but more efficient versions of Get*.
public short GetShort(int offset)
{
return (short)GetUshort(offset);
}
public unsafe ushort GetUshort(int offset)
{
AssertOffsetAndLength(offset, sizeof(ushort));
#if ENABLE_SPAN_T
ReadOnlySpan<byte> span = _buffer.ReadOnlySpan.Slice(offset);
return BinaryPrimitives.ReadUInt16LittleEndian(span);
#else
fixed (byte* ptr = _buffer.Buffer)
{
return BitConverter.IsLittleEndian
? *(ushort*)(ptr + offset)
: ReverseBytes(*(ushort*)(ptr + offset));
}
#endif
}
public int GetInt(int offset)
{
return (int)GetUint(offset);
}
public unsafe uint GetUint(int offset)
{
AssertOffsetAndLength(offset, sizeof(uint));
#if ENABLE_SPAN_T
ReadOnlySpan<byte> span = _buffer.ReadOnlySpan.Slice(offset);
return BinaryPrimitives.ReadUInt32LittleEndian(span);
#else
fixed (byte* ptr = _buffer.Buffer)
{
return BitConverter.IsLittleEndian
? *(uint*)(ptr + offset)
: ReverseBytes(*(uint*)(ptr + offset));
}
#endif
}
public long GetLong(int offset)
{
return (long)GetUlong(offset);
}
public unsafe ulong GetUlong(int offset)
{
AssertOffsetAndLength(offset, sizeof(ulong));
#if ENABLE_SPAN_T
ReadOnlySpan<byte> span = _buffer.ReadOnlySpan.Slice(offset);
return BinaryPrimitives.ReadUInt64LittleEndian(span);
#else
fixed (byte* ptr = _buffer.Buffer)
{
return BitConverter.IsLittleEndian
? *(ulong*)(ptr + offset)
: ReverseBytes(*(ulong*)(ptr + offset));
}
#endif
}
public unsafe float GetFloat(int offset)
{
AssertOffsetAndLength(offset, sizeof(float));
#if ENABLE_SPAN_T
fixed (byte* ptr = &MemoryMarshal.GetReference(_buffer.ReadOnlySpan))
#else
fixed (byte* ptr = _buffer.Buffer)
#endif
{
if (BitConverter.IsLittleEndian)
{
return *(float*)(ptr + offset);
}
else
{
uint uvalue = ReverseBytes(*(uint*)(ptr + offset));
return *(float*)(&uvalue);
}
}
}
public unsafe double GetDouble(int offset)
{
AssertOffsetAndLength(offset, sizeof(double));
#if ENABLE_SPAN_T
fixed (byte* ptr = &MemoryMarshal.GetReference(_buffer.ReadOnlySpan))
#else
fixed (byte* ptr = _buffer.Buffer)
#endif
{
if (BitConverter.IsLittleEndian)
{
return *(double*)(ptr + offset);
}
else
{
ulong uvalue = ReverseBytes(*(ulong*)(ptr + offset));
return *(double*)(&uvalue);
}
}
}
#else // !UNSAFE_BYTEBUFFER
// Slower versions of Get* for when unsafe code is not allowed.
public short GetShort(int index)
{
return (short)ReadLittleEndian(index, sizeof(short));
}
public ushort GetUshort(int index)
{
return (ushort)ReadLittleEndian(index, sizeof(ushort));
}
public int GetInt(int index)
{
return (int)ReadLittleEndian(index, sizeof(int));
}
public uint GetUint(int index)
{
return (uint)ReadLittleEndian(index, sizeof(uint));
}
public long GetLong(int index)
{
return (long)ReadLittleEndian(index, sizeof(long));
}
public ulong GetUlong(int index)
{
return ReadLittleEndian(index, sizeof(ulong));
}
public float GetFloat(int index)
{
// TODO(derekbailey): use BitConvert.Int32BitsToSingle() whenever flatbuffers upgrades to a .NET version
// that contains it.
ConversionUnion union;
union.floatValue = 0;
union.intValue = (int)ReadLittleEndian(index, sizeof(float));
return union.floatValue;
}
public double GetDouble(int index)
{
return BitConverter.Int64BitsToDouble((long)ReadLittleEndian(index, sizeof(double)));
}
#endif // UNSAFE_BYTEBUFFER
/// <summary>
/// Copies an array of type T into this buffer, ending at the given
/// offset into this buffer. The starting offset is calculated based on the length
/// of the array and is the value returned.
/// </summary>
/// <typeparam name="T">The type of the input data (must be a struct)</typeparam>
/// <param name="offset">The offset into this buffer where the copy will end</param>
/// <param name="x">The array to copy data from</param>
/// <returns>The 'start' location of this buffer now, after the copy completed</returns>
public int Put<T>(int offset, T[] x)
where T : struct
{
if (x == null)
{
throw new ArgumentNullException("Cannot put a null array");
}
if (x.Length == 0)
{
throw new ArgumentException("Cannot put an empty array");
}
if (!IsSupportedType<T>())
{
throw new ArgumentException("Cannot put an array of type "
+ typeof(T) + " into this buffer");
}
if (BitConverter.IsLittleEndian)
{
int numBytes = ByteBuffer.ArraySize(x);
offset -= numBytes;
AssertOffsetAndLength(offset, numBytes);
// if we are LE, just do a block copy
#if ENABLE_SPAN_T
MemoryMarshal.Cast<T, byte>(x).CopyTo(_buffer.Span.Slice(offset, numBytes));
#else
Buffer.BlockCopy(x, 0, _buffer.Buffer, offset, numBytes);
#endif
}
else
{
throw new NotImplementedException("Big Endian Support not implemented yet " +
"for putting typed arrays");
// if we are BE, we have to swap each element by itself
//for(int i = x.Length - 1; i >= 0; i--)
//{
// todo: low priority, but need to genericize the Put<T>() functions
//}
}
return offset;
}
#if ENABLE_SPAN_T
public int Put<T>(int offset, Span<T> x)
where T : struct
{
if (x.Length == 0)
{
throw new ArgumentException("Cannot put an empty array");
}
if (!IsSupportedType<T>())
{
throw new ArgumentException("Cannot put an array of type "
+ typeof(T) + " into this buffer");
}
if (BitConverter.IsLittleEndian)
{
int numBytes = ByteBuffer.ArraySize(x);
offset -= numBytes;
AssertOffsetAndLength(offset, numBytes);
// if we are LE, just do a block copy
MemoryMarshal.Cast<T, byte>(x).CopyTo(_buffer.Span.Slice(offset, numBytes));
}
else
{
throw new NotImplementedException("Big Endian Support not implemented yet " +
"for putting typed arrays");
// if we are BE, we have to swap each element by itself
//for(int i = x.Length - 1; i >= 0; i--)
//{
// todo: low priority, but need to genericize the Put<T>() functions
//}
}
return offset;
}
#endif
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace AgeRanger.Api.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using log4net;
using MySql.Data.MySqlClient;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Data;
namespace OpenSim.Data.MySQL
{
public class MySQLXAssetData : IXAssetDataPlugin
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
/// <summary>
/// Number of days that must pass before we update the access time on an asset when it has been fetched.
/// </summary>
private const int DaysBetweenAccessTimeUpdates = 30;
private bool m_enableCompression = false;
private string m_connectionString;
/// <summary>
/// We can reuse this for all hashing since all methods are single-threaded through m_dbBLock
/// </summary>
private HashAlgorithm hasher = new SHA256CryptoServiceProvider();
#region IPlugin Members
public string Version { get { return "1.0.0.0"; } }
/// <summary>
/// <para>Initialises Asset interface</para>
/// <para>
/// <list type="bullet">
/// <item>Loads and initialises the MySQL storage plugin.</item>
/// <item>Warns and uses the obsolete mysql_connection.ini if connect string is empty.</item>
/// <item>Check for migration</item>
/// </list>
/// </para>
/// </summary>
/// <param name="connect">connect string</param>
public void Initialise(string connect)
{
m_log.ErrorFormat("[MYSQL XASSETDATA]: ***********************************************************");
m_log.ErrorFormat("[MYSQL XASSETDATA]: ***********************************************************");
m_log.ErrorFormat("[MYSQL XASSETDATA]: ***********************************************************");
m_log.ErrorFormat("[MYSQL XASSETDATA]: THIS PLUGIN IS STRICTLY EXPERIMENTAL.");
m_log.ErrorFormat("[MYSQL XASSETDATA]: DO NOT USE FOR ANY DATA THAT YOU DO NOT MIND LOSING.");
m_log.ErrorFormat("[MYSQL XASSETDATA]: DATABASE TABLES CAN CHANGE AT ANY TIME, CAUSING EXISTING DATA TO BE LOST.");
m_log.ErrorFormat("[MYSQL XASSETDATA]: ***********************************************************");
m_log.ErrorFormat("[MYSQL XASSETDATA]: ***********************************************************");
m_log.ErrorFormat("[MYSQL XASSETDATA]: ***********************************************************");
m_connectionString = connect;
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
Migration m = new Migration(dbcon, Assembly, "XAssetStore");
m.Update();
}
}
public void Initialise()
{
throw new NotImplementedException();
}
public void Dispose() { }
/// <summary>
/// The name of this DB provider
/// </summary>
public string Name
{
get { return "MySQL XAsset storage engine"; }
}
#endregion
#region IAssetDataPlugin Members
/// <summary>
/// Fetch Asset <paramref name="assetID"/> from database
/// </summary>
/// <param name="assetID">Asset UUID to fetch</param>
/// <returns>Return the asset</returns>
/// <remarks>On failure : throw an exception and attempt to reconnect to database</remarks>
public AssetBase GetAsset(UUID assetID)
{
// m_log.DebugFormat("[MYSQL XASSET DATA]: Looking for asset {0}", assetID);
AssetBase asset = null;
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd = new MySqlCommand(
"SELECT Name, Description, AccessTime, AssetType, Local, Temporary, AssetFlags, CreatorID, Data FROM XAssetsMeta JOIN XAssetsData ON XAssetsMeta.Hash = XAssetsData.Hash WHERE ID=?ID",
dbcon))
{
cmd.Parameters.AddWithValue("?ID", assetID.ToString());
try
{
using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if (dbReader.Read())
{
asset = new AssetBase(assetID, (string)dbReader["Name"], (sbyte)dbReader["AssetType"], dbReader["CreatorID"].ToString());
asset.Data = (byte[])dbReader["Data"];
asset.Description = (string)dbReader["Description"];
string local = dbReader["Local"].ToString();
if (local.Equals("1") || local.Equals("true", StringComparison.InvariantCultureIgnoreCase))
asset.Local = true;
else
asset.Local = false;
asset.Temporary = Convert.ToBoolean(dbReader["Temporary"]);
asset.Flags = (AssetFlags)Convert.ToInt32(dbReader["AssetFlags"]);
if (m_enableCompression)
{
using (GZipStream decompressionStream = new GZipStream(new MemoryStream(asset.Data), CompressionMode.Decompress))
{
MemoryStream outputStream = new MemoryStream();
WebUtil.CopyStream(decompressionStream, outputStream, int.MaxValue);
// int compressedLength = asset.Data.Length;
asset.Data = outputStream.ToArray();
// m_log.DebugFormat(
// "[XASSET DB]: Decompressed {0} {1} to {2} bytes from {3}",
// asset.ID, asset.Name, asset.Data.Length, compressedLength);
}
}
UpdateAccessTime(asset.Metadata, (int)dbReader["AccessTime"]);
}
}
}
catch (Exception e)
{
m_log.Error(string.Format("[MYSQL XASSET DATA]: Failure fetching asset {0}", assetID), e);
}
}
}
return asset;
}
/// <summary>
/// Create an asset in database, or update it if existing.
/// </summary>
/// <param name="asset">Asset UUID to create</param>
/// <remarks>On failure : Throw an exception and attempt to reconnect to database</remarks>
public void StoreAsset(AssetBase asset)
{
// m_log.DebugFormat("[XASSETS DB]: Storing asset {0} {1}", asset.Name, asset.ID);
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlTransaction transaction = dbcon.BeginTransaction())
{
string assetName = asset.Name;
if (asset.Name.Length > AssetBase.MAX_ASSET_NAME)
{
assetName = asset.Name.Substring(0, AssetBase.MAX_ASSET_NAME);
m_log.WarnFormat(
"[XASSET DB]: Name '{0}' for asset {1} truncated from {2} to {3} characters on add",
asset.Name, asset.ID, asset.Name.Length, assetName.Length);
}
string assetDescription = asset.Description;
if (asset.Description.Length > AssetBase.MAX_ASSET_DESC)
{
assetDescription = asset.Description.Substring(0, AssetBase.MAX_ASSET_DESC);
m_log.WarnFormat(
"[XASSET DB]: Description '{0}' for asset {1} truncated from {2} to {3} characters on add",
asset.Description, asset.ID, asset.Description.Length, assetDescription.Length);
}
if (m_enableCompression)
{
MemoryStream outputStream = new MemoryStream();
using (GZipStream compressionStream = new GZipStream(outputStream, CompressionMode.Compress, false))
{
// Console.WriteLine(WebUtil.CopyTo(new MemoryStream(asset.Data), compressionStream, int.MaxValue));
// We have to close the compression stream in order to make sure it writes everything out to the underlying memory output stream.
compressionStream.Close();
byte[] compressedData = outputStream.ToArray();
asset.Data = compressedData;
}
}
byte[] hash = hasher.ComputeHash(asset.Data);
// m_log.DebugFormat(
// "[XASSET DB]: Compressed data size for {0} {1}, hash {2} is {3}",
// asset.ID, asset.Name, hash, compressedData.Length);
try
{
using (MySqlCommand cmd =
new MySqlCommand(
"replace INTO XAssetsMeta(ID, Hash, Name, Description, AssetType, Local, Temporary, CreateTime, AccessTime, AssetFlags, CreatorID)" +
"VALUES(?ID, ?Hash, ?Name, ?Description, ?AssetType, ?Local, ?Temporary, ?CreateTime, ?AccessTime, ?AssetFlags, ?CreatorID)",
dbcon))
{
// create unix epoch time
int now = (int)Utils.DateTimeToUnixTime(DateTime.UtcNow);
cmd.Parameters.AddWithValue("?ID", asset.ID);
cmd.Parameters.AddWithValue("?Hash", hash);
cmd.Parameters.AddWithValue("?Name", assetName);
cmd.Parameters.AddWithValue("?Description", assetDescription);
cmd.Parameters.AddWithValue("?AssetType", asset.Type);
cmd.Parameters.AddWithValue("?Local", asset.Local);
cmd.Parameters.AddWithValue("?Temporary", asset.Temporary);
cmd.Parameters.AddWithValue("?CreateTime", now);
cmd.Parameters.AddWithValue("?AccessTime", now);
cmd.Parameters.AddWithValue("?CreatorID", asset.Metadata.CreatorID);
cmd.Parameters.AddWithValue("?AssetFlags", (int)asset.Flags);
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_log.ErrorFormat("[ASSET DB]: MySQL failure creating asset metadata {0} with name \"{1}\". Error: {2}",
asset.FullID, asset.Name, e.Message);
transaction.Rollback();
return;
}
if (!ExistsData(dbcon, transaction, hash))
{
try
{
using (MySqlCommand cmd =
new MySqlCommand(
"INSERT INTO XAssetsData(Hash, Data) VALUES(?Hash, ?Data)",
dbcon))
{
cmd.Parameters.AddWithValue("?Hash", hash);
cmd.Parameters.AddWithValue("?Data", asset.Data);
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_log.ErrorFormat("[XASSET DB]: MySQL failure creating asset data {0} with name \"{1}\". Error: {2}",
asset.FullID, asset.Name, e.Message);
transaction.Rollback();
return;
}
}
transaction.Commit();
}
}
}
/// <summary>
/// Updates the access time of the asset if it was accessed above a given threshhold amount of time.
/// </summary>
/// <remarks>
/// This gives us some insight into assets which haven't ben accessed for a long period. This is only done
/// over the threshold time to avoid excessive database writes as assets are fetched.
/// </remarks>
/// <param name='asset'></param>
/// <param name='accessTime'></param>
private void UpdateAccessTime(AssetMetadata assetMetadata, int accessTime)
{
DateTime now = DateTime.UtcNow;
if ((now - Utils.UnixTimeToDateTime(accessTime)).TotalDays < DaysBetweenAccessTimeUpdates)
return;
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
MySqlCommand cmd =
new MySqlCommand("update XAssetsMeta set AccessTime=?AccessTime where ID=?ID", dbcon);
try
{
using (cmd)
{
// create unix epoch time
cmd.Parameters.AddWithValue("?ID", assetMetadata.ID);
cmd.Parameters.AddWithValue("?AccessTime", (int)Utils.DateTimeToUnixTime(now));
cmd.ExecuteNonQuery();
}
}
catch (Exception)
{
m_log.ErrorFormat(
"[XASSET MYSQL DB]: Failure updating access_time for asset {0} with name {1}",
assetMetadata.ID, assetMetadata.Name);
}
}
}
/// <summary>
/// We assume we already have the m_dbLock.
/// </summary>
/// TODO: need to actually use the transaction.
/// <param name="dbcon"></param>
/// <param name="transaction"></param>
/// <param name="hash"></param>
/// <returns></returns>
private bool ExistsData(MySqlConnection dbcon, MySqlTransaction transaction, byte[] hash)
{
// m_log.DebugFormat("[ASSETS DB]: Checking for asset {0}", uuid);
bool exists = false;
using (MySqlCommand cmd = new MySqlCommand("SELECT Hash FROM XAssetsData WHERE Hash=?Hash", dbcon))
{
cmd.Parameters.AddWithValue("?Hash", hash);
try
{
using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if (dbReader.Read())
{
// m_log.DebugFormat("[ASSETS DB]: Found asset {0}", uuid);
exists = true;
}
}
}
catch (Exception e)
{
m_log.ErrorFormat(
"[XASSETS DB]: MySql failure in ExistsData fetching hash {0}. Exception {1}{2}",
hash, e.Message, e.StackTrace);
}
}
return exists;
}
/// <summary>
/// Check if the assets exist in the database.
/// </summary>
/// <param name="uuids">The asset UUID's</param>
/// <returns>For each asset: true if it exists, false otherwise</returns>
public bool[] AssetsExist(UUID[] uuids)
{
if (uuids.Length == 0)
return new bool[0];
HashSet<UUID> exists = new HashSet<UUID>();
string ids = "'" + string.Join("','", uuids) + "'";
string sql = string.Format("SELECT ID FROM assets WHERE ID IN ({0})", ids);
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd = new MySqlCommand(sql, dbcon))
{
using (MySqlDataReader dbReader = cmd.ExecuteReader())
{
while (dbReader.Read())
{
UUID id = DBGuid.FromDB(dbReader["ID"]);
exists.Add(id);
}
}
}
}
bool[] results = new bool[uuids.Length];
for (int i = 0; i < uuids.Length; i++)
results[i] = exists.Contains(uuids[i]);
return results;
}
/// <summary>
/// Returns a list of AssetMetadata objects. The list is a subset of
/// the entire data set offset by <paramref name="start" /> containing
/// <paramref name="count" /> elements.
/// </summary>
/// <param name="start">The number of results to discard from the total data set.</param>
/// <param name="count">The number of rows the returned list should contain.</param>
/// <returns>A list of AssetMetadata objects.</returns>
public List<AssetMetadata> FetchAssetMetadataSet(int start, int count)
{
List<AssetMetadata> retList = new List<AssetMetadata>(count);
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using(MySqlCommand cmd = new MySqlCommand("SELECT Name, Description, AccessTime, AssetType, Temporary, ID, AssetFlags, CreatorID FROM XAssetsMeta LIMIT ?start, ?count",dbcon))
{
cmd.Parameters.AddWithValue("?start",start);
cmd.Parameters.AddWithValue("?count", count);
try
{
using (MySqlDataReader dbReader = cmd.ExecuteReader())
{
while (dbReader.Read())
{
AssetMetadata metadata = new AssetMetadata();
metadata.Name = (string)dbReader["Name"];
metadata.Description = (string)dbReader["Description"];
metadata.Type = (sbyte)dbReader["AssetType"];
metadata.Temporary = Convert.ToBoolean(dbReader["Temporary"]); // Not sure if this is correct.
metadata.Flags = (AssetFlags)Convert.ToInt32(dbReader["AssetFlags"]);
metadata.FullID = DBGuid.FromDB(dbReader["ID"]);
metadata.CreatorID = dbReader["CreatorID"].ToString();
// We'll ignore this for now - it appears unused!
// metadata.SHA1 = dbReader["hash"]);
UpdateAccessTime(metadata, (int)dbReader["AccessTime"]);
retList.Add(metadata);
}
}
}
catch (Exception e)
{
m_log.Error("[XASSETS DB]: MySql failure fetching asset set" + Environment.NewLine + e.ToString());
}
}
}
return retList;
}
public bool Delete(string id)
{
// m_log.DebugFormat("[XASSETS DB]: Deleting asset {0}", id);
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd = new MySqlCommand("delete from XAssetsMeta where ID=?ID", dbcon))
{
cmd.Parameters.AddWithValue("?ID", id);
cmd.ExecuteNonQuery();
}
// TODO: How do we deal with data from deleted assets? Probably not easily reapable unless we
// keep a reference count (?)
}
return true;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using WebApplication2.Areas.HelpPage.ModelDescriptions;
using WebApplication2.Areas.HelpPage.Models;
namespace WebApplication2.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System.Collections.Generic;
using System.Composition;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Text;
using Microsoft.Extensions.Configuration;
#if DNX451
using Microsoft.Extensions.FileSystemGlobbing;
#endif
using Microsoft.Extensions.Logging;
using Microsoft.Framework.DesignTimeHost.Models;
using Microsoft.Framework.DesignTimeHost.Models.IncomingMessages;
using Microsoft.Framework.DesignTimeHost.Models.OutgoingMessages;
using Newtonsoft.Json.Linq;
using OmniSharp.Models;
using OmniSharp.Models.v1;
using OmniSharp.Options;
using OmniSharp.Services;
using OmniSharp.Utilities;
namespace OmniSharp.Dnx
{
[Export(typeof(IProjectSystem)), Shared]
public class DnxProjectSystem : IProjectSystem
{
private readonly OmnisharpWorkspace _workspace;
private readonly IOmnisharpEnvironment _env;
private readonly ILogger _logger;
private readonly IMetadataFileReferenceCache _metadataFileReferenceCache;
private DnxPaths _dnxPaths;
private DesignTimeHostManager _designTimeHostManager;
private PackagesRestoreTool _packagesRestoreTool;
private DnxOptions _options;
private readonly DnxContext _context;
private readonly IFileSystemWatcher _watcher;
private readonly IEventEmitter _emitter;
private readonly DirectoryEnumerator _directoryEnumerator;
private readonly ILoggerFactory _loggerFactory;
[ImportingConstructor]
public DnxProjectSystem(OmnisharpWorkspace workspace,
IOmnisharpEnvironment env,
ILoggerFactory loggerFactory,
IMetadataFileReferenceCache metadataFileReferenceCache,
IApplicationLifetime lifetime,
IFileSystemWatcher watcher,
IEventEmitter emitter,
DnxContext context)
{
_workspace = workspace;
_env = env;
_loggerFactory = loggerFactory;
_logger = loggerFactory.CreateLogger<DnxProjectSystem>();
_metadataFileReferenceCache = metadataFileReferenceCache;
_context = context;
_watcher = watcher;
_emitter = emitter;
_directoryEnumerator = new DirectoryEnumerator(loggerFactory);
lifetime?.ApplicationStopping.Register(OnShutdown);
}
public string Key { get { return "Dnx"; } }
public string Language { get { return LanguageNames.CSharp; } }
public IEnumerable<string> Extensions { get; } = new[] { ".cs" };
public void Initalize(IConfiguration configuration)
{
_options = new DnxOptions();
ConfigurationBinder.Bind(configuration, _options);
_dnxPaths = new DnxPaths(_env, _options, _loggerFactory);
_packagesRestoreTool = new PackagesRestoreTool(_options, _emitter, _context, _dnxPaths); ;
_designTimeHostManager = new DesignTimeHostManager(_loggerFactory, _dnxPaths);
var runtimePath = _dnxPaths.RuntimePath;
_context.RuntimePath = runtimePath.Value;
_context.Options = _options;
if (!ScanForProjects())
{
// No DNX projects found so do nothing
_logger.LogInformation("No project.json based projects found");
return;
}
if (_context.RuntimePath == null)
{
// There is no default dnx found so do nothing
_logger.LogInformation("No default runtime found");
_emitter.Emit(EventTypes.Error, runtimePath.Error);
return;
}
var wh = new ManualResetEventSlim();
_designTimeHostManager.Start(_context.HostId, port =>
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(new IPEndPoint(IPAddress.Loopback, port));
var networkStream = new NetworkStream(socket);
_logger.LogInformation("Connected");
_context.DesignTimeHostPort = port;
_context.Connection = new ProcessingQueue(networkStream, _logger);
_context.Connection.OnReceive += m =>
{
var project = _context.Projects[m.ContextId];
if (m.MessageType == "ProjectInformation")
{
var val = m.Payload.ToObject<ProjectMessage>();
project.Name = val.Name;
project.GlobalJsonPath = val.GlobalJsonPath;
project.Configurations = val.Configurations;
project.Commands = val.Commands;
project.ProjectSearchPaths = val.ProjectSearchPaths;
this._emitter.Emit(EventTypes.ProjectChanged, new ProjectInformationResponse()
{
{nameof(DnxProject), new DnxProject(project)}
});
var unprocessed = project.ProjectsByFramework.Keys.ToList();
foreach (var frameworkData in val.Frameworks)
{
unprocessed.Remove(frameworkData.FrameworkName);
var frameworkProject = project.ProjectsByFramework.GetOrAdd(frameworkData.FrameworkName, framework =>
{
return new FrameworkProject(project, frameworkData);
});
var id = frameworkProject.ProjectId;
if (_workspace.CurrentSolution.ContainsProject(id))
{
continue;
}
else
{
var projectInfo = ProjectInfo.Create(
id,
VersionStamp.Create(),
val.Name + "+" + frameworkData.ShortName,
val.Name,
LanguageNames.CSharp,
project.Path);
_workspace.AddProject(projectInfo);
_context.WorkspaceMapping[id] = frameworkProject;
}
lock (frameworkProject.PendingProjectReferences)
{
var reference = new Microsoft.CodeAnalysis.ProjectReference(id);
foreach (var referenceId in frameworkProject.PendingProjectReferences)
{
_workspace.AddProjectReference(referenceId, reference);
}
frameworkProject.PendingProjectReferences.Clear();
}
}
// Remove old projects
foreach (var frameworkName in unprocessed)
{
FrameworkProject frameworkProject;
project.ProjectsByFramework.TryRemove(frameworkName, out frameworkProject);
_workspace.RemoveProject(frameworkProject.ProjectId);
}
}
// This is where we can handle messages and update the
// language service
else if (m.MessageType == "References")
{
// References as well as the dependency graph information
var val = m.Payload.ToObject<ReferencesMessage>();
var frameworkProject = project.ProjectsByFramework[val.Framework.FrameworkName];
var projectId = frameworkProject.ProjectId;
var metadataReferences = new List<MetadataReference>();
var projectReferences = new List<Microsoft.CodeAnalysis.ProjectReference>();
var removedFileReferences = frameworkProject.FileReferences.ToDictionary(p => p.Key, p => p.Value);
var removedRawReferences = frameworkProject.RawReferences.ToDictionary(p => p.Key, p => p.Value);
var removedProjectReferences = frameworkProject.ProjectReferences.ToDictionary(p => p.Key, p => p.Value);
foreach (var file in val.FileReferences)
{
if (removedFileReferences.Remove(file))
{
continue;
}
var metadataReference = _metadataFileReferenceCache.GetMetadataReference(file);
frameworkProject.FileReferences[file] = metadataReference;
metadataReferences.Add(metadataReference);
}
foreach (var rawReference in val.RawReferences)
{
if (removedRawReferences.Remove(rawReference.Key))
{
continue;
}
var metadataReference = MetadataReference.CreateFromImage(rawReference.Value);
frameworkProject.RawReferences[rawReference.Key] = metadataReference;
metadataReferences.Add(metadataReference);
}
foreach (var projectReference in val.ProjectReferences)
{
if (removedProjectReferences.Remove(projectReference.Path))
{
continue;
}
int projectReferenceContextId;
if (!_context.ProjectContextMapping.TryGetValue(projectReference.Path, out projectReferenceContextId))
{
projectReferenceContextId = AddProject(projectReference.Path);
}
var referencedProject = _context.Projects[projectReferenceContextId];
var referencedFrameworkProject = referencedProject.ProjectsByFramework.GetOrAdd(projectReference.Framework.FrameworkName,
framework =>
{
return new FrameworkProject(referencedProject, projectReference.Framework);
});
var projectReferenceId = referencedFrameworkProject.ProjectId;
if (_workspace.CurrentSolution.ContainsProject(projectReferenceId))
{
projectReferences.Add(new Microsoft.CodeAnalysis.ProjectReference(projectReferenceId));
}
else
{
lock (referencedFrameworkProject.PendingProjectReferences)
{
referencedFrameworkProject.PendingProjectReferences.Add(projectId);
}
}
referencedFrameworkProject.ProjectDependeees[project.Path] = projectId;
frameworkProject.ProjectReferences[projectReference.Path] = projectReferenceId;
}
foreach (var reference in metadataReferences)
{
_workspace.AddMetadataReference(projectId, reference);
}
foreach (var projectReference in projectReferences)
{
_workspace.AddProjectReference(projectId, projectReference);
}
foreach (var pair in removedProjectReferences)
{
_workspace.RemoveProjectReference(projectId, new Microsoft.CodeAnalysis.ProjectReference(pair.Value));
frameworkProject.ProjectReferences.Remove(pair.Key);
// TODO: Update the dependee's list
}
foreach (var pair in removedFileReferences)
{
_workspace.RemoveMetadataReference(projectId, pair.Value);
frameworkProject.FileReferences.Remove(pair.Key);
}
foreach (var pair in removedRawReferences)
{
_workspace.RemoveMetadataReference(projectId, pair.Value);
frameworkProject.RawReferences.Remove(pair.Key);
}
}
else if (m.MessageType == "Dependencies")
{
var val = m.Payload.ToObject<DependenciesMessage>();
var unresolvedDependencies = val.Dependencies.Values
.Where(dep => dep.Type == "Unresolved");
if (unresolvedDependencies.Any())
{
_logger.LogInformation("Project {0} has these unresolved references: {1}", project.Path, string.Join(", ", unresolvedDependencies.Select(d => d.Name)));
_emitter.Emit(EventTypes.UnresolvedDependencies, new UnresolvedDependenciesMessage()
{
FileName = project.Path,
UnresolvedDependencies = unresolvedDependencies.Select(d => new PackageDependency() { Name = d.Name, Version = d.Version })
});
_packagesRestoreTool.Run(project);
}
}
else if (m.MessageType == "CompilerOptions")
{
// Configuration and compiler options
var val = m.Payload.ToObject<CompilationOptionsMessage>();
var projectId = project.ProjectsByFramework[val.Framework.FrameworkName].ProjectId;
var options = val.CompilationOptions.CompilationOptions;
var specificDiagnosticOptions = options.SpecificDiagnosticOptions
.ToDictionary(p => p.Key, p => (ReportDiagnostic)p.Value);
var csharpOptions = new CSharpCompilationOptions(
outputKind: (OutputKind)options.OutputKind,
optimizationLevel: (OptimizationLevel)options.OptimizationLevel,
platform: (Platform)options.Platform,
generalDiagnosticOption: (ReportDiagnostic)options.GeneralDiagnosticOption,
warningLevel: options.WarningLevel,
allowUnsafe: options.AllowUnsafe,
concurrentBuild: options.ConcurrentBuild,
specificDiagnosticOptions: specificDiagnosticOptions
);
var parseOptions = new CSharpParseOptions(val.CompilationOptions.LanguageVersion,
preprocessorSymbols: val.CompilationOptions.Defines);
_workspace.SetCompilationOptions(projectId, csharpOptions);
_workspace.SetParseOptions(projectId, parseOptions);
}
else if (m.MessageType == "Sources")
{
// The sources to feed to the language service
var val = m.Payload.ToObject<SourcesMessage>();
project.SourceFiles = val.Files
.Where(fileName => Path.GetExtension(fileName) == ".cs")
.ToList();
var frameworkProject = project.ProjectsByFramework[val.Framework.FrameworkName];
var projectId = frameworkProject.ProjectId;
var unprocessed = new HashSet<string>(frameworkProject.Documents.Keys);
foreach (var file in project.SourceFiles)
{
if (unprocessed.Remove(file))
{
continue;
}
using (var stream = File.OpenRead(file))
{
var sourceText = SourceText.From(stream, encoding: Encoding.UTF8);
var id = DocumentId.CreateNewId(projectId);
var version = VersionStamp.Create();
frameworkProject.Documents[file] = id;
var loader = TextLoader.From(TextAndVersion.Create(sourceText, version));
_workspace.AddDocument(DocumentInfo.Create(id, file, filePath: file, loader: loader));
}
}
foreach (var file in unprocessed)
{
var docId = frameworkProject.Documents[file];
frameworkProject.Documents.Remove(file);
_workspace.RemoveDocument(docId);
}
frameworkProject.Loaded = true;
}
else if (m.MessageType == "Error")
{
var val = m.Payload.ToObject<Microsoft.Framework.DesignTimeHost.Models.OutgoingMessages.ErrorMessage>();
_logger.LogError(val.Message);
}
if (project.ProjectsByFramework.Values.All(p => p.Loaded))
{
wh.Set();
}
};
// Start the message channel
_context.Connection.Start();
// Initialize the DNX projects
Initialize();
});
wh.Wait();
}
public Project GetProject(string path)
{
int contextId;
if (!_context.ProjectContextMapping.TryGetValue(path, out contextId))
{
return null;
}
return _context.Projects[contextId];
}
private void OnShutdown()
{
_designTimeHostManager.Stop();
}
private void TriggerDependeees(string path, string messageType)
{
// temp: run [dnu|kpm] restore when project.json changed
var project = GetProject(path);
if (project != null)
{
_packagesRestoreTool.Run(project);
}
var seen = new HashSet<string>();
var results = new HashSet<int>();
var stack = new Stack<string>();
stack.Push(path);
while (stack.Count > 0)
{
var projectPath = stack.Pop();
if (!seen.Add(projectPath))
{
continue;
}
int contextId;
if (_context.ProjectContextMapping.TryGetValue(projectPath, out contextId))
{
results.Add(contextId);
foreach (var frameworkProject in _context.Projects[contextId].ProjectsByFramework.Values)
{
foreach (var dependee in frameworkProject.ProjectDependeees.Keys)
{
stack.Push(dependee);
}
}
}
}
foreach (var contextId in results)
{
var message = new Message();
message.HostId = _context.HostId;
message.ContextId = contextId;
message.MessageType = messageType;
_context.Connection.Post(message);
}
}
private void WatchProject(string projectFile)
{
// Whenever the project file changes, trigger FilesChanged to the design time host
// and all dependendees of the project. That means if A -> B -> C
// if C changes, notify A and B
_watcher.Watch(projectFile, path => TriggerDependeees(path, "FilesChanged"));
// When the project.lock.json file changes, refresh dependencies
var lockFile = Path.ChangeExtension(projectFile, "lock.json");
_watcher.Watch(lockFile, _ => TriggerDependeees(projectFile, "RefreshDependencies"));
}
private void Initialize()
{
foreach (var project in _context.Projects.Values)
{
if (project.InitializeSent)
{
continue;
}
WatchProject(project.Path);
var projectDirectory = Path.GetDirectoryName(project.Path).TrimEnd(Path.DirectorySeparatorChar);
// Send an InitializeMessage for each project
var initializeMessage = new InitializeMessage
{
ProjectFolder = projectDirectory,
};
// Initialize this project
_context.Connection.Post(new Message
{
ContextId = project.ContextId,
MessageType = "Initialize",
Payload = JToken.FromObject(initializeMessage),
HostId = _context.HostId
});
project.InitializeSent = true;
}
}
private int AddProject(string projectFile)
{
Project project;
if (!_context.TryAddProject(projectFile, out project))
{
return project.ContextId;
}
WatchProject(projectFile);
// Send an InitializeMessage for each project
var initializeMessage = new InitializeMessage
{
ProjectFolder = Path.GetDirectoryName(projectFile),
};
// Initialize this project
_context.Connection.Post(new Message
{
ContextId = project.ContextId,
MessageType = "Initialize",
Payload = JToken.FromObject(initializeMessage),
HostId = _context.HostId
});
project.InitializeSent = true;
return project.ContextId;
}
private bool ScanForProjects()
{
_logger.LogInformation(string.Format("Scanning '{0}' for DNX projects", _env.Path));
var anyProjects = false;
// Single project in this folder
var projectInThisFolder = Path.Combine(_env.Path, "project.json");
if (File.Exists(projectInThisFolder))
{
if (_context.TryAddProject(projectInThisFolder))
{
_logger.LogInformation(string.Format("Found project '{0}'.", projectInThisFolder));
anyProjects = true;
}
}
else
{
IEnumerable<string> paths;
#if DNX451
if (_options.Projects != "**/project.json")
{
var matcher = new Matcher();
matcher.AddIncludePatterns(_options.Projects.Split(';'));
paths = matcher.GetResultsInFullPath(_env.Path);
}
else
{
paths = _directoryEnumerator.SafeEnumerateFiles(_env.Path, "project.json");
}
#else
// The matcher works on CoreCLR but Omnisharp still targets aspnetcore50 instead of
// dnxcore50
paths = _directoryEnumerator.SafeEnumerateFiles(_env.Path, "project.json");
#endif
foreach (var path in paths)
{
string projectFile = null;
if (Path.GetFileName(path) == "project.json")
{
projectFile = path;
}
else
{
projectFile = Path.Combine(path, "project.json");
if (!File.Exists(projectFile))
{
projectFile = null;
}
}
if (string.IsNullOrEmpty(projectFile))
{
continue;
}
if (!_context.TryAddProject(projectFile))
{
continue;
}
_logger.LogInformation(string.Format("Found project '{0}'.", projectFile));
anyProjects = true;
}
}
return anyProjects;
}
private static Task ConnectAsync(Socket socket, IPEndPoint endPoint)
{
#if DNX451
return Task.Factory.FromAsync((cb, state) => socket.BeginConnect(endPoint, cb, state), ar => socket.EndConnect(ar), null);
#else
return Task.Run(() => socket.Connect(endPoint));
#endif
}
Task<object> IProjectSystem.GetProjectModel(string path)
{
var document = _workspace.GetDocument(path);
if (document == null)
return Task.FromResult<object>(null);
var project = GetProject(document.Project.FilePath);
if (project == null)
return Task.FromResult<object>(null);
return Task.FromResult<object>(new DnxProject(project));
}
Task<object> IProjectSystem.GetInformationModel(WorkspaceInformationRequest request)
{
return Task.FromResult<object>(new DnxWorkspaceInformation(_context));
}
}
}
| |
using System;
using UnityEngine;
namespace UnityStandardAssets.ImageEffects
{
[ExecuteInEditMode]
[RequireComponent(typeof (Camera))]
[AddComponentMenu("Image Effects/Color Adjustments/Tonemapping")]
public class Tonemapping : PostEffectsBase
{
public enum TonemapperType
{
SimpleReinhard,
UserCurve,
Hable,
Photographic,
OptimizedHejiDawson,
AdaptiveReinhard,
AdaptiveReinhardAutoWhite,
};
public enum AdaptiveTexSize
{
Square16 = 16,
Square32 = 32,
Square64 = 64,
Square128 = 128,
Square256 = 256,
Square512 = 512,
Square1024 = 1024,
};
public TonemapperType type = TonemapperType.Photographic;
public AdaptiveTexSize adaptiveTextureSize = AdaptiveTexSize.Square256;
// CURVE parameter
public AnimationCurve remapCurve;
private Texture2D curveTex = null;
// UNCHARTED parameter
public float exposureAdjustment = 1.5f;
// REINHARD parameter
public float middleGrey = 0.4f;
public float white = 2.0f;
public float adaptionSpeed = 1.5f;
// usual & internal stuff
public Shader tonemapper = null;
public bool validRenderTextureFormat = true;
private Material tonemapMaterial = null;
private RenderTexture rt = null;
private RenderTextureFormat rtFormat = RenderTextureFormat.ARGBHalf;
public override bool CheckResources()
{
CheckSupport(false, true);
tonemapMaterial = CheckShaderAndCreateMaterial(tonemapper, tonemapMaterial);
if (!curveTex && type == TonemapperType.UserCurve)
{
curveTex = new Texture2D(256, 1, TextureFormat.ARGB32, false, true);
curveTex.filterMode = FilterMode.Bilinear;
curveTex.wrapMode = TextureWrapMode.Clamp;
curveTex.hideFlags = HideFlags.DontSave;
}
if (!isSupported)
ReportAutoDisable();
return isSupported;
}
public float UpdateCurve()
{
float range = 1.0f;
if (remapCurve.keys.Length < 1)
remapCurve = new AnimationCurve(new Keyframe(0, 0), new Keyframe(2, 1));
if (remapCurve != null)
{
if (remapCurve.length > 0)
range = remapCurve[remapCurve.length - 1].time;
for (float i = 0.0f; i <= 1.0f; i += 1.0f/255.0f)
{
float c = remapCurve.Evaluate(i*1.0f*range);
curveTex.SetPixel((int) Mathf.Floor(i*255.0f), 0, new Color(c, c, c));
}
curveTex.Apply();
}
return 1.0f/range;
}
private void OnDisable()
{
if (rt)
{
DestroyImmediate(rt);
rt = null;
}
if (tonemapMaterial)
{
DestroyImmediate(tonemapMaterial);
tonemapMaterial = null;
}
if (curveTex)
{
DestroyImmediate(curveTex);
curveTex = null;
}
}
private bool CreateInternalRenderTexture()
{
if (rt)
{
return false;
}
rtFormat = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.RGHalf) ? RenderTextureFormat.RGHalf : RenderTextureFormat.ARGBHalf;
rt = new RenderTexture(1, 1, 0, rtFormat);
rt.hideFlags = HideFlags.DontSave;
return true;
}
// attribute indicates that the image filter chain will continue in LDR
[ImageEffectTransformsToLDR]
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (CheckResources() == false)
{
Graphics.Blit(source, destination);
return;
}
#if UNITY_EDITOR
validRenderTextureFormat = true;
if (source.format != RenderTextureFormat.ARGBHalf)
{
validRenderTextureFormat = false;
}
#endif
// clamp some values to not go out of a valid range
exposureAdjustment = exposureAdjustment < 0.001f ? 0.001f : exposureAdjustment;
// SimpleReinhard tonemappers (local, non adaptive)
if (type == TonemapperType.UserCurve)
{
float rangeScale = UpdateCurve();
tonemapMaterial.SetFloat("_RangeScale", rangeScale);
tonemapMaterial.SetTexture("_Curve", curveTex);
Graphics.Blit(source, destination, tonemapMaterial, 4);
return;
}
if (type == TonemapperType.SimpleReinhard)
{
tonemapMaterial.SetFloat("_ExposureAdjustment", exposureAdjustment);
Graphics.Blit(source, destination, tonemapMaterial, 6);
return;
}
if (type == TonemapperType.Hable)
{
tonemapMaterial.SetFloat("_ExposureAdjustment", exposureAdjustment);
Graphics.Blit(source, destination, tonemapMaterial, 5);
return;
}
if (type == TonemapperType.Photographic)
{
tonemapMaterial.SetFloat("_ExposureAdjustment", exposureAdjustment);
Graphics.Blit(source, destination, tonemapMaterial, 8);
return;
}
if (type == TonemapperType.OptimizedHejiDawson)
{
tonemapMaterial.SetFloat("_ExposureAdjustment", 0.5f*exposureAdjustment);
Graphics.Blit(source, destination, tonemapMaterial, 7);
return;
}
// still here?
// => adaptive tone mapping:
// builds an average log luminance, tonemaps according to
// middle grey and white values (user controlled)
// AdaptiveReinhardAutoWhite will calculate white value automagically
bool freshlyBrewedInternalRt = CreateInternalRenderTexture(); // this retrieves rtFormat, so should happen before rt allocations
RenderTexture rtSquared = RenderTexture.GetTemporary((int) adaptiveTextureSize, (int) adaptiveTextureSize, 0, rtFormat);
Graphics.Blit(source, rtSquared);
int downsample = (int) Mathf.Log(rtSquared.width*1.0f, 2);
int div = 2;
var rts = new RenderTexture[downsample];
for (int i = 0; i < downsample; i++)
{
rts[i] = RenderTexture.GetTemporary(rtSquared.width/div, rtSquared.width/div, 0, rtFormat);
div *= 2;
}
// downsample pyramid
var lumRt = rts[downsample - 1];
Graphics.Blit(rtSquared, rts[0], tonemapMaterial, 1);
if (type == TonemapperType.AdaptiveReinhardAutoWhite)
{
for (int i = 0; i < downsample - 1; i++)
{
Graphics.Blit(rts[i], rts[i + 1], tonemapMaterial, 9);
lumRt = rts[i + 1];
}
}
else if (type == TonemapperType.AdaptiveReinhard)
{
for (int i = 0; i < downsample - 1; i++)
{
Graphics.Blit(rts[i], rts[i + 1]);
lumRt = rts[i + 1];
}
}
// we have the needed values, let's apply adaptive tonemapping
adaptionSpeed = adaptionSpeed < 0.001f ? 0.001f : adaptionSpeed;
tonemapMaterial.SetFloat("_AdaptionSpeed", adaptionSpeed);
rt.MarkRestoreExpected(); // keeping luminance values between frames, RT restore expected
#if UNITY_EDITOR
if (Application.isPlaying && !freshlyBrewedInternalRt)
Graphics.Blit(lumRt, rt, tonemapMaterial, 2);
else
Graphics.Blit(lumRt, rt, tonemapMaterial, 3);
#else
Graphics.Blit (lumRt, rt, tonemapMaterial, freshlyBrewedInternalRt ? 3 : 2);
#endif
middleGrey = middleGrey < 0.001f ? 0.001f : middleGrey;
tonemapMaterial.SetVector("_HdrParams", new Vector4(middleGrey, middleGrey, middleGrey, white*white));
tonemapMaterial.SetTexture("_SmallTex", rt);
if (type == TonemapperType.AdaptiveReinhard)
{
Graphics.Blit(source, destination, tonemapMaterial, 0);
}
else if (type == TonemapperType.AdaptiveReinhardAutoWhite)
{
Graphics.Blit(source, destination, tonemapMaterial, 10);
}
else
{
Debug.LogError("No valid adaptive tonemapper type found!");
Graphics.Blit(source, destination); // at least we get the TransformToLDR effect
}
// cleanup for adaptive
for (int i = 0; i < downsample; i++)
{
RenderTexture.ReleaseTemporary(rts[i]);
}
RenderTexture.ReleaseTemporary(rtSquared);
}
}
}
| |
// 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.Linq;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
public class HttpClientMiniStress
{
private static bool HttpStressEnabled => Environment.GetEnvironmentVariable("HTTP_STRESS") == "1";
[ConditionalTheory(nameof(HttpStressEnabled))]
[MemberData(nameof(GetStressOptions))]
public void SingleClient_ManyGets_Sync(int numRequests, int dop, HttpCompletionOption completionOption)
{
string responseText = CreateResponse("abcdefghijklmnopqrstuvwxyz");
using (var client = new HttpClient())
{
Parallel.For(0, numRequests, new ParallelOptions { MaxDegreeOfParallelism = dop, TaskScheduler = new ThreadPerTaskScheduler() }, _ =>
{
CreateServerAndGet(client, completionOption, responseText);
});
}
}
[ConditionalTheory(nameof(HttpStressEnabled))]
public async Task SingleClient_ManyGets_Async(int numRequests, int dop, HttpCompletionOption completionOption)
{
string responseText = CreateResponse("abcdefghijklmnopqrstuvwxyz");
using (var client = new HttpClient())
{
await ForCountAsync(numRequests, dop, i => CreateServerAndGetAsync(client, completionOption, responseText));
}
}
[ConditionalTheory(nameof(HttpStressEnabled))]
[MemberData(nameof(GetStressOptions))]
public void ManyClients_ManyGets(int numRequests, int dop, HttpCompletionOption completionOption)
{
string responseText = CreateResponse("abcdefghijklmnopqrstuvwxyz");
Parallel.For(0, numRequests, new ParallelOptions { MaxDegreeOfParallelism = dop, TaskScheduler = new ThreadPerTaskScheduler() }, _ =>
{
using (var client = new HttpClient())
{
CreateServerAndGet(client, completionOption, responseText);
}
});
}
[ConditionalTheory(nameof(HttpStressEnabled))]
[MemberData(nameof(PostStressOptions))]
public async Task ManyClients_ManyPosts_Async(int numRequests, int dop, int numBytes)
{
string responseText = CreateResponse("");
await ForCountAsync(numRequests, dop, async i =>
{
using (HttpClient client = new HttpClient())
{
await CreateServerAndPostAsync(client, numBytes, responseText);
}
});
}
[ConditionalTheory(nameof(HttpStressEnabled))]
[InlineData(1000000)]
public void CreateAndDestroyManyClients(int numClients)
{
for (int i = 0; i < numClients; i++)
{
new HttpClient().Dispose();
}
}
[ConditionalTheory(nameof(HttpStressEnabled))]
[InlineData(5000)]
public async Task MakeAndFaultManyRequests(int numRequests)
{
await LoopbackServer.CreateClientAndServerAsync(async (handler, client, server, url) =>
{
client.Timeout = Timeout.InfiniteTimeSpan;
var ep = (IPEndPoint)server.LocalEndPoint;
Task<string>[] tasks =
(from i in Enumerable.Range(0, numRequests)
select client.GetStringAsync($"http://{ep.Address}:{ep.Port}"))
.ToArray();
Assert.All(tasks, t => Assert.Equal(TaskStatus.WaitingForActivation, t.Status));
server.Dispose();
foreach (Task<string> task in tasks)
{
await Assert.ThrowsAnyAsync<HttpRequestException>(() => task);
}
}, backlog: numRequests);
}
public static IEnumerable<object[]> GetStressOptions()
{
foreach (int numRequests in new[] { 5000 }) // number of requests
foreach (int dop in new[] { 1, 32 }) // number of threads
foreach (var completionoption in new[] { HttpCompletionOption.ResponseContentRead, HttpCompletionOption.ResponseHeadersRead })
yield return new object[] { numRequests, dop, completionoption };
}
private static void CreateServerAndGet(HttpClient client, HttpCompletionOption completionOption, string responseText)
{
LoopbackServer.CreateServerAsync((server, url) =>
{
Task<HttpResponseMessage> getAsync = client.GetAsync(url, completionOption);
LoopbackServer.AcceptSocketAsync(server, (s, stream, reader, writer) =>
{
while (!string.IsNullOrEmpty(reader.ReadLine())) ;
writer.Write(responseText);
writer.Flush();
s.Shutdown(SocketShutdown.Send);
return Task.CompletedTask;
}).GetAwaiter().GetResult();
getAsync.GetAwaiter().GetResult().Dispose();
return Task.CompletedTask;
}).GetAwaiter().GetResult();
}
private static async Task CreateServerAndGetAsync(HttpClient client, HttpCompletionOption completionOption, string responseText)
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
Task<HttpResponseMessage> getAsync = client.GetAsync(url, completionOption);
await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) =>
{
while (!string.IsNullOrEmpty(await reader.ReadLineAsync().ConfigureAwait(false))) ;
await writer.WriteAsync(responseText).ConfigureAwait(false);
await writer.FlushAsync().ConfigureAwait(false);
s.Shutdown(SocketShutdown.Send);
});
(await getAsync.ConfigureAwait(false)).Dispose();
});
}
public static IEnumerable<object[]> PostStressOptions()
{
foreach (int numRequests in new[] { 5000 }) // number of requests
foreach (int dop in new[] { 1, 32 }) // number of threads
foreach (int numBytes in new[] { 0, 100 }) // number of bytes to post
yield return new object[] { numRequests, dop, numBytes };
}
private static async Task CreateServerAndPostAsync(HttpClient client, int numBytes, string responseText)
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
var content = new ByteArrayContent(new byte[numBytes]);
Task<HttpResponseMessage> postAsync = client.PostAsync(url, content);
await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) =>
{
while (!string.IsNullOrEmpty(await reader.ReadLineAsync().ConfigureAwait(false))) ;
for (int i = 0; i < numBytes; i++) Assert.NotEqual(-1, reader.Read());
await writer.WriteAsync(responseText).ConfigureAwait(false);
await writer.FlushAsync().ConfigureAwait(false);
s.Shutdown(SocketShutdown.Send);
});
(await postAsync.ConfigureAwait(false)).Dispose();
});
}
[ConditionalFact(nameof(HttpStressEnabled))]
public async Task UnreadResponseMessage_Collectible()
{
await LoopbackServer.CreateClientAndServerAsync(async (handler, client, server, url) =>
{
Func<Task<WeakReference>> getAsync = async () =>
new WeakReference(await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead));
Task<WeakReference> wrt = getAsync();
await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) =>
{
while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) ;
await writer.WriteAsync(CreateResponse(new string('a', 32 * 1024)));
await writer.FlushAsync();
WeakReference wr = wrt.GetAwaiter().GetResult();
Assert.True(SpinWait.SpinUntil(() =>
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
return !wr.IsAlive;
}, 10 * 1000), "Response object should have been collected");
});
});
}
private static string CreateResponse(string asciiBody) =>
$"HTTP/1.1 200 OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
"Content-Type: text/plain\r\n" +
"Content-Length: {asciiBody.Length}\r\n" +
"\r\n" +
"{asciiBody}\r\n";
private static Task ForCountAsync(int count, int dop, Func<int, Task> bodyAsync)
{
var sched = new ThreadPerTaskScheduler();
int nextAvailableIndex = 0;
return Task.WhenAll(Enumerable.Range(0, dop).Select(_ => Task.Factory.StartNew(async delegate
{
int index;
while ((index = Interlocked.Increment(ref nextAvailableIndex) - 1) < count)
{
try { await bodyAsync(index); }
catch
{
Volatile.Write(ref nextAvailableIndex, count); // avoid any further iterations
throw;
}
}
}, CancellationToken.None, TaskCreationOptions.None, sched).Unwrap()));
}
private sealed class ThreadPerTaskScheduler : TaskScheduler
{
protected override void QueueTask(Task task) =>
Task.Factory.StartNew(() => TryExecuteTask(task), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) => TryExecuteTask(task);
protected override IEnumerable<Task> GetScheduledTasks() => null;
}
}
}
| |
/* 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:
*
* * 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Security.Permissions;
using System.Windows.Forms;
using XenAdmin.Controls;
using XenAdmin.Core;
using Message = System.Windows.Forms.Message;
using System.Runtime.InteropServices;
namespace XenAdmin.Controls
{
public partial class SnapshotTreeView : ListView
{
private const int straightLineLength = 8;
private SnapshotIcon root;
//We need this fake thing to make the scrollbars work with the customdrawdate.
private ListViewItem whiteIcon = new ListViewItem();
private Color linkLineColor = SystemColors.ControlDark;
private float linkLineWidth = 2.0f;
private int hGap = 50;
private int vGap = 20;
private readonly CustomLineCap linkLineArrow = new AdjustableArrowCap(4f, 4f, true);
#region Properties
[Browsable(true), Category("Appearance"), Description("Color used to draw connecting lines")]
[DefaultValue(typeof(Color), "ControlDark")]
public Color LinkLineColor
{
get { return linkLineColor; }
set
{
linkLineColor = value;
Invalidate();
}
}
[Browsable(true), Category("Appearance"), Description("Width of connecting lines")]
[DefaultValue(2.0f)]
public float LinkLineWidth
{
get { return linkLineWidth; }
set
{
linkLineWidth = value;
Invalidate();
}
}
[Browsable(true), Category("Appearance"), Description("Horizontal gap between icons")]
[DefaultValue(50)]
public int HGap
{
get { return hGap; }
set
{
if (value < 4 * straightLineLength)
value = 4 * straightLineLength;
hGap = value;
PerformLayout(this, "HGap");
}
}
[Browsable(true), Category("Appearance"), Description("Vertical gap between icons")]
[DefaultValue(20)]
public int VGap
{
get { return vGap; }
set
{
if (value < 0)
value = 0;
vGap = value;
PerformLayout(this, "VGap");
}
}
#endregion
private ImageList imageList = new ImageList();
public SnapshotTreeView(IContainer container)
{
if (container == null)
throw new ArgumentNullException("container");
container.Add(this);
InitializeComponent();
DoubleBuffered = true;
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
base.Items.Add(whiteIcon);
//Init image list
imageList.ColorDepth = ColorDepth.Depth32Bit;
imageList.ImageSize=new Size(32,32);
imageList.Images.Add(Properties.Resources._000_HighLightVM_h32bit_32);
imageList.Images.Add(Properties.Resources.VMTemplate_h32bit_32);
imageList.Images.Add(Properties.Resources.VMTemplate_h32bit_32);
imageList.Images.Add(Properties.Resources._000_VMSnapShotDiskOnly_h32bit_32);
imageList.Images.Add(Properties.Resources._000_VMSnapshotDiskMemory_h32bit_32);
imageList.Images.Add(Properties.Resources._000_ScheduledVMsnapshotDiskOnly_h32bit_32);
imageList.Images.Add(Properties.Resources._000_ScheduledVMSnapshotDiskMemory_h32bit_32);
imageList.Images.Add(Properties.Resources.SpinningFrame0);
imageList.Images.Add(Properties.Resources.SpinningFrame1);
imageList.Images.Add(Properties.Resources.SpinningFrame2);
imageList.Images.Add(Properties.Resources.SpinningFrame3);
imageList.Images.Add(Properties.Resources.SpinningFrame4);
imageList.Images.Add(Properties.Resources.SpinningFrame5);
imageList.Images.Add(Properties.Resources.SpinningFrame6);
imageList.Images.Add(Properties.Resources.SpinningFrame7);
this.LargeImageList = imageList;
}
[SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters",
MessageId = "System.InvalidOperationException.#ctor(System.String)",
Justification = "Indicates a programming error - not user facing")]
internal ListViewItem AddSnapshot(SnapshotIcon snapshot)
{
if (snapshot == null)
throw new ArgumentNullException("snapshot");
if (snapshot.Parent != null)
{
snapshot.Parent.AddChild(snapshot);
snapshot.Parent.Invalidate();
}
else if (root != null)
{
throw new InvalidOperationException("Adding a new root!");
}
else
{
root = snapshot;
}
if (snapshot.ImageIndex == SnapshotIcon.VMImageIndex)
{
//Sort all the parents of the VM to make the path to the VM the first one.
SnapshotIcon current = snapshot;
while (current.Parent != null)
{
if (current.Parent.Children.Count > 1)
{
int indexCurrent = current.Parent.Children.IndexOf(current);
SnapshotIcon temp = current.Parent.Children[0];
current.Parent.Children[0] = current;
current.Parent.Children[indexCurrent] = temp;
}
current.IsInVMBranch = true;
current = current.Parent;
}
}
ListViewItem item = Items.Add(snapshot);
if (Items.Count == 1)
Items.Add(whiteIcon);
return item;
}
public new void Clear()
{
base.Clear();
RemoveSnapshot(root);
}
internal void RemoveSnapshot(SnapshotIcon snapshot)
{
if (snapshot != null && snapshot.Parent != null)
{
IList<SnapshotIcon> siblings = snapshot.Parent.Children;
int pos = siblings.IndexOf(snapshot);
siblings.Remove(snapshot);
// add our children in our place
foreach (SnapshotIcon child in snapshot.Children)
{
siblings.Insert(pos++, child);
child.Parent = snapshot.Parent;
}
snapshot.Parent.Invalidate();
snapshot.Parent = null;
}
else
{
root = null;
}
}
protected override void OnSelectedIndexChanged(EventArgs e)
{
if (SelectedItems.Count == 1)
{
SnapshotIcon item = SelectedItems[0] as SnapshotIcon;
if (item != null && !item.Selectable)
{
item.Selected = false;
item.Focused = false;
}
}
else if (this.SelectedItems.Count > 1)
{
foreach (ListViewItem item in SelectedItems)
{
SnapshotIcon snapItem = item as SnapshotIcon;
if (snapItem != null && !snapItem.Selectable)
{
item.Selected = false;
item.Focused = false;
}
}
}
base.OnSelectedIndexChanged(e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
ListViewItem item = this.HitTest(e.X, e.Y).Item;
if (item == null)
{
ListViewItem item2 = this.HitTest(e.X, e.Y - 23).Item;
if (item2 != null)
{
item2.Selected = true;
item2.Focused = true;
}
else
{
base.OnMouseUp(new MouseEventArgs(e.Button, e.Clicks, e.X, e.Y - 23, e.Delta));
return;
}
}
base.OnMouseUp(e);
}
#region Layout
protected override void OnLayout(LayoutEventArgs levent)
{
if (root != null && this.Parent != null)
{
//This is needed to maximize and minimize properly, there is some issue in the ListView Control
Win32.POINT pt = new Win32.POINT();
IntPtr hResult = SendMessage(Handle, LVM_GETORIGIN, IntPtr.Zero, ref pt);
origin = pt;
root.InvalidateAll();
int x = Math.Max(this.HGap, this.Size.Width / 2 - root.SubtreeWidth / 2);
int y = Math.Max(this.VGap, this.Size.Height / 2 - root.SubtreeHeight / 2);
PositionSnapshots(root, x, y);
Invalidate();
whiteIcon.Position = new Point(x + origin.X, y + root.SubtreeHeight - 20 + origin.Y);
}
}
protected override void OnParentChanged(EventArgs e)
{
//We need to cancel the parent changes when we change to the other view
}
private void PositionSnapshots(SnapshotIcon icon, int x, int y)
{
try
{
Size iconSize = icon.DefaultSize;
Point newPoint = new Point(x, y + icon.CentreHeight - iconSize.Height / 2);
icon.Position = new Point(newPoint.X + origin.X, newPoint.Y + origin.Y);
x += iconSize.Width + HGap;
for (int i = 0; i < icon.Children.Count; i++)
{
SnapshotIcon child = icon.Children[i];
PositionSnapshots(child, x, y);
y += child.SubtreeHeight;
}
}
catch (Exception)
{
// Debugger.Break();
}
}
public const int LVM_GETORIGIN = 0x1000 + 41;
private Win32.POINT origin = new Win32.POINT();
[DllImport("user32.dll")]
internal static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, ref Win32.POINT pt);
public override Size GetPreferredSize(Size proposedSize)
{
if (root == null && Parent != null)
{
return DefaultSize;
}
return new Size(root.SubtreeWidth, root.SubtreeHeight);
}
#endregion
#region Drawing
private bool m_empty = false;
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
protected override void WndProc(ref Message m)
{
const int WM_HSCROLL = 0x0114;
const int WM_VSCROLL = 0x0115;
const int WM_MOUSEWHEEL = 0x020A;
const int WM_PAINT = 0x000F;
base.WndProc(ref m);
if (m.Msg == WM_HSCROLL || m.Msg == WM_VSCROLL || (m.Msg == WM_MOUSEWHEEL && (IsVerticalScrollBarVisible(this) || IsHorizontalScrollBarVisible(this))))
{
Invalidate();
}
if (m.Msg == WM_PAINT)
{
Graphics gg = CreateGraphics();
if (this.Items.Count == 0)
{
m_empty = true;
Graphics g = CreateGraphics();
string text = Messages.SNAPSHOTS_EMPTY;
SizeF proposedSize = g.MeasureString(text, Font, 275);
float x = this.Width / 2 - proposedSize.Width / 2;
float y = this.Height / 2 - proposedSize.Height / 2;
RectangleF rect = new RectangleF(x, y, proposedSize.Width, proposedSize.Height);
using (var brush = new SolidBrush(BackColor))
g.FillRectangle(brush, rect);
g.DrawString(text, Font, Brushes.Black, rect);
}
}
else if (m_empty && this.Items.Count > 0)
{
m_empty = false;
this.Invalidate();
}
}
private const int WS_HSCROLL = 0x100000;
private const int WS_VSCROLL = 0x200000;
private const int GWL_STYLE = (-16);
[System.Runtime.InteropServices.DllImport("user32",
CharSet = System.Runtime.InteropServices.CharSet.Auto)]
private static extern int GetWindowLong(IntPtr hwnd, int nIndex);
internal static bool IsVerticalScrollBarVisible(Control ctrl)
{
if (!ctrl.IsHandleCreated)
return false;
return (GetWindowLong(ctrl.Handle, GWL_STYLE) & WS_VSCROLL) != 0;
}
internal static bool IsHorizontalScrollBarVisible(Control ctrl)
{
if (!ctrl.IsHandleCreated)
return false;
return (GetWindowLong(ctrl.Handle, GWL_STYLE) & WS_HSCROLL) != 0;
}
private void SnapshotTreeView_DrawItem(object sender, DrawListViewItemEventArgs e)
{
if (this.Parent != null)
{
e.DrawDefault = true;
SnapshotIcon icon = e.Item as SnapshotIcon;
if (icon == null)
return;
DrawDate(e, icon, false);
if (icon.Parent != null)
PaintLine(e.Graphics, icon.Parent, icon, icon.IsInVMBranch);
for (int i = 0; i < icon.Children.Count; i++)
{
SnapshotIcon child = icon.Children[i];
PaintLine(e.Graphics, icon, child, child.IsInVMBranch);
}
}
}
public void DrawRoundRect(Graphics g, Brush b, float x, float y, float width, float height, float radius)
{
GraphicsPath gp = new GraphicsPath();
gp.AddLine(x + radius, y, x + width - (radius * 2), y); // Line
gp.AddArc(x + width - (radius * 2), y, radius * 2, radius * 2, 270, 90); // Corner
gp.AddLine(x + width, y + radius, x + width, y + height - (radius * 2)); // Line
gp.AddArc(x + width - (radius * 2), y + height - (radius * 2), radius * 2, radius * 2, 0, 90); // Corner
gp.AddLine(x + width - (radius * 2), y + height, x + radius, y + height); // Line
gp.AddArc(x, y + height - (radius * 2), radius * 2, radius * 2, 90, 90); // Corner
gp.AddLine(x, y + height - (radius * 2), x, y + radius); // Line
gp.AddArc(x, y, radius * 2, radius * 2, 180, 90); // Corner
gp.CloseFigure();
g.FillPath(b, gp);
}
private void DrawDate(DrawListViewItemEventArgs e, SnapshotIcon icon, bool background)
{
StringFormat stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Center;
//Time
int timeX = e.Bounds.X;
int timeY = e.Bounds.Y + e.Bounds.Height;
Size proposedSizeName = new Size(e.Bounds.Width,
Int32.MaxValue);
Size timeSize = TextRenderer.MeasureText(e.Graphics, icon.LabelCreationTime,
new Font(this.Font.FontFamily, this.Font.Size - 1), proposedSizeName, TextFormatFlags.WordBreak);
timeSize = new Size(e.Bounds.Width, timeSize.Height);
Rectangle timeRect = new Rectangle(new Point(timeX, timeY), timeSize);
if (background)
{
e.Graphics.FillRectangle(Brushes.GreenYellow, timeRect);
}
e.Graphics.DrawString(icon.LabelCreationTime, new Font(this.Font.FontFamily, this.Font.Size - 1), Brushes.Black, timeRect, stringFormat);
}
private void PaintLine(Graphics g, SnapshotIcon icon, SnapshotIcon child, bool highlight)
{
if (child.Index == -1)
return;
try
{
Rectangle leftItemBounds = icon.GetBounds(ItemBoundsPortion.Entire);
Rectangle rightItemBounds = child.GetBounds(ItemBoundsPortion.Entire);
leftItemBounds.Size = icon.DefaultSize;
rightItemBounds.Size = child.DefaultSize;
int left = leftItemBounds.Right + 6;
int right = rightItemBounds.Left;
int mid = (left + right) / 2;
Point start = new Point(left, (leftItemBounds.Bottom + leftItemBounds.Top) / 2);
Point end = new Point(right, (rightItemBounds.Top + rightItemBounds.Bottom) / 2);
Point curveStart = start;
curveStart.Offset(straightLineLength, 0);
Point curveEnd = end;
curveEnd.Offset(-straightLineLength, 0);
Point control1 = new Point(mid + straightLineLength, start.Y);
Point control2 = new Point(mid - straightLineLength, end.Y);
Color lineColor = LinkLineColor;
float lineWidth = LinkLineWidth;
if (highlight)
{
lineColor = Color.ForestGreen;
lineWidth = 2.5f;
}
using (Pen p = new Pen(lineColor, lineWidth))
{
p.SetLineCap(LineCap.Round, LineCap.Custom, DashCap.Flat);
p.CustomEndCap = linkLineArrow;
g.SmoothingMode = SmoothingMode.AntiAlias;
GraphicsPath path = new GraphicsPath();
path.AddLine(start, curveStart);
path.AddBezier(curveStart, control1, control2, curveEnd);
path.AddLine(curveEnd, end);
g.DrawPath(p, path);
}
}
catch (Exception)
{
//Debugger.Break();
}
}
#endregion
private string _spinningMessage = "";
public string SpinningMessage { get { return _spinningMessage; } }
internal void ChangeVMToSpinning(bool p, string message)
{
_spinningMessage = message;
foreach (var item in Items)
{
SnapshotIcon snapshotIcon = item as SnapshotIcon;
if (snapshotIcon != null && (snapshotIcon.ImageIndex == SnapshotIcon.VMImageIndex || snapshotIcon.ImageIndex > SnapshotIcon.UnknownImage))
{
if (string.IsNullOrEmpty(message))
{
snapshotIcon.ChangeSpinningIcon(p, _spinningMessage);
}
else
{
snapshotIcon.ChangeSpinningIcon(p, _spinningMessage);
}
return;
}
}
}
}
internal class SnapshotIcon : ListViewItem
{
public const int VMImageIndex = 0;
public const int Template = 1;
public const int CustomTemplate = 2;
public const int DiskSnapshot = 3;
public const int DiskAndMemorySnapshot = 4;
public const int ScheduledDiskSnapshot = 5;
public const int ScheduledDiskMemorySnapshot = 6;
public const int UnknownImage = 6;
private SnapshotIcon parent;
private readonly SnapshotTreeView treeView;
private readonly List<SnapshotIcon> children = new List<SnapshotIcon>();
private readonly string _name;
private readonly string _creationTime;
public Size DefaultSize = new Size(70, 64);
private Timer spinningTimer = new Timer();
#region Cached dimensions
private int subtreeWidth;
private int subtreeHeight;
private int subtreeWeight;
private int centreHeight;
#endregion
#region Properties
public string LabelCreationTime
{
get { return _creationTime; }
}
public string LabelName
{
get { return _name; }
}
internal SnapshotIcon Parent
{
get { return parent; }
set { parent = value; }
}
internal IList<SnapshotIcon> Children
{
get { return children; }
}
internal bool Selectable
{
get
{
// It's selectable if it's a snapshot; otherwise not
return ImageIndex == DiskSnapshot || ImageIndex == DiskAndMemorySnapshot || ImageIndex == ScheduledDiskSnapshot || ImageIndex == ScheduledDiskMemorySnapshot;
}
}
#endregion
public SnapshotIcon(string name, string createTime, SnapshotIcon parent, SnapshotTreeView treeView, int imageIndex)
: base(name.Ellipsise(35))
{
this._name = name.Ellipsise(35);
this._creationTime = createTime;
this.parent = parent;
this.treeView = treeView;
this.UseItemStyleForSubItems = false;
this.ToolTipText = String.Format("{0} {1}", name, createTime);
this.ImageIndex = imageIndex;
if (imageIndex == SnapshotIcon.VMImageIndex)
{
spinningTimer.Tick += new EventHandler(timer_Tick);
spinningTimer.Interval = 150;
}
}
private int currentSpinningFrame = 7;
private void timer_Tick(object sender, EventArgs e)
{
this.ImageIndex = currentSpinningFrame <= 14 ? currentSpinningFrame++ : currentSpinningFrame = 7;
}
internal void ChangeSpinningIcon(bool enabled, string message)
{
if (this.ImageIndex > UnknownImage || this.ImageIndex == VMImageIndex)
{
this.ImageIndex = enabled ? 7 : VMImageIndex;
this.Text = enabled ? message : Messages.NOW;
if (enabled)
spinningTimer.Start();
else
spinningTimer.Stop();
}
}
private bool _isInVMBranch = false;
public bool IsInVMBranch
{
get { return _isInVMBranch; }
set { _isInVMBranch = value; }
}
internal void AddChild(SnapshotIcon icon)
{
children.Add(icon);
Invalidate();
}
public override void Remove()
{
SnapshotTreeView view = (SnapshotTreeView)ListView;
view.RemoveSnapshot(this);
base.Remove();
view.PerformLayout();
}
/// <summary>
/// Causes the item and its ancestors to forget their cached dimensions.
/// </summary>
public void Invalidate()
{
subtreeWeight = 0;
subtreeHeight = 0;
centreHeight = 0;
subtreeWidth = 0;
if (parent != null)
parent.Invalidate();
}
/// <summary>
/// Causes the item and all its descendents to forget their cached dimensions.
/// </summary>
public void InvalidateAll()
{
subtreeWeight = 0;
subtreeHeight = 0;
centreHeight = 0;
subtreeWidth = 0;
foreach (SnapshotIcon icon in children)
{
icon.InvalidateAll();
}
}
#region Layout/Dimensions
public int SubtreeWidth
{
get
{
if (subtreeWidth == 0)
{
int currentWidth = this.DefaultSize.Width + treeView.HGap;
if (children.Count > 0)
{
int maxWidth = 0;
foreach (SnapshotIcon icon in children)
{
int childSubtree = icon.SubtreeWidth;
if (currentWidth + childSubtree > maxWidth)
maxWidth = currentWidth + childSubtree;
}
if (maxWidth > currentWidth)
subtreeWidth = maxWidth;
else
subtreeWidth = currentWidth;
}
}
return subtreeWidth;
}
}
/// <summary>
/// Height of the subtree rooted at this node, including the margin above and below.
/// </summary>
public int SubtreeHeight
{
get
{
if (subtreeHeight == 0)
{
subtreeHeight = this.DefaultSize.Height + treeView.VGap;
if (children.Count > 0)
{
int height = 0;
foreach (SnapshotIcon icon in children)
{
height += icon.SubtreeHeight; // recurse
}
if (height > subtreeHeight)
subtreeHeight = height;
}
}
return subtreeHeight;
}
}
/// <summary>
/// The number of items rooted at this node (including the node itself)
/// </summary>
public int SubtreeWeight
{
get
{
if (subtreeWeight == 0)
{
int weight = 1; // this
foreach (SnapshotIcon icon in children)
{
weight += icon.SubtreeWeight;
}
subtreeWeight = weight;
}
return subtreeWeight;
}
}
/// <summary>
/// The weighted mean centre height for this node, within the range 0 - SubtreeHeight
/// </summary>
public int CentreHeight
{
get
{
if (centreHeight == 0)
{
int top = 0;
int totalWeight = 0;
int weightedCentre = 0;
foreach (SnapshotIcon icon in children)
{
int iconWeight = icon.SubtreeWeight;
totalWeight += iconWeight;
weightedCentre += iconWeight * (top + icon.CentreHeight); // recurse
top += icon.SubtreeHeight;
}
if (totalWeight > 0)
centreHeight = weightedCentre / totalWeight;
else
centreHeight = (top + SubtreeHeight) / 2;
}
return centreHeight;
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Cdn.Fluent
{
using Models;
using ResourceManager.Fluent.Core;
using Rest.Azure;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Implementation for CdnProfiles.
/// </summary>
///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LmNkbi5pbXBsZW1lbnRhdGlvbi5DZG5Qcm9maWxlc0ltcGw=
internal partial class CdnProfilesImpl :
TopLevelModifiableResources<ICdnProfile, CdnProfileImpl, ProfileInner, IProfilesOperations, ICdnManager>,
ICdnProfiles
{
///GENMHASH:8B3976582303B73AC81C5220073E2D55:A4104491D327BA3667E857CA7A2EC15D
public CheckNameAvailabilityResult CheckEndpointNameAvailability(string name)
{
return Extensions.Synchronize(() => CheckEndpointNameAvailabilityAsync(name));
}
///GENMHASH:2CEB6E35574F5C7F1D19ADAC97C93D65:1B5FDD33003D9073F97F1C9831CA2660
public IEnumerable<Operation> ListOperations()
{
return Extensions.Synchronize(() => Manager.Inner.Operations.ListAsync())
.AsContinuousCollection(link => Extensions.Synchronize(() => Manager.Inner.Operations.ListNextAsync(link)))
.Select(inner => new Operation(inner));
}
///GENMHASH:89CD44AA5060CAB16CB0AF1FB046BC64:416FABEC3862B2A47FF2F9DD56AFEFF6
public IEnumerable<ResourceUsage> ListResourceUsage()
{
return Extensions.Synchronize(() => Manager.Inner.ResourceUsageInner.ListAsync())
.AsContinuousCollection(link => Extensions.Synchronize(() => Manager.Inner.ResourceUsageInner.ListNextAsync(link)))
.Select(inner => new ResourceUsage(inner));
}
///GENMHASH:6F0D776A3FBBF84EE0312C9E28F2D855:EC99713AFF94DCD8E902241A49011E4B
public IEnumerable<EdgeNode> ListEdgeNodes()
{
return Extensions.Synchronize(() => Manager.Inner.EdgeNodeInners.ListAsync())
.AsContinuousCollection(link => Extensions.Synchronize(() => Manager.Inner.EdgeNodeInners.ListNextAsync(link)))
.Select(inner => new EdgeNode(inner));
}
///GENMHASH:8C72A32C69D3B2099B1D93E3B9873A71:11F71B6989FF140BBFACEF8AABC579A8
public async Task LoadEndpointContentAsync(
string resourceGroupName,
string profileName,
string endpointName,
IList<string> contentPaths,
CancellationToken cancellationToken = default(CancellationToken))
{
await Manager.Inner.Endpoints.LoadContentAsync(resourceGroupName, profileName, endpointName, contentPaths, cancellationToken);
}
internal void LoadEndpointContent(
string resourceGroupName,
string profileName,
string endpointName,
IList<string> contentPaths)
{
Extensions.Synchronize(() => LoadEndpointContentAsync(resourceGroupName, profileName, endpointName, contentPaths));
}
///GENMHASH:7D6013E8B95E991005ED921F493EFCE4:6FB4EA69673E1D8A74E1418EB52BB9FE
protected async override Task<IPage<ProfileInner>> ListInnerAsync(CancellationToken cancellationToken)
{
return await Inner.ListAsync(cancellationToken);
}
protected async override Task<IPage<ProfileInner>> ListInnerNextAsync(string nextLink, CancellationToken cancellationToken)
{
return await Inner.ListNextAsync(nextLink, cancellationToken);
}
///GENMHASH:B76E119E66FC2C5D09617333DC4FF4E3:50CAB688056CFBD731F264F50EA813EF
public async Task StartEndpointAsync(
string resourceGroupName,
string profileName,
string endpointName,
CancellationToken cancellationToken = default(CancellationToken))
{
await Manager.Inner.Endpoints.StartAsync(resourceGroupName, profileName, endpointName, cancellationToken);
}
internal void StartEndpoint(
string resourceGroupName,
string profileName,
string endpointName
)
{
Extensions.Synchronize(() => StartEndpointAsync(resourceGroupName, profileName, endpointName));
}
///GENMHASH:EB7BCC87B72405260E2C64D3F60E7D12:27C4EEED8156C99311E5C3646A2873AB
public async Task StopEndpointAsync(
string resourceGroupName,
string profileName,
string endpointName,
CancellationToken cancellationToken = default(CancellationToken))
{
await Manager.Inner.Endpoints.StopAsync(resourceGroupName, profileName, endpointName, cancellationToken);
}
internal void StopEndpoint(
string resourceGroupName,
string profileName,
string endpointName)
{
Extensions.Synchronize(() => StopEndpointAsync(resourceGroupName, profileName, endpointName));
}
///GENMHASH:64DEF1711FC41C47500E107416B7F805:506E827968295A02B09C6EA38E8B9C1E
public async Task<CheckNameAvailabilityResult> CheckEndpointNameAvailabilityAsync(
string name,
CancellationToken cancellationToken = default(CancellationToken))
{
return new CheckNameAvailabilityResult(await Manager.Inner.CheckNameAvailabilityAsync(name, cancellationToken));
}
///GENMHASH:0679DF8CA692D1AC80FC21655835E678:B9B028D620AC932FDF66D2783E476B0D
protected async override Task DeleteInnerByGroupAsync(string groupName, string name, CancellationToken cancellationToken)
{
await Inner.DeleteAsync(groupName, name, cancellationToken);
}
///GENMHASH:83F5C51B6E80CB8E2B2AB13088098EAD:7A8055F61731CABECC9333BD0AB0BDA2
public async Task<string> GenerateSsoUriAsync(
string resourceGroupName,
string profileName,
CancellationToken cancellationToken = default(CancellationToken))
{
SsoUriInner ssoUri = await Manager.Inner.Profiles.GenerateSsoUriAsync(resourceGroupName, profileName, cancellationToken);
if (ssoUri != null)
{
return ssoUri.SsoUriValue;
}
return null;
}
public string GenerateSsoUri(string resourceGroupName, string profileName)
{
return Extensions.Synchronize(() => GenerateSsoUriAsync(resourceGroupName, profileName));
}
///GENMHASH:2404C5CA15B0D5D6226D2C7D01E79303:FA381ABED6F4688FD47A380CF0F41845
internal CdnProfilesImpl(CdnManager cdnManager)
: base(cdnManager.Inner.Profiles, cdnManager)
{
}
///GENMHASH:8ACFB0E23F5F24AD384313679B65F404:AD7C28D26EC1F237B93E54AD31899691
public CdnProfileImpl Define(string name)
{
return WrapModel(name);
}
///GENMHASH:AB63F782DA5B8D22523A284DAD664D17:7C0A1D0C3FE28C45F35B565F4AFF751D
protected async override Task<ProfileInner> GetInnerByGroupAsync(string groupName, string name, CancellationToken cancellationToken)
{
return await Inner.GetAsync(groupName, name, cancellationToken);
}
///GENMHASH:95834C6C7DA388E666B705A62A7D02BF:BDFF4CB61E8A8D975417EA5FC914921A
protected async override Task<IPage<ProfileInner>> ListInnerByGroupAsync(string groupName, CancellationToken cancellationToken)
{
return await Inner.ListByResourceGroupAsync(groupName, cancellationToken);
}
protected async override Task<IPage<ProfileInner>> ListInnerByGroupNextAsync(string nextLink, CancellationToken cancellationToken)
{
return await Inner.ListByResourceGroupNextAsync(nextLink, cancellationToken);
}
///GENMHASH:2FE8C4C2D5EAD7E37787838DE0B47D92:BA164FA13589E15D154A149930A7318A
protected override CdnProfileImpl WrapModel(string name)
{
return new CdnProfileImpl(name, new ProfileInner(), Manager);
}
///GENMHASH:96AD55F2D1A183F1EF3F3859FC90630B:E7C740DCEB274D49AE272A1212126D43
protected override ICdnProfile WrapModel(ProfileInner inner)
{
return new CdnProfileImpl(inner.Name, inner, Manager);
}
///GENMHASH:5ABD9E20ED5A3AA9092DC3AC7B3573AC:38A65CDCA635B6616A2B2FC37922C9E1
public async Task PurgeEndpointContentAsync(
string resourceGroupName,
string profileName,
string endpointName,
IList<string> contentPaths,
CancellationToken cancellationToken = default(CancellationToken))
{
await Manager.Inner.Endpoints.PurgeContentAsync(resourceGroupName, profileName, endpointName, contentPaths, cancellationToken);
}
public void PurgeEndpointContent(
string resourceGroupName,
string profileName,
string endpointName,
IList<string> contentPaths)
{
Extensions.Synchronize(() => PurgeEndpointContentAsync(resourceGroupName, profileName, endpointName, contentPaths));
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Diagnostics.Contracts;
namespace System.Reflection
{
public class Assembly
{
public string! FullName
{
get;
}
public string EscapedCodeBase
{
get;
}
public MethodInfo EntryPoint
{
get;
}
public bool GlobalAssemblyCache
{
get;
}
public System.Security.Policy.Evidence Evidence
{
get;
}
public string! CodeBase
{
get;
}
public string Location
{
get;
}
public string ImageRuntimeVersion
{
get;
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public string ToString () {
CodeContract.Ensures(CodeContract.Result<string>() != null);
return default(string);
}
public ManifestResourceInfo GetManifestResourceInfo (string resourceName) {
return default(ManifestResourceInfo);
}
public AssemblyName[] GetReferencedAssemblies () {
return default(AssemblyName[]);
}
public static Assembly GetEntryAssembly () {
return default(Assembly);
}
public static Assembly GetCallingAssembly () {
return default(Assembly);
}
public static Assembly GetExecutingAssembly () {
CodeContract.Ensures(CodeContract.Result<Assembly>() != null);
return default(Assembly);
}
public String[] GetManifestResourceNames () {
CodeContract.Ensures(CodeContract.Result<String[]>() != null);
return default(String[]);
}
public System.IO.FileStream[] GetFiles (bool getResourceModules) {
CodeContract.Ensures(CodeContract.Result<System.IO.FileStream[]>() != null);
return default(System.IO.FileStream[]);
}
public System.IO.FileStream[] GetFiles () {
CodeContract.Ensures(CodeContract.Result<System.IO.FileStream[]>() != null);
return default(System.IO.FileStream[]);
}
public System.IO.FileStream GetFile (string name) {
return default(System.IO.FileStream);
}
public Module GetModule (string arg0) {
return default(Module);
}
public Module[] GetModules (bool getResourceModules) {
CodeContract.Ensures(CodeContract.Result<Module[]>() != null);
return default(Module[]);
}
public Module[] GetModules () {
CodeContract.Ensures(CodeContract.Result<Module[]>() != null);
return default(Module[]);
}
public Module[] GetLoadedModules (bool getResourceModules) {
CodeContract.Ensures(CodeContract.Result<Module[]>() != null);
return default(Module[]);
}
public Module[] GetLoadedModules () {
CodeContract.Ensures(CodeContract.Result<Module[]>() != null);
return default(Module[]);
}
public object CreateInstance (string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, System.Globalization.CultureInfo culture, Object[] activationAttributes) {
return default(object);
}
public object CreateInstance (string typeName, bool ignoreCase) {
return default(object);
}
public object CreateInstance (string typeName) {
return default(object);
}
public Module LoadModule (string moduleName, Byte[] rawModule, Byte[] rawSymbolStore) {
return default(Module);
}
public Module LoadModule (string moduleName, Byte[] rawModule) {
return default(Module);
}
public static Assembly LoadFile (string path, System.Security.Policy.Evidence securityEvidence) {
return default(Assembly);
}
public static Assembly LoadFile (string path) {
return default(Assembly);
}
public static Assembly Load (Byte[] rawAssembly, Byte[] rawSymbolStore, System.Security.Policy.Evidence securityEvidence) {
return default(Assembly);
}
public static Assembly Load (Byte[] rawAssembly, Byte[] rawSymbolStore) {
return default(Assembly);
}
public static Assembly Load (Byte[] rawAssembly) {
return default(Assembly);
}
public static Assembly LoadWithPartialName (string partialName, System.Security.Policy.Evidence securityEvidence) {
return default(Assembly);
}
public static Assembly LoadWithPartialName (string partialName) {
return default(Assembly);
}
public static Assembly Load (AssemblyName assemblyRef, System.Security.Policy.Evidence assemblySecurity) {
return default(Assembly);
}
public static Assembly Load (AssemblyName assemblyRef) {
return default(Assembly);
}
public static Assembly Load (string assemblyString, System.Security.Policy.Evidence assemblySecurity) {
return default(Assembly);
}
public static Assembly Load (string assemblyString) {
return default(Assembly);
}
public static Assembly LoadFrom (string! assemblyFile, System.Security.Policy.Evidence securityEvidence, Byte[] hashValue, System.Configuration.Assemblies.AssemblyHashAlgorithm hashAlgorithm) {
CodeContract.Requires(assemblyFile != null);
return default(Assembly);
}
public static Assembly LoadFrom (string assemblyFile, System.Security.Policy.Evidence securityEvidence) {
return default(Assembly);
}
public static Assembly LoadFrom (string assemblyFile) {
return default(Assembly);
}
public bool IsDefined (Type! attributeType, bool inherit) {
CodeContract.Requires(attributeType != null);
return default(bool);
}
public Object[] GetCustomAttributes (Type! attributeType, bool inherit) {
CodeContract.Requires(attributeType != null);
CodeContract.Ensures(CodeContract.Result<Object[]>() != null);
return default(Object[]);
}
public Object[] GetCustomAttributes (bool inherit) {
CodeContract.Ensures(CodeContract.Result<Object[]>() != null);
return default(Object[]);
}
public void GetObjectData (System.Runtime.Serialization.SerializationInfo! info, System.Runtime.Serialization.StreamingContext context) {
CodeContract.Requires(info != null);
}
public Assembly GetSatelliteAssembly (System.Globalization.CultureInfo culture, Version version) {
return default(Assembly);
}
public Assembly GetSatelliteAssembly (System.Globalization.CultureInfo culture) {
return default(Assembly);
}
public System.IO.Stream GetManifestResourceStream (string name) {
return default(System.IO.Stream);
}
public System.IO.Stream GetManifestResourceStream (Type type, string name) {
return default(System.IO.Stream);
}
public Type[] GetTypes () {
CodeContract.Ensures(CodeContract.Result<Type[]>() != null);
return default(Type[]);
}
public Type[] GetExportedTypes () {
CodeContract.Ensures(CodeContract.Result<Type[]>() != null);
return default(Type[]);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)][ResultNotNewlyAllocated]
public Type GetType () {
CodeContract.Ensures(CodeContract.Result<Type>() != null);
return default(Type);
}
public Type GetType (string arg0, bool arg1, bool arg2) {
return default(Type);
}
public Type GetType (string arg0, bool arg1) {
return default(Type);
}
public Type GetType (string arg0) {
return default(Type);
}
public static Assembly GetAssembly (Type! type) {
CodeContract.Requires(type != null);
return default(Assembly);
}
public static string CreateQualifiedName (string arg0, string arg1) {
return default(string);
}
public AssemblyName GetName (bool copiedName) {
CodeContract.Ensures(CodeContract.Result<AssemblyName>() != null);
return default(AssemblyName);
}
public AssemblyName GetName () {
CodeContract.Ensures(CodeContract.Result<AssemblyName>() != null);
return default(AssemblyName);
}
public void remove_ModuleResolve (ModuleResolveEventHandler value) {
}
public void add_ModuleResolve (ModuleResolveEventHandler value) {
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Linq;
using System.Reflection;
using System.Threading;
using Adxstudio.Xrm.Cms;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Diagnostics;
using Microsoft.Xrm.Client.Security;
using Microsoft.Xrm.Portal.Web.Providers;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
namespace Adxstudio.Xrm.Web.Handlers.ElFinder
{
public interface IDirectory
{
bool CanRead { get; }
bool CanWrite { get; }
DirectoryContent[] Children { get; }
Entity Entity { get; }
EntityReference EntityReference { get; }
bool Exists { get; }
DirectoryContent Info { get; }
bool SupportsUpload { get; }
string WebFileForeignKeyAttribute { get; }
}
internal abstract class Directory : IDirectory
{
protected const string DirectoryMimeType = "directory";
private readonly Lazy<bool> _canRead;
private readonly Lazy<bool> _canWrite;
private readonly Lazy<DirectoryContent[]> _children;
private readonly Lazy<DirectoryContent> _info;
private readonly Lazy<Entity> _entity;
private readonly Lazy<string> _url;
protected Directory(IEntityDirectoryFileSystem fileSystem)
{
if (fileSystem == null) throw new ArgumentNullException("fileSystem");
FileSystem = fileSystem;
_canRead = new Lazy<bool>(GetCanRead, LazyThreadSafetyMode.None);
_canWrite = new Lazy<bool>(GetCanWrite, LazyThreadSafetyMode.None);
_children = new Lazy<DirectoryContent[]>(GetChildren, LazyThreadSafetyMode.None);
_entity = new Lazy<Entity>(GetEntity, LazyThreadSafetyMode.None);
_info = new Lazy<DirectoryContent>(GetInfo, LazyThreadSafetyMode.None);
_url = new Lazy<string>(GetUrl, LazyThreadSafetyMode.None);
}
public bool CanRead
{
get { return _canRead.Value; }
}
public bool CanWrite
{
get { return _canWrite.Value; }
}
public DirectoryContent[] Children
{
get { return _children.Value; }
}
public Entity Entity
{
get { return _entity.Value; }
}
public abstract EntityReference EntityReference { get; }
public virtual bool Exists
{
get { return Entity != null && CanRead; }
}
public DirectoryContent Info
{
get { return _info.Value; }
}
public abstract bool SupportsUpload { get; }
public abstract string WebFileForeignKeyAttribute { get; }
protected IEntityDirectoryFileSystem FileSystem { get; private set; }
protected ICrmEntitySecurityProvider SecurityProvider
{
get { return FileSystem.SecurityProvider; }
}
protected OrganizationServiceContext ServiceContext
{
get { return FileSystem.ServiceContext; }
}
protected string Url
{
get { return _url.Value; }
}
protected IEntityUrlProvider UrlProvider
{
get { return FileSystem.UrlProvider; }
}
protected EntityReference Website
{
get { return FileSystem.Website; }
}
protected virtual bool GetCanRead()
{
return TryAssertSecurity(CrmEntityRight.Read);
}
protected virtual bool GetCanWrite()
{
return TryAssertSecurity(CrmEntityRight.Change);
}
protected abstract DirectoryContent[] GetChildren();
protected abstract DirectoryContent GetInfo();
protected abstract Entity GetEntity();
protected abstract string GetUrl();
protected virtual DirectoryContent GetDirectoryContent(Entity entity)
{
if (entity == null)
{
return null;
}
string url;
try
{
url = UrlProvider.GetUrl(ServiceContext, entity);
}
catch (Exception e)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Error getting URL for entity [{0}:{1}]: {2}", entity.LogicalName, entity.Id, e.ToString()));
return null;
}
if (url == null)
{
return null;
}
bool canWrite;
try
{
if (!SecurityProvider.TryAssert(ServiceContext, entity, CrmEntityRight.Read))
{
return null;
}
canWrite = SecurityProvider.TryAssert(ServiceContext, entity, CrmEntityRight.Change);
}
catch (InvalidOperationException e)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Error validating security for entity [{0}:{1}]: {2}", entity.LogicalName, entity.Id, e.ToString()));
return null;
}
var content = new DirectoryContent
{
url = url,
date = FormatDateTime(entity.GetAttributeValue<DateTime?>("modifiedon")),
read = true,
rm = false,
};
DirectoryType directoryType;
if (FileSystem.EntityDirectoryTypes.TryGetValue(entity.LogicalName, out directoryType))
{
content.hash = new DirectoryContentHash(entity, true).ToString();
content.name = directoryType.GetDirectoryName(entity);
content.mime = DirectoryMimeType;
content.size = 0;
content.write = directoryType.SupportsUpload && SecurityProvider.TryAssert(ServiceContext, entity, CrmEntityRight.Change);
return content;
}
content.write = canWrite;
content.name = entity.GetAttributeValue<string>("adx_name");
content.hash = new DirectoryContentHash(entity).ToString();
if (entity.LogicalName != "adx_webfile")
{
content.mime = "application/x-{0}".FormatWith(entity.LogicalName);
content.size = 0;
return content;
}
var fileNote = ServiceContext.GetNotes(entity)
.Where(e => e.GetAttributeValue<bool?>("isdocument").GetValueOrDefault())
.OrderByDescending(e => e.GetAttributeValue<DateTime?>("createdon"))
.FirstOrDefault();
if (fileNote == null)
{
return null;
}
content.mime = fileNote.GetAttributeValue<string>("mimetype");
content.size = fileNote.GetAttributeValue<int?>("filesize").GetValueOrDefault();
content.rm = canWrite;
return content;
}
protected static string FormatDateTime(DateTime? dateTime)
{
return dateTime == null ? null : dateTime.ToString();
}
private bool TryAssertSecurity(CrmEntityRight right)
{
try
{
return SecurityProvider.TryAssert(ServiceContext, Entity, right);
}
catch (InvalidOperationException e)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Error validating security for entity [{0}:{1}]: {2}", Entity.LogicalName, Entity.Id, e.ToString()));
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.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net.WebSockets;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Text;
namespace System.Net
{
public sealed unsafe partial class HttpListenerRequest
{
private readonly ulong _requestId;
internal ulong _connectionId;
private readonly SslStatus _sslStatus;
private readonly string _cookedUrlHost;
private readonly string _cookedUrlPath;
private readonly string _cookedUrlQuery;
private long _contentLength;
private Stream _requestStream;
private string _httpMethod;
private WebHeaderCollection _webHeaders;
private IPEndPoint _localEndPoint;
private IPEndPoint _remoteEndPoint;
private BoundaryType _boundaryType;
private int _clientCertificateError;
private RequestContextBase _memoryBlob;
private readonly HttpListenerContext _httpContext;
private bool _isDisposed = false;
internal const uint CertBoblSize = 1500;
private string _serviceName;
private enum SslStatus : byte
{
Insecure,
NoClientCert,
ClientCert
}
internal HttpListenerRequest(HttpListenerContext httpContext, RequestContextBase memoryBlob)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Info(this, $"httpContext:${httpContext} memoryBlob {((IntPtr)memoryBlob.RequestBlob)}");
NetEventSource.Associate(this, httpContext);
}
_httpContext = httpContext;
_memoryBlob = memoryBlob;
_boundaryType = BoundaryType.None;
// Set up some of these now to avoid refcounting on memory blob later.
_requestId = memoryBlob.RequestBlob->RequestId;
_connectionId = memoryBlob.RequestBlob->ConnectionId;
_sslStatus = memoryBlob.RequestBlob->pSslInfo == null ? SslStatus.Insecure :
memoryBlob.RequestBlob->pSslInfo->SslClientCertNegotiated == 0 ? SslStatus.NoClientCert :
SslStatus.ClientCert;
if (memoryBlob.RequestBlob->pRawUrl != null && memoryBlob.RequestBlob->RawUrlLength > 0)
{
_rawUrl = Marshal.PtrToStringAnsi((IntPtr)memoryBlob.RequestBlob->pRawUrl, memoryBlob.RequestBlob->RawUrlLength);
}
Interop.HttpApi.HTTP_COOKED_URL cookedUrl = memoryBlob.RequestBlob->CookedUrl;
if (cookedUrl.pHost != null && cookedUrl.HostLength > 0)
{
_cookedUrlHost = Marshal.PtrToStringUni((IntPtr)cookedUrl.pHost, cookedUrl.HostLength / 2);
}
if (cookedUrl.pAbsPath != null && cookedUrl.AbsPathLength > 0)
{
_cookedUrlPath = Marshal.PtrToStringUni((IntPtr)cookedUrl.pAbsPath, cookedUrl.AbsPathLength / 2);
}
if (cookedUrl.pQueryString != null && cookedUrl.QueryStringLength > 0)
{
_cookedUrlQuery = Marshal.PtrToStringUni((IntPtr)cookedUrl.pQueryString, cookedUrl.QueryStringLength / 2);
}
_version = new Version(memoryBlob.RequestBlob->Version.MajorVersion, memoryBlob.RequestBlob->Version.MinorVersion);
if (NetEventSource.IsEnabled)
{
NetEventSource.Info(this, $"RequestId:{RequestId} ConnectionId:{_connectionId} RawConnectionId:{memoryBlob.RequestBlob->RawConnectionId} UrlContext:{memoryBlob.RequestBlob->UrlContext} RawUrl:{_rawUrl} Version:{_version} Secure:{_sslStatus}");
NetEventSource.Info(this, $"httpContext:${httpContext} RequestUri:{RequestUri} Content-Length:{ContentLength64} HTTP Method:{HttpMethod}");
}
// Log headers
if (NetEventSource.IsEnabled)
{
StringBuilder sb = new StringBuilder("HttpListenerRequest Headers:\n");
for (int i = 0; i < Headers.Count; i++)
{
sb.Append("\t");
sb.Append(Headers.GetKey(i));
sb.Append(" : ");
sb.Append(Headers.Get(i));
sb.Append("\n");
}
NetEventSource.Info(this, sb.ToString());
}
}
internal HttpListenerContext HttpListenerContext => _httpContext;
// Note: RequestBuffer may get moved in memory. If you dereference a pointer from inside the RequestBuffer,
// you must use 'OriginalBlobAddress' below to adjust the location of the pointer to match the location of
// RequestBuffer.
internal IntPtr RequestBuffer
{
get
{
CheckDisposed();
return _memoryBlob.RequestBuffer;
}
}
internal IntPtr OriginalBlobAddress
{
get
{
CheckDisposed();
return _memoryBlob.OriginalBlobAddress;
}
}
// Use this to save the blob from dispose if this object was never used (never given to a user) and is about to be
// disposed.
internal void DetachBlob(RequestContextBase memoryBlob)
{
if (memoryBlob != null && (object)memoryBlob == (object)_memoryBlob)
{
_memoryBlob = null;
}
}
// Finalizes ownership of the memory blob. DetachBlob can't be called after this.
internal void ReleasePins()
{
_memoryBlob.ReleasePins();
}
internal ulong RequestId => _requestId;
public Guid RequestTraceIdentifier
{
get
{
Guid guid = new Guid();
*(1 + (ulong*)&guid) = RequestId;
return guid;
}
}
public long ContentLength64
{
get
{
if (_boundaryType == BoundaryType.None)
{
string transferEncodingHeader = Headers[HttpKnownHeaderNames.TransferEncoding];
if (transferEncodingHeader != null && transferEncodingHeader.Equals("chunked", StringComparison.OrdinalIgnoreCase))
{
_boundaryType = BoundaryType.Chunked;
_contentLength = -1;
}
else
{
_contentLength = 0;
_boundaryType = BoundaryType.ContentLength;
string length = Headers[HttpKnownHeaderNames.ContentLength];
if (length != null)
{
bool success = long.TryParse(length, NumberStyles.None, CultureInfo.InvariantCulture.NumberFormat, out _contentLength);
if (!success)
{
_contentLength = 0;
_boundaryType = BoundaryType.Invalid;
}
}
}
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_contentLength:{_contentLength} _boundaryType:{_boundaryType}");
return _contentLength;
}
}
public NameValueCollection Headers
{
get
{
if (_webHeaders == null)
{
_webHeaders = Interop.HttpApi.GetHeaders(RequestBuffer, OriginalBlobAddress);
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"webHeaders:{_webHeaders}");
return _webHeaders;
}
}
public string HttpMethod
{
get
{
if (_httpMethod == null)
{
_httpMethod = Interop.HttpApi.GetVerb(RequestBuffer, OriginalBlobAddress);
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_httpMethod:{_httpMethod}");
return _httpMethod;
}
}
public Stream InputStream
{
get
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (_requestStream == null)
{
_requestStream = HasEntityBody ? new HttpRequestStream(HttpListenerContext) : Stream.Null;
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
return _requestStream;
}
}
public bool IsAuthenticated
{
get
{
IPrincipal user = HttpListenerContext.User;
return user != null && user.Identity != null && user.Identity.IsAuthenticated;
}
}
public bool IsSecureConnection => _sslStatus != SslStatus.Insecure;
public string ServiceName
{
get => _serviceName;
internal set => _serviceName = value;
}
private int GetClientCertificateErrorCore()
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"ClientCertificateError:{_clientCertificateError}");
return _clientCertificateError;
}
internal void SetClientCertificateError(int clientCertificateError)
{
_clientCertificateError = clientCertificateError;
}
public X509Certificate2 EndGetClientCertificate(IAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
X509Certificate2 clientCertificate = null;
try
{
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
ListenerClientCertAsyncResult clientCertAsyncResult = asyncResult as ListenerClientCertAsyncResult;
if (clientCertAsyncResult == null || clientCertAsyncResult.AsyncObject != this)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (clientCertAsyncResult.EndCalled)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, nameof(EndGetClientCertificate)));
}
clientCertAsyncResult.EndCalled = true;
clientCertificate = clientCertAsyncResult.InternalWaitForCompletion() as X509Certificate2;
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_clientCertificate:{ClientCertificate}");
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
return clientCertificate;
}
public TransportContext TransportContext => new HttpListenerRequestContext(this);
public bool HasEntityBody
{
get
{
// accessing the ContentLength property delay creates m_BoundaryType
return (ContentLength64 > 0 && _boundaryType == BoundaryType.ContentLength) ||
_boundaryType == BoundaryType.Chunked || _boundaryType == BoundaryType.Multipart;
}
}
public IPEndPoint RemoteEndPoint
{
get
{
if (_remoteEndPoint == null)
{
_remoteEndPoint = Interop.HttpApi.GetRemoteEndPoint(RequestBuffer, OriginalBlobAddress);
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "_remoteEndPoint" + _remoteEndPoint);
return _remoteEndPoint;
}
}
public IPEndPoint LocalEndPoint
{
get
{
if (_localEndPoint == null)
{
_localEndPoint = Interop.HttpApi.GetLocalEndPoint(RequestBuffer, OriginalBlobAddress);
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_localEndPoint={_localEndPoint}");
return _localEndPoint;
}
}
//should only be called from httplistenercontext
internal void Close()
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
RequestContextBase memoryBlob = _memoryBlob;
if (memoryBlob != null)
{
memoryBlob.Close();
_memoryBlob = null;
}
_isDisposed = true;
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
private ListenerClientCertAsyncResult BeginGetClientCertificateCore(AsyncCallback requestCallback, object state)
{
ListenerClientCertAsyncResult asyncResult = null;
//--------------------------------------------------------------------
//When you configure the HTTP.SYS with a flag value 2
//which means require client certificates, when the client makes the
//initial SSL connection, server (HTTP.SYS) demands the client certificate
//
//Some apps may not want to demand the client cert at the beginning
//perhaps server the default.htm. In this case the HTTP.SYS is configured
//with a flag value other than 2, whcih means that the client certificate is
//optional.So initially when SSL is established HTTP.SYS won't ask for client
//certificate. This works fine for the default.htm in the case above
//However, if the app wants to demand a client certficate at a later time
//perhaps showing "YOUR ORDERS" page, then the server wans to demand
//Client certs. this will inturn makes HTTP.SYS to do the
//SEC_I_RENOGOTIATE through which the client cert demand is made
//
//THE BUG HERE IS THAT PRIOR TO QFE 4796, we call
//GET Client certificate native API ONLY WHEN THE HTTP.SYS is configured with
//flag = 2. Which means that apps using HTTPListener will not be able to
//demand a client cert at a later point
//
//The fix here is to demand the client cert when the channel is NOT INSECURE
//which means whether the client certs are requried at the beginning or not,
//if this is an SSL connection, Call HttpReceiveClientCertificate, thus
//starting the cert negotiation at that point
//
//NOTE: WHEN CALLING THE HttpReceiveClientCertificate, you can get
//ERROR_NOT_FOUND - which means the client did not provide the cert
//If this is important, the server should respond with 403 forbidden
//HTTP.SYS will not do this for you automatically ***
//--------------------------------------------------------------------
if (_sslStatus != SslStatus.Insecure)
{
// at this point we know that DefaultFlags has the 2 bit set (Negotiate Client certificate)
// the cert, though might or might not be there. try to retrieve it
// this number is the same that IIS decided to use
uint size = CertBoblSize;
asyncResult = new ListenerClientCertAsyncResult(HttpListenerContext.RequestQueueBoundHandle, this, state, requestCallback, size);
try
{
while (true)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Calling Interop.HttpApi.HttpReceiveClientCertificate size:" + size);
uint bytesReceived = 0;
uint statusCode =
Interop.HttpApi.HttpReceiveClientCertificate(
HttpListenerContext.RequestQueueHandle,
_connectionId,
(uint)Interop.HttpApi.HTTP_FLAGS.NONE,
asyncResult.RequestBlob,
size,
&bytesReceived,
asyncResult.NativeOverlapped);
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, "Call to Interop.HttpApi.HttpReceiveClientCertificate returned:" + statusCode + " bytesReceived:" + bytesReceived);
if (statusCode == Interop.HttpApi.ERROR_MORE_DATA)
{
Interop.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo = asyncResult.RequestBlob;
size = bytesReceived + pClientCertInfo->CertEncodedSize;
asyncResult.Reset(size);
continue;
}
if (statusCode != Interop.HttpApi.ERROR_SUCCESS &&
statusCode != Interop.HttpApi.ERROR_IO_PENDING)
{
// someother bad error, possible return values are:
// ERROR_INVALID_HANDLE, ERROR_INSUFFICIENT_BUFFER, ERROR_OPERATION_ABORTED
// Also ERROR_BAD_DATA if we got it twice or it reported smaller size buffer required.
throw new HttpListenerException((int)statusCode);
}
if (statusCode == Interop.HttpApi.ERROR_SUCCESS &&
HttpListener.SkipIOCPCallbackOnSuccess)
{
asyncResult.IOCompleted(statusCode, bytesReceived);
}
break;
}
}
catch
{
asyncResult?.InternalCleanup();
throw;
}
}
else
{
asyncResult = new ListenerClientCertAsyncResult(HttpListenerContext.RequestQueueBoundHandle, this, state, requestCallback, 0);
asyncResult.InvokeCallback();
}
return asyncResult;
}
private void GetClientCertificateCore()
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this);
//--------------------------------------------------------------------
//When you configure the HTTP.SYS with a flag value 2
//which means require client certificates, when the client makes the
//initial SSL connection, server (HTTP.SYS) demands the client certificate
//
//Some apps may not want to demand the client cert at the beginning
//perhaps server the default.htm. In this case the HTTP.SYS is configured
//with a flag value other than 2, whcih means that the client certificate is
//optional.So initially when SSL is established HTTP.SYS won't ask for client
//certificate. This works fine for the default.htm in the case above
//However, if the app wants to demand a client certficate at a later time
//perhaps showing "YOUR ORDERS" page, then the server wans to demand
//Client certs. this will inturn makes HTTP.SYS to do the
//SEC_I_RENOGOTIATE through which the client cert demand is made
//
//THE BUG HERE IS THAT PRIOR TO QFE 4796, we call
//GET Client certificate native API ONLY WHEN THE HTTP.SYS is configured with
//flag = 2. Which means that apps using HTTPListener will not be able to
//demand a client cert at a later point
//
//The fix here is to demand the client cert when the channel is NOT INSECURE
//which means whether the client certs are requried at the beginning or not,
//if this is an SSL connection, Call HttpReceiveClientCertificate, thus
//starting the cert negotiation at that point
//
//NOTE: WHEN CALLING THE HttpReceiveClientCertificate, you can get
//ERROR_NOT_FOUND - which means the client did not provide the cert
//If this is important, the server should respond with 403 forbidden
//HTTP.SYS will not do this for you automatically ***
//--------------------------------------------------------------------
if (_sslStatus != SslStatus.Insecure)
{
// at this point we know that DefaultFlags has the 2 bit set (Negotiate Client certificate)
// the cert, though might or might not be there. try to retrieve it
// this number is the same that IIS decided to use
uint size = CertBoblSize;
while (true)
{
byte[] clientCertInfoBlob = new byte[checked((int)size)];
fixed (byte* pClientCertInfoBlob = &clientCertInfoBlob[0])
{
Interop.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo = (Interop.HttpApi.HTTP_SSL_CLIENT_CERT_INFO*)pClientCertInfoBlob;
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Calling Interop.HttpApi.HttpReceiveClientCertificate size:" + size);
uint bytesReceived = 0;
uint statusCode =
Interop.HttpApi.HttpReceiveClientCertificate(
HttpListenerContext.RequestQueueHandle,
_connectionId,
(uint)Interop.HttpApi.HTTP_FLAGS.NONE,
pClientCertInfo,
size,
&bytesReceived,
null);
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, "Call to Interop.HttpApi.HttpReceiveClientCertificate returned:" + statusCode + " bytesReceived:" + bytesReceived);
if (statusCode == Interop.HttpApi.ERROR_MORE_DATA)
{
size = bytesReceived + pClientCertInfo->CertEncodedSize;
continue;
}
else if (statusCode == Interop.HttpApi.ERROR_SUCCESS)
{
if (pClientCertInfo != null)
{
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, $"pClientCertInfo:{(IntPtr)pClientCertInfo} pClientCertInfo->CertFlags: {pClientCertInfo->CertFlags} pClientCertInfo->CertEncodedSize: {pClientCertInfo->CertEncodedSize} pClientCertInfo->pCertEncoded: {(IntPtr)pClientCertInfo->pCertEncoded} pClientCertInfo->Token: {(IntPtr)pClientCertInfo->Token} pClientCertInfo->CertDeniedByMapper: {pClientCertInfo->CertDeniedByMapper}");
if (pClientCertInfo->pCertEncoded != null)
{
try
{
byte[] certEncoded = new byte[pClientCertInfo->CertEncodedSize];
Marshal.Copy((IntPtr)pClientCertInfo->pCertEncoded, certEncoded, 0, certEncoded.Length);
ClientCertificate = new X509Certificate2(certEncoded);
}
catch (CryptographicException exception)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"CryptographicException={exception}");
}
catch (SecurityException exception)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SecurityException={exception}");
}
}
_clientCertificateError = (int)pClientCertInfo->CertFlags;
}
}
else
{
Debug.Assert(statusCode == Interop.HttpApi.ERROR_NOT_FOUND,
$"Call to Interop.HttpApi.HttpReceiveClientCertificate() failed with statusCode {statusCode}.");
}
}
break;
}
}
}
private Uri RequestUri
{
get
{
if (_requestUri == null)
{
_requestUri = HttpListenerRequestUriBuilder.GetRequestUri(
_rawUrl, RequestScheme, _cookedUrlHost, _cookedUrlPath, _cookedUrlQuery);
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_requestUri:{_requestUri}");
return _requestUri;
}
}
internal ChannelBinding GetChannelBinding()
{
return HttpListenerContext.Listener.GetChannelBindingFromTls(_connectionId);
}
internal void CheckDisposed()
{
if (_isDisposed)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
}
private bool SupportsWebSockets => WebSocketProtocolComponent.IsSupported;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Xunit;
namespace System.IO.MemoryMappedFiles.Tests
{
/// <summary>
/// Tests for MemoryMappedFile.CreateFromFile.
/// </summary>
public class MemoryMappedFileTests_CreateFromFile : MemoryMappedFilesTestBase
{
/// <summary>
/// Tests invalid arguments to the CreateFromFile path parameter.
/// </summary>
[Fact]
public void InvalidArguments_Path()
{
// null is an invalid path
AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null));
AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open));
AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open, CreateUniqueMapName()));
AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open, CreateUniqueMapName(), 4096));
AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Read));
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile fileStream parameter.
/// </summary>
[Fact]
public void InvalidArguments_FileStream()
{
// null is an invalid stream
AssertExtensions.Throws<ArgumentNullException>("fileStream", () => MemoryMappedFile.CreateFromFile(null, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile mode parameter.
/// </summary>
[Fact]
public void InvalidArguments_Mode()
{
// FileMode out of range
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42));
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null));
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null, 4096));
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null, 4096, MemoryMappedFileAccess.ReadWrite));
// FileMode.Append never allowed
AssertExtensions.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append));
AssertExtensions.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null));
AssertExtensions.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null, 4096));
AssertExtensions.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null, 4096, MemoryMappedFileAccess.ReadWrite));
// FileMode.CreateNew/Create/OpenOrCreate can't be used with default capacity, as the file will be empty
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew));
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Create));
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.OpenOrCreate));
// FileMode.Truncate can't be used with default capacity, as resulting file will be empty
using (TempFile file = new TempFile(GetTestFilePath()))
{
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Truncate));
}
}
[Fact]
public void InvalidArguments_Mode_Truncate()
{
// FileMode.Truncate never allowed
AssertExtensions.Throws<ArgumentException>("mode", null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Truncate));
AssertExtensions.Throws<ArgumentException>("mode", null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Truncate, null));
AssertExtensions.Throws<ArgumentException>("mode", null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Truncate, null, 4096));
AssertExtensions.Throws<ArgumentException>("mode", null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Truncate, null, 4096, MemoryMappedFileAccess.ReadWrite));
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile access parameter.
/// </summary>
[Fact]
public void InvalidArguments_Access()
{
// Out of range access values with a path
AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(-2)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(42)));
// Write-only access is not allowed on maps (only on views)
AssertExtensions.Throws<ArgumentException>("access", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Write));
// Test the same things, but with a FileStream instead of a path
using (TempFile file = new TempFile(GetTestFilePath()))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
// Out of range values with a stream
AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(-2), HandleInheritability.None, true));
AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(42), HandleInheritability.None, true));
// Write-only access is not allowed
AssertExtensions.Throws<ArgumentException>("access", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Write, HandleInheritability.None, true));
}
}
/// <summary>
/// Tests various values of FileAccess used to construct a FileStream and MemoryMappedFileAccess used
/// to construct a map over that stream. The combinations should all be valid.
/// </summary>
[Theory]
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.Read)]
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.Read)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.CopyOnWrite)]
public void FileAccessAndMapAccessCombinations_Valid(FileAccess fileAccess, MemoryMappedFileAccess mmfAccess)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (FileStream fs = new FileStream(file.Path, FileMode.Open, fileAccess))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, Capacity, mmfAccess, HandleInheritability.None, true))
{
ValidateMemoryMappedFile(mmf, Capacity, mmfAccess);
}
}
/// <summary>
/// Tests various values of FileAccess used to construct a FileStream and MemoryMappedFileAccess used
/// to construct a map over that stream on Windows. The combinations should all be invalid, resulting in exception.
/// </summary>
[PlatformSpecific(TestPlatforms.Windows)] // On Windows, permission errors come from CreateFromFile
[Theory]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadExecute)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.Read)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadExecute)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.ReadExecute)] // this and the next are explicitly left off of the Unix test due to differences in Unix permissions
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.ReadWriteExecute)]
public void FileAccessAndMapAccessCombinations_Invalid_Windows(FileAccess fileAccess, MemoryMappedFileAccess mmfAccess)
{
// On Windows, creating the file mapping does the permissions checks, so the exception comes from CreateFromFile.
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (FileStream fs = new FileStream(file.Path, FileMode.Open, fileAccess))
{
Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(fs, null, Capacity, mmfAccess, HandleInheritability.None, true));
}
}
/// <summary>
/// Tests various values of FileAccess used to construct a FileStream and MemoryMappedFileAccess used
/// to construct a map over that stream on Unix. The combinations should all be invalid, resulting in exception.
/// </summary>
[PlatformSpecific(TestPlatforms.AnyUnix)] // On Unix, permission errors come from CreateView*
[Theory]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadExecute)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.Read)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadExecute)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWriteExecute)]
public void FileAccessAndMapAccessCombinations_Invalid_Unix(FileAccess fileAccess, MemoryMappedFileAccess mmfAccess)
{
// On Unix we don't actually create the OS map until the view is created; this results in the permissions
// error being thrown from CreateView* instead of from CreateFromFile.
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (FileStream fs = new FileStream(file.Path, FileMode.Open, fileAccess))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, Capacity, mmfAccess, HandleInheritability.None, true))
{
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor());
}
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile mapName parameter.
/// </summary>
[Fact]
public void InvalidArguments_MapName()
{
using (TempFile file = new TempFile(GetTestFilePath()))
{
// Empty string is an invalid map name
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty));
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty, 4096));
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty, 4096, MemoryMappedFileAccess.Read));
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty, 4096, MemoryMappedFileAccess.Read));
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(fs, string.Empty, 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true));
}
}
}
/// <summary>
/// Test to verify that map names are left unsupported on Unix.
/// </summary>
[PlatformSpecific(TestPlatforms.AnyUnix)] // Check map names are unsupported on Unix
[Theory]
[MemberData(nameof(CreateValidMapNames))]
public void MapNamesNotSupported_Unix(string mapName)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
{
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName));
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, Capacity));
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, Capacity, MemoryMappedFileAccess.ReadWrite));
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, Capacity, MemoryMappedFileAccess.ReadWrite));
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(fs, mapName, 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true));
}
}
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile capacity parameter.
/// </summary>
[Fact]
public void InvalidArguments_Capacity()
{
using (TempFile file = new TempFile(GetTestFilePath()))
{
// Out of range values for capacity
Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), -1));
Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), -1, MemoryMappedFileAccess.Read));
// Positive capacity required when creating a map from an empty file
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, 0, MemoryMappedFileAccess.Read));
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), 0, MemoryMappedFileAccess.Read));
// With Read, the capacity can't be larger than the backing file's size.
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), 1, MemoryMappedFileAccess.Read));
// Now with a FileStream...
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
// The subsequent tests are only valid we if we start with an empty FileStream, which we should have.
// This also verifies the previous failed tests didn't change the length of the file.
Assert.Equal(0, fs.Length);
// Out of range values for capacity
Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMappedFile.CreateFromFile(fs, null, -1, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
// Default (0) capacity with an empty file
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(fs, null, 0, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 0, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
// Larger capacity than the underlying file, but read-only such that we can't expand the file
fs.SetLength(4096);
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(fs, null, 8192, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 8192, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
// Capacity can't be less than the file size (for such cases a view can be created with the smaller size)
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateFromFile(fs, null, 1, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true));
}
// Capacity can't be less than the file size
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), 1, MemoryMappedFileAccess.Read));
}
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile inheritability parameter.
/// </summary>
[Theory]
[InlineData((HandleInheritability)(-1))]
[InlineData((HandleInheritability)(42))]
public void InvalidArguments_Inheritability(HandleInheritability inheritability)
{
// Out of range values for inheritability
using (TempFile file = new TempFile(GetTestFilePath()))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("inheritability", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.ReadWrite, inheritability, true));
}
}
/// <summary>
/// Test various combinations of arguments to CreateFromFile, focusing on the Open and OpenOrCreate modes,
/// and validating the creating maps each time they're created.
/// </summary>
[Theory]
[MemberData(nameof(MemberData_ValidArgumentCombinationsWithPath),
new FileMode[] { FileMode.Open, FileMode.OpenOrCreate },
new string[] { null, "CreateUniqueMapName()" },
new long[] { 1, 256, -1 /*pagesize*/, 10000 },
new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite })]
public void ValidArgumentCombinationsWithPath_ModesOpenOrCreate(
FileMode mode, string mapName, long capacity, MemoryMappedFileAccess access)
{
// Test each of the four path-based CreateFromFile overloads
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
// Finally, re-test the last overload, this time with an empty file to start
using (TempFile file = new TempFile(GetTestFilePath()))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
}
/// <summary>
/// Test various combinations of arguments to CreateFromFile, focusing on the CreateNew mode,
/// and validating the creating maps each time they're created.
/// </summary>
[Theory]
[MemberData(nameof(MemberData_ValidArgumentCombinationsWithPath),
new FileMode[] { FileMode.CreateNew },
new string[] { null, "CreateUniqueMapName()" },
new long[] { 1, 256, -1 /*pagesize*/, 10000 },
new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite })]
public void ValidArgumentCombinationsWithPath_ModeCreateNew(
FileMode mode, string mapName, long capacity, MemoryMappedFileAccess access)
{
// For FileMode.CreateNew, the file will be created new and thus be empty, so we can only use the overloads
// that take a capacity, since the default capacity doesn't work with an empty file.
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, mapName, capacity, access))
{
ValidateMemoryMappedFile(mmf, capacity, access);
}
}
/// <summary>
/// Test various combinations of arguments to CreateFromFile, focusing on the Create mode,
/// and validating the creating maps each time they're created.
/// </summary>
[Theory]
[MemberData(nameof(MemberData_ValidNameCapacityCombinationsWithPath),
new string[] { null, "CreateUniqueMapName()" },
new long[] { 1, 256, -1 /*pagesize*/, 10000 })]
public void ValidArgumentCombinationsWithPath_ModeCreate(string mapName, long capacity)
{
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Create, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Create, mapName, capacity, MemoryMappedFileAccess.ReadWrite))
{
ValidateMemoryMappedFile(mmf, capacity, MemoryMappedFileAccess.ReadWrite);
}
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Create, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
}
/// <summary>
/// Provides input data to the ValidArgumentCombinationsWithPath tests, yielding the full matrix
/// of combinations of input values provided, except for those that are known to be unsupported
/// (e.g. non-null map names on Unix), and with appropriate values substituted in for placeholders
/// listed in the MemberData attribute (e.g. actual system page size instead of -1).
/// </summary>
/// <param name="modes">The modes to yield.</param>
/// <param name="mapNames">
/// The names to yield.
/// non-null may be excluded based on platform.
/// "CreateUniqueMapName()" will be translated to an invocation of that method.
/// </param>
/// <param name="capacities">The capacities to yield. -1 will be translated to system page size.</param>
/// <param name="accesses">
/// The accesses to yield. Non-writable accesses will be skipped if the current mode doesn't support it.
/// </param>
public static IEnumerable<object[]> MemberData_ValidArgumentCombinationsWithPath(
FileMode[] modes, string[] mapNames, long[] capacities, MemoryMappedFileAccess[] accesses)
{
foreach (object[] namesCaps in MemberData_ValidNameCapacityCombinationsWithPath(mapNames, capacities))
{
foreach (FileMode mode in modes)
{
foreach (MemoryMappedFileAccess access in accesses)
{
if ((mode == FileMode.Create || mode == FileMode.CreateNew || mode == FileMode.Truncate) &&
!IsWritable(access))
{
continue;
}
yield return new object[] { mode, namesCaps[0], namesCaps[1], access };
}
}
}
}
public static IEnumerable<object[]> MemberData_ValidNameCapacityCombinationsWithPath(
string[] mapNames, long[] capacities)
{
foreach (string tmpMapName in mapNames)
{
if (tmpMapName != null && !MapNamesSupported)
{
continue;
}
foreach (long tmpCapacity in capacities)
{
long capacity = tmpCapacity == -1 ? s_pageSize.Value : tmpCapacity;
string mapName = tmpMapName == "CreateUniqueMapName()" ? CreateUniqueMapName() : tmpMapName;
yield return new object[] { mapName, capacity, };
}
}
}
/// <summary>
/// Test various combinations of arguments to CreateFromFile that accepts a FileStream.
/// </summary>
[Theory]
[MemberData(nameof(MemberData_ValidArgumentCombinationsWithStream),
new string[] { null, "CreateUniqueMapName()" },
new long[] { 1, 256, -1 /*pagesize*/, 10000 },
new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite },
new HandleInheritability[] { HandleInheritability.None, HandleInheritability.Inheritable },
new bool[] { false, true })]
public void ValidArgumentCombinationsWithStream(
string mapName, long capacity, MemoryMappedFileAccess access, HandleInheritability inheritability, bool leaveOpen)
{
// Create a file of the right size, then create the map for it.
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, mapName, capacity, access, inheritability, leaveOpen))
{
ValidateMemoryMappedFile(mmf, capacity, access, inheritability);
}
// Start with an empty file and let the map grow it to the right size. This requires write access.
if (IsWritable(access))
{
using (FileStream fs = File.Create(GetTestFilePath()))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, mapName, capacity, access, inheritability, leaveOpen))
{
ValidateMemoryMappedFile(mmf, capacity, access, inheritability);
}
}
}
/// <summary>
/// Provides input data to the ValidArgumentCombinationsWithStream tests, yielding the full matrix
/// of combinations of input values provided, except for those that are known to be unsupported
/// (e.g. non-null map names on Unix), and with appropriate values substituted in for placeholders
/// listed in the MemberData attribute (e.g. actual system page size instead of -1).
/// </summary>
/// <param name="mapNames">
/// The names to yield.
/// non-null may be excluded based on platform.
/// "CreateUniqueMapName()" will be translated to an invocation of that method.
/// </param>
/// <param name="capacities">The capacities to yield. -1 will be translated to system page size.</param>
/// <param name="accesses">
/// The accesses to yield. Non-writable accesses will be skipped if the current mode doesn't support it.
/// </param>
/// <param name="inheritabilities">The inheritabilities to yield.</param>
/// <param name="inheritabilities">The leaveOpen values to yield.</param>
public static IEnumerable<object[]> MemberData_ValidArgumentCombinationsWithStream(
string[] mapNames, long[] capacities, MemoryMappedFileAccess[] accesses, HandleInheritability[] inheritabilities, bool[] leaveOpens)
{
foreach (string tmpMapName in mapNames)
{
if (tmpMapName != null && !MapNamesSupported)
{
continue;
}
foreach (long tmpCapacity in capacities)
{
long capacity = tmpCapacity == -1 ?
s_pageSize.Value :
tmpCapacity;
foreach (MemoryMappedFileAccess access in accesses)
{
foreach (HandleInheritability inheritability in inheritabilities)
{
foreach (bool leaveOpen in leaveOpens)
{
string mapName = tmpMapName == "CreateUniqueMapName()" ? CreateUniqueMapName() : tmpMapName;
yield return new object[] { mapName, capacity, access, inheritability, leaveOpen };
}
}
}
}
}
}
/// <summary>
/// Test that a map using the default capacity (0) grows to the size of the underlying file.
/// </summary>
[Fact]
public void DefaultCapacityIsFileLength()
{
const int DesiredCapacity = 8192;
const int DefaultCapacity = 0;
// With path
using (TempFile file = new TempFile(GetTestFilePath(), DesiredCapacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, DefaultCapacity))
{
ValidateMemoryMappedFile(mmf, DesiredCapacity);
}
// With stream
using (TempFile file = new TempFile(GetTestFilePath(), DesiredCapacity))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, DefaultCapacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true))
{
ValidateMemoryMappedFile(mmf, DesiredCapacity);
}
}
/// <summary>
/// Test that appropriate exceptions are thrown creating a map with a non-existent file and a mode
/// that requires the file to exist.
/// </summary>
[Fact]
public void FileDoesNotExist_OpenFileMode()
{
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath()));
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open));
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, null));
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, null, 4096));
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, null, 4096, MemoryMappedFileAccess.ReadWrite));
}
/// <summary>
/// Test that appropriate exceptions are thrown creating a map with an existing file and a mode
/// that requires the file to not exist.
/// </summary>
[Fact]
public void FileAlreadyExists()
{
using (TempFile file = new TempFile(GetTestFilePath()))
{
// FileMode.CreateNew invalid when the file already exists
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew));
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew, CreateUniqueMapName()));
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew, CreateUniqueMapName(), 4096));
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.ReadWrite));
}
}
/// <summary>
/// Test exceptional behavior when trying to create a map for a read-write file that's currently in use.
/// </summary>
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // FileShare is limited on Unix, with None == exclusive, everything else == concurrent
public void FileInUse_CreateFromFile_FailsWithExistingReadWriteFile()
{
// Already opened with a FileStream
using (TempFile file = new TempFile(GetTestFilePath(), 4096))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path));
}
}
/// <summary>
/// Test exceptional behavior when trying to create a map for a non-shared file that's currently in use.
/// </summary>
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // FileShare is limited on Unix, with None == exclusive, everything else == concurrent
public void FileInUse_CreateFromFile_FailsWithExistingReadWriteMap()
{
// Already opened with another read-write map
using (TempFile file = new TempFile(GetTestFilePath(), 4096))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path))
{
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path));
}
}
/// <summary>
/// Test exceptional behavior when trying to create a map for a non-shared file that's currently in use.
/// </summary>
[Fact]
public void FileInUse_CreateFromFile_FailsWithExistingNoShareFile()
{
// Already opened with a FileStream
using (TempFile file = new TempFile(GetTestFilePath(), 4096))
using (FileStream fs = File.Open(file.Path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path));
}
}
/// <summary>
/// Test to validate we can create multiple concurrent read-only maps from the same file path.
/// </summary>
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "On netfx, the MMF.CreateFromFile default FileShare is None. We intentionally changed it in netcoreapp in #6092.")]
public void FileInUse_CreateFromFile_SucceedsWithReadOnly()
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (MemoryMappedFile mmf1 = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, MemoryMappedFileAccess.Read))
using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, MemoryMappedFileAccess.Read))
using (MemoryMappedViewAccessor acc1 = mmf1.CreateViewAccessor(0, Capacity, MemoryMappedFileAccess.Read))
using (MemoryMappedViewAccessor acc2 = mmf2.CreateViewAccessor(0, Capacity, MemoryMappedFileAccess.Read))
{
Assert.Equal(acc1.Capacity, acc2.Capacity);
}
}
/// <summary>
/// Test the exceptional behavior of *Execute access levels.
/// </summary>
[PlatformSpecific(TestPlatforms.Windows)] // Unix model for executable differs from Windows
[Theory]
[InlineData(MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "CreateFromFile in desktop uses FileStream's ctor that takes a FileSystemRights in order to specify execute privileges.")]
public void FileNotOpenedForExecute(MemoryMappedFileAccess access)
{
using (TempFile file = new TempFile(GetTestFilePath(), 4096))
{
// The FileStream created by the map doesn't have GENERIC_EXECUTE set
Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, 4096, access));
// The FileStream opened explicitly doesn't have GENERIC_EXECUTE set
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(fs, null, 4096, access, HandleInheritability.None, true));
}
}
}
/// <summary>
/// On Unix, modifying a file that is ReadOnly will fail under normal permissions.
/// If the test is being run under the superuser, however, modification of a ReadOnly
/// file is allowed.
/// </summary>
public void WriteToReadOnlyFile(MemoryMappedFileAccess access, bool succeeds)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
{
FileAttributes original = File.GetAttributes(file.Path);
File.SetAttributes(file.Path, FileAttributes.ReadOnly);
try
{
if (succeeds)
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, access))
ValidateMemoryMappedFile(mmf, Capacity, MemoryMappedFileAccess.Read);
else
Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, access));
}
finally
{
File.SetAttributes(file.Path, original);
}
}
}
[Theory]
[InlineData(MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.ReadWrite)]
public void WriteToReadOnlyFile_ReadWrite(MemoryMappedFileAccess access)
{
WriteToReadOnlyFile(access, access == MemoryMappedFileAccess.Read ||
(!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && geteuid() == 0));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "CreateFromFile in desktop uses FileStream's ctor that takes a FileSystemRights in order to specify execute privileges.")]
public void WriteToReadOnlyFile_CopyOnWrite()
{
WriteToReadOnlyFile(MemoryMappedFileAccess.CopyOnWrite, (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && geteuid() == 0));
}
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "CreateFromFile in desktop uses FileStream's ctor that takes a FileSystemRights in order to specify execute privileges.")]
public void WriteToReadOnlyFile_CopyOnWrite_netfx()
{
WriteToReadOnlyFile(MemoryMappedFileAccess.CopyOnWrite, succeeds: true);
}
/// <summary>
/// Test to ensure that leaveOpen is appropriately respected, either leaving the FileStream open
/// or closing it on disposal.
/// </summary>
[Theory]
[InlineData(true)]
[InlineData(false)]
public void LeaveOpenRespected_Basic(bool leaveOpen)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath()))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
// Handle should still be open
SafeFileHandle handle = fs.SafeFileHandle;
Assert.False(handle.IsClosed);
// Create and close the map
MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, leaveOpen).Dispose();
// The handle should now be open iff leaveOpen
Assert.NotEqual(leaveOpen, handle.IsClosed);
}
}
/// <summary>
/// Test to ensure that leaveOpen is appropriately respected, either leaving the FileStream open
/// or closing it on disposal.
/// </summary>
[Theory]
[InlineData(true)]
[InlineData(false)]
public void LeaveOpenRespected_OutstandingViews(bool leaveOpen)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath()))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
// Handle should still be open
SafeFileHandle handle = fs.SafeFileHandle;
Assert.False(handle.IsClosed);
// Create the map, create each of the views, then close the map
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, leaveOpen))
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, Capacity))
using (MemoryMappedViewStream s = mmf.CreateViewStream(0, Capacity))
{
// Explicitly close the map. The handle should now be open iff leaveOpen.
mmf.Dispose();
Assert.NotEqual(leaveOpen, handle.IsClosed);
// But the views should still be usable.
ValidateMemoryMappedViewAccessor(acc, Capacity, MemoryMappedFileAccess.ReadWrite);
ValidateMemoryMappedViewStream(s, Capacity, MemoryMappedFileAccess.ReadWrite);
}
}
}
/// <summary>
/// Test to validate we can create multiple maps from the same FileStream.
/// </summary>
[Fact]
public void MultipleMapsForTheSameFileStream()
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (FileStream fs = new FileStream(file.Path, FileMode.Open))
using (MemoryMappedFile mmf1 = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true))
using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true))
using (MemoryMappedViewAccessor acc1 = mmf1.CreateViewAccessor())
using (MemoryMappedViewAccessor acc2 = mmf2.CreateViewAccessor())
{
// The capacity of the two maps should be equal
Assert.Equal(acc1.Capacity, acc2.Capacity);
var rand = new Random();
for (int i = 1; i <= 10; i++)
{
// Write a value to one map, then read it from the other,
// ping-ponging between the two.
int pos = rand.Next((int)acc1.Capacity - 1);
MemoryMappedViewAccessor reader = acc1, writer = acc2;
if (i % 2 == 0)
{
reader = acc2;
writer = acc1;
}
writer.Write(pos, (byte)i);
writer.Flush();
Assert.Equal(i, reader.ReadByte(pos));
}
}
}
/// <summary>
/// Test to verify that the map's size increases the underlying file size if the map's capacity is larger.
/// </summary>
[Fact]
public void FileSizeExpandsToCapacity()
{
const int InitialCapacity = 256;
using (TempFile file = new TempFile(GetTestFilePath(), InitialCapacity))
{
// Create a map with a larger capacity, and verify the file has expanded.
MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, InitialCapacity * 2).Dispose();
using (FileStream fs = File.OpenRead(file.Path))
{
Assert.Equal(InitialCapacity * 2, fs.Length);
}
// Do the same thing again but with a FileStream.
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
MemoryMappedFile.CreateFromFile(fs, null, InitialCapacity * 4, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true).Dispose();
Assert.Equal(InitialCapacity * 4, fs.Length);
}
}
}
/// <summary>
/// Test the exceptional behavior when attempting to create a map so large it's not supported.
/// </summary>
[PlatformSpecific(~TestPlatforms.OSX)] // Because of the file-based backing, OS X pops up a warning dialog about being out-of-space (even though we clean up immediately)
[Fact]
public void TooLargeCapacity()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.CreateNew))
{
try
{
long length = long.MaxValue;
MemoryMappedFile.CreateFromFile(fs, null, length, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true).Dispose();
Assert.Equal(length, fs.Length); // if it didn't fail to create the file, the length should be what was requested.
}
catch (IOException)
{
// Expected exception for too large a capacity
}
}
}
/// <summary>
/// Test to verify map names are handled appropriately, causing a conflict when they're active but
/// reusable in a sequential manner.
/// </summary>
[PlatformSpecific(TestPlatforms.Windows)] // Tests reusability of map names on Windows
[Theory]
[MemberData(nameof(CreateValidMapNames))]
public void ReusingNames_Windows(string name)
{
const int Capacity = 4096;
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew, name, Capacity))
{
ValidateMemoryMappedFile(mmf, Capacity);
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew, name, Capacity));
}
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew, name, Capacity))
{
ValidateMemoryMappedFile(mmf, Capacity);
}
}
}
}
| |
using IrcClientCore;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Storage;
using Windows.Storage.AccessCache;
using Windows.UI.Notifications;
using WinIRC.Net;
namespace WinIRC.Utils
{
public class MessageCollection : ObservableCollection<Message>
{
public int MaxSize { get; }
public MessageCollectionLogWriter LogWriter { get; }
public string Server { get; private set; }
public string Channel { get; private set; }
public MessageCollection(int size, string server, string channel) : base()
{
this.MaxSize = size;
if (Config.GetBoolean(Config.EnableLogs))
{
this.LogWriter = new MessageCollectionLogWriter(this, server, channel);
Task.Run(this.LogWriter.Process);
}
this.Server = server;
this.Channel = channel;
this.CollectionChanged += MessageCollection_CollectionChanged;
}
private void MessageCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (this.Count > MaxSize)
{
Task.Run(() => RemoveAt(0));
}
var key = Config.PerChannelSetting(Server, Channel, Config.AlwaysNotify);
var ping = Config.GetBoolean(key, false);
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
{
var items = e.NewItems;
foreach (var item in items)
{
var message = (Message)item;
if (LogWriter != null && !LogWriter.Error)
{
LogWriter.Add(message);
}
if (ping)
{
var toast = IrcUWPBase.CreateMentionToast(Server, message.User, Channel, message.Text);
toast.ExpirationTime = DateTime.Now.AddDays(2);
ToastNotificationManager.CreateToastNotifier().Show(toast);
}
}
}
}
}
public class MessageCollectionLogWriter
{
private ConcurrentQueue<Message> msgQueue;
private MessageCollection msgs;
private string server;
private string channel;
private StorageFolder serverFolder;
private string currentDate;
private StreamWriter sw;
private bool PathChanged;
public StorageFile LogFile { get; private set; }
public bool Error { get; private set; }
private readonly System.Threading.EventWaitHandle waitHandle = new System.Threading.AutoResetEvent(true);
public MessageCollectionLogWriter(MessageCollection msgs, string server, string channel)
{
this.server = server;
this.channel = channel;
msgQueue = new ConcurrentQueue<Message>();
this.msgs = msgs;
}
public async Task OpenFile()
{
if (sw != null) await sw.FlushAsync();
LogFile = await serverFolder.CreateFileAsync(channel + "-" + currentDate + ".log", CreationCollisionOption.OpenIfExists);
PathChanged = true;
await WriteLine("----- Opened log on " + currentDate + " " + DateTime.Now.ToString("hh:mm") + " -----");
}
public void Add(Message message)
{
msgQueue.Enqueue(message);
waitHandle.Set();
}
public async Task WriteLine(string str)
{
if (PathChanged || sw == null)
{
sw = File.AppendText(LogFile.Path);
}
await sw.WriteLineAsync(str);
await sw.FlushAsync();
PathChanged = false;
//await FileIO.AppendTextAsync(LogFile, str + "\r\n");
}
private string MessageToString(Message msg)
{
var user = "";
if (msg.Type == MessageType.Action || msg.Type == MessageType.Info)
{
user = String.Format("* {0}", msg.User);
}
else if (msg.User == "")
{
user = "*";
}
else
{
user = String.Format("<{0}>", msg.User);
}
return $"[{msg.Timestamp}] {user} {msg.Text}";
}
public async Task Process()
{
while (!Error)
{
if (msgQueue.Count == 0)
{
waitHandle.WaitOne();
}
try
{
var folderList = StorageApplicationPermissions.FutureAccessList;
if (LogFile == null && Config.GetBoolean(Config.EnableLogs) && folderList.ContainsItem(Config.LogsFolder))
{
var parent = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(Config.LogsFolder);
serverFolder = await parent.CreateFolderAsync(server, CreationCollisionOption.OpenIfExists);
currentDate = DateTime.Now.ToString("yyyy-MM-dd");
await OpenFile();
}
else if (LogFile != null)
{
var newDate = DateTime.Now.ToString("yyyy-MM-dd");
if (newDate != currentDate)
{
currentDate = newDate;
await OpenFile();
}
Message msg;
msgQueue.TryDequeue(out msg);
if (msg != null)
{
await WriteLine(MessageToString(msg));
}
}
else
{
Error = true;
break;
}
}
catch (Exception e)
{
Error = true;
Message error = new Message()
{
User = "Error",
Type = MessageType.Info,
Text = e.Message + "\r\n Logging disabled for this channel"
};
msgs.Add(error);
}
waitHandle.Reset();
}
}
}
}
| |
// 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.CSharp.CodeRefactorings.MoveDeclarationNearReference;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.MoveDeclarationNearReference
{
public class MoveDeclarationNearReferenceTests : AbstractCSharpCodeActionTest
{
protected override object CreateCodeRefactoringProvider(Workspace workspace)
{
return new MoveDeclarationNearReferenceCodeRefactoringProvider();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)]
public async Task TestMove1()
{
await TestAsync(
@"class C { void M() { int [||]x; { Console.WriteLine(x); } } }",
@"class C { void M() { { int x; Console.WriteLine(x); } } }",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)]
public async Task TestMove2()
{
await TestAsync(
@"class C { void M() { int [||]x; Console.WriteLine(); Console.WriteLine(x); } }",
@"class C { void M() { Console.WriteLine(); int x; Console.WriteLine(x); } }",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)]
public async Task TestMove3()
{
await TestAsync(
@"class C { void M() { int [||]x; Console.WriteLine(); { Console.WriteLine(x); } { Console.WriteLine(x); } }",
@"class C { void M() { Console.WriteLine(); int x; { Console.WriteLine(x); } { Console.WriteLine(x); } }",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)]
public async Task TestMove4()
{
await TestAsync(
@"class C { void M() { int [||]x; Console.WriteLine(); { Console.WriteLine(x); } }",
@"class C { void M() { Console.WriteLine(); { int x; Console.WriteLine(x); } }",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)]
public async Task TestAssign1()
{
await TestAsync(
@"class C { void M() { int [||]x; { x = 5; Console.WriteLine(x); } } }",
@"class C { void M() { { int x = 5; Console.WriteLine(x); } } }",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)]
public async Task TestAssign2()
{
await TestAsync(
@"class C { void M() { int [||]x = 0; { x = 5; Console.WriteLine(x); } } }",
@"class C { void M() { { int x = 5; Console.WriteLine(x); } } }",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)]
public async Task TestAssign3()
{
await TestAsync(
@"class C { void M() { var [||]x = (short)0; { x = 5; Console.WriteLine(x); } } }",
@"class C { void M() { { var x = (short)0; x = 5; Console.WriteLine(x); } } }",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)]
public async Task TestMissing1()
{
await TestMissingAsync(
@"class C { void M() { int [||]x; Console.WriteLine(x); } }");
}
[WorkItem(538424, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538424")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)]
public async Task TestMissingWhenReferencedInDeclaration()
{
await TestMissingAsync(
@"class Program { static void Main ( ) { object [ ] [||]x = { x = null } ; x . ToString ( ) ; } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)]
public async Task TestMissingWhenInDeclarationGroup()
{
await TestMissingAsync(
@"class Program { static void Main ( ) { int [||]i = 5; int j = 10; Console.WriteLine(i); } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)]
[WorkItem(541475, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541475")]
public async Task Regression8190()
{
await TestMissingAsync(
@"class Program { void M() { { object x; [|object|] } } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)]
public async Task TestFormatting()
{
await TestAsync(
@"class Program
{
static void Main(string[] args)
{
int [||]i = 5; Console.WriteLine();
Console.Write(i);
}
}",
@"class Program
{
static void Main(string[] args)
{
Console.WriteLine();
int i = 5; Console.Write(i);
}
}",
index: 0,
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)]
public async Task TestMissingInHiddenBlock1()
{
await TestMissingAsync(
@"class Program
{
void Main()
{
int [|x|] = 0;
Foo();
#line hidden
Bar(x);
}
#line default
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)]
public async Task TestMissingInHiddenBlock2()
{
await TestMissingAsync(
@"class Program
{
void Main()
{
int [|x|] = 0;
Foo();
#line hidden
Foo();
#line default
Bar(x);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)]
public async Task TestAvailableInNonHiddenBlock1()
{
await TestAsync(
@"#line default
class Program
{
void Main()
{
int [||]x = 0;
Foo();
Bar(x);
#line hidden
}
#line default
}",
@"#line default
class Program
{
void Main()
{
Foo();
int x = 0;
Bar(x);
#line hidden
}
#line default
}",
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)]
public async Task TestAvailableInNonHiddenBlock2()
{
await TestAsync(
@"class Program
{
void Main()
{
int [||]x = 0;
Foo();
#line hidden
Foo();
#line default
Foo();
Bar(x);
}
}",
@"class Program
{
void Main()
{
Foo();
#line hidden
Foo();
#line default
Foo();
int x = 0;
Bar(x);
}
}",
compareTokens: false);
}
[WorkItem(545435, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545435")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)]
public async Task TestWarnOnChangingScopes1()
{
await TestAsync(
@"using System . Linq ; class Program { void Main ( ) { var [||]@lock = new object ( ) ; new [ ] { 1 } . AsParallel ( ) . ForAll ( ( i ) => { lock ( @lock ) { } } ) ; } } ",
@"using System . Linq ; class Program { void Main ( ) { new [ ] { 1 } . AsParallel ( ) . ForAll ( ( i ) => { {|Warning:var @lock = new object ( ) ;|} lock ( @lock ) { } } ) ; } } ");
}
[WorkItem(545435, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545435")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)]
public async Task TestWarnOnChangingScopes2()
{
await TestAsync(
@"using System ; using System . Linq ; class Program { void Main ( ) { var [||]i = 0 ; foreach ( var v in new [ ] { 1 } ) { Console . Write ( i ) ; i ++ ; } } } ",
@"using System ; using System . Linq ; class Program { void Main ( ) { foreach ( var v in new [ ] { 1 } ) { {|Warning:var i = 0 ;|} Console . Write ( i ) ; i ++ ; } } } ");
}
[WorkItem(545840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545840")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)]
public async Task InsertCastIfNecessary1()
{
await TestAsync(
@"using System;
static class C
{
static int Outer(Action<int> x, object y) { return 1; }
static int Outer(Action<string> x, string y) { return 2; }
static void Inner(int x, int[] y) { }
unsafe static void Inner(string x, int*[] y) { }
static void Main()
{
var [||]a = Outer(x => Inner(x, null), null);
unsafe
{
Console.WriteLine(a);
}
}
}",
@"using System;
static class C
{
static int Outer(Action<int> x, object y) { return 1; }
static int Outer(Action<string> x, string y) { return 2; }
static void Inner(int x, int[] y) { }
unsafe static void Inner(string x, int*[] y) { }
static void Main()
{
unsafe
{
var a = Outer(x => Inner(x, null), (object)null);
Console.WriteLine(a);
}
}
}",
compareTokens: false);
}
[WorkItem(545835, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545835")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)]
public async Task InsertCastIfNecessary2()
{
await TestAsync(
@"using System;
class X
{
static int Foo(Func<int?, byte> x, object y) { return 1; }
static int Foo(Func<X, byte> x, string y) { return 2; }
const int Value = 1000;
static void Main()
{
var [||]a = Foo(X => (byte)X.Value, null);
unchecked
{
Console.WriteLine(a);
}
}
}",
@"using System;
class X
{
static int Foo(Func<int?, byte> x, object y) { return 1; }
static int Foo(Func<X, byte> x, string y) { return 2; }
const int Value = 1000;
static void Main()
{
unchecked
{
var a = Foo(X => (byte)X.Value, (object)null);
Console.WriteLine(a);
}
}
}",
compareTokens: false);
}
[WorkItem(546267, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546267")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)]
public async Task MissingIfNotInDeclarationSpan()
{
await TestMissingAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
// Comment [||]about foo!
// Comment about foo!
// Comment about foo!
// Comment about foo!
// Comment about foo!
// Comment about foo!
// Comment about foo!
int foo;
Console.WriteLine();
Console.WriteLine(foo);
}
}");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using Microsoft.CSharp.RuntimeBinder.Errors;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal sealed class SymbolLoader
{
private readonly NameManager _nameManager;
public PredefinedMembers PredefinedMembers { get; }
private GlobalSymbolContext GlobalSymbolContext { get; }
public ErrorHandling ErrorContext { get; }
public SymbolTable RuntimeBinderSymbolTable { get; private set; }
public SymbolLoader(
GlobalSymbolContext globalSymbols,
UserStringBuilder userStringBuilder,
ErrorHandling errorContext
)
{
_nameManager = globalSymbols.GetNameManager();
PredefinedMembers = new PredefinedMembers(this);
ErrorContext = errorContext;
GlobalSymbolContext = globalSymbols;
Debug.Assert(GlobalSymbolContext != null);
}
public ErrorHandling GetErrorContext()
{
return ErrorContext;
}
public GlobalSymbolContext GetGlobalSymbolContext()
{
return GlobalSymbolContext;
}
public MethodSymbol LookupInvokeMeth(AggregateSymbol pAggDel)
{
Debug.Assert(pAggDel.AggKind() == AggKindEnum.Delegate);
for (Symbol pSym = LookupAggMember(NameManager.GetPredefinedName(PredefinedName.PN_INVOKE), pAggDel, symbmask_t.MASK_ALL);
pSym != null;
pSym = LookupNextSym(pSym, pAggDel, symbmask_t.MASK_ALL))
{
if (pSym.IsMethodSymbol() && pSym.AsMethodSymbol().isInvoke())
{
return pSym.AsMethodSymbol();
}
}
return null;
}
public NameManager GetNameManager()
{
return _nameManager;
}
public PredefinedTypes getPredefTypes()
{
return GlobalSymbolContext.GetPredefTypes();
}
public TypeManager GetTypeManager()
{
return TypeManager;
}
public TypeManager TypeManager
{
get { return GlobalSymbolContext.TypeManager; }
}
public PredefinedMembers getPredefinedMembers()
{
return PredefinedMembers;
}
public BSYMMGR getBSymmgr()
{
return GlobalSymbolContext.GetGlobalSymbols();
}
public SymFactory GetGlobalSymbolFactory()
{
return GlobalSymbolContext.GetGlobalSymbolFactory();
}
public MiscSymFactory GetGlobalMiscSymFactory()
{
return GlobalSymbolContext.GetGlobalMiscSymFactory();
}
public AggregateType GetReqPredefType(PredefinedType pt)
{
return GetReqPredefType(pt, true);
}
public AggregateType GetReqPredefType(PredefinedType pt, bool fEnsureState)
{
AggregateSymbol agg = GetTypeManager().GetReqPredefAgg(pt);
if (agg == null)
{
Debug.Assert(false, "Required predef type missing");
return null;
}
AggregateType ats = agg.getThisType();
return ats;
}
public AggregateSymbol GetOptPredefAgg(PredefinedType pt)
{
return GetOptPredefAgg(pt, true);
}
private AggregateSymbol GetOptPredefAgg(PredefinedType pt, bool fEnsureState)
{
AggregateSymbol agg = GetTypeManager().GetOptPredefAgg(pt);
return agg;
}
public AggregateType GetOptPredefType(PredefinedType pt)
{
return GetOptPredefType(pt, true);
}
public AggregateType GetOptPredefType(PredefinedType pt, bool fEnsureState)
{
AggregateSymbol agg = GetTypeManager().GetOptPredefAgg(pt);
if (agg == null)
return null;
AggregateType ats = agg.getThisType();
return ats;
}
public AggregateType GetOptPredefTypeErr(PredefinedType pt, bool fEnsureState)
{
AggregateSymbol agg = GetTypeManager().GetOptPredefAgg(pt);
if (agg == null)
{
getPredefTypes().ReportMissingPredefTypeError(ErrorContext, pt);
return null;
}
AggregateType ats = agg.getThisType();
return ats;
}
public Symbol LookupAggMember(Name name, AggregateSymbol agg, symbmask_t mask)
{
return getBSymmgr().LookupAggMember(name, agg, mask);
}
public Symbol LookupNextSym(Symbol sym, ParentSymbol parent, symbmask_t kindmask)
{
return BSYMMGR.LookupNextSym(sym, parent, kindmask);
}
// It would be nice to make this a virtual method on typeSym.
public AggregateType GetAggTypeSym(CType typeSym)
{
Debug.Assert(typeSym != null);
Debug.Assert(typeSym.IsAggregateType() ||
typeSym.IsTypeParameterType() ||
typeSym.IsArrayType() ||
typeSym.IsNullableType());
switch (typeSym.GetTypeKind())
{
case TypeKind.TK_AggregateType:
return typeSym.AsAggregateType();
case TypeKind.TK_ArrayType:
return GetReqPredefType(PredefinedType.PT_ARRAY);
case TypeKind.TK_TypeParameterType:
return typeSym.AsTypeParameterType().GetEffectiveBaseClass();
case TypeKind.TK_NullableType:
return typeSym.AsNullableType().GetAts(ErrorContext);
}
Debug.Assert(false, "Bad typeSym!");
return null;
}
private bool IsBaseInterface(CType pDerived, CType pBase)
{
Debug.Assert(pDerived != null);
Debug.Assert(pBase != null);
if (!pBase.isInterfaceType())
{
return false;
}
if (!pDerived.IsAggregateType())
{
return false;
}
AggregateType atsDer = pDerived.AsAggregateType();
while (atsDer != null)
{
TypeArray ifacesAll = atsDer.GetIfacesAll();
for (int i = 0; i < ifacesAll.Count; i++)
{
if (AreTypesEqualForConversion(ifacesAll[i], pBase))
{
return true;
}
}
atsDer = atsDer.GetBaseClass();
}
return false;
}
public bool IsBaseClassOfClass(CType pDerived, CType pBase)
{
Debug.Assert(pDerived != null);
Debug.Assert(pBase != null);
// This checks to see whether derived is a class, and if so,
// if base is a base class of derived.
if (!pDerived.isClassType())
{
return false;
}
return IsBaseClass(pDerived, pBase);
}
private bool IsBaseClass(CType pDerived, CType pBase)
{
Debug.Assert(pDerived != null);
Debug.Assert(pBase != null);
// A base class has got to be a class. The derived type might be a struct.
if (!pBase.isClassType())
{
return false;
}
if (pDerived.IsNullableType())
{
pDerived = pDerived.AsNullableType().GetAts(ErrorContext);
if (pDerived == null)
{
return false;
}
}
if (!pDerived.IsAggregateType())
{
return false;
}
AggregateType atsDer = pDerived.AsAggregateType();
AggregateType atsBase = pBase.AsAggregateType();
AggregateType atsCur = atsDer.GetBaseClass();
while (atsCur != null)
{
if (atsCur == atsBase)
{
return true;
}
atsCur = atsCur.GetBaseClass();
}
return false;
}
private bool HasCovariantArrayConversion(ArrayType pSource, ArrayType pDest)
{
Debug.Assert(pSource != null);
Debug.Assert(pDest != null);
// * S and T differ only in element type. In other words, S and T have the same number of dimensions.
// * Both SE and TE are reference types.
// * An implicit reference conversion exists from SE to TE.
return (pSource.rank == pDest.rank) && pSource.IsSZArray == pDest.IsSZArray &&
HasImplicitReferenceConversion(pSource.GetElementType(), pDest.GetElementType());
}
public bool HasIdentityOrImplicitReferenceConversion(CType pSource, CType pDest)
{
Debug.Assert(pSource != null);
Debug.Assert(pDest != null);
if (AreTypesEqualForConversion(pSource, pDest))
{
return true;
}
return HasImplicitReferenceConversion(pSource, pDest);
}
private bool AreTypesEqualForConversion(CType pType1, CType pType2)
{
return pType1.Equals(pType2);
}
private bool HasArrayConversionToInterface(ArrayType pSource, CType pDest)
{
Debug.Assert(pSource != null);
Debug.Assert(pDest != null);
if (!pSource.IsSZArray)
{
return false;
}
if (!pDest.isInterfaceType())
{
return false;
}
// * From a single-dimensional array type S[] to IList<T> or IReadOnlyList<T> and their base
// interfaces, provided that there is an implicit identity or reference
// conversion from S to T.
// We only have six interfaces to check. IList<T>, IReadOnlyList<T> and their bases:
// * The base interface of IList<T> is ICollection<T>.
// * The base interface of ICollection<T> is IEnumerable<T>.
// * The base interface of IEnumerable<T> is IEnumerable.
// * The base interface of IReadOnlyList<T> is IReadOnlyCollection<T>.
// * The base interface of IReadOnlyCollection<T> is IEnumerable<T>.
if (pDest.isPredefType(PredefinedType.PT_IENUMERABLE))
{
return true;
}
AggregateType atsDest = pDest.AsAggregateType();
AggregateSymbol aggDest = pDest.getAggregate();
if (!aggDest.isPredefAgg(PredefinedType.PT_G_ILIST) &&
!aggDest.isPredefAgg(PredefinedType.PT_G_ICOLLECTION) &&
!aggDest.isPredefAgg(PredefinedType.PT_G_IENUMERABLE) &&
!aggDest.isPredefAgg(PredefinedType.PT_G_IREADONLYCOLLECTION) &&
!aggDest.isPredefAgg(PredefinedType.PT_G_IREADONLYLIST))
{
return false;
}
Debug.Assert(atsDest.GetTypeArgsAll().Count == 1);
CType pSourceElement = pSource.GetElementType();
CType pDestTypeArgument = atsDest.GetTypeArgsAll()[0];
return HasIdentityOrImplicitReferenceConversion(pSourceElement, pDestTypeArgument);
}
private bool HasImplicitReferenceConversion(CType pSource, CType pDest)
{
Debug.Assert(pSource != null);
Debug.Assert(pDest != null);
// The implicit reference conversions are:
// * From any reference type to Object.
if (pSource.IsRefType() && pDest.isPredefType(PredefinedType.PT_OBJECT))
{
return true;
}
// * From any class type S to any class type T provided S is derived from T.
if (pSource.isClassType() && pDest.isClassType() && IsBaseClass(pSource, pDest))
{
return true;
}
// ORIGINAL RULES:
// // * From any class type S to any interface type T provided S implements T.
// if (pSource.isClassType() && pDest.isInterfaceType() && IsBaseInterface(pSource, pDest))
// {
// return true;
// }
// // * from any interface type S to any interface type T, provided S is derived from T.
// if (pSource.isInterfaceType() && pDest.isInterfaceType() && IsBaseInterface(pSource, pDest))
// {
// return true;
// }
// VARIANCE EXTENSIONS:
// * From any class type S to any interface type T provided S implements an interface
// convertible to T.
// * From any interface type S to any interface type T provided S implements an interface
// convertible to T.
// * From any interface type S to any interface type T provided S is not T and S is
// an interface convertible to T.
if (pSource.isClassType() && pDest.isInterfaceType() && HasAnyBaseInterfaceConversion(pSource, pDest))
{
return true;
}
if (pSource.isInterfaceType() && pDest.isInterfaceType() && HasAnyBaseInterfaceConversion(pSource, pDest))
{
return true;
}
if (pSource.isInterfaceType() && pDest.isInterfaceType() && pSource != pDest &&
HasInterfaceConversion(pSource.AsAggregateType(), pDest.AsAggregateType()))
{
return true;
}
// * From an array type S with an element type SE to an array type T with element type TE
// provided that all of the following are true:
// * S and T differ only in element type. In other words, S and T have the same number of dimensions.
// * Both SE and TE are reference types.
// * An implicit reference conversion exists from SE to TE.
if (pSource.IsArrayType() && pDest.IsArrayType() &&
HasCovariantArrayConversion(pSource.AsArrayType(), pDest.AsArrayType()))
{
return true;
}
// * From any array type to System.Array or any interface implemented by System.Array.
if (pSource.IsArrayType() && (pDest.isPredefType(PredefinedType.PT_ARRAY) ||
IsBaseInterface(GetReqPredefType(PredefinedType.PT_ARRAY, false), pDest)))
{
return true;
}
// * From a single-dimensional array type S[] to IList<T> and its base
// interfaces, provided that there is an implicit identity or reference
// conversion from S to T.
if (pSource.IsArrayType() && HasArrayConversionToInterface(pSource.AsArrayType(), pDest))
{
return true;
}
// * From any delegate type to System.Delegate
//
// SPEC OMISSION:
//
// The spec should actually say
//
// * From any delegate type to System.Delegate
// * From any delegate type to System.MulticastDelegate
// * From any delegate type to any interface implemented by System.MulticastDelegate
if (pSource.isDelegateType() &&
(pDest.isPredefType(PredefinedType.PT_MULTIDEL) ||
pDest.isPredefType(PredefinedType.PT_DELEGATE) ||
IsBaseInterface(GetReqPredefType(PredefinedType.PT_MULTIDEL, false), pDest)))
{
return true;
}
// VARIANCE EXTENSION:
// * From any delegate type S to a delegate type T provided S is not T and
// S is a delegate convertible to T
if (pSource.isDelegateType() && pDest.isDelegateType() &&
HasDelegateConversion(pSource.AsAggregateType(), pDest.AsAggregateType()))
{
return true;
}
// * From the null literal to any reference type
// NOTE: We extend the specification here. The C# 3.0 spec does not describe
// a "null type". Rather, it says that the null literal is typeless, and is
// convertible to any reference or nullable type. However, the C# 2.0 and 3.0
// implementations have a "null type" which some expressions other than the
// null literal may have. (For example, (null??null), which is also an
// extension to the specification.)
if (pSource.IsNullType() && pDest.IsRefType())
{
return true;
}
if (pSource.IsNullType() && pDest.IsNullableType())
{
return true;
}
// * Implicit conversions involving type parameters that are known to be reference types.
if (pSource.IsTypeParameterType() &&
HasImplicitReferenceTypeParameterConversion(pSource.AsTypeParameterType(), pDest))
{
return true;
}
return false;
}
private bool HasImplicitReferenceTypeParameterConversion(
TypeParameterType pSource, CType pDest)
{
Debug.Assert(pSource != null);
Debug.Assert(pDest != null);
if (!pSource.IsRefType())
{
// Not a reference conversion.
return false;
}
// The following implicit conversions exist for a given type parameter T:
//
// * From T to its effective base class C.
AggregateType pEBC = pSource.GetEffectiveBaseClass();
if (pDest == pEBC)
{
return true;
}
// * From T to any base class of C.
if (IsBaseClass(pEBC, pDest))
{
return true;
}
// * From T to any interface implemented by C.
if (IsBaseInterface(pEBC, pDest))
{
return true;
}
// * From T to any interface type I in T's effective interface set, and
// from T to any base interface of I.
TypeArray pInterfaces = pSource.GetInterfaceBounds();
for (int i = 0; i < pInterfaces.Count; ++i)
{
if (pInterfaces[i] == pDest)
{
return true;
}
}
// * From T to a type parameter U, provided T depends on U.
if (pDest.IsTypeParameterType() && pSource.DependsOn(pDest.AsTypeParameterType()))
{
return true;
}
return false;
}
private bool HasAnyBaseInterfaceConversion(CType pDerived, CType pBase)
{
if (!pBase.isInterfaceType())
{
return false;
}
if (!pDerived.IsAggregateType())
{
return false;
}
AggregateType atsDer = pDerived.AsAggregateType();
while (atsDer != null)
{
TypeArray ifacesAll = atsDer.GetIfacesAll();
for (int i = 0; i < ifacesAll.Count; i++)
{
if (HasInterfaceConversion(ifacesAll[i].AsAggregateType(), pBase.AsAggregateType()))
{
return true;
}
}
atsDer = atsDer.GetBaseClass();
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
// The rules for variant interface and delegate conversions are the same:
//
// An interface/delegate type S is convertible to an interface/delegate type T
// if and only if T is U<S1, ... Sn> and T is U<T1, ... Tn> such that for all
// parameters of U:
//
// * if the ith parameter of U is invariant then Si is exactly equal to Ti.
// * if the ith parameter of U is covariant then either Si is exactly equal
// to Ti, or there is an implicit reference conversion from Si to Ti.
// * if the ith parameter of U is contravariant then either Si is exactly
// equal to Ti, or there is an implicit reference conversion from Ti to Si.
private bool HasInterfaceConversion(AggregateType pSource, AggregateType pDest)
{
Debug.Assert(pSource != null && pSource.isInterfaceType());
Debug.Assert(pDest != null && pDest.isInterfaceType());
return HasVariantConversion(pSource, pDest);
}
//////////////////////////////////////////////////////////////////////////////
private bool HasDelegateConversion(AggregateType pSource, AggregateType pDest)
{
Debug.Assert(pSource != null && pSource.isDelegateType());
Debug.Assert(pDest != null && pDest.isDelegateType());
return HasVariantConversion(pSource, pDest);
}
//////////////////////////////////////////////////////////////////////////////
private bool HasVariantConversion(AggregateType pSource, AggregateType pDest)
{
Debug.Assert(pSource != null);
Debug.Assert(pDest != null);
if (pSource == pDest)
{
return true;
}
AggregateSymbol pAggSym = pSource.getAggregate();
if (pAggSym != pDest.getAggregate())
{
return false;
}
TypeArray pTypeParams = pAggSym.GetTypeVarsAll();
TypeArray pSourceArgs = pSource.GetTypeArgsAll();
TypeArray pDestArgs = pDest.GetTypeArgsAll();
Debug.Assert(pTypeParams.Count == pSourceArgs.Count);
Debug.Assert(pTypeParams.Count == pDestArgs.Count);
for (int iParam = 0; iParam < pTypeParams.Count; ++iParam)
{
CType pSourceArg = pSourceArgs[iParam];
CType pDestArg = pDestArgs[iParam];
// If they're identical then this one is automatically good, so skip it.
if (pSourceArg == pDestArg)
{
continue;
}
TypeParameterType pParam = pTypeParams[iParam].AsTypeParameterType();
if (pParam.Invariant)
{
return false;
}
if (pParam.Covariant)
{
if (!HasImplicitReferenceConversion(pSourceArg, pDestArg))
{
return false;
}
}
if (pParam.Contravariant)
{
if (!HasImplicitReferenceConversion(pDestArg, pSourceArg))
{
return false;
}
}
}
return true;
}
private bool HasImplicitBoxingTypeParameterConversion(
TypeParameterType pSource, CType pDest)
{
Debug.Assert(pSource != null);
Debug.Assert(pDest != null);
if (pSource.IsRefType())
{
// Not a boxing conversion; both source and destination are references.
return false;
}
// The following implicit conversions exist for a given type parameter T:
//
// * From T to its effective base class C.
AggregateType pEBC = pSource.GetEffectiveBaseClass();
if (pDest == pEBC)
{
return true;
}
// * From T to any base class of C.
if (IsBaseClass(pEBC, pDest))
{
return true;
}
// * From T to any interface implemented by C.
if (IsBaseInterface(pEBC, pDest))
{
return true;
}
// * From T to any interface type I in T's effective interface set, and
// from T to any base interface of I.
TypeArray pInterfaces = pSource.GetInterfaceBounds();
for (int i = 0; i < pInterfaces.Count; ++i)
{
if (pInterfaces[i] == pDest)
{
return true;
}
}
// * The conversion from T to a type parameter U, provided T depends on U, is not
// classified as a boxing conversion because it is not guaranteed to box.
// (If both T and U are value types then it is an identity conversion.)
return false;
}
private bool HasImplicitTypeParameterBaseConversion(
TypeParameterType pSource, CType pDest)
{
Debug.Assert(pSource != null);
Debug.Assert(pDest != null);
if (HasImplicitReferenceTypeParameterConversion(pSource, pDest))
{
return true;
}
if (HasImplicitBoxingTypeParameterConversion(pSource, pDest))
{
return true;
}
if (pDest.IsTypeParameterType() && pSource.DependsOn(pDest.AsTypeParameterType()))
{
return true;
}
return false;
}
public bool HasImplicitBoxingConversion(CType pSource, CType pDest)
{
Debug.Assert(pSource != null);
Debug.Assert(pDest != null);
// Certain type parameter conversions are classified as boxing conversions.
if (pSource.IsTypeParameterType() &&
HasImplicitBoxingTypeParameterConversion(pSource.AsTypeParameterType(), pDest))
{
return true;
}
// The rest of the boxing conversions only operate when going from a value type
// to a reference type.
if (!pSource.IsValType() || !pDest.IsRefType())
{
return false;
}
// A boxing conversion exists from a nullable type to a reference type
// if and only if a boxing conversion exists from the underlying type.
if (pSource.IsNullableType())
{
return HasImplicitBoxingConversion(pSource.AsNullableType().GetUnderlyingType(), pDest);
}
// A boxing conversion exists from any non-nullable value type to object,
// to System.ValueType, and to any interface type implemented by the
// non-nullable value type. Furthermore, an enum type can be converted
// to the type System.Enum.
// We set the base class of the structs to System.ValueType, System.Enum, etc,
// so we can just check here.
if (IsBaseClass(pSource, pDest))
{
return true;
}
if (HasAnyBaseInterfaceConversion(pSource, pDest))
{
return true;
}
return false;
}
public bool HasBaseConversion(CType pSource, CType pDest)
{
// By a "base conversion" we mean:
//
// * an identity conversion
// * an implicit reference conversion
// * an implicit boxing conversion
// * an implicit type parameter conversion
//
// In other words, these are conversions that can be made to a base
// class, base interface or co/contravariant type without any change in
// representation other than boxing. A conversion from, say, int to double,
// is NOT a "base conversion", because representation is changed. A conversion
// from, say, lambda to expression tree is not a "base conversion" because
// do not have a type.
//
// The existence of a base conversion depends solely upon the source and
// destination types, not the source expression.
//
// This notion is not found in the spec but it is useful in the implementation.
if (pSource.IsAggregateType() && pDest.isPredefType(PredefinedType.PT_OBJECT))
{
// If we are going from any aggregate type (class, struct, interface, enum or delegate)
// to object, we immediately return true. This may seem like a mere optimization --
// after all, if we have an aggregate then we have some kind of implicit conversion
// to object.
//
// However, it is not a mere optimization; this introduces a control flow change
// in error reporting scenarios for unresolved type forwarders. If a type forwarder
// cannot be resolved then the resulting type symbol will be an aggregate, but
// we will not be able to classify it into class, struct, etc.
//
// We know that we will have an error in this case; we do not wish to compound
// that error by giving a spurious "you cannot convert this thing to object"
// error, which, after all, will go away when the type forwarding problem is
// fixed.
return true;
}
if (HasIdentityOrImplicitReferenceConversion(pSource, pDest))
{
return true;
}
if (HasImplicitBoxingConversion(pSource, pDest))
{
return true;
}
if (pSource.IsTypeParameterType() &&
HasImplicitTypeParameterBaseConversion(pSource.AsTypeParameterType(), pDest))
{
return true;
}
return false;
}
public bool FCanLift()
{
return null != GetOptPredefAgg(PredefinedType.PT_G_OPTIONAL, false);
}
public bool IsBaseAggregate(AggregateSymbol derived, AggregateSymbol @base)
{
Debug.Assert(!derived.IsEnum() && !@base.IsEnum());
if (derived == @base)
return true; // identity.
// refactoring error tolerance: structs and delegates can be base classes in error scenarios so
// we cannot filter on whether or not the base is marked as sealed.
if (@base.IsInterface())
{
// Search the direct and indirect interfaces via ifacesAll, going up the base chain...
while (derived != null)
{
for (int i = 0; i < derived.GetIfacesAll().Count; i++)
{
AggregateType iface = derived.GetIfacesAll()[i].AsAggregateType();
if (iface.getAggregate() == @base)
return true;
}
derived = derived.GetBaseAgg();
}
return false;
}
// base is a class. Just go up the base class chain to look for it.
while (derived.GetBaseClass() != null)
{
derived = derived.GetBaseClass().getAggregate();
if (derived == @base)
return true;
}
return false;
}
internal void SetSymbolTable(SymbolTable symbolTable)
{
RuntimeBinderSymbolTable = symbolTable;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using Internal.Runtime.CompilerServices;
#pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)'
#if BIT64
using nuint = System.UInt64;
#else
using nuint = System.UInt32;
#endif
namespace System
{
/// <summary>
/// Span represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed
/// or native memory, or to memory allocated on the stack. It is type- and memory-safe.
/// </summary>
[DebuggerTypeProxy(typeof(SpanDebugView<>))]
[DebuggerDisplay("{DebuggerDisplay,nq}")]
[NonVersionable]
public readonly ref partial struct Span<T>
{
/// <summary>A byref or a native ptr.</summary>
internal readonly ByReference<T> _pointer;
/// <summary>The number of elements this Span contains.</summary>
#if PROJECTN
[Bound]
#endif
private readonly int _length;
/// <summary>
/// Creates a new span over the entirety of the target array.
/// </summary>
/// <param name="array">The target array.</param>
/// <remarks>Returns default when <paramref name="array"/> is null.</remarks>
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span(T[] array)
{
if (array == null)
{
this = default;
return; // returns default
}
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException();
_pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()));
_length = array.Length;
}
/// <summary>
/// Creates a new span over the portion of the target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the span.</param>
/// <param name="length">The number of items in the span.</param>
/// <remarks>Returns default when <paramref name="array"/> is null.</remarks>
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span(T[] array, int start, int length)
{
if (array == null)
{
if (start != 0 || length != 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
this = default;
return; // returns default
}
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException();
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
_pointer = new ByReference<T>(ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), start));
_length = length;
}
/// <summary>
/// Creates a new span over the target unmanaged buffer. Clearly this
/// is quite dangerous, because we are creating arbitrarily typed T's
/// out of a void*-typed block of memory. And the length is not checked.
/// But if this creation is correct, then all subsequent uses are correct.
/// </summary>
/// <param name="pointer">An unmanaged pointer to memory.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="T"/> is reference type or contains pointers and hence cannot be stored in unmanaged memory.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="length"/> is negative.
/// </exception>
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe Span(void* pointer, int length)
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
if (length < 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
_pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref *(byte*)pointer));
_length = length;
}
// Constructor for internal use only.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Span(ref T ptr, int length)
{
Debug.Assert(length >= 0);
_pointer = new ByReference<T>(ref ptr);
_length = length;
}
/// Returns a reference to specified element of the Span.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
/// <exception cref="System.IndexOutOfRangeException">
/// Thrown when index less than 0 or index greater than or equal to Length
/// </exception>
public ref T this[int index]
{
#if PROJECTN
[BoundsChecking]
get
{
return ref Unsafe.Add(ref _pointer.Value, index);
}
#else
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[NonVersionable]
get
{
if ((uint)index >= (uint)_length)
ThrowHelper.ThrowIndexOutOfRangeException();
return ref Unsafe.Add(ref _pointer.Value, index);
}
#endif
}
/// <summary>
/// Clears the contents of this span.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Clear()
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
Span.ClearWithReferences(ref Unsafe.As<T, IntPtr>(ref _pointer.Value), (nuint)_length * (nuint)(Unsafe.SizeOf<T>() / sizeof(nuint)));
}
else
{
Span.ClearWithoutReferences(ref Unsafe.As<T, byte>(ref _pointer.Value), (nuint)_length * (nuint)Unsafe.SizeOf<T>());
}
}
/// <summary>
/// Fills the contents of this span with the given value.
/// </summary>
public void Fill(T value)
{
if (Unsafe.SizeOf<T>() == 1)
{
uint length = (uint)_length;
if (length == 0)
return;
T tmp = value; // Avoid taking address of the "value" argument. It would regress performance of the loop below.
Unsafe.InitBlockUnaligned(ref Unsafe.As<T, byte>(ref _pointer.Value), Unsafe.As<T, byte>(ref tmp), length);
}
else
{
// Do all math as nuint to avoid unnecessary 64->32->64 bit integer truncations
nuint length = (uint)_length;
if (length == 0)
return;
ref T r = ref _pointer.Value;
// TODO: Create block fill for value types of power of two sizes e.g. 2,4,8,16
nuint elementSize = (uint)Unsafe.SizeOf<T>();
nuint i = 0;
for (; i < (length & ~(nuint)7); i += 8)
{
Unsafe.AddByteOffset<T>(ref r, (i + 0) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 1) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 2) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 3) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 4) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 5) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 6) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 7) * elementSize) = value;
}
if (i < (length & ~(nuint)3))
{
Unsafe.AddByteOffset<T>(ref r, (i + 0) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 1) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 2) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 3) * elementSize) = value;
i += 4;
}
for (; i < length; i++)
{
Unsafe.AddByteOffset<T>(ref r, i * elementSize) = value;
}
}
}
/// <summary>
/// Copies the contents of this span into destination span. If the source
/// and destinations overlap, this method behaves as if the original values in
/// a temporary location before the destination is overwritten.
/// </summary>
/// <param name="destination">The span to copy items into.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when the destination Span is shorter than the source Span.
/// </exception>
public void CopyTo(Span<T> destination)
{
// Using "if (!TryCopyTo(...))" results in two branches: one for the length
// check, and one for the result of TryCopyTo. Since these checks are equivalent,
// we can optimize by performing the check once ourselves then calling Memmove directly.
if ((uint)_length <= (uint)destination.Length)
{
Buffer.Memmove(ref destination._pointer.Value, ref _pointer.Value, (nuint)_length);
}
else
{
ThrowHelper.ThrowArgumentException_DestinationTooShort();
}
}
/// <summary>
/// Copies the contents of this span into destination span. If the source
/// and destinations overlap, this method behaves as if the original values in
/// a temporary location before the destination is overwritten.
/// </summary>
/// <param name="destination">The span to copy items into.</param>
/// <returns>If the destination span is shorter than the source span, this method
/// return false and no data is written to the destination.</returns>
public bool TryCopyTo(Span<T> destination)
{
bool retVal = false;
if ((uint)_length <= (uint)destination.Length)
{
Buffer.Memmove(ref destination._pointer.Value, ref _pointer.Value, (nuint)_length);
retVal = true;
}
return retVal;
}
/// <summary>
/// Returns true if left and right point at the same memory and have the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public static bool operator ==(Span<T> left, Span<T> right)
{
return left._length == right._length && Unsafe.AreSame<T>(ref left._pointer.Value, ref right._pointer.Value);
}
/// <summary>
/// Defines an implicit conversion of a <see cref="Span{T}"/> to a <see cref="ReadOnlySpan{T}"/>
/// </summary>
public static implicit operator ReadOnlySpan<T>(Span<T> span) => new ReadOnlySpan<T>(ref span._pointer.Value, span._length);
/// <summary>
/// For <see cref="Span{Char}"/>, returns a new instance of string that represents the characters pointed to by the span.
/// Otherwise, returns a <see cref="String"/> with the name of the type and the number of elements.
/// </summary>
public override string ToString()
{
if (typeof(T) == typeof(char))
{
unsafe
{
fixed (char* src = &Unsafe.As<T, char>(ref _pointer.Value))
return new string(src, 0, _length);
}
}
return string.Format("System.Span<{0}>[{1}]", typeof(T).Name, _length);
}
/// <summary>
/// Forms a slice out of the given span, beginning at 'start'.
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span<T> Slice(int start)
{
if ((uint)start > (uint)_length)
ThrowHelper.ThrowArgumentOutOfRangeException();
return new Span<T>(ref Unsafe.Add(ref _pointer.Value, start), _length - start);
}
/// <summary>
/// Forms a slice out of the given span, beginning at 'start', of given length
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The desired length for the slice (exclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span<T> Slice(int start, int length)
{
if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
return new Span<T>(ref Unsafe.Add(ref _pointer.Value, start), length);
}
/// <summary>
/// Copies the contents of this span into a new array. This heap
/// allocates, so should generally be avoided, however it is sometimes
/// necessary to bridge the gap with APIs written in terms of arrays.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T[] ToArray()
{
if (_length == 0)
return Array.Empty<T>();
var destination = new T[_length];
Buffer.Memmove(ref Unsafe.As<byte, T>(ref destination.GetRawSzArrayData()), ref _pointer.Value, (nuint)_length);
return destination;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="StrokeNodeOperations2.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;
using System.Windows.Input;
namespace MS.Internal.Ink
{
/// <summary>
/// Static methods implementing generic hit-testing operations
/// </summary>
internal partial class StrokeNodeOperations
{
#region enum HitResult
/// <summary> A set of possible results frequently used in StrokeNodeOperations and derived classes</summary>
internal enum HitResult
{
Hit,
Left,
Right,
InFront,
Behind
}
#endregion
#region HitTestXxxYyy
/// <summary>
/// Hit-tests a linear segment against a convex polygon.
/// </summary>
/// <param name="vertices">Vertices of the polygon (in clockwise order)</param>
/// <param name="hitBegin">an end point of the hitting segment</param>
/// <param name="hitEnd">an end point of the hitting segment</param>
/// <returns>true if hit; false otherwise</returns>
internal static bool HitTestPolygonSegment(Vector[] vertices, Vector hitBegin, Vector hitEnd)
{
System.Diagnostics.Debug.Assert((null != vertices) && (2 < vertices.Length));
HitResult hitResult = HitResult.Right, firstResult = HitResult.Right, prevResult = HitResult.Right;
int count = vertices.Length;
Vector vertex = vertices[count - 1];
for (int i = 0; i < count; i++)
{
Vector nextVertex = vertices[i];
hitResult = WhereIsSegmentAboutSegment(hitBegin, hitEnd, vertex, nextVertex);
if (HitResult.Hit == hitResult)
{
return true;
}
if (IsOutside(hitResult, prevResult))
{
return false;
}
if (i == 0)
{
firstResult = hitResult;
}
prevResult = hitResult;
vertex = nextVertex;
}
return (false == IsOutside(firstResult, hitResult));
}
/// <summary>
/// This is a specialized version of HitTestPolygonSegment that takes
/// a Quad for a polygon. This method is called very intensively by
/// hit-testing API and we don't want to create Vector[] for every quad it hit-tests.
/// </summary>
/// <param name="quad">the connecting quad to test against</param>
/// <param name="hitBegin">begin point of the hitting segment</param>
/// <param name="hitEnd">end point of the hitting segment</param>
/// <returns>true if hit, false otherwise</returns>
internal static bool HitTestQuadSegment(Quad quad, Point hitBegin, Point hitEnd)
{
System.Diagnostics.Debug.Assert(quad.IsEmpty == false);
HitResult hitResult = HitResult.Right, firstResult = HitResult.Right, prevResult = HitResult.Right;
int count = 4;
Vector zeroVector = new Vector(0, 0);
Vector hitVector = hitEnd - hitBegin;
Vector vertex = quad[count - 1] - hitBegin;
for (int i = 0; i < count; i++)
{
Vector nextVertex = quad[i] - hitBegin;
hitResult = WhereIsSegmentAboutSegment(zeroVector, hitVector, vertex, nextVertex);
if (HitResult.Hit == hitResult)
{
return true;
}
if (true == IsOutside(hitResult, prevResult))
{
return false;
}
if (i == 0)
{
firstResult = hitResult;
}
prevResult = hitResult;
vertex = nextVertex;
}
return (false == IsOutside(firstResult, hitResult));
}
/// <summary>
/// Hit-test a polygin against a circle
/// </summary>
/// <param name="vertices">Vectors representing the vertices of the polygon, ordered in clockwise order</param>
/// <param name="center">Vector representing the center of the circle</param>
/// <param name="radius">Vector representing the radius of the circle</param>
/// <returns>true if hit, false otherwise</returns>
internal static bool HitTestPolygonCircle(Vector[] vertices, Vector center, Vector radius)
{
// NTRAID#WINDOWS-1448096-2006/1/9-SAMGEO, this code is not called, but will be in VNext
throw new NotImplementedException();
/*
System.Diagnostics.Debug.Assert((null != vertices) && (2 < vertices.Length));
HitResult hitResult = HitResult.Right, firstResult = HitResult.Right, prevResult = HitResult.Right;
int count = vertices.Length;
Vector vertex = vertices[count - 1];
for (int i = 0; i < count; i++)
{
Vector nextVertex = vertices[i];
hitResult = WhereIsCircleAboutSegment(center, radius, vertex, nextVertex);
if (HitResult.Hit == hitResult)
{
return true;
}
if (true == IsOutside(hitResult, prevResult))
{
return false;
}
if (i == 0)
{
firstResult = hitResult;
}
prevResult = hitResult;
vertex = nextVertex;
}
return (false == IsOutside(firstResult, hitResult));
*/
}
/// <summary>
/// This is a specialized version of HitTestPolygonCircle that takes
/// a Quad for a polygon. This method is called very intensively by
/// hit-testing API and we don't want to create Vector[] for every quad it hit-tests.
/// </summary>
/// <param name="quad">the connecting quad</param>
/// <param name="center">center of the circle</param>
/// <param name="radius">radius of the circle </param>
/// <returns>true if hit; false otherwise</returns>
internal static bool HitTestQuadCircle(Quad quad, Point center, Vector radius)
{
// NTRAID#WINDOWS-1448096-2006/1/9-SAMGEO, this code is not called, but will be in VNext
throw new NotImplementedException();
/*
System.Diagnostics.Debug.Assert(quad.IsEmpty == false);
Vector centerVector = (Vector)center;
HitResult hitResult = HitResult.Right, firstResult = HitResult.Right, prevResult = HitResult.Right;
int count = 4;
Vector vertex = (Vector)quad[count - 1];
for (int i = 0; i < count; i++)
{
Vector nextVertex = (Vector)quad[i];
hitResult = WhereIsCircleAboutSegment(centerVector, radius, vertex, nextVertex);
if (HitResult.Hit == hitResult)
{
return true;
}
if (true == IsOutside(hitResult, prevResult))
{
return false;
}
if (i == 0)
{
firstResult = hitResult;
}
prevResult = hitResult;
vertex = nextVertex;
}
return (false == IsOutside(firstResult, hitResult));
*/
}
#endregion
#region Whereabouts
/// <summary>
/// Finds out where the segment [hitBegin, hitEnd]
/// is about the segment [orgBegin, orgEnd].
/// </summary>
internal static HitResult WhereIsSegmentAboutSegment(
Vector hitBegin, Vector hitEnd, Vector orgBegin, Vector orgEnd)
{
if (hitEnd == hitBegin)
{
return WhereIsCircleAboutSegment(hitBegin, new Vector(0, 0), orgBegin, orgEnd);
}
//----------------------------------------------------------------------
// Source: http://isc.faqs.org/faqs/graphics/algorithms-faq/
// Subject 1.03: How do I find intersections of 2 2D line segments?
//
// Let A,B,C,D be 2-space position vectors. Then the directed line
// segments AB & CD are given by:
//
// AB=A+r(B-A), r in [0,1]
// CD=C+s(D-C), s in [0,1]
//
// If AB & CD intersect, then
//
// A+r(B-A)=C+s(D-C), or Ax+r(Bx-Ax)=Cx+s(Dx-Cx)
// Ay+r(By-Ay)=Cy+s(Dy-Cy) for some r,s in [0,1]
//
// Solving the above for r and s yields
//
// (Ay-Cy)(Dx-Cx)-(Ax-Cx)(Dy-Cy)
// r = ----------------------------- (eqn 1)
// (Bx-Ax)(Dy-Cy)-(By-Ay)(Dx-Cx)
//
// (Ay-Cy)(Bx-Ax)-(Ax-Cx)(By-Ay)
// s = ----------------------------- (eqn 2)
// (Bx-Ax)(Dy-Cy)-(By-Ay)(Dx-Cx)
//
// Let P be the position vector of the intersection point, then
//
// P=A+r(B-A) or Px=Ax+r(Bx-Ax) and Py=Ay+r(By-Ay)
//
// By examining the values of r & s, you can also determine some
// other limiting conditions:
// If 0 <= r <= 1 && 0 <= s <= 1, intersection exists
// r < 0 or r > 1 or s < 0 or s > 1 line segments do not intersect
// If the denominator in eqn 1 is zero, AB & CD are parallel
// If the numerator in eqn 1 is also zero, AB & CD are collinear.
// If they are collinear, then the segments may be projected to the x-
// or y-axis, and overlap of the projected intervals checked.
//
// If the intersection point of the 2 lines are needed (lines in this
// context mean infinite lines) regardless whether the two line
// segments intersect, then
// If r > 1, P is located on extension of AB
// If r < 0, P is located on extension of BA
// If s > 1, P is located on extension of CD
// If s < 0, P is located on extension of DC
// Also note that the denominators of eqn 1 & 2 are identical.
//
// References:
// [O'Rourke (C)] pp. 249-51
// [Gems III] pp. 199-202 "Faster Line Segment Intersection,"
//----------------------------------------------------------------------
// The result tells where the segment CD is about the vector AB.
// Return "Right" if either C or D is not on the left from AB.
HitResult result = HitResult.Right;
// Calculate the vectors.
Vector AB = orgEnd - orgBegin; // B - A
Vector CA = orgBegin - hitBegin; // A - C
Vector CD = hitEnd - hitBegin; // D - C
double det = Vector.Determinant(AB, CD);
if (DoubleUtil.IsZero(det))
{
// The segments are parallel.
/*if (DoubleUtil.IsZero(Vector.Determinant(CD, CA)))
{
// The segments are collinear.
// Check if their X and Y projections overlap.
if ((Math.Max(orgBegin.X, orgEnd.X) >= Math.Min(hitBegin.X, hitEnd.X)) &&
(Math.Min(orgBegin.X, orgEnd.X) <= Math.Max(hitBegin.X, hitEnd.X)) &&
(Math.Max(orgBegin.Y, orgEnd.Y) >= Math.Min(hitBegin.Y, hitEnd.Y)) &&
(Math.Min(orgBegin.Y, orgEnd.Y) <= Math.Max(hitBegin.Y, hitEnd.Y)))
{
// The segments overlap.
result = HitResult.Hit;
}
else if (false == DoubleUtil.IsZero(AB.X))
{
result = ((AB.X * CA.X) > 0) ? HitResult.Behind : HitResult.InFront;
}
else
{
result = ((AB.Y * CA.Y) > 0) ? HitResult.Behind : HitResult.InFront;
}
}
else */
if (DoubleUtil.IsZero(Vector.Determinant(CD, CA)) || DoubleUtil.GreaterThan(Vector.Determinant(AB, CA), 0))
{
// C is on the left from AB, and, since the segments are parallel, D is also on the left.
result = HitResult.Left;
}
}
else
{
double r = AdjustFIndex(Vector.Determinant(AB, CA) / det);
if (r > 0 && r < 1)
{
// The line defined AB does cross the segment CD.
double s = AdjustFIndex(Vector.Determinant(CD, CA) / det);
if (s > 0 && s < 1)
{
// The crossing point is on the segment AB as well.
result = HitResult.Hit;
}
else
{
result = (0 < s) ? HitResult.InFront : HitResult.Behind;
}
}
else if ((WhereIsVectorAboutVector(hitBegin - orgBegin, AB) == HitResult.Left)
|| (WhereIsVectorAboutVector(hitEnd - orgBegin, AB) == HitResult.Left))
{
// The line defined AB doesn't cross the segment CD, and neither C nor D
// is on the right from AB
result = HitResult.Left;
}
}
return result;
}
/// <summary>
/// Find out the relative location of a circle relative to a line segment
/// </summary>
/// <param name="center">center of the circle</param>
/// <param name="radius">radius of the circle. center.radius is a point on the circle</param>
/// <param name="segBegin">begin point of the line segment</param>
/// <param name="segEnd">end point of the line segment</param>
/// <returns>test result</returns>
internal static HitResult WhereIsCircleAboutSegment(
Vector center, Vector radius, Vector segBegin, Vector segEnd)
{
segBegin -= center;
segEnd -= center;
double radiusSquared = radius.LengthSquared;
// This will find out the nearest path from center to a point on the segment
double distanceSquared = GetNearest(segBegin, segEnd).LengthSquared;
// The segment must cross the circle, hit
if (radiusSquared > distanceSquared)
{
return HitResult.Hit;
}
Vector segVector = segEnd - segBegin;
HitResult result = HitResult.Right;
// NTRAID#Tablet PC bugs-26556-2004/10/19-xiaotu,resolved two issues with the original code:
// 1. The local varial "normal" is assigned a value but it is never used afterwards. \
// 2. the code indicates that that only case result is HitResult.InFront or HitResult.Behind is
// when WhereIsVectorAboutVector(-segBegin, segVector) == HitResult.Left.
HitResult vResult = WhereIsVectorAboutVector(-segBegin, segVector);
//either front or behind
if (vResult == HitResult.Hit)
{
result = DoubleUtil.LessThan(segBegin.LengthSquared, segEnd.LengthSquared) ? HitResult.InFront :
HitResult.Behind;
}
else
{
// Find the projection of center on the segment.
double findex = GetProjectionFIndex(segBegin, segEnd);
// Get the normal vector, pointing from center to the projection point
Vector normal = segBegin + (segVector * findex);
// recalculate distanceSquared using normal
distanceSquared = normal.LengthSquared;
// The extension of the segment won't hit the circle
if (radiusSquared <= distanceSquared)
{
// either left or right
result = vResult;
}
else
{
result = (findex > 0) ? HitResult.InFront : HitResult.Behind;
}
}
return result;
}
/// <summary>
/// Finds out where the vector1 is about the vector2.
/// </summary>
internal static HitResult WhereIsVectorAboutVector(Vector vector1, Vector vector2)
{
double determinant = Vector.Determinant(vector1, vector2);
if (DoubleUtil.IsZero(determinant))
{
return HitResult.Hit; // collinear
}
return (0 < determinant) ? HitResult.Left : HitResult.Right;
}
/// <summary>
/// Tells whether the hitVector intersects the arc defined by two vectors.
/// </summary>
internal static HitResult WhereIsVectorAboutArc(Vector hitVector, Vector arcBegin, Vector arcEnd)
{
//HitResult result = HitResult.Right;
if (arcBegin == arcEnd)
{
// full circle
return HitResult.Hit;
}
if (HitResult.Right == WhereIsVectorAboutVector(arcEnd, arcBegin))
{
// small arc
if ((HitResult.Left != WhereIsVectorAboutVector(hitVector, arcBegin)) &&
(HitResult.Right != WhereIsVectorAboutVector(hitVector, arcEnd)))
{
return HitResult.Hit;
}
}
else if ((HitResult.Left != WhereIsVectorAboutVector(hitVector, arcBegin)) ||
(HitResult.Right != WhereIsVectorAboutVector(hitVector, arcEnd)))
{
return HitResult.Hit;
}
if ((WhereIsVectorAboutVector(hitVector - arcBegin, TurnLeft(arcBegin)) != HitResult.Left) ||
(WhereIsVectorAboutVector(hitVector - arcEnd, TurnRight(arcEnd)) != HitResult.Right))
{
return HitResult.Left;
}
return HitResult.Right;
}
#endregion
#region Misc. helpers
/// <summary>
///
/// </summary>
/// <param name="vector"></param>
/// <returns></returns>
internal static Vector TurnLeft(Vector vector)
{
// NTRAID#WINDOWS-1448096-2006/1/9-SAMGEO, this code is not called, but will be in VNext
throw new NotImplementedException();
//return new Vector(-vector.Y, vector.X);
}
/// <summary>
///
/// </summary>
/// <param name="vector"></param>
/// <returns></returns>
internal static Vector TurnRight(Vector vector)
{
// NTRAID#WINDOWS-1448096-2006/1/9-SAMGEO, this code is not called, but will be in VNext
throw new NotImplementedException();
//return new Vector(vector.Y, -vector.X);
}
/// <summary>
///
/// </summary>
/// <param name="hitResult"></param>
/// <param name="prevHitResult"></param>
/// <returns></returns>
internal static bool IsOutside(HitResult hitResult, HitResult prevHitResult)
{
// ISSUE-2004/10/08-XiaoTu For Polygon and Circle, ((HitResult.Behind == hitResult) && (HitResult.InFront == prevHitResult))
// cannot be true.
return ((HitResult.Left == hitResult)
|| ((HitResult.Behind == hitResult) && (HitResult.InFront == prevHitResult)));
}
/// <summary>
/// Internal helper function to find out the ratio of the distance from hitpoint to lineVector
/// and the distance from lineVector to (lineVector+nextLine)
/// </summary>
/// <param name="linesVector">This is one edge of a polygonal node</param>
/// <param name="nextLine">The connection vector between the same edge on biginNode and ednNode</param>
/// <param name="hitPoint">a point</param>
/// <returns>the relative position of hitPoint</returns>
internal static double GetPositionBetweenLines(Vector linesVector, Vector nextLine, Vector hitPoint)
{
Vector nearestOnFirst = GetProjection(-hitPoint, linesVector - hitPoint);
hitPoint = nextLine - hitPoint;
Vector nearestOnSecond = GetProjection(hitPoint, hitPoint + linesVector);
Vector shortest = nearestOnFirst - nearestOnSecond;
System.Diagnostics.Debug.Assert((false == DoubleUtil.IsZero(shortest.X)) || (false == DoubleUtil.IsZero(shortest.Y)));
//return DoubleUtil.IsZero(shortest.X) ? (nearestOnFirst.Y / shortest.Y) : (nearestOnFirst.X / shortest.X);
return Math.Sqrt(nearestOnFirst.LengthSquared / shortest.LengthSquared);
}
/// <summary>
/// On a line defined buy two points finds the findex of the point
/// nearest to the origin (0,0). Same as FindNearestOnLine just
/// different output.
/// </summary>
/// <param name="begin">A point on the line.</param>
/// <param name="end">Another point on the line.</param>
/// <returns></returns>
internal static double GetProjectionFIndex(Vector begin, Vector end)
{
Vector segment = end - begin;
double lengthSquared = segment.LengthSquared;
if (DoubleUtil.IsZero(lengthSquared))
{
return 0;
}
double dotProduct = -(begin * segment);
return AdjustFIndex(dotProduct / lengthSquared);
}
/// <summary>
/// On a line defined buy two points finds the point nearest to the origin (0,0).
/// </summary>
/// <param name="begin">A point on the line.</param>
/// <param name="end">Another point on the line.</param>
/// <returns></returns>
internal static Vector GetProjection(Vector begin, Vector end)
{
double findex = GetProjectionFIndex(begin, end);
return (begin + (end - begin) * findex);
}
/// <summary>
/// On a given segment finds the point nearest to the origin (0,0).
/// </summary>
/// <param name="begin">The segment's begin point.</param>
/// <param name="end">The segment's end point.</param>
/// <returns></returns>
internal static Vector GetNearest(Vector begin, Vector end)
{
double findex = GetProjectionFIndex(begin, end);
if (findex <= 0)
{
return begin;
}
if (findex >= 1)
{
return end;
}
return (begin + ((end - begin) * findex));
}
/// <summary>
/// Clears double's computation fuzz around 0 and 1
/// </summary>
internal static double AdjustFIndex(double findex)
{
return DoubleUtil.IsZero(findex) ? 0 : (DoubleUtil.IsOne(findex) ? 1 : findex);
}
#endregion
}
}
| |
using System;
using System.Text;
using VisualHint.SmartPropertyGrid;
using System.Globalization;
using System.Resources;
using System.Reflection;
using System.Collections.Generic;
using System.Xml;
using System.IO;
namespace RunfileEditor
{
/// <summary>
/// This class creates the RunfileObject that contains all the XML information in a class structure.
/// This also has a directory accessor that allows you to return any object:
/// 1.) Module
/// 2.) I-O-P
/// as a
/// </summary>
public class EarlabRunfile
{
//Private Data Members ==========================================================================================///
#region Private Data Members
/// <summary>
/// The module directory is ...
/// These are the unique EarlabModule titles that are needed from the EFI
/// </summary>
private ModuleDirectory ModuleDirectory;
/// <summary>
/// Has the Runfile Object Changed
/// </summary>
private bool RHasChanged = false;
/// <summary>
/// This collection contains all the children
/// </summary>
private List<EarlabSession> mChildren = new List<EarlabSession>();
/// <summary>
/// This is the list of Modules contained in the Runfile
/// </summary>
private List<RunfileModule> RunfileModules = new List<RunfileModule>();
#endregion
//Public Data Members ============================================================================================///
#region Public Data Memebers
/// <summary>
/// Run File Information -- contains informaiton about the model
/// This can be reconfigured to public-private
/// </summary>
public RunfileInformation RunfileInformation;
/// <summary>
/// Modules carry two data structures: (XML data as strings),(XML data as the appropriate value)
/// </summary>
public List<EarlabModule> EarlabModules = new List<EarlabModule>();
//errors in an accessable format
public List<VerificationError> VErrorCollection = new List<VerificationError>();
#endregion
//Event Handler Items ============================================================================================///
#region Event Handler Items
//Basically I can do the event on change of a Module Repaint the Tabs.
public event EventHandler DataChanged;
protected virtual void OnDataChanged()
{
if (DataChanged != null)
DataChanged(this, new EventArgs());
}
#endregion
//Properties ====================================================================================================///
#region Properties
public int ModuleCount
{
get
{
return RunfileModules.Count;
}
}
//Module -- IOP -- Module IOP etc.. alternative is Module, Module, Module, IOP, IOP, IOP or some such.
public List<EarlabSession> Children
{
get
{
//mChildren = null;
foreach (EarlabModule EarlabM in EarlabModules)
{
mChildren.Add(EarlabM);
foreach (EarlabSession EarlabS in EarlabM.Children)
{
mChildren.Add(EarlabS);
}
}
return mChildren;
}
}
// need to write the set
public bool HasChanged
{
get
{
return RHasChanged;
}
set
{
foreach (EarlabModule etModule in EarlabModules)
{
if (etModule.HasChanged == true)
{
RHasChanged = true;
OnDataChanged();
}
else
RHasChanged = false;
}
}
}
//info
///<summary>
/// This is a property that accesses the RunfileModule Collection
/// And gives back a string array of all the unique Module XML titles in the Runfile.
///
///
///</summary>
public string[] UniqueEarlabModuleXMLs
{
//compare all theRunfileModuleDescriptors against each other.
//if it is not listed keep it, otherwise don't add it.
get
{
//1st shot doest not work, you can't add to a collection that's in a foreach loop.
//Internal data memebers
List<string> Uniques = new List<string>();
//sorted in order
foreach (RunfileModule RfMd in RunfileModules)
{
bool foundit = false;
foreach (string s in Uniques)
{
if (s == RfMd.ModuleInformation.ExecutableName)
{
foundit = true;
break;
}
}
if (!foundit)
Uniques.Add(RfMd.ModuleInformation.ExecutableName);
}
return Uniques.ToArray();
}
}
//unneeded
public RunfileModule this[int ModuleIndex]
{
get
{
if ((ModuleIndex < 0) || (ModuleIndex >= RunfileModules.Count))
throw new IndexOutOfRangeException("The requested module at index " + ModuleIndex + " was not found in the Runfile");
return RunfileModules[ModuleIndex];
}
}
//
public RunfileModule this[string ModuleName]
{
get
{
//(**)
//Search for the Matching moduleName
foreach (RunfileModule currentModule in RunfileModules)
{
if (currentModule.ModuleInformation.ExecutableName.ToLower() == ModuleName)
return currentModule;
}
throw new IndexOutOfRangeException("The requested module executable \"" + ModuleName + "\" was not found in the Runfile");
}
}
/// <summary>
/// This allows you to access the Earlabsession object you want by using the path.
/// 1.) Module
/// 2.) I-O-P
/// 3.) Thus you have to cast the object when you want to use it.
/// </summary>
/// <param name="VError"></param>
/// <returns></returns>
public EarlabSession this[VerificationError VError]
{
//problem if module error and parameter error.
//how to you return the problem twice.
//no problem, b/c there will be two diffferetn paths
//VError.ModuleName
//VError.parameter
//VError.IOPName
get
{
//string searchString = VError.IOPName;
//module
if (VError.IOPName == null )
{
foreach (EarlabModule currentModule in EarlabModules)
{
if (currentModule.theEarlabModuleInformation.InstanceName.ToLower() == VError.ModuleInstanceName)
return currentModule;
}
}
//this is a input-output-parameter
//VError.IOPType.ToLower()
else
{
//go through each module
foreach (EarlabModule currentModule in EarlabModules)
{
//We have the right module now
if (VError.ModuleInstanceName == currentModule.theEarlabModuleInformation.InstanceName.ToLower())
{
//Now we need the input output or parameter
switch (VError.IOPType.ToLower())
{
case "parameter":
//code pattern for finding the IOP
foreach (EarlabParameter parameter in currentModule.EarlabParameters)
{
if (parameter.PName == VError.IOPName)
return parameter;
//we have some error
else
return null;
}
break;
case "input":
//foreach (EarlabInput input in currentModule.EarlabInputs)
//{
// if (input.PName == VError.IOPName)
// TheVar = input;
return null;
//}
case "output":
//foreach (EarlabOutput output in currentModule.EarlabOutputs)
//{
// if (output.PName == VError.IOPName)
// TheVar = output;
return null;
//}
default:
throw new System.NotSupportedException("The Error type " + VError.IOPType + " is not recognized.");
}//end switch
}//end if
//module name is not recognized what would this mean?
//else
//throw new System.NotSupportedException("The Error type " + VError.ModuleName + " is not recognized.");
}//end foreach
//this is the same problem as above -- module name not recognized, no reason to have the code twice.
throw new System.NotSupportedException("The Error type " + VError.ModuleInstanceName + " is not recognized.");
}//end else
throw new System.NotSupportedException("The Full Verification Error type with path" + VError.FullErrorPath + "is not recognized.");
}
}
#endregion
//Constructors ===================================================================================================///
#region Constructors
/// <summary>
/// Here is the default constructor, it is unused.
/// </summary>
public EarlabRunfile()
{
}
/// <summary>
/// Here is the constructor that is used.
/// This constructor takes a valid Runfile as input, and then creates the RunfileObject.
/// The RunfileObject is a collection of objects that comprise the information in the XML Runfile Document
/// The constructor relies on the intialization method
/// </summary>
/// <param name="Runfile"></param>
public EarlabRunfile(XmlDocument Runfile)
{
Initialize(Runfile);
}
#endregion Constructors
//Controller Region ==============================================================================================///
#region This is the Controller Section of the EarlabRunfileObject
/// <summary>
/// [Move] This needs to be moved to a static controller class
/// Takes in XML Document produces Model Object
/// </summary>
/// <param name="Runfile"></param>
public void Initialize(XmlDocument Runfile)
{
//code --- calls to other small classes
//1.) Create Run File Information using RunfileInformation class
//XmlNode, RunfileInformation
//the indexing method returns a xmlnode list
//perhaps a better way to do this.
XmlNodeList XList = Runfile.GetElementsByTagName("RunfileInformation");
RunfileInformation = new RunfileInformation(XList[0], Runfile);
//2.) Run File Modules that are used
//RunfileDescriptors -> ModuleData
//(?)I'm not sure these "string data modules are needed"
//(xml statement) --Additional information: Object reference not set to an instance of an object.
//Reformat the xml statement!!*****
XmlNodeList MList = Runfile.GetElementsByTagName("Module");
foreach (XmlNode theModule in MList)
{
/// Converts XML Node Module into the collection of ModuleInfo and IOP
RunfileModules.Add(new RunfileModule(theModule));
}
//-----------------------
//3.) Hey EFI give me those Module XMLs i want.
//(?) For now use the contructor on ModuleDirectory
//ModuleDirectory interacts with the EFI and gets what is necessary
ModuleDirectory = new ModuleDirectory(UniqueEarlabModuleXMLs);
//4.) Run File -- Earlab Modules using EarlabModule and loop
//RunfileDescriptors + ModuleData => Factories -------> SPGs in GUI
//The logical separation in this is a bit dicey.....
//(?) Not sure rather to have this here, or put it somewhere else
foreach (RunfileModule sModule in RunfileModules)
{
//Label the proper Module Name
string ModuleName = sModule.ModuleInformation.ExecutableName.ToLower();
//Send that RunfileModule and the ModuleXML Module
//(xml statement)
EarlabModules.Add(new EarlabModule(sModule, ModuleDirectory[ModuleName]));
}
}
/// <summary>
/// Creates a Runfile from the RunfileObject
/// </summary>
/// <returns></returns>
public XmlDocument RunfileXMLCreate()
{
XmlDocument NewRunfile = new XmlDocument();
//1.) Top Header
//<?xml version="1.0" encoding="utf-8" ?>
NewRunfile.AppendChild(NewRunfile.CreateXmlDeclaration("1.0", "utf-8", ""));
//2.) Routine to Write Runfile header
XmlNode root = NewRunfile.CreateElement("Runfile");
NewRunfile.AppendChild(root);
#region RunfileInformation XML Node
//2.) Start modules -- open module tag
/*
<Runfile>
<RunfileInformation>
<Author> Blah Smith </Author>
<Abstract> afldlkdklasdjsad </Abstract>
<EditDate> 1/1/09 </EditDate>
<ImageLocation> /image/image.jpg </ImageLocation>
</RunfileInformation>
<Modules>
*/
#endregion
#region RunfileInformation Code
XmlNode eRunfileInformation = NewRunfile.CreateElement("RunfileInformation");
root.AppendChild(eRunfileInformation);
//Author ---
XmlNode eRFIAuthor = NewRunfile.CreateElement("Author");
eRFIAuthor.InnerText = this.RunfileInformation.RunfileInformationAuthor.ToString();
XmlNode eRFIAbstract = NewRunfile.CreateElement("Abstract");
eRFIAbstract.InnerText = this.RunfileInformation.RunfileInformationAbstract.ToString();
XmlNode eRFIEditDate = NewRunfile.CreateElement("EditDate");
eRFIEditDate.InnerText = this.RunfileInformation.RunfileInformationEditDate.ToString();
XmlNode eRFIImageLocation = NewRunfile.CreateElement("ImageLocation");
eRFIImageLocation.InnerText = this.RunfileInformation.RunfileInformationImageLocation.ToString();
eRunfileInformation.AppendChild(eRFIAuthor);
eRunfileInformation.AppendChild(eRFIAbstract);
eRunfileInformation.AppendChild(eRFIEditDate);
eRunfileInformation.AppendChild(eRFIImageLocation);
///-----------------------------------------------------------------------------------------------------|
#endregion
#region ModuleInformation Node Notes
//3.) Write modules
//foreach write module
//module write method
//method to write module information
//method to write module I-O-P
/*
<ModuleInformation>
<InstanceName>Left_Pinna</InstanceName>
<ExecutableName>DataSource</ExecutableName>
</ModuleInformation>
*/
#endregion
XmlNode ModulesRoot = NewRunfile.CreateElement("Modules");
root.AppendChild(ModulesRoot);
foreach (EarlabModule Module in this.EarlabModules)
{
XmlNode ModuleRoot = NewRunfile.CreateElement("Module");
#region ModuleInformation Write Method
//Module Info
XmlNode eModuleInfo = NewRunfile.CreateElement("ModuleInformation");
ModuleRoot.AppendChild(eModuleInfo);
XmlNode eMName = NewRunfile.CreateElement("InstanceName");
eMName.InnerText = Module.theEarlabModuleInformation.InstanceName.ToString();
eModuleInfo.AppendChild(eMName);
XmlNode eName = NewRunfile.CreateElement("ExecutableName");
eName.InnerText = Module.theEarlabModuleInformation.ExecutableName.ToString();
eModuleInfo.AppendChild(eName);
// Mod. end
#endregion
#region Inputs && Outputs Methods
XmlNode eInputs = NewRunfile.CreateElement("Inputs");
foreach (EarlabInput elIn in Module.EarlabInputs)
{
}
ModuleRoot.AppendChild(eInputs);
XmlNode eOutputs = NewRunfile.CreateElement("Outputs");
foreach (EarlabOutput elOut in Module.EarlabOutputs)
{
}
ModuleRoot.AppendChild(eOutputs);
#endregion
//Sample parameter -- we have to cast it to get value
XmlNode eParams = NewRunfile.CreateElement("Parameters");
foreach (EarlabParameter elParam in Module.EarlabParameters)
{
//XmlNode thing!! damn it :|
//problem with the node that is returned.
//XmlNode TempNode = NewRunfile.CreateElement("Parameter");
XmlNode ParamRoot = NewRunfile.CreateElement("Parameter");
XmlNode ePName = NewRunfile.CreateElement("Name");
ePName.InnerText = elParam.PName.ToString();
ParamRoot.AppendChild(ePName);
XmlNode ePType = NewRunfile.CreateElement("Type");
ePType.InnerText = elParam.PType.ToString();
ParamRoot.AppendChild(ePType);
//////////////////////////////////////////////////// Value is hard part/////
string TestType = ePType.InnerXml.ToString();
TestType = TestType.ToLower();
XmlNode ePValue = NewRunfile.CreateElement("Value");
//ParamRoot.AppendChild(ePValue);
switch (TestType)
{
case "integer":
case "int":
ePValue.InnerText = ((EarlabParameterInteger)elParam).PValue.ToString();
ParamRoot.AppendChild(ePValue);
break;
case "float":
case "double":
case "dbl":
case "fl":
ePValue.InnerText = ((EarlabParameterDouble)elParam).PValue.ToString();
ParamRoot.AppendChild(ePValue);
break;
case "str":
case "string":
ePValue.InnerText = ((EarlabParameterString)elParam).PValue.ToString();
ParamRoot.AppendChild(ePValue);
break;
case "bool":
case "boolean":
ePValue.InnerText = ((EarlabParameterBoolean)elParam).PValue.ToString();
ParamRoot.AppendChild(ePValue);
break;
case "integer[]":
case "int[]":
//only for ease of use
EarlabParameterIntegerArray IntParam = ((EarlabParameterIntegerArray)elParam);
//to covert the array to a node of element tags that contain values
//trying to figure out how to encapsulate this into a method.
for (int counter = 0; counter < IntParam.PValue.Length; counter++)
{
XmlNode Element1 = NewRunfile.CreateElement("Element");
Element1.InnerText = IntParam.PValue[counter].ToString();
ePValue.AppendChild(Element1);
}
ParamRoot.AppendChild(ePValue);
break;
case "double[]":
case "float[]":
case "dbl[]":
case "fl[]":
//only for ease of use
EarlabParameterDoubleArray DblParam = ((EarlabParameterDoubleArray)elParam);
//to covert the array to a node of element tags that contain values
//trying to figure out how to encapsulate this into a method.
for (int counter = 0; counter < DblParam.PValue.Length; counter++)
{
XmlNode Element1 = NewRunfile.CreateElement("Element");
Element1.InnerText = DblParam.PValue[counter].ToString();
ePValue.AppendChild(Element1);
}
ParamRoot.AppendChild(ePValue);
break;
default:
//fragged
break;
}
eParams.AppendChild(ParamRoot);
}//end the massive foreach loop --
ModuleRoot.AppendChild(eParams);
//Added all the I-O-Ps
ModulesRoot.AppendChild(ModuleRoot);
}
//5.) Check File against schema
//6.) Send file back
return NewRunfile;
}
//Verrors section
public void AllEarlabObjectUpdate(XmlDocument Verrors)
{
VErrorCollection = ErrorListCreator(Verrors);
foreach (VerificationError VerrorObject in VErrorCollection)
{
OneObjectErrorUpdate(VerrorObject);
//some error here then
}
}
/// <summary>
///
/// </summary>
/// <param name="RunfileVerificationErrors"></param>
/// <returns></returns>
private List<VerificationError> ErrorListCreator(XmlDocument RunfileVerificationErrors)
{
//clear the old errors
List<VerificationError> mVErrorCollection = new List<VerificationError>();
XmlNodeList VList = RunfileVerificationErrors.GetElementsByTagName("VerificationEvent");
foreach (XmlNode errorNode in VList)
{
/// Converts XML Node Module into the collection of ModuleInfo and IOP
mVErrorCollection.Add( new VerificationError(errorNode) );
}
return mVErrorCollection;
}
/// <summary>
///
/// </summary>
/// <param name="VError"></param>
/// <returns></returns>
private void OneObjectErrorUpdate(VerificationError VError)
{
//Problem with the design ---
//Once it HasChanged been updated we need to exit the loop.
//Each error is only going to be there 1 time.
//Once we find it we need out!!
//string searchString = VError.IOPName;
//module
// if null then it is a module, else it is an IOP
if (VError.IOPName == null)
{
#region Module Level Error Method
foreach (EarlabModule currentModule in EarlabModules)
{
//This is NOT working b/c it is not referencing the right Object!!!
if (currentModule.theEarlabModuleInformation.InstanceName.ToLower() == VError.ModuleInstanceName.ToLower())
{
//update module with verror info
currentModule.Message = VError.Message;
currentModule.Severity = VError.Severity;
return;
}
}
#endregion
}
//this is a input-output-parameter
//VError.IOPType.ToLower()
else if (VError.IOPType.ToLower() == "parameter" || VError.IOPType.ToLower() == "input" || VError.IOPType.ToLower() == "output")
{
#region IOP Level Error Method
//go through each module
foreach (EarlabModule currentModule in EarlabModules)
{
//We have the right module now
if (VError.ModuleInstanceName.ToLower() == currentModule.theEarlabModuleInformation.InstanceName.ToLower())
{
//Now we need the input output or parameter
switch (VError.IOPType.ToLower())
{
case "parameter":
//code pattern for finding the IOP
foreach (EarlabParameter parameter in currentModule.EarlabParameters)
{
if (parameter.PName.ToLower() == VError.IOPName.ToLower())
{
//update parameter with verror info
parameter.Message = VError.Message;
parameter.Severity = VError.Severity;
//return true;
return;
}
}
//This means that the error sent back from the EFI is a parameter, but not named properly.
throw new System.NotSupportedException("The Parameter Name " + VError.IOPName + " is not recognized.");
//break;
case "input":
//foreach (EarlabInput input in currentModule.EarlabInputs)
//{
// if (input.PName == VError.IOPName)
// TheVar = input;
//return;
break;
//}
case "output":
//foreach (EarlabOutput output in currentModule.EarlabOutputs)
//{
// if (output.PName == VError.IOPName)
// TheVar = output;
//return true;
//}
break;
default:
throw new System.NotSupportedException("The Error type " + VError.IOPType + " is not recognized.");
}//end switch
}//end if
//module name is not recognized what would this mean?
//else
//throw new System.NotSupportedException("The Error type " + VError.ModuleName + " is not recognized.");
}//end foreach
#endregion
//this is the same problem as above -- module name not recognized, no reason to have the code twice.
//throw new System.NotSupportedException("The Error type " + VError.ModuleName + " is not recognized.");
}//end else if
//catch -- all we have soem error and it doesn't correspond to a module or module's IOP.
else
{
throw new System.NotSupportedException("The Full Verification Error type with path " + VError.FullErrorPath + " is not recognized.");
}
}
public void EFI_Run()
{
XmlDocument RunfileVerificationErrors;
//need to give doc a title?
EFIVerification.GetRunfileEFIError(this.RunfileXMLCreate(), out RunfileVerificationErrors);
//
//Process errors
this.AllEarlabObjectUpdate(RunfileVerificationErrors);
//Display Errors on "Summary" GUI
//if no errors, create the Desktop Earlab launch
//button_create_if_no_errors();
}
#endregion
}
}
| |
// DeflateStream.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2009-2010 Dino Chiesa.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// last saved (in emacs):
// Time-stamp: <2010-February-05 08:49:04>
//
// ------------------------------------------------------------------
//
// This module defines the DeflateStream class, which can be used as a replacement for
// the System.IO.Compression.DeflateStream class in the .NET BCL.
//
// ------------------------------------------------------------------
using System;
using System.IO;
namespace SharpCompress.Compressor.Deflate
{
public class DeflateStream : Stream
{
private readonly ZlibBaseStream _baseStream;
private bool _disposed;
public DeflateStream(Stream stream, CompressionMode mode )
: this(stream, mode, CompressionLevel.Default, false) {
}
public DeflateStream(Stream stream, CompressionMode mode,
CompressionLevel level)
: this(stream,mode,level,false) {
}
public DeflateStream(Stream stream, CompressionMode mode,
CompressionLevel level ,
bool leaveOpen )
{
_baseStream = new ZlibBaseStream(stream, mode, level, ZlibStreamFlavor.DEFLATE, leaveOpen);
}
#region Zlib properties
/// <summary>
/// This property sets the flush behavior on the stream.
/// </summary>
/// <remarks> See the ZLIB documentation for the meaning of the flush behavior.
/// </remarks>
public virtual FlushType FlushMode
{
get { return (_baseStream._flushMode); }
set
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
_baseStream._flushMode = value;
}
}
/// <summary>
/// The size of the working buffer for the compression codec.
/// </summary>
///
/// <remarks>
/// <para>
/// The working buffer is used for all stream operations. The default size is
/// 1024 bytes. The minimum size is 128 bytes. You may get better performance
/// with a larger buffer. Then again, you might not. You would have to test
/// it.
/// </para>
///
/// <para>
/// Set this before the first call to <c>Read()</c> or <c>Write()</c> on the
/// stream. If you try to set it afterwards, it will throw.
/// </para>
/// </remarks>
public int BufferSize
{
get { return _baseStream._bufferSize; }
set
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
if (_baseStream._workingBuffer != null)
throw new ZlibException("The working buffer is already set.");
if (value < ZlibConstants.WorkingBufferSizeMin)
throw new ZlibException(
String.Format("Don't be silly. {0} bytes?? Use a bigger buffer, at least {1}.", value,
ZlibConstants.WorkingBufferSizeMin));
_baseStream._bufferSize = value;
}
}
/// <summary>
/// The ZLIB strategy to be used during compression.
/// </summary>
///
/// <remarks>
/// By tweaking this parameter, you may be able to optimize the compression for
/// data with particular characteristics.
/// </remarks>
public CompressionStrategy Strategy
{
get { return _baseStream.Strategy; }
set
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
_baseStream.Strategy = value;
}
}
/// <summary> Returns the total number of bytes input so far.</summary>
public virtual long TotalIn
{
get { return _baseStream._z.TotalBytesIn; }
}
/// <summary> Returns the total number of bytes output so far.</summary>
public virtual long TotalOut
{
get { return _baseStream._z.TotalBytesOut; }
}
#endregion
#region System.IO.Stream methods
/// <summary>
/// Indicates whether the stream can be read.
/// </summary>
/// <remarks>
/// The return value depends on whether the captive stream supports reading.
/// </remarks>
public override bool CanRead
{
get
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
return _baseStream._stream.CanRead;
}
}
/// <summary>
/// Indicates whether the stream supports Seek operations.
/// </summary>
/// <remarks>
/// Always returns false.
/// </remarks>
public override bool CanSeek
{
get { return false; }
}
/// <summary>
/// Indicates whether the stream can be written.
/// </summary>
/// <remarks>
/// The return value depends on whether the captive stream supports writing.
/// </remarks>
public override bool CanWrite
{
get
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
return _baseStream._stream.CanWrite;
}
}
/// <summary>
/// Reading this property always throws a <see cref="NotImplementedException"/>.
/// </summary>
public override long Length
{
get { throw new NotSupportedException(); }
}
/// <summary>
/// The position of the stream pointer.
/// </summary>
///
/// <remarks>
/// Setting this property always throws a <see
/// cref="NotImplementedException"/>. Reading will return the total bytes
/// written out, if used in writing, or the total bytes read in, if used in
/// reading. The count may refer to compressed bytes or uncompressed bytes,
/// depending on how you've used the stream.
/// </remarks>
public override long Position
{
get
{
if (_baseStream._streamMode == ZlibBaseStream.StreamMode.Writer)
return _baseStream._z.TotalBytesOut;
if (_baseStream._streamMode == ZlibBaseStream.StreamMode.Reader)
return _baseStream._z.TotalBytesIn;
return 0;
}
set { throw new NotSupportedException(); }
}
/// <summary>
/// Dispose the stream.
/// </summary>
/// <remarks>
/// This may or may not result in a <c>Close()</c> call on the captive stream.
/// See the constructors that have a <c>leaveOpen</c> parameter for more information.
/// </remarks>
protected override void Dispose(bool disposing)
{
try
{
if (!_disposed)
{
if (disposing && (_baseStream != null))
_baseStream.Dispose();
_disposed = true;
}
}
finally
{
base.Dispose(disposing);
}
}
/// <summary>
/// Flush the stream.
/// </summary>
public override void Flush()
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
_baseStream.Flush();
}
/// <summary>
/// Read data from the stream.
/// </summary>
/// <remarks>
///
/// <para>
/// If you wish to use the <c>DeflateStream</c> to compress data while
/// reading, you can create a <c>DeflateStream</c> with
/// <c>CompressionMode.Compress</c>, providing an uncompressed data stream.
/// Then call Read() on that <c>DeflateStream</c>, and the data read will be
/// compressed as you read. If you wish to use the <c>DeflateStream</c> to
/// decompress data while reading, you can create a <c>DeflateStream</c> with
/// <c>CompressionMode.Decompress</c>, providing a readable compressed data
/// stream. Then call Read() on that <c>DeflateStream</c>, and the data read
/// will be decompressed as you read.
/// </para>
///
/// <para>
/// A <c>DeflateStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but not both.
/// </para>
///
/// </remarks>
/// <param name="buffer">The buffer into which the read data should be placed.</param>
/// <param name="offset">the offset within that data array to put the first byte read.</param>
/// <param name="count">the number of bytes to read.</param>
/// <returns>the number of bytes actually read</returns>
public override int Read(byte[] buffer, int offset, int count)
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
return _baseStream.Read(buffer, offset, count);
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="offset">this is irrelevant, since it will always throw!</param>
/// <param name="origin">this is irrelevant, since it will always throw!</param>
/// <returns>irrelevant!</returns>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="value">this is irrelevant, since it will always throw!</param>
public override void SetLength(long value)
{
throw new NotSupportedException();
}
/// <summary>
/// Write data to the stream.
/// </summary>
/// <remarks>
///
/// <para>
/// If you wish to use the <c>DeflateStream</c> to compress data while
/// writing, you can create a <c>DeflateStream</c> with
/// <c>CompressionMode.Compress</c>, and a writable output stream. Then call
/// <c>Write()</c> on that <c>DeflateStream</c>, providing uncompressed data
/// as input. The data sent to the output stream will be the compressed form
/// of the data written. If you wish to use the <c>DeflateStream</c> to
/// decompress data while writing, you can create a <c>DeflateStream</c> with
/// <c>CompressionMode.Decompress</c>, and a writable output stream. Then
/// call <c>Write()</c> on that stream, providing previously compressed
/// data. The data sent to the output stream will be the decompressed form of
/// the data written.
/// </para>
///
/// <para>
/// A <c>DeflateStream</c> can be used for <c>Read()</c> or <c>Write()</c>,
/// but not both.
/// </para>
///
/// </remarks>
///
/// <param name="buffer">The buffer holding data to write to the stream.</param>
/// <param name="offset">the offset within that data array to find the first byte to write.</param>
/// <param name="count">the number of bytes to write.</param>
public override void Write(byte[] buffer, int offset, int count)
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
_baseStream.Write(buffer, offset, count);
}
#endregion
public MemoryStream InputBuffer
{
get
{
return new MemoryStream(_baseStream._z.InputBuffer, _baseStream._z.NextIn,
_baseStream._z.AvailableBytesIn);
}
}
}
}
| |
// Required data structures
using System;
using System.Runtime.InteropServices;
// ReSharper disable UnusedMember.Global
// ReSharper disable InconsistentNaming
// ReSharper disable IdentifierTypo
// ReSharper disable ArrangeTypeMemberModifiers
// ReSharper disable CommentTypo
namespace CombineFileContentsForListOfFilesOnClipboard
{
public struct POINTAPI
{
public long x;
public long y;
}
public struct DROPFILES
{
public long pFiles;
public POINTAPI pt;
public long fNC;
public long fWide;
}
public static class X
{
// Predefined Clipboard Formats
public const int CF_TEXT = 1;
public const int CF_BITMAP = 2;
public const int CF_METAFILEPICT = 3;
public const int CF_SYLK = 4;
public const int CF_DIF = 5;
public const int CF_TIFF = 6;
public const int CF_OEMTEXT = 7;
public const int CF_DIB = 8;
public const int CF_PALETTE = 9;
public const int CF_PENDATA = 10;
public const int CF_RIFF = 11;
public const int CF_WAVE = 12;
public const int CF_UNICODETEXT = 13;
public const int CF_ENHMETAFILE = 14;
public const int CF_HDROP = 15;
public const int CF_LOCALE = 16;
public const int CF_MAX = 17;
public const int GMEM_FIXED = 0;
public const int GMEM_MOVEABLE = 2;
public const int GMEM_NOCOMPACT = 16;
public const int GMEM_NODISCARD = 32;
public const int GMEM_ZEROINIT = 64;
public const int GMEM_MODIFY = 128;
public const int GMEM_DISCARDABLE = 256;
public const int GMEM_NOT_BANKED = 4096;
public const int GMEM_SHARE = 8192;
public const int GMEM_DDESHARE = 8192;
public const int GMEM_NOTIFY = 16384;
public const int GMEM_LOWER = GMEM_NOT_BANKED;
public const int GMEM_VALID_FLAGS = 32626;
public const int GMEM_INVALID_HANDLE = 32768;
public const int GHND = GMEM_MOVEABLE | GMEM_ZEROINIT;
public const int GPTR = GMEM_FIXED | GMEM_ZEROINIT;
// New shell-oriented clipboard formats
public const string CFSTR_SHELLIDLIST = "Shell IDList Array";
public const string CFSTR_SHELLIDLISTOFFSET = "Shell Object Offsets";
public const string CFSTR_NETRESOURCES = "Net Resource";
public const string CFSTR_FILEDESCRIPTOR = "FileGroupDescriptor";
public const string CFSTR_FILECONTENTS = "FileContents";
public const string CFSTR_FILENAME = "FileName";
public const string CFSTR_PRINTERGROUP = "PrinterFriendlyName";
public const string CFSTR_FILENAMEMAP = "FileNameMap";
public const int MAX_PATH = 260;
// Clipboard Manager Functions
[DllImport("user32.dll")] static extern long EmptyClipboard();
[DllImport("user32.dll")] static extern long OpenClipboard(long hWnd);
[DllImport("user32.dll")] static extern long CloseClipboard();
[DllImport("user32.dll")] static extern long SetClipboardData(long wFormat, IntPtr hMem);
[DllImport("user32.dll")] static extern long GetClipboardData(long wFormat);
[DllImport("user32.dll")] static extern long IsClipboardFormatAvailable(long wFormat);
// Other required Win32 APIs
[DllImport("shell32.dll", EntryPoint = "DragQueryFileA")]
static extern long DragQueryFile(long hDrop, long UINT, string lpStr, long ch);
[DllImport("shell32.dll")]
static extern long DragQueryPoint(long hDrop, POINTAPI lpPoint);
[DllImport("kernel32.dll")]
static extern IntPtr GlobalAlloc(long wFlags, long dwBytes);
[DllImport("kernel32.dll")]
static extern IntPtr GlobalFree(IntPtr hMem);
[DllImport("kernel32.dll")]
static extern IntPtr GlobalLock(IntPtr hMem);
[DllImport("kernel32.dll")]
static extern IntPtr GlobalUnlock(IntPtr hMem);
[DllImport("kernel32.dll", EntryPoint = "RtlMoveMemory")]
static extern void CopyMem(IntPtr Destination, IntPtr Source, long Length);
public static bool PutFileListOnClipboard(string[] files)
{
DROPFILES df = new DROPFILES();
// Open and clear existing crud off clipboard.
if (OpenClipboard(0) != 0)
{
EmptyClipboard();
// Build double-null terminated list of files.
string data = "";
for (int i = 0; i <= files.Length; i++)
data += files[i] + '\0';
data += '\0';
// Allocate and get pointer to global memory,
// then copy file list to it.
var sizeOfDROPFILES = Marshal.SizeOf(typeof(DROPFILES));
int size = sizeOfDROPFILES + data.Length;
IntPtr handleToDestinationMemory = GlobalAlloc(GHND, size);
if (handleToDestinationMemory != IntPtr.Zero)
{
IntPtr lockedHandle = GlobalLock(handleToDestinationMemory);
// Build DROPFILES structure in global memory.
df.pFiles = sizeOfDROPFILES;
IntPtr pointerToDf = IntPtr.Zero;
Marshal.StructureToPtr(df, pointerToDf, false);
IntPtr pointerToData = Marshal.StringToHGlobalAuto(data);
CopyMem(lockedHandle, pointerToDf, sizeOfDROPFILES);
CopyMem(lockedHandle + sizeOfDROPFILES, pointerToData, data.Length);
GlobalUnlock(handleToDestinationMemory);
// Copy data to clipboard, and return success.
if (SetClipboardData(CF_HDROP, handleToDestinationMemory) != 0)
{
CloseClipboard();
return true;
}
}
// Clean up
CloseClipboard();
}
return false;
}
public static string[] GetFilenamesFromClipboard()
{
// Insure desired format is there, and open clipboard.
if (IsClipboardFormatAvailable(CF_HDROP) != 0)
{
string[] files = Array.Empty<string>();
if (OpenClipboard(0) != 0)
{
// Get handle to Dropped Filelist data, and number of files.
var handleToDroppedFilenames = GetClipboardData(CF_HDROP);
var numberofFilenames = DragQueryFile(handleToDroppedFilenames, -1, "", 0);
// Allocate space for return and working variables.
files = new string[numberofFilenames];
string filename = new string(' ', MAX_PATH);
// Retrieve each filename in Dropped Filelist.
for (int i = 0; i <= numberofFilenames - 1; i++)
{
DragQueryFile(handleToDroppedFilenames, i, filename, filename.Length);
files[i] = filename.FirstToken("\0");
}
// Clean up
CloseClipboard();
}
// Assign return value equal to number of files dropped.
return files;
}
return Array.Empty<string>();
}
public static string TrimNull(string target)
{
//
// Truncate input string at first null.
// If no nulls, perform ordinary Trim.
//
int indexOfNullChar = target.IndexOf('\0') + 1;
if(indexOfNullChar > 1)
return target.Substring(0, indexOfNullChar - 1);
if (indexOfNullChar == 1)
return "";
return target.Trim();
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="SettingsDialog.cs" company="None">
// Copyright (c) Brandon Wallace and Jesse Calhoun. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace TQVaultAE.GUI
{
using System;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Windows.Forms;
using TQVaultAE.GUI.Models;
using TQVaultAE.Presentation;
using EnumsNET;
using TQVaultAE.Domain.Results;
using TQVaultAE.GUI.Components;
/// <summary>
/// Class for the Settings/Configuration Dialog
/// </summary>
internal partial class SettingsDialog : VaultForm, IScalingControl
{
public string BaseFont { get; private set; }
/// <summary>
/// Indicates whether the last opened vault will be loaded at startup
/// </summary>
private bool loadLastVault;
/// <summary>
/// Indicates that the <see cref="Config.Settings.EnableItemRequirementRestriction"/> setting has been changed
/// </summary>
public bool enableItemRequirementRestriction;
/// <summary>
/// Indicates whether the title screen will be skipped on startup
/// </summary>
private bool skipTitle;
/// <summary>
/// Save path for the vault files
/// </summary>
public string VaultPath { get; private set; }
/// <summary>
/// Indicates whether item copying is allowed
/// </summary>
private bool allowItemCopy;
/// <summary>
/// Indicates whether item editing is allowed
/// </summary>
private bool allowItemEdit;
/// <summary>
/// Indicates whether character editing is allowed
/// </summary>
private bool allowCharacterEdit;
/// <summary>
/// Indicates whether the last opened character will be loaded at startup
/// </summary>
private bool loadLastCharacter;
/// <summary>
/// Indicates whether the language will be auto detected
/// </summary>
private bool detectLanguage;
/// <summary>
/// Activate the alternative Tooltip display
/// </summary>
private bool enableDetailedTooltipView;
/// <summary>
/// Value Range (0-255) for item background color opacity
/// </summary>
private int itemBGColorOpacity;
/// <summary>
/// The language we will be using.
/// </summary>
private string titanQuestLanguage;
/// <summary>
/// Indicates whether the game paths will be auto detected
/// </summary>
private bool detectGamePath;
/// <summary>
/// Titan Quest game path
/// </summary>
private string titanQuestPath;
/// <summary>
/// Immortal Throne game path
/// </summary>
private string immortalThronePath;
/// <summary>
/// Indicates whether custom maps have been enabled
/// </summary>
private bool enableMods;
/// <summary>
/// Current custom map
/// </summary>
private string customMap;
/// <summary>
/// Indicates whether we are loading all data files on startup
/// </summary>
private bool loadAllFiles;
/// <summary>
/// Indicates whether warning messages are suppressed
/// </summary>
private bool suppressWarnings;
/// <summary>
/// Indicates whether player items will be readonly.
/// </summary>
private bool playerReadonly;
/// <summary>
/// Indicates whether the vault path has been changed
/// </summary>
public bool VaultPathChanged { get; private set; }
/// <summary>
/// Indicates whether the play list filter has been changed
/// </summary>
public bool PlayerFilterChanged { get; private set; }
/// <summary>
/// Indicates that any configuration item has been changed
/// </summary>
public bool ConfigurationChanged { get; private set; }
/// <summary>
/// Indicates that the UI setting has changed.
/// </summary>
public bool UISettingChanged { get; private set; }
/// <summary>
/// Indicates that the settings have been loaded
/// </summary>
private bool settingsLoaded;
/// <summary>
/// Indicates that the ItemBGColorOpacity setting has been changed
/// </summary>
public bool ItemBGColorOpacityChanged { get; private set; }
/// <summary>
/// Indicates that the <see cref="Config.Settings.EnableItemRequirementRestriction"/> setting has been changed
/// </summary>
public bool EnableItemRequirementRestrictionChanged { get; private set; }
/// <summary>
/// Indicates that the allow character edit setting has been changed.
/// </summary>
public bool EnableCharacterEditChanged { get; private set; }
/// <summary>
/// Enale the hot reload feature
/// </summary>
private bool enableHotReload;
/// <summary>
/// Indicates that the <see cref="Config.Settings.EnableHotReload"/> setting has been changed
/// </summary>
public bool EnableHotReloadChanged { get; private set; }
/// <summary>
/// Indicates that the language setting has been changed
/// </summary>
public bool LanguageChanged { get; private set; }
/// <summary>
/// Indicates that the game language has been changed
/// </summary>
public bool GamePathChanged { get; private set; }
/// <summary>
/// Indicates that the custom map selection has changed
/// </summary>
public bool CustomMapsChanged { get; private set; }
/// <summary>
/// Initializes a new instance of the SettingsDialog class.
/// </summary>
public SettingsDialog(MainForm instance) : base(instance.ServiceProvider)
{
this.Owner = instance;
this.InitializeComponent();
#region Apply custom font
this.characterEditCheckBox.Font = FontService.GetFontLight(11.25F);
this.allowItemEditCheckBox.Font = FontService.GetFontLight(11.25F);
this.allowItemCopyCheckBox.Font = FontService.GetFontLight(11.25F);
this.skipTitleCheckBox.Font = FontService.GetFontLight(11.25F);
this.loadLastCharacterCheckBox.Font = FontService.GetFontLight(11.25F);
this.loadLastVaultCheckBox.Font = FontService.GetFontLight(11.25F);
this.vaultPathTextBox.Font = FontService.GetFontLight(11.25F);
this.vaultPathLabel.Font = FontService.GetFontLight(11.25F);
this.cancelButton.Font = FontService.GetFontLight(12F);
this.okayButton.Font = FontService.GetFontLight(12F);
this.resetButton.Font = FontService.GetFontLight(12F);
this.vaultPathBrowseButton.Font = FontService.GetFontLight(12F);
this.enableCustomMapsCheckBox.Font = FontService.GetFontLight(11.25F);
this.loadAllFilesCheckBox.Font = FontService.GetFontLight(11.25F);
this.suppressWarningsCheckBox.Font = FontService.GetFontLight(11.25F);
this.playerReadonlyCheckbox.Font = FontService.GetFontLight(11.25F);
this.languageComboBox.Font = FontService.GetFontLight(11.25F);
this.languageLabel.Font = FontService.GetFontLight(11.25F);
this.detectLanguageCheckBox.Font = FontService.GetFontLight(11.25F);
this.titanQuestPathTextBox.Font = FontService.GetFontLight(11.25F);
this.titanQuestPathLabel.Font = FontService.GetFontLight(11.25F);
this.immortalThronePathLabel.Font = FontService.GetFontLight(11.25F);
this.immortalThronePathTextBox.Font = FontService.GetFontLight(11.25F);
this.detectGamePathsCheckBox.Font = FontService.GetFontLight(11.25F);
this.titanQuestPathBrowseButton.Font = FontService.GetFontLight(12F);
this.immortalThronePathBrowseButton.Font = FontService.GetFontLight(12F);
this.customMapLabel.Font = FontService.GetFontLight(11.25F);
this.mapListComboBox.Font = FontService.GetFontLight(11.25F);
this.baseFontLabel.Font = FontService.GetFontLight(11.25F);
this.baseFontComboBox.Font = FontService.GetFontLight(11.25F);
this.EnableDetailedTooltipViewCheckBox.Font = FontService.GetFontLight(11.25F);
this.EnableItemRequirementRestrictionCheckBox.Font = FontService.GetFontLight(11.25F);
this.ItemBGColorOpacityLabel.Font = FontService.GetFontLight(11.25F);
this.Font = FontService.GetFontLight(11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, (byte)(0));
#endregion
this.vaultPathLabel.Text = Resources.SettingsLabel1;
this.languageLabel.Text = Resources.SettingsLabel2;
this.titanQuestPathLabel.Text = Resources.SettingsLabel3;
this.immortalThronePathLabel.Text = Resources.SettingsLabel4;
this.customMapLabel.Text = Resources.SettingsLabel5;
this.detectGamePathsCheckBox.Text = Resources.SettingsDetectGamePath;
this.detectLanguageCheckBox.Text = Resources.SettingsDetectLanguage;
this.enableCustomMapsCheckBox.Text = Resources.SettingsEnableMod;
this.toolTip.SetToolTip(this.enableCustomMapsCheckBox, Resources.SettingsEnableModTT);
this.skipTitleCheckBox.Text = Resources.SettingsSkipTitle;
this.toolTip.SetToolTip(this.skipTitleCheckBox, Resources.SettingsSkipTitleTT);
this.allowItemCopyCheckBox.Text = Resources.SettingsAllowCopy;
this.toolTip.SetToolTip(this.allowItemCopyCheckBox, Resources.SettingsAllowCopyTT);
this.allowItemEditCheckBox.Text = Resources.SettingsAllowEdit;
this.toolTip.SetToolTip(this.allowItemEditCheckBox, Resources.SettingsAllowEdit);
this.characterEditCheckBox.Text = Resources.SettingsAllowEditCE;
this.toolTip.SetToolTip(this.characterEditCheckBox, Resources.SettingsAllowEditCE);
this.loadLastCharacterCheckBox.Text = Resources.SettingsLoadChar;
this.toolTip.SetToolTip(this.loadLastCharacterCheckBox, Resources.SettingsLoadCharTT);
this.loadLastVaultCheckBox.Text = Resources.SettingsLoadVault;
this.toolTip.SetToolTip(this.loadLastVaultCheckBox, Resources.SettingsLoadVaultTT);
this.loadAllFilesCheckBox.Text = Resources.SettingsPreLoad;
this.toolTip.SetToolTip(this.loadAllFilesCheckBox, Resources.SettingsPreLoadTT);
this.suppressWarningsCheckBox.Text = Resources.SettingsNoWarning;
this.toolTip.SetToolTip(this.suppressWarningsCheckBox, Resources.SettingsNoWarningTT);
this.playerReadonlyCheckbox.Text = Resources.SettingsPlayerReadonly;
this.toolTip.SetToolTip(this.playerReadonlyCheckbox, Resources.SettingsPlayerReadonlyTT);
this.resetButton.Text = Resources.SettingsReset;
this.toolTip.SetToolTip(this.resetButton, Resources.SettingsResetTT);
this.EnableDetailedTooltipViewCheckBox.Text = Resources.SettingEnableDetailedTooltipView;
this.toolTip.SetToolTip(this.EnableDetailedTooltipViewCheckBox, Resources.SettingEnableDetailedTooltipViewTT);
this.ItemBGColorOpacityLabel.Text = Resources.SettingsItemBGColorOpacityLabel;
this.toolTip.SetToolTip(this.ItemBGColorOpacityLabel, Resources.SettingsItemBGColorOpacityLabelTT);
this.EnableItemRequirementRestrictionCheckBox.Text = Resources.SettingsEnableItemRequirementRestriction;
this.toolTip.SetToolTip(this.EnableItemRequirementRestrictionCheckBox, Resources.SettingsEnableItemRequirementRestrictionTT);
this.hotReloadCheckBox.Text = Resources.SettingsEnableHotReload;
this.toolTip.SetToolTip(this.hotReloadCheckBox, Resources.SettingsEnableHotReloadTT);
this.cancelButton.Text = Resources.GlobalCancel;
this.okayButton.Text = Resources.GlobalOK;
this.Text = Resources.SettingsTitle;
//this.NormalizeBox = false;
this.DrawCustomBorder = true;
this.mapListComboBox.Items.Clear();
var maps = GamePathResolver.GetCustomMapList();
if (maps?.Any() ?? false)
this.mapListComboBox.Items.AddRange(maps);
if (!Config.Settings.Default.AllowCheats)
{
this.allowItemEditCheckBox.Visible = false;
this.allowItemCopyCheckBox.Visible = false;
this.characterEditCheckBox.Visible = false;
}
}
/// <summary>
/// Override of ScaleControl which supports font scaling.
/// </summary>
/// <param name="factor">SizeF for the scale factor</param>
/// <param name="specified">BoundsSpecified value.</param>
protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
{
this.Font = new Font(this.Font.FontFamily, this.Font.SizeInPoints * factor.Height, this.Font.Style);
base.ScaleControl(factor, specified);
}
/// <summary>
/// Handler for clicking the vault path browse button
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void VaultPathBrowseButtonClick(object sender, EventArgs e)
{
this.folderBrowserDialog.Description = Resources.SettingsBrowseVault;
this.folderBrowserDialog.RootFolder = Environment.SpecialFolder.Desktop;
this.folderBrowserDialog.SelectedPath = this.VaultPath;
this.folderBrowserDialog.ShowDialog();
if (this.folderBrowserDialog.SelectedPath.Trim().ToUpperInvariant() != this.VaultPath.Trim().ToUpperInvariant())
{
this.VaultPath = this.folderBrowserDialog.SelectedPath.Trim().ToUpperInvariant();
this.vaultPathTextBox.Text = this.VaultPath.Trim().ToUpperInvariant();
this.vaultPathTextBox.Invalidate();
this.ConfigurationChanged = true;
this.VaultPathChanged = true;
}
}
/// <summary>
/// Handler for clicking the reset button
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void ResetButtonClick(object sender, EventArgs e)
{
if (this.ConfigurationChanged)
{
this.LoadSettings();
this.UpdateDialogSettings();
this.Invalidate();
}
}
/// <summary>
/// Handler for clicking the skip title check box
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void SkipTitleCheckBoxCheckedChanged(object sender, EventArgs e)
{
if (this.skipTitleCheckBox.Checked)
{
if (!this.skipTitle)
{
this.ConfigurationChanged = this.skipTitle = true;
}
}
else
{
if (this.skipTitle)
{
this.skipTitle = false;
this.ConfigurationChanged = true;
}
}
}
/// <summary>
/// Handler for loading this dialog box
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void SettingsDialogLoad(object sender, EventArgs e)
{
this.settingsLoaded = false;
this.LoadSettings();
this.UpdateDialogSettings();
}
/// <summary>
/// Loads the settings from the config file
/// </summary>
private void LoadSettings()
{
this.BaseFont = Config.Settings.Default.BaseFont;
this.skipTitle = Config.Settings.Default.SkipTitle;
this.VaultPath = Config.Settings.Default.VaultPath;
this.allowItemCopy = Config.Settings.Default.AllowItemCopy;
this.allowItemEdit = Config.Settings.Default.AllowItemEdit;
this.allowCharacterEdit = Config.Settings.Default.AllowCharacterEdit;
this.loadLastCharacter = Config.Settings.Default.LoadLastCharacter;
this.loadLastVault = Config.Settings.Default.LoadLastVault;
this.detectLanguage = Config.Settings.Default.AutoDetectLanguage;
this.enableDetailedTooltipView = Config.Settings.Default.EnableDetailedTooltipView;
this.itemBGColorOpacity = Config.Settings.Default.ItemBGColorOpacity;
this.enableItemRequirementRestriction = Config.Settings.Default.EnableItemRequirementRestriction;
this.enableHotReload = Config.Settings.Default.EnableHotReload;
// Force English since there was some issue with getting the proper language setting.
var gl = Database.GameLanguage;
this.titanQuestLanguage = gl == null ? "English" : gl;
this.detectGamePath = Config.Settings.Default.AutoDetectGamePath;
this.titanQuestPath = GamePathResolver.TQPath;
this.immortalThronePath = GamePathResolver.ImmortalThronePath;
this.enableMods = Config.Settings.Default.ModEnabled;
this.customMap = Config.Settings.Default.CustomMap;
this.loadAllFiles = Config.Settings.Default.LoadAllFiles;
this.suppressWarnings = Config.Settings.Default.SuppressWarnings;
this.playerReadonly = Config.Settings.Default.PlayerReadonly;
this.settingsLoaded = true;
this.ConfigurationChanged = false;
this.VaultPathChanged = false;
this.PlayerFilterChanged = false;
this.LanguageChanged = false;
this.GamePathChanged = false;
this.UISettingChanged = false;
}
/// <summary>
/// Updates the dialog settings display
/// </summary>
private void UpdateDialogSettings()
{
// Check to see that we can update things
if (!this.settingsLoaded)
return;
// Build language combo box
this.languageComboBox.Items.Clear();
// Read the languages from the config file
ComboBoxItem[] languages = Config.Settings.Default.GameLanguages.Split(',').Select(iso =>
{
CultureInfo ci = new CultureInfo(iso.ToUpperInvariant(), true);
return new ComboBoxItem() { Value = ci.EnglishName, DisplayName = ci.DisplayName };// to keep EnglishName as baseline value
}).OrderBy(cb => cb.DisplayName).ToArray();
// Reading failed so we default to English
if (!languages.Any()) languages = new ComboBoxItem[] { new ComboBoxItem() { Value = "English", DisplayName = "English" } };
this.languageComboBox.Items.AddRange(languages);
this.vaultPathTextBox.Text = this.VaultPath;
this.skipTitleCheckBox.Checked = this.skipTitle;
this.allowItemEditCheckBox.Checked = this.allowItemEdit;
this.allowItemCopyCheckBox.Checked = this.allowItemCopy;
this.characterEditCheckBox.Checked = this.allowCharacterEdit;
this.loadLastCharacterCheckBox.Checked = this.loadLastCharacter;
this.loadLastVaultCheckBox.Checked = this.loadLastVault;
this.detectLanguageCheckBox.Checked = this.detectLanguage;
this.detectGamePathsCheckBox.Checked = this.detectGamePath;
this.immortalThronePathTextBox.Text = this.immortalThronePath;
this.immortalThronePathTextBox.Enabled = !this.detectGamePath;
this.immortalThronePathBrowseButton.Enabled = !this.detectGamePath;
this.titanQuestPathTextBox.Text = this.titanQuestPath;
this.titanQuestPathTextBox.Enabled = !this.detectGamePath;
this.titanQuestPathBrowseButton.Enabled = !this.detectGamePath;
this.loadAllFilesCheckBox.Checked = this.loadAllFiles;
this.suppressWarningsCheckBox.Checked = this.suppressWarnings;
this.playerReadonlyCheckbox.Checked = this.playerReadonly;
this.EnableDetailedTooltipViewCheckBox.Checked = this.enableDetailedTooltipView;
this.ItemBGColorOpacityTrackBar.Value = this.itemBGColorOpacity;
this.EnableItemRequirementRestrictionCheckBox.Checked = this.enableItemRequirementRestriction;
this.hotReloadCheckBox.Checked = this.enableHotReload;
this.enableCustomMapsCheckBox.Checked = this.enableMods;
var lst = this.mapListComboBox.Items.Cast<GamePathEntry>();
var found = lst.Where(m => m.Path == this.customMap).FirstOrDefault();
this.mapListComboBox.SelectedItem = found;
this.mapListComboBox.Enabled = this.enableMods;
this.languageComboBox.SelectedItem = languages.FirstOrDefault(cb => cb.Value.Equals(this.titanQuestLanguage, StringComparison.InvariantCultureIgnoreCase));
this.languageComboBox.Enabled = !this.detectLanguage;
// Build Font combo box
this.baseFontComboBox.Items.Clear();
var listItem = Enums.GetMembers<FontFamilyList>()
.Select(m => new ComboBoxItem()
{
Value = m.AsString(EnumFormat.Name),
DisplayName = m.AsString(EnumFormat.Description, EnumFormat.Name)
}).ToArray();
this.baseFontComboBox.Items.AddRange(listItem);
this.baseFontComboBox.SelectedItem = listItem.Where(i => i.Value == this.BaseFont).FirstOrDefault() ?? listItem.First();
}
/// <summary>
/// Handler for clicking the OK button
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void OkayButtonClick(object sender, EventArgs e)
{
if (this.ConfigurationChanged)
{
Config.Settings.Default.SkipTitle = this.skipTitle;
Config.Settings.Default.VaultPath = this.VaultPath;
Config.Settings.Default.AllowItemCopy = this.allowItemCopy;
Config.Settings.Default.AllowItemEdit = this.allowItemEdit;
Config.Settings.Default.AllowCharacterEdit = this.allowCharacterEdit;
Config.Settings.Default.LoadLastCharacter = this.loadLastCharacter;
Config.Settings.Default.LoadLastVault = this.loadLastVault;
Config.Settings.Default.AutoDetectLanguage = this.detectLanguage;
Config.Settings.Default.TQLanguage = this.titanQuestLanguage;
Config.Settings.Default.AutoDetectGamePath = this.detectGamePath;
Config.Settings.Default.TQITPath = this.immortalThronePath;
Config.Settings.Default.TQPath = this.titanQuestPath;
Config.Settings.Default.ModEnabled = this.enableMods;
Config.Settings.Default.CustomMap = this.customMap;
Config.Settings.Default.LoadAllFiles = this.loadAllFiles;
Config.Settings.Default.SuppressWarnings = this.suppressWarnings;
Config.Settings.Default.PlayerReadonly = this.playerReadonly;
Config.Settings.Default.BaseFont = this.BaseFont;
Config.Settings.Default.EnableDetailedTooltipView = this.enableDetailedTooltipView;
Config.Settings.Default.ItemBGColorOpacity = this.itemBGColorOpacity;
Config.Settings.Default.EnableItemRequirementRestriction = this.enableItemRequirementRestriction;
Config.Settings.Default.EnableHotReload = this.enableHotReload;
}
}
/// <summary>
/// Handler for clicking the allow item editing check box
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void AllowItemEditCheckBoxCheckedChanged(object sender, EventArgs e)
{
if (this.allowItemEditCheckBox.Checked)
{
if (!this.allowItemEdit)
{
this.ConfigurationChanged = this.allowItemEdit = true;
}
}
else
{
if (this.allowItemEdit)
{
this.allowItemEdit = false;
this.ConfigurationChanged = true;
}
}
}
/// <summary>
/// Handler for clicking the allow item copy check box
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void AllowItemCopyCheckBoxCheckedChanged(object sender, EventArgs e)
{
if (this.allowItemCopyCheckBox.Checked)
{
if (!this.allowItemCopy)
{
this.ConfigurationChanged = this.allowItemCopy = true;
}
}
else
{
if (this.allowItemCopy)
{
this.allowItemCopy = false;
this.ConfigurationChanged = true;
}
}
}
/// <summary>
/// Handler for clicking the load last character check box
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void LoadLastCharacterCheckBoxCheckedChanged(object sender, EventArgs e)
{
if (this.loadLastCharacterCheckBox.Checked)
{
if (!this.loadLastCharacter)
{
this.ConfigurationChanged = this.loadLastCharacter = true;
}
}
else
{
if (this.loadLastCharacter)
{
this.loadLastCharacter = false;
this.ConfigurationChanged = true;
}
}
}
/// <summary>
/// Handler for clicking the load last vault check box
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void LoadLastVaultCheckBoxCheckedChanged(object sender, EventArgs e)
{
if (this.loadLastVaultCheckBox.Checked)
{
if (!this.loadLastVault)
{
this.ConfigurationChanged = this.loadLastVault = true;
}
}
else
{
if (this.loadLastVault)
{
this.loadLastVault = false;
this.ConfigurationChanged = true;
}
}
}
/// <summary>
/// Handler for clicking the detect language check box
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void DetectLanguageCheckBoxCheckedChanged(object sender, EventArgs e)
{
if (this.detectLanguageCheckBox.Checked)
{
if (!this.detectLanguage)
{
this.languageComboBox.Enabled = false;
this.ConfigurationChanged = this.detectLanguage = true;
// Force TQVault to restart to autodetect the language
this.LanguageChanged = true;
}
}
else
{
if (this.detectLanguage)
{
this.detectLanguage = false;
this.ConfigurationChanged = this.languageComboBox.Enabled = true;
}
}
}
/// <summary>
/// Handler for clicking the detect game paths check box
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void DetectGamePathsCheckBoxCheckedChanged(object sender, EventArgs e)
{
if (this.detectGamePathsCheckBox.Checked)
{
if (!this.detectGamePath)
{
this.titanQuestPathTextBox.Enabled = this.immortalThronePathTextBox.Enabled
= this.titanQuestPathBrowseButton.Enabled = this.immortalThronePathBrowseButton.Enabled = false;
// Force TQVault to restart to autodetect the game path
this.GamePathChanged = this.ConfigurationChanged = this.detectGamePath = true;
}
}
else
{
if (this.detectGamePath)
{
this.detectGamePath = false;
this.ConfigurationChanged = this.immortalThronePathTextBox.Enabled = this.titanQuestPathTextBox.Enabled
= this.titanQuestPathBrowseButton.Enabled = this.immortalThronePathBrowseButton.Enabled = true;
}
}
}
/// <summary>
/// Handler for changing the language selection
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void LanguageComboBoxSelectedIndexChanged(object sender, EventArgs e)
{
// There was some problem getting the game language so we ignore changing it.
var gl = Database.GameLanguage;
if (gl == null)
return;
this.titanQuestLanguage = ((ComboBoxItem)this.languageComboBox.SelectedItem).Value;
if (this.titanQuestLanguage.ToUpperInvariant() != gl.ToUpperInvariant())
this.LanguageChanged = true;
this.ConfigurationChanged = true;
}
/// <summary>
/// Handler for leaving the vault text box
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void VaultPathTextBoxLeave(object sender, EventArgs e)
{
if (this.VaultPath.ToUpperInvariant() != this.vaultPathTextBox.Text.Trim().ToUpperInvariant())
{
this.VaultPath = this.vaultPathTextBox.Text.Trim();
this.vaultPathTextBox.Invalidate();
this.ConfigurationChanged = this.VaultPathChanged = true;
}
}
/// <summary>
/// Handler for leaving the Titan Quest game path text box
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void TitanQuestPathTextBoxLeave(object sender, EventArgs e)
{
if (this.titanQuestPath.ToUpperInvariant() != this.titanQuestPathTextBox.Text.Trim().ToUpperInvariant())
{
this.titanQuestPath = this.titanQuestPathTextBox.Text.Trim();
this.titanQuestPathTextBox.Invalidate();
this.ConfigurationChanged = this.GamePathChanged = true;
}
}
/// <summary>
/// Handler for leaving the Immortal Throne game path text box
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void ImmortalThronePathTextBoxLeave(object sender, EventArgs e)
{
if (this.immortalThronePath.ToUpperInvariant() != this.immortalThronePathTextBox.Text.Trim().ToUpperInvariant())
{
this.immortalThronePath = this.immortalThronePathTextBox.Text.Trim();
this.immortalThronePathTextBox.Invalidate();
this.ConfigurationChanged = this.GamePathChanged = true;
}
}
/// <summary>
/// Handler for clicking the Titan Quest game path browse button
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void TitanQuestPathBrowseButtonClick(object sender, EventArgs e)
{
this.folderBrowserDialog.Description = Resources.SettingsBrowseTQ;
this.folderBrowserDialog.RootFolder = Environment.SpecialFolder.MyComputer;
this.folderBrowserDialog.SelectedPath = this.titanQuestPath;
this.folderBrowserDialog.ShowDialog();
if (this.folderBrowserDialog.SelectedPath.Trim().ToUpperInvariant() != this.titanQuestPath.Trim().ToUpperInvariant())
{
this.titanQuestPath = this.folderBrowserDialog.SelectedPath.Trim().ToUpperInvariant();
this.titanQuestPathTextBox.Text = this.titanQuestPath.Trim().ToUpperInvariant();
this.titanQuestPathTextBox.Invalidate();
this.ConfigurationChanged = this.GamePathChanged = true;
}
}
/// <summary>
/// Handler for clicking the Immortal Throne game path browse button
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void ImmortalThronePathBrowseButtonClick(object sender, EventArgs e)
{
this.folderBrowserDialog.Description = Resources.SettingsBrowseIT;
this.folderBrowserDialog.RootFolder = Environment.SpecialFolder.MyComputer;
this.folderBrowserDialog.SelectedPath = this.immortalThronePath;
this.folderBrowserDialog.ShowDialog();
if (this.folderBrowserDialog.SelectedPath.Trim().ToUpperInvariant() != this.immortalThronePath.Trim().ToUpperInvariant())
{
this.immortalThronePath = this.folderBrowserDialog.SelectedPath.Trim().ToUpperInvariant();
this.immortalThronePathTextBox.Text = this.immortalThronePath.Trim().ToUpperInvariant();
this.immortalThronePathTextBox.Invalidate();
this.ConfigurationChanged = this.GamePathChanged = true;
}
}
/// <summary>
/// Handler for clicking enable custom maps
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void EnableCustomMapsCheckBoxCheckedChanged(object sender, EventArgs e)
{
if (this.enableCustomMapsCheckBox.Checked)
{
if (!this.enableMods)
{
this.mapListComboBox.Enabled = this.CustomMapsChanged = this.enableMods = this.ConfigurationChanged = true;
}
}
else
{
if (this.enableMods)
{
this.enableMods = this.mapListComboBox.Enabled = false;
this.ConfigurationChanged = this.CustomMapsChanged = true;
this.customMap = string.Empty;// Reset value
}
}
}
/// <summary>
/// Handler for changing the selected custom map
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void MapListComboBoxSelectedIndexChanged(object sender, EventArgs e)
{
if (!this.settingsLoaded)
return;
var custommap = (this.mapListComboBox.SelectedItem as GamePathEntry)?.Path ?? string.Empty;
if (custommap != Config.Settings.Default.CustomMap)
{
this.customMap = custommap;
this.ConfigurationChanged = this.CustomMapsChanged = true;
}
}
/// <summary>
/// Handler for clicking the load all files check box
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void LoadAllFilesCheckBoxCheckedChanged(object sender, EventArgs e)
{
if (this.loadAllFilesCheckBox.Checked)
{
if (!this.loadAllFiles)
{
this.loadAllFiles = this.ConfigurationChanged = true;
}
}
else
{
if (this.loadAllFiles)
{
this.loadAllFiles = false;
this.ConfigurationChanged = true;
}
}
}
/// <summary>
/// Handler for clicking the suppress warnings check box
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void SuppressWarningsCheckBoxCheckedChanged(object sender, EventArgs e)
{
if (this.suppressWarningsCheckBox.Checked)
{
if (!this.suppressWarnings)
{
this.suppressWarnings = this.ConfigurationChanged = true;
}
}
else
{
if (this.suppressWarnings)
{
this.suppressWarnings = false;
this.ConfigurationChanged = true;
}
}
}
private void PlayerReadonlyCheckboxCheckedChanged(object sender, EventArgs e)
{
if (this.playerReadonlyCheckbox.Checked)
{
if (!this.playerReadonly)
{
this.playerReadonly = this.ConfigurationChanged = true;
}
}
else
{
if (this.playerReadonly)
{
this.playerReadonly = false;
this.ConfigurationChanged = true;
}
}
}
private void CharacterEditCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (this.characterEditCheckBox.Checked)
{
if (!this.allowCharacterEdit)
{
this.allowCharacterEdit = this.ConfigurationChanged = this.EnableCharacterEditChanged = true;
}
}
else
{
if (this.allowCharacterEdit)
{
this.allowCharacterEdit = false;
this.ConfigurationChanged = this.EnableCharacterEditChanged = true;
}
}
}
private void FontComboBoxBase_SelectedIndexChanged(object sender, EventArgs e)
{
var font = this.baseFontComboBox.SelectedItem as ComboBoxItem;
if (font == null)
return;
if (font.Value != Config.Settings.Default.BaseFont)
{
this.BaseFont = font.Value;
this.ConfigurationChanged = this.UISettingChanged = true;// Force restart
}
}
private void EnableDetailedTooltipViewCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (this.EnableDetailedTooltipViewCheckBox.Checked)
{
if (!this.enableDetailedTooltipView)
this.enableDetailedTooltipView = this.ConfigurationChanged = true;
}
else
{
if (this.enableDetailedTooltipView)
{
this.enableDetailedTooltipView = false;
this.ConfigurationChanged = true;
}
}
}
private void ItemBGColorOpacityTrackBar_Scroll(object sender, EventArgs e)
{
this.itemBGColorOpacity = this.ItemBGColorOpacityTrackBar.Value;
this.ConfigurationChanged = this.ItemBGColorOpacityChanged = true;
}
private void EnableItemRequirementRestrictionCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (this.EnableItemRequirementRestrictionCheckBox.Checked)
{
if (!this.enableItemRequirementRestriction)
this.enableItemRequirementRestriction = this.ConfigurationChanged = this.EnableItemRequirementRestrictionChanged = true;
}
else
{
if (this.enableItemRequirementRestriction)
{
this.enableItemRequirementRestriction = false;
this.ConfigurationChanged = this.EnableItemRequirementRestrictionChanged = true;
}
}
}
private void hotReloadCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (this.hotReloadCheckBox.Checked && !this.enableHotReload)
{
this.enableHotReload = this.ConfigurationChanged = this.EnableHotReloadChanged = this.UISettingChanged = true;// Force restart
return;
}
if (!this.hotReloadCheckBox.Checked && this.enableHotReload)
{
this.enableHotReload = false;
this.ConfigurationChanged = this.EnableHotReloadChanged = this.UISettingChanged = true;// Force restart
}
}
}
}
| |
/* ====================================================================
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 NPOI.POIFS.Common;
using NPOI.POIFS.Storage;
using NPOI.POIFS.Properties;
using System.Collections.Generic;
using System;
using NPOI.Util;
namespace NPOI.POIFS.FileSystem
{
/**
* This class handles the MiniStream (small block store)
* in the NIO case for {@link NPOIFSFileSystem}
*/
public class NPOIFSMiniStore : BlockStore
{
private NPOIFSFileSystem _filesystem;
private NPOIFSStream _mini_stream;
private List<BATBlock> _sbat_blocks;
private HeaderBlock _header;
private RootProperty _root;
public NPOIFSMiniStore(NPOIFSFileSystem filesystem, RootProperty root,
List<BATBlock> sbats, HeaderBlock header)
{
this._filesystem = filesystem;
this._sbat_blocks = sbats;
this._header = header;
this._root = root;
this._mini_stream = new NPOIFSStream(filesystem, root.StartBlock);
}
/**
* Load the block at the given offset.
*/
public override ByteBuffer GetBlockAt(int offset)
{
// Which big block is this?
int byteOffset = offset * POIFSConstants.SMALL_BLOCK_SIZE;
int bigBlockNumber = byteOffset / _filesystem.GetBigBlockSize();
int bigBlockOffset = byteOffset % _filesystem.GetBigBlockSize();
// Now locate the data block for it
NPOIFSStream.StreamBlockByteBufferIterator it = _mini_stream.GetBlockIterator() as NPOIFSStream.StreamBlockByteBufferIterator;
for (int i = 0; i < bigBlockNumber; i++)
{
it.Next();
}
ByteBuffer dataBlock = it.Next();
if (dataBlock == null)
{
throw new IndexOutOfRangeException("Big block " + bigBlockNumber + " outside stream");
}
// Position ourselves, and take a slice
dataBlock.Position = dataBlock.Position + bigBlockOffset;
ByteBuffer miniBuffer = dataBlock.Slice();
miniBuffer.Limit = POIFSConstants.SMALL_BLOCK_SIZE;
return miniBuffer;
}
/**
* Load the block, extending the underlying stream if needed
*/
public override ByteBuffer CreateBlockIfNeeded(int offset)
{
bool firstInStore = false;
// If we are the first block to be allocated, initialise the stream
if (_mini_stream.GetStartBlock() == POIFSConstants.END_OF_CHAIN)
{
firstInStore = true;
}
// Try to Get it without extending the stream
if (! firstInStore) {
try
{
return GetBlockAt(offset);
}catch (IndexOutOfRangeException){}
}
// Need to extend the stream
// TODO Replace this with proper append support
// For now, do the extending by hand...
// Ask for another block
int newBigBlock = _filesystem.GetFreeBlock();
_filesystem.CreateBlockIfNeeded(newBigBlock);
// If we are the first block to be allocated, initialise the stream
if (firstInStore)
{
_filesystem.PropertyTable.Root.StartBlock = (newBigBlock);
_mini_stream = new NPOIFSStream(_filesystem, newBigBlock);
}
else
{
// Tack it onto the end of our chain
ChainLoopDetector loopDetector = _filesystem.GetChainLoopDetector();
int block = _mini_stream.GetStartBlock();
while (true)
{
loopDetector.Claim(block);
int next = _filesystem.GetNextBlock(block);
if (next == POIFSConstants.END_OF_CHAIN)
{
break;
}
block = next;
}
_filesystem.SetNextBlock(block, newBigBlock);
}
_filesystem.SetNextBlock(newBigBlock, POIFSConstants.END_OF_CHAIN);
// Now try again, to get the real small block
return CreateBlockIfNeeded(offset);
}
/**
* Returns the BATBlock that handles the specified offset,
* and the relative index within it
*/
public override BATBlockAndIndex GetBATBlockAndIndex(int offset)
{
return BATBlock.GetSBATBlockAndIndex(
offset, _header, _sbat_blocks);
}
/**
* Works out what block follows the specified one.
*/
public override int GetNextBlock(int offset)
{
BATBlockAndIndex bai = GetBATBlockAndIndex(offset);
return bai.Block.GetValueAt(bai.Index);
}
/**
* Changes the record of what block follows the specified one.
*/
public override void SetNextBlock(int offset, int nextBlock)
{
BATBlockAndIndex bai = GetBATBlockAndIndex(offset);
bai.Block.SetValueAt(bai.Index, nextBlock);
}
/**
* Finds a free block, and returns its offset.
* This method will extend the file if needed, and if doing
* so, allocate new FAT blocks to Address the extra space.
*/
public override int GetFreeBlock()
{
int sectorsPerSBAT = _filesystem.GetBigBlockSizeDetails().GetBATEntriesPerBlock();
// First up, do we have any spare ones?
int offset = 0;
for (int i = 0; i < _sbat_blocks.Count; i++)
{
// Check this one
BATBlock sbat = _sbat_blocks[i];
if (sbat.HasFreeSectors)
{
// Claim one of them and return it
for (int j = 0; j < sectorsPerSBAT; j++)
{
int sbatValue = sbat.GetValueAt(j);
if (sbatValue == POIFSConstants.UNUSED_BLOCK)
{
// Bingo
return offset + j;
}
}
}
// Move onto the next SBAT
offset += sectorsPerSBAT;
}
// If we Get here, then there aren't any
// free sectors in any of the SBATs
// So, we need to extend the chain and add another
// Create a new BATBlock
BATBlock newSBAT = BATBlock.CreateEmptyBATBlock(_filesystem.GetBigBlockSizeDetails(), false);
int batForSBAT = _filesystem.GetFreeBlock();
newSBAT.OurBlockIndex = batForSBAT;
// Are we the first SBAT?
if (_header.SBATCount == 0)
{
// Tell the header that we've got our first SBAT there
_header.SBATStart = batForSBAT;
_header.SBATBlockCount = 1;
}
else
{
// Find the end of the SBAT stream, and add the sbat in there
ChainLoopDetector loopDetector = _filesystem.GetChainLoopDetector();
int batOffset = _header.SBATStart;
while (true)
{
loopDetector.Claim(batOffset);
int nextBat = _filesystem.GetNextBlock(batOffset);
if (nextBat == POIFSConstants.END_OF_CHAIN)
{
break;
}
batOffset = nextBat;
}
// Add it in at the end
_filesystem.SetNextBlock(batOffset, batForSBAT);
// And update the count
_header.SBATBlockCount = _header.SBATCount + 1;
}
// Finish allocating
_filesystem.SetNextBlock(batForSBAT, POIFSConstants.END_OF_CHAIN);
_sbat_blocks.Add(newSBAT);
// Return our first spot
return offset;
}
public override ChainLoopDetector GetChainLoopDetector()
{
return new ChainLoopDetector(_root.Size, this);
}
public override int GetBlockStoreBlockSize()
{
return POIFSConstants.SMALL_BLOCK_SIZE;
}
/**
* Writes the SBATs to their backing blocks
*/
public void SyncWithDataSource()
{
foreach (BATBlock sbat in _sbat_blocks)
{
ByteBuffer block = _filesystem.GetBlockAt(sbat.OurBlockIndex);
BlockAllocationTableWriter.WriteBlock(sbat, block);
}
}
}
}
| |
// <copyright file="CholeskyTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// 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.
// </copyright>
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Single;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Single.Factorization
{
/// <summary>
/// Cholesky factorization tests for a dense matrix.
/// </summary>
[TestFixture, Category("LAFactorization")]
public class CholeskyTests
{
/// <summary>
/// Can factorize identity matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(10)]
[TestCase(100)]
public void CanFactorizeIdentity(int order)
{
var matrixI = DenseMatrix.CreateIdentity(order);
var factorC = matrixI.Cholesky().Factor;
Assert.AreEqual(matrixI.RowCount, factorC.RowCount);
Assert.AreEqual(matrixI.ColumnCount, factorC.ColumnCount);
for (var i = 0; i < factorC.RowCount; i++)
{
for (var j = 0; j < factorC.ColumnCount; j++)
{
Assert.AreEqual(i == j ? 1.0 : 0.0, factorC[i, j]);
}
}
}
/// <summary>
/// Cholesky factorization fails with diagonal a non-positive definite matrix.
/// </summary>
[Test]
public void CholeskyFailsWithDiagonalNonPositiveDefiniteMatrix()
{
var matrixI = DenseMatrix.CreateIdentity(10);
matrixI[3, 3] = -4.0f;
Assert.That(() => matrixI.Cholesky(), Throws.ArgumentException);
}
/// <summary>
/// Cholesky factorization fails with a non-square matrix.
/// </summary>
[Test]
public void CholeskyFailsWithNonSquareMatrix()
{
var matrix = new DenseMatrix(3, 2);
Assert.That(() => matrix.Cholesky(), Throws.ArgumentException);
}
/// <summary>
/// Identity determinant is one.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(10)]
[TestCase(100)]
public void IdentityDeterminantIsOne(int order)
{
var matrixI = DenseMatrix.CreateIdentity(order);
var factorC = matrixI.Cholesky();
Assert.AreEqual(1.0, factorC.Determinant);
Assert.AreEqual(0.0, factorC.DeterminantLn);
}
/// <summary>
/// Can factorize a random square matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanFactorizeRandomMatrix(int order)
{
var matrixX = Matrix<float>.Build.RandomPositiveDefinite(order, 1);
var chol = matrixX.Cholesky();
var factorC = chol.Factor;
// Make sure the Cholesky factor has the right dimensions.
Assert.AreEqual(order, factorC.RowCount);
Assert.AreEqual(order, factorC.ColumnCount);
// Make sure the Cholesky factor is lower triangular.
for (var i = 0; i < factorC.RowCount; i++)
{
for (var j = i + 1; j < factorC.ColumnCount; j++)
{
Assert.AreEqual(0.0, factorC[i, j]);
}
}
// Make sure the cholesky factor times it's transpose is the original matrix.
var matrixXfromC = factorC * factorC.Transpose();
for (var i = 0; i < matrixXfromC.RowCount; i++)
{
for (var j = 0; j < matrixXfromC.ColumnCount; j++)
{
Assert.AreEqual(matrixX[i, j], matrixXfromC[i, j], 1e-3);
}
}
}
/// <summary>
/// Can solve a system of linear equations for a random vector (Ax=b).
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomVector(int order)
{
var matrixA = Matrix<float>.Build.RandomPositiveDefinite(order, 1);
var matrixACopy = matrixA.Clone();
var chol = matrixA.Cholesky();
var matrixB = Vector<float>.Build.Random(order, 1);
var x = chol.Solve(matrixB);
Assert.AreEqual(matrixB.Count, x.Count);
var matrixBReconstruct = matrixA * x;
// Check the reconstruction.
for (var i = 0; i < order; i++)
{
Assert.AreEqual(matrixB[i], matrixBReconstruct[i], 0.5f);
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
}
/// <summary>
/// Can solve a system of linear equations for a random matrix (AX=B).
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="col">Matrix column number.</param>
[TestCase(1, 1)]
[TestCase(2, 4)]
[TestCase(5, 8)]
[TestCase(10, 3)]
[TestCase(50, 10)]
[TestCase(100, 100)]
public void CanSolveForRandomMatrix(int row, int col)
{
var matrixA = Matrix<float>.Build.RandomPositiveDefinite(row, 1);
var matrixACopy = matrixA.Clone();
var chol = matrixA.Cholesky();
var matrixB = Matrix<float>.Build.Random(row, col, 1);
var matrixX = chol.Solve(matrixB);
Assert.AreEqual(matrixB.RowCount, matrixX.RowCount);
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA * matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1f);
}
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
}
/// <summary>
/// Can solve for a random vector into a result vector.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomVectorWhenResultVectorGiven(int order)
{
var matrixA = Matrix<float>.Build.RandomPositiveDefinite(order, 1);
var matrixACopy = matrixA.Clone();
var chol = matrixA.Cholesky();
var matrixB = Vector<float>.Build.Random(order, 1);
var matrixBCopy = matrixB.Clone();
var x = new DenseVector(order);
chol.Solve(matrixB, x);
Assert.AreEqual(matrixB.Count, x.Count);
var matrixBReconstruct = matrixA * x;
// Check the reconstruction.
for (var i = 0; i < order; i++)
{
Assert.AreEqual(matrixB[i], matrixBReconstruct[i], 0.5f);
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Make sure b didn't change.
for (var i = 0; i < order; i++)
{
Assert.AreEqual(matrixBCopy[i], matrixB[i]);
}
}
/// <summary>
/// Can solve a system of linear equations for a random matrix (AX=B) into a result matrix.
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="col">Matrix column number.</param>
[TestCase(1, 1)]
[TestCase(2, 4)]
[TestCase(5, 8)]
[TestCase(10, 3)]
[TestCase(50, 10)]
[TestCase(100, 100)]
public void CanSolveForRandomMatrixWhenResultMatrixGiven(int row, int col)
{
var matrixA = Matrix<float>.Build.RandomPositiveDefinite(row, 1);
var matrixACopy = matrixA.Clone();
var chol = matrixA.Cholesky();
var matrixB = Matrix<float>.Build.Random(row, col, 1);
var matrixBCopy = matrixB.Clone();
var matrixX = new DenseMatrix(row, col);
chol.Solve(matrixB, matrixX);
Assert.AreEqual(matrixB.RowCount, matrixX.RowCount);
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA * matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1f);
}
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Make sure B didn't change.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]);
}
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="Process.cs">(c) http://www.codeplex.com/MSBuildExtensionPack. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.</copyright>
//-----------------------------------------------------------------------
namespace MSBuild.ExtensionPack.Computer
{
using System;
using System.Globalization;
using System.Linq;
using System.Management;
using System.Text.RegularExpressions;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
/// <summary>
/// <b>Valid TaskActions are:</b>
/// <para><i>CheckRunning</i> (<b>Required: </b>ProcessName <b>Output: </b> IsRunning)</para>
/// <para><i>Create</i> (<b>Required: </b>Parameters <b>Output: </b> ReturnValue, ProcessId)</para>
/// <para><i>Get</i> (<b>Required: </b>ProcessName, Value <b>Optional: </b>User, ProcessName, IncludeUserInfo <b>Output: </b> Processes)</para>
/// <para><i>Terminate</i> (<b>Required: </b>ProcessName or ProcessId)</para>
/// <para><b>Remote Execution Support:</b> Yes</para>
/// </summary>
/// <example>
/// <code lang="xml"><![CDATA[
/// <Project ToolsVersion="3.5" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
/// <PropertyGroup>
/// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath>
/// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath>
/// </PropertyGroup>
/// <Import Project="$(TPath)"/>
/// <ItemGroup>
/// <WmiExec3 Include="CommandLine#~#notepad.exe"/>
/// </ItemGroup>
/// <Target Name="Default">
/// <MSBuild.ExtensionPack.Computer.Process TaskAction="Terminate" ProcessId="9564"/>
/// <MSBuild.ExtensionPack.Computer.Process TaskAction="Create" Parameters="@(WmiExec3)">
/// <Output TaskParameter="ReturnValue" PropertyName="Rval2"/>
/// <Output TaskParameter="ProcessId" PropertyName="PID"/>
/// </MSBuild.ExtensionPack.Computer.Process>
/// <Message Text="ReturnValue: $(Rval2). ProcessId: $(PID)"/>
/// <MSBuild.ExtensionPack.Computer.Process TaskAction="CheckRunning" ProcessName="notepad.exe">
/// <Output PropertyName="Running" TaskParameter="IsRunning"/>
/// </MSBuild.ExtensionPack.Computer.Process>
/// <Message Text="notepad.exe IsRunning: $(Running)"/>
/// <MSBuild.ExtensionPack.Computer.Process TaskAction="Terminate" ProcessName="notepad.exe"/>
/// <MSBuild.ExtensionPack.Computer.Process TaskAction="CheckRunning" ProcessName="notepad.exe">
/// <Output PropertyName="Running" TaskParameter="IsRunning"/>
/// </MSBuild.ExtensionPack.Computer.Process>
/// <Message Text="notepad.exe IsRunning: $(Running)"/>
/// <MSBuild.ExtensionPack.Computer.Process TaskAction="Get" IncludeUserInfo="true">
/// <Output ItemName="ProcessList" TaskParameter="Processes"/>
/// </MSBuild.ExtensionPack.Computer.Process>
/// <Message Text="%(ProcessList.Identity) - %(ProcessList.User) - %(ProcessList.OwnerSID)"/>
/// </Target>
/// </Project>
/// ]]></code>
/// </example>
[HelpUrl("http://www.msbuildextensionpack.com/help/3.5.12.0/html/5eddaaa1-5a75-e314-d96e-6e8ecc2b2997.htm")]
public class Process : BaseTask
{
private const string GetTaskAction = "Get";
private const string CreateTaskAction = "Create";
private const string TerminateTaskAction = "Terminate";
private const string CheckRunningTaskAction = "CheckRunning";
private string processName = ".*";
private string user = ".*";
[DropdownValue(GetTaskAction)]
[DropdownValue(CreateTaskAction)]
[DropdownValue(TerminateTaskAction)]
[DropdownValue(CheckRunningTaskAction)]
public override string TaskAction
{
get { return base.TaskAction; }
set { base.TaskAction = value; }
}
/// <summary>
/// Sets the regular expression to use for filtering processes. Default is .*
/// </summary>
[TaskAction(CheckRunningTaskAction, true)]
[TaskAction(GetTaskAction, false)]
[TaskAction(TerminateTaskAction, true)]
public string ProcessName
{
get { return this.processName; }
set { this.processName = value; }
}
/// <summary>
/// Sets the regular expression to use for filtering processes. Default is .*
/// </summary>
[TaskAction(GetTaskAction, false)]
public string User
{
get { return this.user; }
set { this.user = value; }
}
/// <summary>
/// Gets the ReturnValue for Create
/// </summary>
[Output]
[TaskAction(CreateTaskAction, false)]
public string ReturnValue { get; set; }
/// <summary>
/// Gets or Sets the ProcessId
/// </summary>
[Output]
[TaskAction(TerminateTaskAction, false)]
[TaskAction(CreateTaskAction, false)]
public int ProcessId { get; set; }
/// <summary>
/// Sets the Parameters for Create. Use #~# separate name and value.
/// </summary>
[TaskAction(CreateTaskAction, false)]
public ITaskItem[] Parameters { get; set; }
/// <summary>
/// Sets whether to include user information for processes. Including this will slow the query. Default is false;
/// </summary>
[TaskAction(GetTaskAction, false)]
public bool IncludeUserInfo { get; set; }
/// <summary>
/// Gets whether the process is running
/// </summary>
[TaskAction(CheckRunningTaskAction, false)]
[Output]
public bool IsRunning { get; set; }
/// <summary>
/// Gets the list of processes. The process name is used as the identity and the following metadata is set: Caption, Description, Handle, HandleCount, KernelModeTime, PageFaults, PageFileUsage, ParentProcessId, PeakPageFileUsage, PeakVirtualSize, PeakWorkingSetSize, Priority, PrivatePageCount, ProcessId, QuotaNonPagedPoolUsage, QuotaPagedPoolUsage, QuotaPeakNonPagedPoolUsage, QuotaPeakPagedPoolUsage, ReadOperationCount, ReadTransferCount, SessionId, ThreadCount, UserModeTime, VirtualSize, WindowsVersion, WorkingSetSize, WriteOperationCount, WriteTransferCount
/// </summary>
[TaskAction(GetTaskAction, false)]
[Output]
public ITaskItem[] Processes { get; set; }
/// <summary>
/// Performs the action of this task.
/// </summary>
protected override void InternalExecute()
{
this.GetManagementScope(@"\root\cimv2");
switch (this.TaskAction)
{
case CreateTaskAction:
this.Create();
break;
case GetTaskAction:
this.Get();
break;
case TerminateTaskAction:
this.Kill();
break;
case CheckRunningTaskAction:
this.CheckRunning();
break;
default:
Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction));
return;
}
}
private void Create()
{
if (this.Parameters == null)
{
this.Log.LogError("Parameters is required");
return;
}
using (ManagementClass mgmtClass = new ManagementClass(this.Scope, new ManagementPath("Win32_Process"), null))
{
// Obtain in-parameters for the method
ManagementBaseObject inParams = mgmtClass.GetMethodParameters("Create");
if (this.Parameters != null)
{
// Add the input parameters.
foreach (string[] data in this.Parameters.Select(param => param.ItemSpec.Split(new[] { "#~#" }, StringSplitOptions.RemoveEmptyEntries)))
{
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Param: {0}. Value: {1}", data[0], data[1]));
inParams[data[0]] = data[1];
}
}
// Execute the method and obtain the return values.
ManagementBaseObject outParams = mgmtClass.InvokeMethod("Create", inParams, null);
if (outParams != null)
{
this.ReturnValue = outParams["ReturnValue"].ToString();
this.ProcessId = Convert.ToInt32(outParams["ProcessId"], CultureInfo.CurrentCulture);
}
}
}
private void CheckRunning()
{
if (string.IsNullOrEmpty(this.ProcessName))
{
this.Log.LogError("ProcessName is required");
return;
}
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Checking whether Process is running: {0}", this.ProcessName));
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Process WHERE Name ='" + this.ProcessName + "'");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(this.Scope, query, null))
{
ManagementObjectCollection moc = searcher.Get();
if (moc.Count > 0)
{
this.IsRunning = true;
}
}
}
private void Kill()
{
if (this.ProcessName == ".*" && this.ProcessId == 0)
{
this.Log.LogError("ProcessName or ProcessId is required");
return;
}
ObjectQuery query = this.ProcessName != ".*" ? new ObjectQuery("SELECT * FROM Win32_Process WHERE Name ='" + this.ProcessName + "'") : new ObjectQuery("SELECT * FROM Win32_Process WHERE Handle ='" + this.ProcessId + "'");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(this.Scope, query, null))
{
foreach (ManagementObject returnedProcess in searcher.Get())
{
this.LogTaskMessage(this.ProcessName != ".*" ? string.Format(CultureInfo.CurrentCulture, "Terminating: {0}", this.ProcessName) : string.Format(CultureInfo.CurrentCulture, "Terminating: {0}", this.ProcessId));
ManagementBaseObject inParams = returnedProcess.GetMethodParameters("Terminate");
ManagementBaseObject outParams = returnedProcess.InvokeMethod("Terminate", inParams, null);
// ReturnValue should be 0, else failure
if (outParams != null)
{
switch (Convert.ToInt32(outParams.Properties["ReturnValue"].Value, CultureInfo.CurrentCulture))
{
case 0:
this.LogTaskMessage("...Process Terminated");
break;
case 2:
this.Log.LogError("...Access Denied");
break;
case 3:
this.Log.LogError("...Insufficient Privilege");
break;
case 8:
this.Log.LogError("...Unknown Failure");
break;
case 9:
this.Log.LogError("...Path Not Found");
break;
case 21:
this.Log.LogError("...Invalid Parameter");
break;
}
}
}
}
}
private void Get()
{
if (string.IsNullOrEmpty(this.ProcessName))
{
this.Log.LogError("ProcessName is required");
return;
}
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Getting Processes matching: {0}", this.ProcessName));
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Process");
Regex userFilter = new Regex(this.User, RegexOptions.Compiled);
Regex processFilter = new Regex(this.ProcessName, RegexOptions.Compiled);
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(this.Scope, query, null))
{
this.Processes = new ITaskItem[searcher.Get().Count];
int i = 0;
foreach (ManagementObject ret in searcher.Get())
{
if (processFilter.IsMatch(ret["Name"].ToString()))
{
ITaskItem processItem = new TaskItem(ret["Name"].ToString());
processItem.SetMetadata("Caption", ret["Caption"].ToString());
processItem.SetMetadata("Description", ret["Description"].ToString());
processItem.SetMetadata("Handle", ret["Handle"].ToString());
processItem.SetMetadata("HandleCount", ret["HandleCount"].ToString());
processItem.SetMetadata("KernelModeTime", ret["KernelModeTime"].ToString());
processItem.SetMetadata("PageFaults", ret["PageFaults"].ToString());
processItem.SetMetadata("PageFileUsage", ret["PageFileUsage"].ToString());
processItem.SetMetadata("ParentProcessId", ret["ParentProcessId"].ToString());
processItem.SetMetadata("PeakPageFileUsage", ret["PeakPageFileUsage"].ToString());
processItem.SetMetadata("PeakVirtualSize", ret["PeakVirtualSize"].ToString());
processItem.SetMetadata("PeakWorkingSetSize", ret["PeakWorkingSetSize"].ToString());
processItem.SetMetadata("Priority", ret["Priority"].ToString());
processItem.SetMetadata("PrivatePageCount", ret["PrivatePageCount"].ToString());
processItem.SetMetadata("ProcessId", ret["ProcessId"].ToString());
processItem.SetMetadata("QuotaNonPagedPoolUsage", ret["QuotaNonPagedPoolUsage"].ToString());
processItem.SetMetadata("QuotaPagedPoolUsage", ret["QuotaPagedPoolUsage"].ToString());
processItem.SetMetadata("QuotaPeakNonPagedPoolUsage", ret["QuotaPeakNonPagedPoolUsage"].ToString());
processItem.SetMetadata("QuotaPeakPagedPoolUsage", ret["QuotaPeakPagedPoolUsage"].ToString());
processItem.SetMetadata("ReadOperationCount", ret["ReadOperationCount"].ToString());
processItem.SetMetadata("ReadTransferCount", ret["ReadTransferCount"].ToString());
processItem.SetMetadata("SessionId", ret["SessionId"].ToString());
processItem.SetMetadata("ThreadCount", ret["ThreadCount"].ToString());
processItem.SetMetadata("UserModeTime", ret["UserModeTime"].ToString());
processItem.SetMetadata("VirtualSize", ret["VirtualSize"].ToString());
processItem.SetMetadata("WindowsVersion", ret["WindowsVersion"].ToString());
processItem.SetMetadata("WorkingSetSize", ret["WorkingSetSize"].ToString());
processItem.SetMetadata("WriteOperationCount", ret["WriteOperationCount"].ToString());
processItem.SetMetadata("WriteTransferCount", ret["WriteTransferCount"].ToString());
if (this.IncludeUserInfo)
{
string[] o = new string[2];
ret.InvokeMethod("GetOwner", o);
if (o[0] == null)
{
continue;
}
if (!userFilter.IsMatch(o[0]))
{
continue;
}
processItem.SetMetadata("User", o[0]);
if (o[1] != null)
{
processItem.SetMetadata("Domain", o[1]);
}
string[] sid = new string[1];
ret.InvokeMethod("GetOwnerSid", sid);
if (sid[0] != null)
{
processItem.SetMetadata("OwnerSID", sid[0]);
}
}
this.Processes[i] = processItem;
i++;
}
}
}
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type WorkbookChartAxisRequest.
/// </summary>
public partial class WorkbookChartAxisRequest : BaseRequest, IWorkbookChartAxisRequest
{
/// <summary>
/// Constructs a new WorkbookChartAxisRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public WorkbookChartAxisRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified WorkbookChartAxis using POST.
/// </summary>
/// <param name="workbookChartAxisToCreate">The WorkbookChartAxis to create.</param>
/// <returns>The created WorkbookChartAxis.</returns>
public System.Threading.Tasks.Task<WorkbookChartAxis> CreateAsync(WorkbookChartAxis workbookChartAxisToCreate)
{
return this.CreateAsync(workbookChartAxisToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified WorkbookChartAxis using POST.
/// </summary>
/// <param name="workbookChartAxisToCreate">The WorkbookChartAxis to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created WorkbookChartAxis.</returns>
public async System.Threading.Tasks.Task<WorkbookChartAxis> CreateAsync(WorkbookChartAxis workbookChartAxisToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<WorkbookChartAxis>(workbookChartAxisToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified WorkbookChartAxis.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified WorkbookChartAxis.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<WorkbookChartAxis>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified WorkbookChartAxis.
/// </summary>
/// <returns>The WorkbookChartAxis.</returns>
public System.Threading.Tasks.Task<WorkbookChartAxis> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified WorkbookChartAxis.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The WorkbookChartAxis.</returns>
public async System.Threading.Tasks.Task<WorkbookChartAxis> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<WorkbookChartAxis>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified WorkbookChartAxis using PATCH.
/// </summary>
/// <param name="workbookChartAxisToUpdate">The WorkbookChartAxis to update.</param>
/// <returns>The updated WorkbookChartAxis.</returns>
public System.Threading.Tasks.Task<WorkbookChartAxis> UpdateAsync(WorkbookChartAxis workbookChartAxisToUpdate)
{
return this.UpdateAsync(workbookChartAxisToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified WorkbookChartAxis using PATCH.
/// </summary>
/// <param name="workbookChartAxisToUpdate">The WorkbookChartAxis to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated WorkbookChartAxis.</returns>
public async System.Threading.Tasks.Task<WorkbookChartAxis> UpdateAsync(WorkbookChartAxis workbookChartAxisToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<WorkbookChartAxis>(workbookChartAxisToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartAxisRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartAxisRequest Expand(Expression<Func<WorkbookChartAxis, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartAxisRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartAxisRequest Select(Expression<Func<WorkbookChartAxis, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="workbookChartAxisToInitialize">The <see cref="WorkbookChartAxis"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(WorkbookChartAxis workbookChartAxisToInitialize)
{
}
}
}
| |
// Copyright (c) 2009 DotNetAnywhere
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Drawing.Text;
namespace System.Drawing {
public sealed class Graphics : MarshalByRefObject, IDisposable {
public static Graphics FromHdc(IntPtr hdc) {
if (hdc != IntPtr.Zero) {
throw new NotImplementedException();
}
int xSize, ySize;
PixelFormat pixelFormat;
IntPtr native = LibIGraph.GetScreen(out xSize, out ySize, out pixelFormat);
if (native == IntPtr.Zero) {
throw new Exception("CreateScreen() failed");
}
return new Graphics(xSize, ySize, pixelFormat, native);
}
public static Graphics FromImage(Image image) {
if (image == null) {
throw new ArgumentNullException("image");
}
IntPtr native = LibIGraph.GetGraphicsFromImage(image.native);
if (native == IntPtr.Zero) {
throw new ArgumentException("Failed to get Graphics from given Image", "image");
}
return new Graphics(image.Width, image.Height, image.PixelFormat, native);
}
private IntPtr native = IntPtr.Zero;
private int xSizePixels, ySizePixels;
private PixelFormat pixelFormat;
private TextRenderingHint textRenderingHint;
private Region clip;
private Graphics(int xSize, int ySize, PixelFormat pixelFormat, IntPtr native) {
this.xSizePixels = xSize;
this.ySizePixels = ySize;
this.pixelFormat = pixelFormat;
this.native = native;
this.textRenderingHint = TextRenderingHint.SystemDefault;
this.Clip = new Region();
}
~Graphics() {
this.Dispose();
}
public void Dispose() {
if (this.native != IntPtr.Zero) {
LibIGraph.DisposeGraphics(this.native);
this.native = IntPtr.Zero;
GC.SuppressFinalize(this);
}
}
public Region Clip {
get {
return this.clip;
}
set {
if (value == null) {
throw new ArgumentNullException();
}
this.clip = value;
LibIGraph.Graphics_SetClip(this.native, value.native);
}
}
public void ResetClip() {
this.Clip = new Region();
}
public void Clear(Color color) {
LibIGraph.Clear(this.native, color.ToArgb());
}
public TextRenderingHint TextRenderingHint {
get {
return this.textRenderingHint;
}
set {
LibIGraph.TextRenderingHint_Set(this.native, value);
this.textRenderingHint = value;
}
}
public void DrawLine(Pen pen, int x1, int y1, int x2, int y2) {
LibIGraph.DrawLine_Ints(this.native, pen.native, x1, y1, x2, y2);
}
public void DrawLine(Pen pen, Point pt1, Point pt2) {
LibIGraph.DrawLine_Ints(this.native, pen.native, pt1.X, pt1.Y, pt2.X, pt2.Y);
}
public void DrawLines(Pen pen, Point[] points) {
int num = points.Length - 1;
for (int i = 0; i < num; i++) {
this.DrawLine(pen, points[i], points[i + 1]);
}
}
public void DrawPolygon(Pen pen, Point[] points) {
this.DrawLines(pen, points);
this.DrawLine(pen, points[points.Length - 1], points[0]);
}
public void DrawRectangle(Pen pen, int x, int y, int width, int height) {
DrawLines(pen, new Point[] {
new Point(x, y),
new Point(x + width, y),
new Point(x + width, y + height),
new Point(x, y + height),
new Point(x, y)
});
}
public void DrawRectangle(Pen pen, Rectangle rect) {
this.DrawRectangle(pen, rect.X, rect.Y, rect.Width, rect.Height);
}
public void DrawRectangle(Pen pen, float x, float y, float width, float height) {
this.DrawRectangle(pen, (int)x, (int)y, (int)width, (int)height);
}
public void FillRectangle(Brush brush, int x, int y, int width, int height) {
LibIGraph.FillRectangle_Ints(this.native, brush.native, x, y, width, height);
}
public void FillRectangle(Brush brush, Rectangle rect) {
this.FillRectangle(brush, rect.X, rect.Y, rect.Width, rect.Height);
}
public void FillRectangle(Brush brush, float x, float y, float width, float height) {
this.FillRectangle(brush, (int)x, (int)y, (int)width, (int)height);
}
public void FillRectangle(Brush brush, RectangleF rect) {
this.FillRectangle(brush, rect.X, rect.Y, rect.Width, rect.Height);
}
public void DrawEllipse(Pen pen, int x, int y, int width, int height) {
LibIGraph.DrawEllipse_Ints(this.native, pen.native, x, y, width, height);
}
public void DrawEllipse(Pen pen, Rectangle rect) {
this.DrawRectangle(pen, rect.X, rect.Y, rect.Width, rect.Height);
}
public void FillEllipse(Brush brush, int x, int y, int width, int height) {
LibIGraph.FillEllipse_Ints(this.native, brush.native, x, y, width, height);
}
public void FillEllipse(Brush brush, Rectangle rect) {
this.FillEllipse(brush, rect.X, rect.Y, rect.Width, rect.Height);
}
public void DrawString(string s, Font font, Brush brush, float x, float y, StringFormat format) {
LibIGraph.DrawString(this.native, s, font.native, brush.native, (int)x, (int)y, int.MaxValue, int.MaxValue, (format == null) ? IntPtr.Zero : format.native);
}
public void DrawString(string s, Font font, Brush brush, float x, float y) {
this.DrawString(s, font, brush, x, y, StringFormat.GenericDefault);
}
public void DrawString(string s, Font font, Brush brush, PointF point) {
this.DrawString(s, font, brush, point.X, point.Y, StringFormat.GenericDefault);
}
public void DrawString(string s, Font font, Brush brush, RectangleF rect) {
LibIGraph.DrawString(this.native, s, font.native, brush.native,
(int)rect.Left, (int)rect.Top, (int)rect.Right, (int)rect.Bottom,
StringFormat.GenericDefault.native);
}
public void DrawString(string s, Font font, Brush brush, RectangleF rect, StringFormat format) {
LibIGraph.DrawString(this.native, s, font.native, brush.native,
(int)rect.Left, (int)rect.Top, (int)rect.Right, (int)rect.Bottom, format.native);
}
public SizeF MeasureString(string s, Font font) {
return this.MeasureString(s, font, int.MaxValue, StringFormat.GenericDefault);
}
public SizeF MeasureString(string s, Font font, int width) {
return this.MeasureString(s, font, width, StringFormat.GenericDefault);
}
public SizeF MeasureString(string s, Font font, int width, StringFormat format) {
int szWidth, szHeight;
LibIGraph.MeasureString(this.native, s, font.native, width, format.native, out szWidth, out szHeight);
return new SizeF(szWidth, szHeight);
}
public void DrawImage(Image image, int x, int y) {
LibIGraph.DrawImageUnscaled(this.native, image.native, x, y);
}
public void DrawImageUnscaled(Image image, int x, int y) {
LibIGraph.DrawImageUnscaled(this.native, image.native, x, y);
}
public void CopyFromScreen(int srcX, int srcY, int destX, int destY, Size size) {
LibIGraph.Graphics_CopyFromScreen(this.native, srcX, srcY, destX, destY, size.Width, size.Height);
}
public void CopyFromScreen(Point upperLeftSource, Point upperLeftDestination, Size size) {
this.CopyFromScreen(upperLeftSource.X, upperLeftSource.Y, upperLeftDestination.X, upperLeftDestination.Y, size);
}
}
}
| |
// 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.IO;
using System.Net.Http;
using System.Net.Test.Common;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Tests
{
public class FileWebRequestTest
{
private readonly ITestOutputHelper _output;
public FileWebRequestTest(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public void Ctor_VerifyDefaults_Success()
{
Uri uri = new Uri("file://somefilepath");
FileWebRequest request = (FileWebRequest)WebRequest.Create(uri);
Assert.Null(request.ContentType);
Assert.Null(request.Credentials);
Assert.NotNull(request.Headers);
Assert.Equal(0, request.Headers.Count);
Assert.Equal("GET", request.Method);
Assert.Null(request.Proxy);
Assert.Equal(uri, request.RequestUri);
}
[Fact]
public void FileWebRequest_Properties_Roundtrips()
{
WebRequest request = WebRequest.Create("file://anything");
request.ContentLength = 42;
Assert.Equal(42, request.ContentLength);
request.ContentType = "anything";
Assert.Equal("anything", request.ContentType);
request.Timeout = 42000;
Assert.Equal(42000, request.Timeout);
}
[Fact]
public void InvalidArguments_Throws()
{
WebRequest request = WebRequest.Create("file://anything");
Assert.Throws<ArgumentException>("value", () => request.ContentLength = -1);
Assert.Throws<ArgumentException>("value", () => request.Method = null);
Assert.Throws<ArgumentException>("value", () => request.Method = "");
Assert.Throws<ArgumentOutOfRangeException>("value", () => request.Timeout = -2);
}
[Fact]
public void GetRequestStream_MethodGet_ThrowsProtocolViolation()
{
WebRequest request = WebRequest.Create("file://anything");
Assert.Throws<ProtocolViolationException>(() => request.BeginGetRequestStream(null, null));
}
[Fact]
public void GetRequestResponseAfterAbort_Throws()
{
WebRequest request = WebRequest.Create("file://anything");
request.Abort();
Assert.Throws<WebException>(() => request.BeginGetRequestStream(null, null));
Assert.Throws<WebException>(() => request.BeginGetResponse(null, null));
}
[Fact]
public void NotImplementedMembers_Throws()
{
WebRequest request = WebRequest.Create("file://anything");
Assert.Throws<NotImplementedException>(() => request.UseDefaultCredentials);
Assert.Throws<NotImplementedException>(() => request.UseDefaultCredentials = true);
}
}
public abstract class FileWebRequestTestBase
{
public abstract Task<WebResponse> GetResponseAsync(WebRequest request);
public abstract Task<Stream> GetRequestStreamAsync(WebRequest request);
[Fact]
public async Task ReadFile_ContainsExpectedContent()
{
string path = Path.GetTempFileName();
try
{
var data = new byte[1024 * 10];
var random = new Random(42);
random.NextBytes(data);
File.WriteAllBytes(path, data);
WebRequest request = WebRequest.Create("file://" + path);
using (WebResponse response = await GetResponseAsync(request))
{
Assert.Equal(data.Length, response.ContentLength);
Assert.Equal(data.Length.ToString(), response.Headers[HttpRequestHeader.ContentLength]);
Assert.Equal("application/octet-stream", response.ContentType);
Assert.Equal("application/octet-stream", response.Headers[HttpRequestHeader.ContentType]);
Assert.True(response.SupportsHeaders);
Assert.NotNull(response.Headers);
Assert.Equal(new Uri("file://" + path), response.ResponseUri);
using (Stream s = response.GetResponseStream())
{
var target = new MemoryStream();
await s.CopyToAsync(target);
Assert.Equal(data, target.ToArray());
}
}
}
finally
{
File.Delete(path);
}
}
[Fact]
public async Task WriteFile_ContainsExpectedContent()
{
string path = Path.GetTempFileName();
try
{
var data = new byte[1024 * 10];
var random = new Random(42);
random.NextBytes(data);
var request = WebRequest.Create("file://" + path);
request.Method = WebRequestMethods.File.UploadFile;
using (Stream s = await GetRequestStreamAsync(request))
{
await s.WriteAsync(data, 0, data.Length);
}
Assert.Equal(data, File.ReadAllBytes(path));
}
finally
{
File.Delete(path);
}
}
[Fact]
public async Task WriteThenReadFile_WriteAccessResultsInNullResponseStream()
{
string path = Path.GetTempFileName();
try
{
var data = new byte[1024 * 10];
var random = new Random(42);
random.NextBytes(data);
var request = WebRequest.Create("file://" + path);
request.Method = WebRequestMethods.File.UploadFile;
using (Stream s = await GetRequestStreamAsync(request))
{
await s.WriteAsync(data, 0, data.Length);
}
using (WebResponse response = await GetResponseAsync(request))
using (Stream s = response.GetResponseStream()) // will hand back a null stream
{
Assert.Equal(0, s.Length);
}
}
finally
{
File.Delete(path);
}
}
protected virtual bool EnableConcurrentReadWriteTests => true;
[Fact]
public async Task RequestAfterResponse_throws()
{
string path = Path.GetTempFileName();
try
{
var data = new byte[1024];
WebRequest request = WebRequest.Create("file://" + path);
request.Method = WebRequestMethods.File.UploadFile;
using (WebResponse response = await GetResponseAsync(request))
{
await Assert.ThrowsAsync<InvalidOperationException>(() => GetRequestStreamAsync(request));
}
}
finally
{
File.Delete(path);
}
}
[Theory]
[InlineData(null)]
[InlineData(false)]
[InlineData(true)]
public async Task BeginGetResponse_OnNonexistentFile_ShouldNotCrashApplication(bool? abortWithDelay)
{
FileWebRequest request = (FileWebRequest)WebRequest.Create("file://" + Path.GetRandomFileName());
Task<WebResponse> responseTask = GetResponseAsync(request);
if (abortWithDelay.HasValue)
{
if (abortWithDelay.Value)
{
await Task.Delay(1);
}
request.Abort();
}
await Assert.ThrowsAsync<WebException>(() => responseTask);
}
}
public abstract class AsyncFileWebRequestTestBase : FileWebRequestTestBase
{
[Fact]
public async Task ConcurrentReadWrite_ResponseBlocksThenGetsNullStream()
{
string path = Path.GetTempFileName();
try
{
var data = new byte[1024 * 10];
var random = new Random(42);
random.NextBytes(data);
var request = WebRequest.Create("file://" + path);
request.Method = WebRequestMethods.File.UploadFile;
Task<Stream> requestStreamTask = GetRequestStreamAsync(request);
Task<WebResponse> responseTask = GetResponseAsync(request);
using (Stream s = await requestStreamTask)
{
await s.WriteAsync(data, 0, data.Length);
}
using (WebResponse response = await responseTask)
using (Stream s = response.GetResponseStream()) // will hand back a null stream
{
Assert.Equal(0, s.Length);
}
}
finally
{
File.Delete(path);
}
}
}
public sealed class SyncFileWebRequestTestBase : FileWebRequestTestBase
{
public override Task<WebResponse> GetResponseAsync(WebRequest request) => Task.Run(() => request.GetResponse());
public override Task<Stream> GetRequestStreamAsync(WebRequest request) => Task.Run(() => request.GetRequestStream());
}
public sealed class BeginEndFileWebRequestTestBase : AsyncFileWebRequestTestBase
{
public override Task<WebResponse> GetResponseAsync(WebRequest request) =>
Task.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null);
public override Task<Stream> GetRequestStreamAsync(WebRequest request) =>
Task.Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, null);
}
public sealed class TaskFileWebRequestTestBase : AsyncFileWebRequestTestBase
{
public override Task<WebResponse> GetResponseAsync(WebRequest request) => request.GetResponseAsync();
public override Task<Stream> GetRequestStreamAsync(WebRequest request) => request.GetRequestStreamAsync();
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Net;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.ClientObservers;
using Orleans.CodeGeneration;
using Orleans.Configuration;
using Orleans.Messaging;
using Orleans.Providers;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Serialization;
using Orleans.Serialization.Invocation;
namespace Orleans
{
internal class OutsideRuntimeClient : IRuntimeClient, IDisposable, IClusterConnectionStatusListener
{
internal static bool TestOnlyThrowExceptionDuringInit { get; set; }
private readonly ILogger logger;
private readonly ClientMessagingOptions clientMessagingOptions;
private readonly ConcurrentDictionary<CorrelationId, CallbackData> callbacks;
private InvokableObjectManager localObjects;
private bool disposing;
private bool disposed;
internal readonly ClientStatisticsManager ClientStatistics;
private readonly MessagingTrace messagingTrace;
private readonly ClientGrainId clientId;
private ThreadTrackingStatistic incomingMessagesThreadTimeTracking;
public IInternalGrainFactory InternalGrainFactory { get; private set; }
private MessageFactory messageFactory;
private IPAddress localAddress;
private readonly ILoggerFactory loggerFactory;
private readonly IOptions<StatisticsOptions> statisticsOptions;
private readonly ApplicationRequestsStatisticsGroup appRequestStatistics;
private readonly StageAnalysisStatisticsGroup schedulerStageStatistics;
private readonly SharedCallbackData sharedCallbackData;
private SafeTimer callbackTimer;
public ActivationAddress CurrentActivationAddress
{
get;
private set;
}
public ClientGatewayObserver gatewayObserver { get; private set; }
public string CurrentActivationIdentity
{
get { return CurrentActivationAddress.ToString(); }
}
public IGrainReferenceRuntime GrainReferenceRuntime { get; private set; }
internal ClientMessageCenter MessageCenter { get; private set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "MessageCenter is IDisposable but cannot call Dispose yet as it lives past the end of this method call.")]
public OutsideRuntimeClient(
ILoggerFactory loggerFactory,
IOptions<ClientMessagingOptions> clientMessagingOptions,
IOptions<StatisticsOptions> statisticsOptions,
ApplicationRequestsStatisticsGroup appRequestStatistics,
StageAnalysisStatisticsGroup schedulerStageStatistics,
ClientStatisticsManager clientStatisticsManager,
MessagingTrace messagingTrace,
IServiceProvider serviceProvider)
{
this.ServiceProvider = serviceProvider;
this.loggerFactory = loggerFactory;
this.statisticsOptions = statisticsOptions;
this.appRequestStatistics = appRequestStatistics;
this.schedulerStageStatistics = schedulerStageStatistics;
this.ClientStatistics = clientStatisticsManager;
this.messagingTrace = messagingTrace;
this.logger = loggerFactory.CreateLogger<OutsideRuntimeClient>();
this.clientId = ClientGrainId.Create();
callbacks = new ConcurrentDictionary<CorrelationId, CallbackData>();
this.clientMessagingOptions = clientMessagingOptions.Value;
this.sharedCallbackData = new SharedCallbackData(
msg => this.UnregisterCallback(msg.Id),
this.loggerFactory.CreateLogger<CallbackData>(),
this.clientMessagingOptions,
this.appRequestStatistics,
this.clientMessagingOptions.ResponseTimeout);
}
internal void ConsumeServices()
{
try
{
var connectionLostHandlers = this.ServiceProvider.GetServices<ConnectionToClusterLostHandler>();
foreach (var handler in connectionLostHandlers)
{
this.ClusterConnectionLost += handler;
}
var gatewayCountChangedHandlers = this.ServiceProvider.GetServices<GatewayCountChangedHandler>();
foreach (var handler in gatewayCountChangedHandlers)
{
this.GatewayCountChanged += handler;
}
this.InternalGrainFactory = this.ServiceProvider.GetRequiredService<IInternalGrainFactory>();
this.messageFactory = this.ServiceProvider.GetService<MessageFactory>();
var copier = this.ServiceProvider.GetRequiredService<DeepCopier>();
this.localObjects = new InvokableObjectManager(
ServiceProvider.GetRequiredService<ClientGrainContext>(),
this,
copier,
this.messagingTrace,
this.loggerFactory.CreateLogger<ClientGrainContext>());
var timerLogger = this.loggerFactory.CreateLogger<SafeTimer>();
var minTicks = Math.Min(this.clientMessagingOptions.ResponseTimeout.Ticks, TimeSpan.FromSeconds(1).Ticks);
var period = TimeSpan.FromTicks(minTicks);
this.callbackTimer = new SafeTimer(timerLogger, this.OnCallbackExpiryTick, null, period, period);
this.GrainReferenceRuntime = this.ServiceProvider.GetRequiredService<IGrainReferenceRuntime>();
this.localAddress = this.clientMessagingOptions.LocalAddress ?? ConfigUtilities.GetLocalIPAddress(this.clientMessagingOptions.PreferredFamily, this.clientMessagingOptions.NetworkInterfaceName);
// Client init / sign-on message
logger.LogInformation((int)ErrorCode.ClientStarting, "Starting Orleans client with runtime version \"{RuntimeVersion}\", local address {LocalAddress} and client id {ClientId}", RuntimeVersion.Current, localAddress, clientId);
if (TestOnlyThrowExceptionDuringInit)
{
throw new InvalidOperationException("TestOnlyThrowExceptionDuringInit");
}
var statisticsLevel = statisticsOptions.Value.CollectionLevel;
if (statisticsLevel.CollectThreadTimeTrackingStats())
{
incomingMessagesThreadTimeTracking = new ThreadTrackingStatistic("ClientReceiver", this.loggerFactory, this.statisticsOptions, this.schedulerStageStatistics);
}
}
catch (Exception exc)
{
if (logger != null) logger.Error(ErrorCode.Runtime_Error_100319, "OutsideRuntimeClient constructor failed.", exc);
ConstructorReset();
throw;
}
}
public IServiceProvider ServiceProvider { get; private set; }
public async Task Start(CancellationToken cancellationToken)
{
ConsumeServices();
// Deliberately avoid capturing the current synchronization context during startup and execute on the default scheduler.
// This helps to avoid any issues (such as deadlocks) caused by executing with the client's synchronization context/scheduler.
await Task.Run(() => this.StartInternal(cancellationToken)).ConfigureAwait(false);
logger.LogInformation((int)ErrorCode.ProxyClient_StartDone, "Started client with address {ActivationAddress} and id {ClientId}", CurrentActivationAddress.ToString(), clientId);
}
// used for testing to (carefully!) allow two clients in the same process
private async Task StartInternal(CancellationToken cancellationToken)
{
var retryFilterInterface = ServiceProvider.GetService<IClientConnectionRetryFilter>();
Func<Exception, CancellationToken, Task<bool>> retryFilter = RetryFilter;
var gatewayManager = this.ServiceProvider.GetRequiredService<GatewayManager>();
await ExecuteWithRetries(async () => await gatewayManager.StartAsync(cancellationToken), retryFilter);
var generation = -SiloAddress.AllocateNewGeneration(); // Client generations are negative
MessageCenter = ActivatorUtilities.CreateInstance<ClientMessageCenter>(this.ServiceProvider, localAddress, generation, clientId);
MessageCenter.RegisterLocalMessageHandler(this.HandleMessage);
MessageCenter.Start();
CurrentActivationAddress = ActivationAddress.NewActivationAddress(MessageCenter.MyAddress, clientId.GrainId);
this.gatewayObserver = new ClientGatewayObserver(gatewayManager);
this.InternalGrainFactory.CreateObjectReference<IClientGatewayObserver>(this.gatewayObserver);
await ExecuteWithRetries(
async () => await this.ServiceProvider.GetRequiredService<ClientClusterManifestProvider>().StartAsync(),
retryFilter);
ClientStatistics.Start(MessageCenter, clientId.GrainId);
async Task ExecuteWithRetries(Func<Task> task, Func<Exception, CancellationToken, Task<bool>> shouldRetry)
{
while (true)
{
try
{
await task();
return;
}
catch (Exception exception) when (shouldRetry != null)
{
var retry = await shouldRetry(exception, cancellationToken);
if (!retry) throw;
}
}
}
async Task<bool> RetryFilter(Exception exception, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return false;
}
if (retryFilterInterface is { })
{
var result = await retryFilterInterface.ShouldRetryConnectionAttempt(exception, cancellationToken);
return result && !cancellationToken.IsCancellationRequested;
}
else
{
// Do not re-attempt connection by default, prefering to fail promptly.
return false;
}
}
}
private void HandleMessage(Message message)
{
switch (message.Direction)
{
case Message.Directions.Response:
{
ReceiveResponse(message);
break;
}
case Message.Directions.OneWay:
case Message.Directions.Request:
{
this.localObjects.Dispatch(message);
break;
}
default:
logger.Error(ErrorCode.Runtime_Error_100327, $"Message not supported: {message}.");
break;
}
}
public void SendResponse(Message request, Response response)
{
ThrowIfDisposed();
var message = this.messageFactory.CreateResponseMessage(request);
OrleansOutsideRuntimeClientEvent.Log.SendResponse(message);
message.BodyObject = response;
MessageCenter.SendMessage(message);
}
public void SendRequest(GrainReference target, IInvokable request, IResponseCompletionSource context, InvokeMethodOptions options)
{
ThrowIfDisposed();
var message = this.messageFactory.CreateMessage(request, options);
OrleansOutsideRuntimeClientEvent.Log.SendRequest(message);
SendRequestMessage(target, message, context, options);
}
private void SendRequestMessage(GrainReference target, Message message, IResponseCompletionSource context, InvokeMethodOptions options)
{
message.InterfaceType = target.InterfaceType;
message.InterfaceVersion = target.InterfaceVersion;
var targetGrainId = target.GrainId;
var oneWay = (options & InvokeMethodOptions.OneWay) != 0;
message.SendingGrain = CurrentActivationAddress.Grain;
message.SendingActivation = CurrentActivationAddress.Activation;
message.TargetGrain = targetGrainId;
if (SystemTargetGrainId.TryParse(targetGrainId, out var systemTargetGrainId))
{
// If the silo isn't be supplied, it will be filled in by the sender to be the gateway silo
message.TargetSilo = systemTargetGrainId.GetSiloAddress();
message.TargetActivation = ActivationId.GetDeterministic(targetGrainId);
}
if (message.IsExpirableMessage(this.clientMessagingOptions.DropExpiredMessages))
{
// don't set expiration for system target messages.
message.TimeToLive = this.clientMessagingOptions.ResponseTimeout;
}
if (!oneWay)
{
var callbackData = new CallbackData(this.sharedCallbackData, context, message);
callbacks.TryAdd(message.Id, callbackData);
}
else
{
context?.Complete();
}
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Send {0}", message);
MessageCenter.SendMessage(message);
}
public void ReceiveResponse(Message response)
{
OrleansOutsideRuntimeClientEvent.Log.ReceiveResponse(response);
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Received {0}", response);
// ignore duplicate requests
if (response.Result == Message.ResponseTypes.Rejection
&& (response.RejectionType == Message.RejectionTypes.DuplicateRequest
|| response.RejectionType == Message.RejectionTypes.CacheInvalidation))
{
return;
}
else if (response.Result == Message.ResponseTypes.Status)
{
var status = (StatusResponse)response.BodyObject;
callbacks.TryGetValue(response.Id, out var callback);
var request = callback?.Message;
if (!(request is null))
{
callback.OnStatusUpdate(status);
if (status.Diagnostics != null && status.Diagnostics.Count > 0 && logger.IsEnabled(LogLevel.Information))
{
var diagnosticsString = string.Join("\n", status.Diagnostics);
this.logger.LogInformation("Received status update for pending request, Request: {RequestMessage}. Status: {Diagnostics}", request, diagnosticsString);
}
}
else
{
if (status.Diagnostics != null && status.Diagnostics.Count > 0 && logger.IsEnabled(LogLevel.Information))
{
var diagnosticsString = string.Join("\n", status.Diagnostics);
this.logger.LogInformation("Received status update for unknown request. Message: {StatusMessage}. Status: {Diagnostics}", response, diagnosticsString);
}
}
return;
}
CallbackData callbackData;
var found = callbacks.TryRemove(response.Id, out callbackData);
if (found)
{
// We need to import the RequestContext here as well.
// Unfortunately, it is not enough, since CallContext.LogicalGetData will not flow "up" from task completion source into the resolved task.
// RequestContextExtensions.Import(response.RequestContextData);
callbackData.DoCallback(response);
}
else
{
logger.Warn(ErrorCode.Runtime_Error_100011, "No callback for response message: " + response);
}
}
private void UnregisterCallback(CorrelationId id)
{
callbacks.TryRemove(id, out _);
}
public void Reset()
{
Utils.SafeExecute(() =>
{
if (logger != null)
{
logger.Info("OutsideRuntimeClient.Reset(): client Id " + clientId);
}
}, this.logger);
Utils.SafeExecute(() =>
{
incomingMessagesThreadTimeTracking?.OnStopExecution();
}, logger, "Client.incomingMessagesThreadTimeTracking.OnStopExecution");
Utils.SafeExecute(() =>
{
if (MessageCenter != null)
{
MessageCenter.Stop();
}
}, logger, "Client.Stop-Transport");
Utils.SafeExecute(() =>
{
if (ClientStatistics != null)
{
ClientStatistics.Stop();
}
}, logger, "Client.Stop-ClientStatistics");
ConstructorReset();
}
private void ConstructorReset()
{
Utils.SafeExecute(() =>
{
if (logger != null)
{
logger.Info("OutsideRuntimeClient.ConstructorReset(): client Id " + clientId);
}
});
Utils.SafeExecute(() => this.Dispose());
}
/// <inheritdoc />
public TimeSpan GetResponseTimeout() => this.sharedCallbackData.ResponseTimeout;
/// <inheritdoc />
public void SetResponseTimeout(TimeSpan timeout) => this.sharedCallbackData.ResponseTimeout = timeout;
public IAddressable CreateObjectReference(IAddressable obj)
{
if (obj is GrainReference)
throw new ArgumentException("Argument obj is already a grain reference.", nameof(obj));
if (obj is Grain)
throw new ArgumentException("Argument must not be a grain class.", nameof(obj));
var observerId = obj is ClientObserver clientObserver
? clientObserver.GetObserverGrainId(this.clientId)
: ObserverGrainId.Create(this.clientId);
var reference = this.InternalGrainFactory.GetGrain(observerId.GrainId);
if (!localObjects.TryRegister(obj, observerId))
{
throw new ArgumentException($"Failed to add new observer {reference} to localObjects collection.", "reference");
}
return reference;
}
public void DeleteObjectReference(IAddressable obj)
{
if (!(obj is GrainReference reference))
{
throw new ArgumentException("Argument reference is not a grain reference.");
}
if (!ObserverGrainId.TryParse(reference.GrainId, out var observerId))
{
throw new ArgumentException($"Reference {reference.GrainId} is not an observer reference");
}
if (!localObjects.TryDeregister(observerId))
{
throw new ArgumentException("Reference is not associated with a local object.", "reference");
}
}
private string PrintAppDomainDetails()
{
return string.Format("<AppDomain.Id={0}, AppDomain.FriendlyName={1}>", AppDomain.CurrentDomain.Id, AppDomain.CurrentDomain.FriendlyName);
}
public void Dispose()
{
if (this.disposing) return;
this.disposing = true;
Utils.SafeExecute(() => this.callbackTimer?.Dispose());
Utils.SafeExecute(() => MessageCenter?.Dispose());
this.ClusterConnectionLost = null;
this.GatewayCountChanged = null;
GC.SuppressFinalize(this);
disposed = true;
}
public void BreakOutstandingMessagesToDeadSilo(SiloAddress deadSilo)
{
foreach (var callback in callbacks)
{
if (deadSilo.Equals(callback.Value.Message.TargetSilo))
{
callback.Value.OnTargetSiloFail();
}
}
}
/// <inheritdoc />
public event ConnectionToClusterLostHandler ClusterConnectionLost;
/// <inheritdoc />
public event GatewayCountChangedHandler GatewayCountChanged;
/// <inheritdoc />
public void NotifyClusterConnectionLost()
{
try
{
this.ClusterConnectionLost?.Invoke(this, EventArgs.Empty);
}
catch (Exception ex)
{
this.logger.Error(ErrorCode.ClientError, "Error when sending cluster disconnection notification", ex);
}
}
/// <inheritdoc />
public void NotifyGatewayCountChanged(int currentNumberOfGateways, int previousNumberOfGateways)
{
try
{
this.GatewayCountChanged?.Invoke(this, new GatewayCountChangedEventArgs(currentNumberOfGateways, previousNumberOfGateways));
}
catch (Exception ex)
{
this.logger.Error(ErrorCode.ClientError, "Error when sending gateway count changed notification", ex);
}
}
private void OnCallbackExpiryTick(object state)
{
var currentStopwatchTicks = Stopwatch.GetTimestamp();
foreach (var pair in callbacks)
{
var callback = pair.Value;
if (callback.IsCompleted) continue;
if (callback.IsExpired(currentStopwatchTicks)) callback.OnTimeout(this.clientMessagingOptions.ResponseTimeout);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ThrowIfDisposed()
{
if (disposed)
{
ThrowObjectDisposedException();
}
[MethodImpl(MethodImplOptions.NoInlining)]
void ThrowObjectDisposedException() => throw new ObjectDisposedException(nameof(OutsideRuntimeClient));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using AutoRest.Core;
using AutoRest.Core.Model;
using AutoRest.Core.Utilities;
using AutoRest.Core.Utilities.Collections;
using AutoRest.Swagger.Model;
using static AutoRest.Core.Utilities.DependencyInjection;
namespace AutoRest.Swagger
{
/// <summary>
/// The builder for building a generic swagger object into parameters,
/// service types or Json serialization types.
/// </summary>
public class ObjectBuilder
{
protected SwaggerObject SwaggerObject { get; set; }
protected SwaggerModeler Modeler { get; set; }
public ObjectBuilder(SwaggerObject swaggerObject, SwaggerModeler modeler)
{
SwaggerObject = swaggerObject;
Modeler = modeler;
}
public virtual IModelType ParentBuildServiceType(string serviceTypeName)
{
// Should not try to get parent from generic swagger object builder
throw new InvalidOperationException();
}
/// <summary>
/// The visitor method for building service types. This is called when an instance of this class is
/// visiting a _swaggerModeler to build a service type.
/// </summary>
/// <param name="serviceTypeName">name for the service type</param>
/// <returns>built service type</returns>
public virtual IModelType BuildServiceType(string serviceTypeName)
{
PrimaryType type = SwaggerObject.ToType();
Debug.Assert(type != null);
if (type.KnownPrimaryType == KnownPrimaryType.Object && SwaggerObject.KnownFormat == KnownFormat.file )
{
type = New<PrimaryType>(KnownPrimaryType.Stream);
}
type.Format = SwaggerObject.Format;
if (SwaggerObject.Enum != null && type.KnownPrimaryType == KnownPrimaryType.String && !(IsSwaggerObjectConstant(SwaggerObject)))
{
var enumType = New<EnumType>();
SwaggerObject.Enum.ForEach(v => enumType.Values.Add(new EnumValue { Name = v, SerializedName = v }));
if (SwaggerObject.Extensions.ContainsKey(Core.Model.XmsExtensions.Enum.Name))
{
var enumObject = SwaggerObject.Extensions[Core.Model.XmsExtensions.Enum.Name] as Newtonsoft.Json.Linq.JContainer;
if (enumObject != null)
{
enumType.SetName( enumObject["name"].ToString() );
if (enumObject["modelAsString"] != null)
{
enumType.ModelAsString = bool.Parse(enumObject["modelAsString"].ToString());
}
}
enumType.SerializedName = enumType.Name;
if (string.IsNullOrEmpty(enumType.Name))
{
throw new InvalidOperationException(
string.Format(CultureInfo.InvariantCulture,
"{0} extension needs to specify an enum name.",
Core.Model.XmsExtensions.Enum.Name));
}
var existingEnum =
Modeler.CodeModel.EnumTypes.FirstOrDefault(
e => e.Name.RawValue.EqualsIgnoreCase(enumType.Name.RawValue));
if (existingEnum != null)
{
if (!existingEnum.StructurallyEquals(enumType))
{
throw new InvalidOperationException(
string.Format(CultureInfo.InvariantCulture,
"Swagger document contains two or more {0} extensions with the same name '{1}' and different values.",
Core.Model.XmsExtensions.Enum.Name,
enumType.Name));
}
// Use the existing one!
enumType = existingEnum;
}
else
{
Modeler.CodeModel.Add(enumType);
}
}
else
{
enumType.ModelAsString = true;
enumType.SetName( string.Empty);
enumType.SerializedName = string.Empty;
}
return enumType;
}
if (SwaggerObject.Type == DataType.Array)
{
string itemServiceTypeName;
if (SwaggerObject.Items.Reference != null)
{
itemServiceTypeName = SwaggerObject.Items.Reference.StripDefinitionPath();
}
else
{
itemServiceTypeName = serviceTypeName + "Item";
}
var elementType =
SwaggerObject.Items.GetBuilder(Modeler).BuildServiceType(itemServiceTypeName);
return New<SequenceType>(new
{
ElementType = elementType,
Extensions = SwaggerObject.Items.Extensions
});
}
if (SwaggerObject.AdditionalProperties != null)
{
string dictionaryValueServiceTypeName;
if (SwaggerObject.AdditionalProperties.Reference != null)
{
dictionaryValueServiceTypeName = SwaggerObject.AdditionalProperties.Reference.StripDefinitionPath();
}
else
{
dictionaryValueServiceTypeName = serviceTypeName + "Value";
}
return New<DictionaryType>(new
{
ValueType =
SwaggerObject.AdditionalProperties.GetBuilder(Modeler)
.BuildServiceType((dictionaryValueServiceTypeName)),
Extensions = SwaggerObject.AdditionalProperties.Extensions
});
}
return type;
}
public static void PopulateParameter(IVariable parameter, SwaggerObject swaggerObject)
{
if (swaggerObject == null)
{
throw new ArgumentNullException("swaggerObject");
}
if (parameter == null)
{
throw new ArgumentNullException("parameter");
}
parameter.IsRequired = swaggerObject.IsRequired;
parameter.DefaultValue = swaggerObject.Default;
if (IsSwaggerObjectConstant(swaggerObject))
{
parameter.DefaultValue = swaggerObject.Enum[0];
parameter.IsConstant = true;
}
parameter.Documentation = swaggerObject.Description;
parameter.CollectionFormat = swaggerObject.CollectionFormat;
// tag the paramter with all the extensions from the swagger object
parameter.Extensions.AddRange(swaggerObject.Extensions);
SetConstraints(parameter.Constraints, swaggerObject);
}
private static bool IsSwaggerObjectConstant(SwaggerObject swaggerObject)
{
return (swaggerObject.Enum != null && swaggerObject.Enum.Count == 1 && swaggerObject.IsRequired);
}
public static void SetConstraints(Dictionary<Constraint, string> constraints, SwaggerObject swaggerObject)
{
if (constraints == null)
{
throw new ArgumentNullException("constraints");
}
if (swaggerObject == null)
{
throw new ArgumentNullException("swaggerObject");
}
if (!string.IsNullOrEmpty(swaggerObject.Maximum)
&& swaggerObject.IsConstraintSupported(nameof(swaggerObject.Maximum))
&& !swaggerObject.ExclusiveMaximum)
{
constraints[Constraint.InclusiveMaximum] = swaggerObject.Maximum;
}
if (!string.IsNullOrEmpty(swaggerObject.Maximum)
&& swaggerObject.IsConstraintSupported(nameof(swaggerObject.Maximum))
&& swaggerObject.ExclusiveMaximum
&& swaggerObject.IsConstraintSupported(nameof(swaggerObject.ExclusiveMaximum)))
{
constraints[Constraint.ExclusiveMaximum] = swaggerObject.Maximum;
}
if (!string.IsNullOrEmpty(swaggerObject.Minimum)
&& swaggerObject.IsConstraintSupported(nameof(swaggerObject.Minimum))
&& !swaggerObject.ExclusiveMinimum)
{
constraints[Constraint.InclusiveMinimum] = swaggerObject.Minimum;
}
if (!string.IsNullOrEmpty(swaggerObject.Minimum)
&& swaggerObject.IsConstraintSupported(nameof(swaggerObject.Minimum))
&& swaggerObject.ExclusiveMinimum
&& swaggerObject.IsConstraintSupported(nameof(swaggerObject.ExclusiveMinimum)))
{
constraints[Constraint.ExclusiveMinimum] = swaggerObject.Minimum;
}
if (!string.IsNullOrEmpty(swaggerObject.MaxLength)
&& swaggerObject.IsConstraintSupported(nameof(swaggerObject.MaxLength)))
{
constraints[Constraint.MaxLength] = swaggerObject.MaxLength;
}
if (!string.IsNullOrEmpty(swaggerObject.MinLength)
&& swaggerObject.IsConstraintSupported(nameof(swaggerObject.MinLength)))
{
constraints[Constraint.MinLength] = swaggerObject.MinLength;
}
if (!string.IsNullOrEmpty(swaggerObject.Pattern)
&& swaggerObject.IsConstraintSupported(nameof(swaggerObject.Pattern)))
{
constraints[Constraint.Pattern] = swaggerObject.Pattern;
}
if (!string.IsNullOrEmpty(swaggerObject.MaxItems)
&& swaggerObject.IsConstraintSupported(nameof(swaggerObject.MaxItems)))
{
constraints[Constraint.MaxItems] = swaggerObject.MaxItems;
}
if (!string.IsNullOrEmpty(swaggerObject.MinItems)
&& swaggerObject.IsConstraintSupported(nameof(swaggerObject.MinItems)))
{
constraints[Constraint.MinItems] = swaggerObject.MinItems;
}
if (!string.IsNullOrEmpty(swaggerObject.MultipleOf)
&& swaggerObject.IsConstraintSupported(nameof(swaggerObject.MultipleOf)))
{
constraints[Constraint.MultipleOf] = swaggerObject.MultipleOf;
}
if (swaggerObject.UniqueItems
&& swaggerObject.IsConstraintSupported(nameof(swaggerObject.UniqueItems)))
{
constraints[Constraint.UniqueItems] = "true";
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Drawing.Internal;
namespace System.Drawing.Drawing2D
{
public sealed class LinearGradientBrush : Brush
{
private bool _interpolationColorsWasSet;
public LinearGradientBrush(PointF point1, PointF point2, Color color1, Color color2)
{
IntPtr nativeBrush;
int status = SafeNativeMethods.Gdip.GdipCreateLineBrush(new GPPOINTF(point1),
new GPPOINTF(point2),
color1.ToArgb(),
color2.ToArgb(),
(int)WrapMode.Tile,
out nativeBrush);
SafeNativeMethods.Gdip.CheckStatus(status);
SetNativeBrushInternal(nativeBrush);
}
public LinearGradientBrush(Point point1, Point point2, Color color1, Color color2)
{
IntPtr nativeBrush;
int status = SafeNativeMethods.Gdip.GdipCreateLineBrushI(new GPPOINT(point1),
new GPPOINT(point2),
color1.ToArgb(),
color2.ToArgb(),
(int)WrapMode.Tile,
out nativeBrush);
SafeNativeMethods.Gdip.CheckStatus(status);
SetNativeBrushInternal(nativeBrush);
}
public LinearGradientBrush(RectangleF rect, Color color1, Color color2, LinearGradientMode linearGradientMode)
{
if (linearGradientMode < LinearGradientMode.Horizontal || linearGradientMode > LinearGradientMode.BackwardDiagonal)
{
throw new InvalidEnumArgumentException(nameof(linearGradientMode), unchecked((int)linearGradientMode), typeof(LinearGradientMode));
}
if (rect.Width == 0.0 || rect.Height == 0.0)
{
throw new ArgumentException(SR.Format(SR.GdiplusInvalidRectangle, rect.ToString()));
}
var gprectf = new GPRECTF(rect);
IntPtr nativeBrush;
int status = SafeNativeMethods.Gdip.GdipCreateLineBrushFromRect(ref gprectf,
color1.ToArgb(),
color2.ToArgb(),
unchecked((int)linearGradientMode),
(int)WrapMode.Tile,
out nativeBrush);
SafeNativeMethods.Gdip.CheckStatus(status);
SetNativeBrushInternal(nativeBrush);
}
public LinearGradientBrush(Rectangle rect, Color color1, Color color2, LinearGradientMode linearGradientMode)
{
if (linearGradientMode < LinearGradientMode.Horizontal || linearGradientMode > LinearGradientMode.BackwardDiagonal)
{
throw new InvalidEnumArgumentException(nameof(linearGradientMode), unchecked((int)linearGradientMode), typeof(LinearGradientMode));
}
if (rect.Width == 0 || rect.Height == 0)
{
throw new ArgumentException(SR.Format(SR.GdiplusInvalidRectangle, rect.ToString()));
}
var gpRect = new GPRECT(rect);
IntPtr nativeBrush;
int status = SafeNativeMethods.Gdip.GdipCreateLineBrushFromRectI(ref gpRect,
color1.ToArgb(),
color2.ToArgb(),
unchecked((int)linearGradientMode),
(int)WrapMode.Tile,
out nativeBrush);
SafeNativeMethods.Gdip.CheckStatus(status);
SetNativeBrushInternal(nativeBrush);
}
public LinearGradientBrush(RectangleF rect, Color color1, Color color2, float angle) : this(rect, color1, color2, angle, false)
{
}
public LinearGradientBrush(RectangleF rect, Color color1, Color color2, float angle, bool isAngleScaleable)
{
if (rect.Width == 0.0 || rect.Height == 0.0)
{
throw new ArgumentException(SR.Format(SR.GdiplusInvalidRectangle, rect.ToString()));
}
var gprectf = new GPRECTF(rect);
IntPtr nativeBrush;
int status = SafeNativeMethods.Gdip.GdipCreateLineBrushFromRectWithAngle(ref gprectf,
color1.ToArgb(),
color2.ToArgb(),
angle,
isAngleScaleable,
(int)WrapMode.Tile,
out nativeBrush);
SafeNativeMethods.Gdip.CheckStatus(status);
SetNativeBrushInternal(nativeBrush);
}
public LinearGradientBrush(Rectangle rect, Color color1, Color color2, float angle) : this(rect, color1, color2, angle, false)
{
}
public LinearGradientBrush(Rectangle rect, Color color1, Color color2, float angle, bool isAngleScaleable)
{
if (rect.Width == 0 || rect.Height == 0)
{
throw new ArgumentException(SR.Format(SR.GdiplusInvalidRectangle, rect.ToString()));
}
var gprect = new GPRECT(rect);
IntPtr nativeBrush;
int status = SafeNativeMethods.Gdip.GdipCreateLineBrushFromRectWithAngleI(ref gprect,
color1.ToArgb(),
color2.ToArgb(),
angle,
isAngleScaleable,
(int)WrapMode.Tile,
out nativeBrush);
SafeNativeMethods.Gdip.CheckStatus(status);
SetNativeBrushInternal(nativeBrush);
}
internal LinearGradientBrush(IntPtr nativeBrush)
{
Debug.Assert(nativeBrush != IntPtr.Zero, "Initializing native brush with null.");
SetNativeBrushInternal(nativeBrush);
}
public override object Clone()
{
IntPtr clonedBrush;
int status = SafeNativeMethods.Gdip.GdipCloneBrush(new HandleRef(this, NativeBrush), out clonedBrush);
SafeNativeMethods.Gdip.CheckStatus(status);
return new LinearGradientBrush(clonedBrush);
}
public Color[] LinearColors
{
get
{
int[] colors = new int[] { 0, 0 };
int status = SafeNativeMethods.Gdip.GdipGetLineColors(new HandleRef(this, NativeBrush), colors);
SafeNativeMethods.Gdip.CheckStatus(status);
return new Color[]
{
Color.FromArgb(colors[0]),
Color.FromArgb(colors[1])
};
}
set
{
int status = SafeNativeMethods.Gdip.GdipSetLineColors(new HandleRef(this, NativeBrush),
value[0].ToArgb(),
value[1].ToArgb());
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
public RectangleF Rectangle
{
get
{
var rect = new GPRECTF();
int status = SafeNativeMethods.Gdip.GdipGetLineRect(new HandleRef(this, NativeBrush), ref rect);
SafeNativeMethods.Gdip.CheckStatus(status);
return rect.ToRectangleF();
}
}
public bool GammaCorrection
{
get
{
int status = SafeNativeMethods.Gdip.GdipGetLineGammaCorrection(new HandleRef(this, NativeBrush),
out bool useGammaCorrection);
SafeNativeMethods.Gdip.CheckStatus(status);
return useGammaCorrection;
}
set
{
int status = SafeNativeMethods.Gdip.GdipSetLineGammaCorrection(new HandleRef(this, NativeBrush), value);
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
public Blend Blend
{
get
{
// Interpolation colors and blends don't work together very well. Getting the Blend when InterpolationColors
// is set set puts the Brush into an unusable state afterwards.
// Bail out here to avoid that.
if (_interpolationColorsWasSet)
{
return null;
}
// Figure out the size of blend factor array.
int status = SafeNativeMethods.Gdip.GdipGetLineBlendCount(new HandleRef(this, NativeBrush), out int retval);
SafeNativeMethods.Gdip.CheckStatus(status);
if (retval <= 0)
{
return null;
}
// Allocate a temporary native memory buffer.
int count = retval;
IntPtr factors = IntPtr.Zero;
IntPtr positions = IntPtr.Zero;
try
{
int size = checked(4 * count);
factors = Marshal.AllocHGlobal(size);
positions = Marshal.AllocHGlobal(size);
// Retrieve horizontal blend factors.
status = SafeNativeMethods.Gdip.GdipGetLineBlend(new HandleRef(this, NativeBrush), factors, positions, count);
SafeNativeMethods.Gdip.CheckStatus(status);
// Return the result in a managed array.
var blend = new Blend(count);
Marshal.Copy(factors, blend.Factors, 0, count);
Marshal.Copy(positions, blend.Positions, 0, count);
return blend;
}
finally
{
if (factors != IntPtr.Zero)
{
Marshal.FreeHGlobal(factors);
}
if (positions != IntPtr.Zero)
{
Marshal.FreeHGlobal(positions);
}
}
}
set
{
// Do explicit parameter validation here; libgdiplus does not correctly validate the arguments
if (value == null || value.Factors == null)
{
// This is the original behavior on Desktop .NET
throw new NullReferenceException();
}
if (value.Positions == null)
{
throw new ArgumentNullException("source");
}
int count = value.Factors.Length;
if (count == 0 || value.Positions.Length == 0)
{
throw new ArgumentException(SR.BlendObjectMustHaveTwoElements);
}
if (count >=2 && count != value.Positions.Length)
{
throw new ArgumentOutOfRangeException();
}
if (count >= 2 && value.Positions[0] != 0.0F)
{
throw new ArgumentException(SR.BlendObjectFirstElementInvalid);
}
if (count >= 2 && value.Positions[count - 1] != 1.0F)
{
throw new ArgumentException(SR.BlendObjectLastElementInvalid);
}
// Allocate temporary native memory buffer and copy input blend factors into it.
IntPtr factors = IntPtr.Zero;
IntPtr positions = IntPtr.Zero;
try
{
int size = checked(4 * count);
factors = Marshal.AllocHGlobal(size);
positions = Marshal.AllocHGlobal(size);
Marshal.Copy(value.Factors, 0, factors, count);
Marshal.Copy(value.Positions, 0, positions, count);
// Set blend factors.
int status = SafeNativeMethods.Gdip.GdipSetLineBlend(new HandleRef(this, NativeBrush), new HandleRef(null, factors), new HandleRef(null, positions), count);
SafeNativeMethods.Gdip.CheckStatus(status);
}
finally
{
if (factors != IntPtr.Zero)
{
Marshal.FreeHGlobal(factors);
}
if (positions != IntPtr.Zero)
{
Marshal.FreeHGlobal(positions);
}
}
}
}
public void SetSigmaBellShape(float focus) => SetSigmaBellShape(focus, (float)1.0);
public void SetSigmaBellShape(float focus, float scale)
{
if (focus < 0 || focus > 1)
{
throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter), nameof(focus));
}
if (scale < 0 || scale > 1)
{
throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter), nameof(scale));
}
int status = SafeNativeMethods.Gdip.GdipSetLineSigmaBlend(new HandleRef(this, NativeBrush), focus, scale);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void SetBlendTriangularShape(float focus) => SetBlendTriangularShape(focus, (float)1.0);
public void SetBlendTriangularShape(float focus, float scale)
{
if (focus < 0 || focus > 1)
{
throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter), nameof(focus));
}
if (scale < 0 || scale > 1)
{
throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter), nameof(scale));
}
int status = SafeNativeMethods.Gdip.GdipSetLineLinearBlend(new HandleRef(this, NativeBrush), focus, scale);
SafeNativeMethods.Gdip.CheckStatus(status);
// Setting a triangular shape overrides the explicitly set interpolation colors. libgdiplus correctly clears
// the interpolation colors (https://github.com/mono/libgdiplus/blob/master/src/lineargradientbrush.c#L959) but
// returns WrongState instead of ArgumentException (https://github.com/mono/libgdiplus/blob/master/src/lineargradientbrush.c#L814)
// when calling GdipGetLinePresetBlend, so it is important we set this to false. This way, we are sure get_InterpolationColors
// will return an ArgumentException.
_interpolationColorsWasSet = false;
}
public ColorBlend InterpolationColors
{
get
{
if (!_interpolationColorsWasSet)
{
throw new ArgumentException(SR.Format(SR.InterpolationColorsCommon,
SR.Format(SR.InterpolationColorsColorBlendNotSet), string.Empty));
}
// Figure out the size of blend factor array.
int status = SafeNativeMethods.Gdip.GdipGetLinePresetBlendCount(new HandleRef(this, NativeBrush), out int retval);
SafeNativeMethods.Gdip.CheckStatus(status);
// Allocate temporary native memory buffer.
int count = retval;
IntPtr colors = IntPtr.Zero;
IntPtr positions = IntPtr.Zero;
try
{
int size = checked(4 * count);
colors = Marshal.AllocHGlobal(size);
positions = Marshal.AllocHGlobal(size);
// Retrieve horizontal blend factors.
status = SafeNativeMethods.Gdip.GdipGetLinePresetBlend(new HandleRef(this, NativeBrush), colors, positions, count);
SafeNativeMethods.Gdip.CheckStatus(status);
// Return the result in a managed array.
var blend = new ColorBlend(count);
int[] argb = new int[count];
Marshal.Copy(colors, argb, 0, count);
Marshal.Copy(positions, blend.Positions, 0, count);
// Copy ARGB values into Color array of ColorBlend.
blend.Colors = new Color[argb.Length];
for (int i = 0; i < argb.Length; i++)
{
blend.Colors[i] = Color.FromArgb(argb[i]);
}
return blend;
}
finally
{
if (colors != IntPtr.Zero)
{
Marshal.FreeHGlobal(colors);
}
if (positions != IntPtr.Zero)
{
Marshal.FreeHGlobal(positions);
}
}
}
set
{
_interpolationColorsWasSet = true;
if (value == null)
{
throw new ArgumentException(SR.Format(SR.InterpolationColorsCommon,
SR.Format(SR.InterpolationColorsInvalidColorBlendObject), string.Empty));
}
else if (value.Colors.Length < 2)
{
throw new ArgumentException(SR.Format(SR.InterpolationColorsCommon,
SR.Format(SR.InterpolationColorsInvalidColorBlendObject),
SR.Format(SR.InterpolationColorsLength)));
}
else if (value.Colors.Length != value.Positions.Length)
{
throw new ArgumentException(SR.Format(SR.InterpolationColorsCommon,
SR.Format(SR.InterpolationColorsInvalidColorBlendObject),
SR.Format(SR.InterpolationColorsLengthsDiffer)));
}
else if (value.Positions[0] != 0.0f)
{
throw new ArgumentException(SR.Format(SR.InterpolationColorsCommon,
SR.Format(SR.InterpolationColorsInvalidColorBlendObject),
SR.Format(SR.InterpolationColorsInvalidStartPosition)));
}
else if (value.Positions[value.Positions.Length - 1] != 1.0f)
{
throw new ArgumentException(SR.Format(SR.InterpolationColorsCommon,
SR.Format(SR.InterpolationColorsInvalidColorBlendObject),
SR.Format(SR.InterpolationColorsInvalidEndPosition)));
}
// Allocate a temporary native memory buffer and copy input blend factors into it.
int count = value.Colors.Length;
IntPtr colors = IntPtr.Zero;
IntPtr positions = IntPtr.Zero;
try
{
int size = checked(4 * count);
colors = Marshal.AllocHGlobal(size);
positions = Marshal.AllocHGlobal(size);
int[] argbs = new int[count];
for (int i = 0; i < count; i++)
{
argbs[i] = value.Colors[i].ToArgb();
}
Marshal.Copy(argbs, 0, colors, count);
Marshal.Copy(value.Positions, 0, positions, count);
// Set blend factors.
int status = SafeNativeMethods.Gdip.GdipSetLinePresetBlend(new HandleRef(this, NativeBrush), new HandleRef(null, colors), new HandleRef(null, positions), count);
SafeNativeMethods.Gdip.CheckStatus(status);
}
finally
{
if (colors != IntPtr.Zero)
{
Marshal.FreeHGlobal(colors);
}
if (positions != IntPtr.Zero)
{
Marshal.FreeHGlobal(positions);
}
}
}
}
public WrapMode WrapMode
{
get
{
int status = SafeNativeMethods.Gdip.GdipGetLineWrapMode(new HandleRef(this, NativeBrush), out int mode);
SafeNativeMethods.Gdip.CheckStatus(status);
return (WrapMode)mode;
}
set
{
if (value < WrapMode.Tile || value > WrapMode.Clamp)
{
throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(WrapMode));
}
int status = SafeNativeMethods.Gdip.GdipSetLineWrapMode(new HandleRef(this, NativeBrush), unchecked((int)value));
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
public Matrix Transform
{
get
{
var matrix = new Matrix();
int status = SafeNativeMethods.Gdip.GdipGetLineTransform(new HandleRef(this, NativeBrush), new HandleRef(matrix, matrix.nativeMatrix));
SafeNativeMethods.Gdip.CheckStatus(status);
return matrix;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
int status = SafeNativeMethods.Gdip.GdipSetLineTransform(new HandleRef(this, NativeBrush), new HandleRef(value, value.nativeMatrix));
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
public void ResetTransform()
{
int status = SafeNativeMethods.Gdip.GdipResetLineTransform(new HandleRef(this, NativeBrush));
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void MultiplyTransform(Matrix matrix) => MultiplyTransform(matrix, MatrixOrder.Prepend);
public void MultiplyTransform(Matrix matrix, MatrixOrder order)
{
if (matrix == null)
{
throw new ArgumentNullException(nameof(matrix));
}
// Multiplying the transform by a disposed matrix is a nop in GDI+, but throws
// with the libgdiplus backend. Simulate a nop for compatability with GDI+.
if (matrix.nativeMatrix == IntPtr.Zero)
{
return;
}
int status = SafeNativeMethods.Gdip.GdipMultiplyLineTransform(new HandleRef(this, NativeBrush),
new HandleRef(matrix, matrix.nativeMatrix),
order);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void TranslateTransform(float dx, float dy) => TranslateTransform(dx, dy, MatrixOrder.Prepend);
public void TranslateTransform(float dx, float dy, MatrixOrder order)
{
int status = SafeNativeMethods.Gdip.GdipTranslateLineTransform(new HandleRef(this, NativeBrush),
dx,
dy,
order);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void ScaleTransform(float sx, float sy) => ScaleTransform(sx, sy, MatrixOrder.Prepend);
public void ScaleTransform(float sx, float sy, MatrixOrder order)
{
int status = SafeNativeMethods.Gdip.GdipScaleLineTransform(new HandleRef(this, NativeBrush),
sx,
sy,
order);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void RotateTransform(float angle) => RotateTransform(angle, MatrixOrder.Prepend);
public void RotateTransform(float angle, MatrixOrder order)
{
int status = SafeNativeMethods.Gdip.GdipRotateLineTransform(new HandleRef(this, NativeBrush),
angle,
order);
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
}
| |
// <copyright>
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
namespace System.Activities.DynamicUpdate
{
using System;
using System.Activities.DynamicUpdate;
using System.Activities.XamlIntegration;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Runtime;
using System.Runtime.Serialization;
[DataContract]
[TypeConverter(typeof(DynamicUpdateMapConverter))]
public class DynamicUpdateMap
{
static DynamicUpdateMap noChanges = new DynamicUpdateMap();
static DynamicUpdateMap dummyMap = new DynamicUpdateMap();
internal EntryCollection entries;
IList<ArgumentInfo> newArguments;
IList<ArgumentInfo> oldArguments;
internal DynamicUpdateMap()
{
}
public static DynamicUpdateMap NoChanges
{
get
{
return noChanges;
}
}
[DataMember(EmitDefaultValue = false, Name = "entries")]
internal EntryCollection SerializedEntries
{
get { return this.entries; }
set { this.entries = value; }
}
[DataMember(EmitDefaultValue = false, Name = "newArguments")]
internal IList<ArgumentInfo> SerializedNewArguments
{
get { return this.newArguments; }
set { this.newArguments = value; }
}
[DataMember(EmitDefaultValue = false, Name = "oldArguments")]
internal IList<ArgumentInfo> SerializedOldArguments
{
get { return this.oldArguments; }
set { this.oldArguments = value; }
}
// this is a dummy map to be used for creating a NativeActivityUpdateContext
// for calling UpdateInstance() on activities without map entries.
// this should not be used anywhere except for creating NativeActivityUpdateContext.
internal static DynamicUpdateMap DummyMap
{
get { return dummyMap; }
}
internal IList<ArgumentInfo> NewArguments
{
get
{
if (this.newArguments == null)
{
this.newArguments = new List<ArgumentInfo>();
}
return this.newArguments;
}
set
{
this.newArguments = value;
}
}
internal IList<ArgumentInfo> OldArguments
{
get
{
if (this.oldArguments == null)
{
this.oldArguments = new List<ArgumentInfo>();
}
return this.oldArguments;
}
set
{
this.oldArguments = value;
}
}
[DataMember(EmitDefaultValue = false)]
internal bool ArgumentsAreUnknown
{
get;
set;
}
[DataMember(EmitDefaultValue = false)]
internal bool IsImplementationAsRoot
{
get;
set;
}
[DataMember(EmitDefaultValue = false)]
internal int NewDefinitionMemberCount
{
get;
set;
}
internal int OldDefinitionMemberCount
{
get
{
return this.Entries.Count;
}
}
[DataMember(EmitDefaultValue = false)]
internal bool IsForImplementation { get; set; }
// IdSpaces always have at least one member. So a count of 0 means that this is
// DynamicUpdateMap.NoChanges, or a serialized equivalent.
internal bool IsNoChanges
{
get
{
return this.NewDefinitionMemberCount == 0;
}
}
// use the internal method AddEntry() instead
private IList<DynamicUpdateMapEntry> Entries
{
get
{
if (this.entries == null)
{
this.entries = new EntryCollection();
}
return this.entries;
}
}
public static IDictionary<object, DynamicUpdateMapItem> CalculateMapItems(Activity workflowDefinitionToBeUpdated)
{
return CalculateMapItems(workflowDefinitionToBeUpdated, null);
}
public static IDictionary<object, DynamicUpdateMapItem> CalculateMapItems(Activity workflowDefinitionToBeUpdated, LocationReferenceEnvironment environment)
{
return InternalCalculateMapItems(workflowDefinitionToBeUpdated, environment, false);
}
public static IDictionary<object, DynamicUpdateMapItem> CalculateImplementationMapItems(Activity activityDefinitionToBeUpdated)
{
return CalculateImplementationMapItems(activityDefinitionToBeUpdated, null);
}
public static IDictionary<object, DynamicUpdateMapItem> CalculateImplementationMapItems(Activity activityDefinitionToBeUpdated, LocationReferenceEnvironment environment)
{
return InternalCalculateMapItems(activityDefinitionToBeUpdated, environment, true);
}
public static DynamicUpdateMap Merge(params DynamicUpdateMap[] maps)
{
return Merge((IEnumerable<DynamicUpdateMap>)maps);
}
public static DynamicUpdateMap Merge(IEnumerable<DynamicUpdateMap> maps)
{
if (maps == null)
{
throw FxTrace.Exception.ArgumentNull("maps");
}
// We could try to optimize this by merging the entire set at once, but it's simpler
// to just do pairwise merging
int index = 0;
DynamicUpdateMap result = null;
foreach (DynamicUpdateMap nextMap in maps)
{
result = Merge(result, nextMap, new MergeErrorContext { MapIndex = index });
index++;
}
return result;
}
static IDictionary<object, DynamicUpdateMapItem> InternalCalculateMapItems(Activity workflowDefinitionToBeUpdated, LocationReferenceEnvironment environment, bool forImplementation)
{
if (workflowDefinitionToBeUpdated == null)
{
throw FxTrace.Exception.ArgumentNull("workflowDefinitionToBeUpdated");
}
DynamicUpdateMapBuilder.Preparer preparer = new DynamicUpdateMapBuilder.Preparer(workflowDefinitionToBeUpdated, environment, forImplementation);
return preparer.Prepare();
}
public DynamicUpdateMapQuery Query(Activity updatedWorkflowDefinition, Activity originalWorkflowDefinition)
{
if (this.IsNoChanges)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.NoChangesMapQueryNotSupported));
}
if (this.IsForImplementation)
{
ValidateDefinitionMatchesImplementationMap(updatedWorkflowDefinition, this.NewDefinitionMemberCount, "updatedWorkflowDefinition");
ValidateDefinitionMatchesImplementationMap(originalWorkflowDefinition, this.OldDefinitionMemberCount, "originalWorkflowDefinition");
}
else
{
ValidateDefinitionMatchesMap(updatedWorkflowDefinition, this.NewDefinitionMemberCount, "updatedWorkflowDefinition");
ValidateDefinitionMatchesMap(originalWorkflowDefinition, this.OldDefinitionMemberCount, "originalWorkflowDefinition");
}
return new DynamicUpdateMapQuery(this, updatedWorkflowDefinition, originalWorkflowDefinition);
}
internal static bool CanUseImplementationMapAsRoot(Activity workflowDefinition)
{
Fx.Assert(workflowDefinition.IsMetadataCached, "This should only be called for cached definition");
// We can only use the implementation map as a root map if the worklflow has no public children
return
workflowDefinition.Children.Count == 0 &&
workflowDefinition.ImportedChildren.Count == 0 &&
workflowDefinition.Delegates.Count == 0 &&
workflowDefinition.ImportedDelegates.Count == 0 &&
workflowDefinition.RuntimeVariables.Count == 0;
}
internal static DynamicUpdateMap Merge(DynamicUpdateMap first, DynamicUpdateMap second, MergeErrorContext errorContext)
{
if (first == null || second == null)
{
return first ?? second;
}
if (first.IsNoChanges || second.IsNoChanges)
{
// DynamicUpdateMap.NoChanges has zero members, so we need to special-case it here.
return first.IsNoChanges ? second : first;
}
ThrowIfMapsIncompatible(first, second, errorContext);
DynamicUpdateMap result = new DynamicUpdateMap
{
IsForImplementation = first.IsForImplementation,
NewDefinitionMemberCount = second.NewDefinitionMemberCount,
ArgumentsAreUnknown = first.ArgumentsAreUnknown && second.ArgumentsAreUnknown,
oldArguments = first.ArgumentsAreUnknown ? second.oldArguments : first.oldArguments,
newArguments = second.ArgumentsAreUnknown ? first.newArguments : second.newArguments
};
foreach (DynamicUpdateMapEntry firstEntry in first.Entries)
{
DynamicUpdateMapEntry parent = null;
if (firstEntry.Parent != null)
{
result.TryGetUpdateEntry(firstEntry.Parent.OldActivityId, out parent);
}
if (firstEntry.IsRemoval)
{
result.AddEntry(firstEntry.Clone(parent));
}
else
{
DynamicUpdateMapEntry secondEntry = second.entries[firstEntry.NewActivityId];
result.AddEntry(DynamicUpdateMapEntry.Merge(firstEntry, secondEntry, parent, errorContext));
}
}
return result;
}
internal void AddEntry(DynamicUpdateMapEntry entry)
{
this.Entries.Add(entry);
}
// Wrap an implementation map in a dummy map. This allows use of an implementation map as the
// root map in the case when the root is an x:Class with no public children.
internal DynamicUpdateMap AsRootMap()
{
Fx.Assert(this.IsForImplementation, "This should only be called on implementation map");
if (!ActivityComparer.ListEquals(this.NewArguments, this.OldArguments))
{
throw FxTrace.Exception.AsError(new InstanceUpdateException(SR.InvalidImplementationAsWorkflowRootForRuntimeStateBecauseArgumentsChanged));
}
DynamicUpdateMap result = new DynamicUpdateMap
{
IsImplementationAsRoot = true,
NewDefinitionMemberCount = 1
};
result.AddEntry(new DynamicUpdateMapEntry(1, 1)
{
ImplementationUpdateMap = this,
});
return result;
}
internal void ThrowIfInvalid(Activity updatedDefinition)
{
Fx.Assert(updatedDefinition.IsMetadataCached, "Caller should have ensured cached definition");
Fx.Assert(updatedDefinition.Parent == null && !this.IsForImplementation, "This should only be called on a workflow definition");
this.ThrowIfInvalid(updatedDefinition.MemberOf);
}
// We verify that the count of all IdSpaces is as expected.
// We could choose to be looser, and only check the IdSpaces that have children active;
// but realistically, if all provided implementation maps don't match, something is probably wrong.
// Conversely, we could check the correctness of every environment map, but it doesn't seem worth
// doing that much work. If we find a mismatch on the environment of an executing activity, we'll
// throw at that point.
void ThrowIfInvalid(IdSpace updatedIdSpace)
{
if (this.IsNoChanges)
{
// 0 means this is NoChanges map, since every workflow has at least one member
return;
}
if (this.NewDefinitionMemberCount != updatedIdSpace.MemberCount)
{
throw FxTrace.Exception.AsError(new InstanceUpdateException(SR.InvalidUpdateMap(
SR.WrongMemberCount(updatedIdSpace.Owner, updatedIdSpace.MemberCount, this.NewDefinitionMemberCount))));
}
foreach (DynamicUpdateMapEntry entry in this.Entries)
{
if (entry.ImplementationUpdateMap != null)
{
Activity implementationOwner = updatedIdSpace[entry.NewActivityId];
if (implementationOwner == null)
{
string expectedId = entry.NewActivityId.ToString(CultureInfo.InvariantCulture);
if (updatedIdSpace.Owner != null)
{
expectedId = updatedIdSpace.Owner.Id + "." + expectedId;
}
throw FxTrace.Exception.AsError(new InstanceUpdateException(SR.InvalidUpdateMap(
SR.ActivityNotFound(expectedId))));
}
if (implementationOwner.ParentOf == null)
{
throw FxTrace.Exception.AsError(new InstanceUpdateException(SR.InvalidUpdateMap(
SR.ActivityHasNoImplementation(implementationOwner))));
}
entry.ImplementationUpdateMap.ThrowIfInvalid(implementationOwner.ParentOf);
}
}
}
internal bool TryGetUpdateEntryByNewId(int newId, out DynamicUpdateMapEntry entry)
{
Fx.Assert(!this.IsNoChanges, "This method is never supposed to be called on the NoChanges map.");
entry = null;
for (int i = 0; i < this.Entries.Count; i++)
{
DynamicUpdateMapEntry currentEntry = this.Entries[i];
if (currentEntry.NewActivityId == newId)
{
entry = currentEntry;
return true;
}
}
return false;
}
internal bool TryGetUpdateEntry(int oldId, out DynamicUpdateMapEntry entry)
{
if (this.entries != null && this.entries.Count > 0)
{
if (this.entries.Contains(oldId))
{
entry = this.entries[oldId];
return true;
}
}
entry = null;
return false;
}
// rootIdSpace is optional. if it's null, result.NewActivity will be null
internal UpdatedActivity GetUpdatedActivity(QualifiedId oldQualifiedId, IdSpace rootIdSpace)
{
UpdatedActivity result = new UpdatedActivity();
int[] oldIdSegments = oldQualifiedId.AsIDArray();
int[] newIdSegments = null;
IdSpace currentIdSpace = rootIdSpace;
DynamicUpdateMap currentMap = this;
Fx.Assert(!this.IsForImplementation, "This method is never supposed to be called on an implementation map.");
for (int i = 0; i < oldIdSegments.Length; i++)
{
if (currentMap == null || currentMap.Entries.Count == 0)
{
break;
}
DynamicUpdateMapEntry entry;
if (!currentMap.TryGetUpdateEntry(oldIdSegments[i], out entry))
{
// UpdateMap should contain entries for all old activities in the IdSpace
int[] subIdSegments = new int[i + 1];
Array.Copy(oldIdSegments, subIdSegments, subIdSegments.Length);
throw FxTrace.Exception.AsError(new InstanceUpdateException(SR.InvalidUpdateMap(
SR.MapEntryNotFound(new QualifiedId(subIdSegments)))));
}
if (entry.IsIdChange)
{
if (newIdSegments == null)
{
newIdSegments = new int[oldIdSegments.Length];
Array.Copy(oldIdSegments, newIdSegments, oldIdSegments.Length);
}
newIdSegments[i] = entry.NewActivityId;
}
Activity currentActivity = null;
if (currentIdSpace != null && !entry.IsRemoval)
{
currentActivity = currentIdSpace[entry.NewActivityId];
if (currentActivity == null)
{
// New Activity pointed to by UpdateMap should exist
string activityId = currentIdSpace.Owner.Id + "." + entry.NewActivityId.ToString(CultureInfo.InvariantCulture);
throw FxTrace.Exception.AsError(new InstanceUpdateException(SR.InvalidUpdateMap(
SR.ActivityNotFound(activityId))));
}
currentIdSpace = currentActivity.ParentOf;
}
if (i == oldIdSegments.Length - 1)
{
result.Map = currentMap;
result.MapEntry = entry;
result.NewActivity = currentActivity;
}
else if (entry.IsRuntimeUpdateBlocked || entry.IsUpdateBlockedByUpdateAuthor)
{
currentMap = null;
}
else
{
currentMap = entry.ImplementationUpdateMap;
}
}
result.IdChanged = newIdSegments != null;
result.NewId = result.IdChanged ? new QualifiedId(newIdSegments) : oldQualifiedId;
return result;
}
static void ThrowIfMapsIncompatible(DynamicUpdateMap first, DynamicUpdateMap second, MergeErrorContext errorContext)
{
Fx.Assert(!first.IsNoChanges && !second.IsNoChanges, "This method is never supposed to be called on the NoChanges map.");
if (first.IsForImplementation != second.IsForImplementation)
{
errorContext.Throw(SR.InvalidMergeMapForImplementation(first.IsForImplementation, second.IsForImplementation));
}
if (first.NewDefinitionMemberCount != second.OldDefinitionMemberCount)
{
errorContext.Throw(SR.InvalidMergeMapMemberCount(first.NewDefinitionMemberCount, second.OldDefinitionMemberCount));
}
if (!first.ArgumentsAreUnknown && !second.ArgumentsAreUnknown && first.IsForImplementation &&
!ActivityComparer.ListEquals(first.newArguments, second.oldArguments))
{
if (first.NewArguments.Count != second.OldArguments.Count)
{
errorContext.Throw(SR.InvalidMergeMapArgumentCount(first.NewArguments.Count, second.OldArguments.Count));
}
else
{
errorContext.Throw(SR.InvalidMergeMapArgumentsChanged);
}
}
}
static void ValidateDefinitionMatchesMap(Activity activity, int memberCount, string parameterName)
{
if (activity == null)
{
throw FxTrace.Exception.ArgumentNull(parameterName);
}
if (activity.MemberOf == null)
{
throw FxTrace.Exception.Argument(parameterName, SR.ActivityIsUncached);
}
if (activity.Parent != null)
{
throw FxTrace.Exception.Argument(parameterName, SR.ActivityIsNotRoot);
}
if (activity.MemberOf.MemberCount != memberCount)
{
throw FxTrace.Exception.Argument(parameterName, SR.InvalidUpdateMap(
SR.WrongMemberCount(activity.MemberOf.Owner, activity.MemberOf.MemberCount, memberCount)));
}
}
static void ValidateDefinitionMatchesImplementationMap(Activity activity, int memberCount, string parameterName)
{
if (activity == null)
{
throw FxTrace.Exception.ArgumentNull(parameterName);
}
if (activity.MemberOf == null)
{
throw FxTrace.Exception.Argument(parameterName, SR.ActivityIsUncached);
}
if (activity.Parent != null)
{
throw FxTrace.Exception.Argument(parameterName, SR.ActivityIsNotRoot);
}
if (activity.ParentOf == null)
{
throw FxTrace.Exception.Argument(parameterName, SR.InvalidUpdateMap(
SR.ActivityHasNoImplementation(activity)));
}
if (activity.ParentOf.MemberCount != memberCount)
{
throw FxTrace.Exception.Argument(parameterName, SR.InvalidUpdateMap(
SR.WrongMemberCount(activity.ParentOf.Owner, activity.ParentOf.MemberCount, memberCount)));
}
if (!CanUseImplementationMapAsRoot(activity))
{
throw FxTrace.Exception.Argument(parameterName, SR.InvalidImplementationAsWorkflowRoot);
}
}
internal struct UpdatedActivity
{
// This can be true even if Map & MapEntry are null, if a parent ID changed.
// It can also be false even when Map & MapEntry are non-null, if the update didn't produce an ID shift.
public bool IdChanged;
public QualifiedId NewId;
// Null if the activity's IDSpace wasn't updated.
public DynamicUpdateMap Map;
public DynamicUpdateMapEntry MapEntry;
// Null when we're dealing with just a serialized instance with no definition.
public Activity NewActivity;
}
internal class MergeErrorContext
{
private Stack<int> currentIdSpace;
public int MapIndex { get; set; }
public void PushIdSpace(int id)
{
if (this.currentIdSpace == null)
{
this.currentIdSpace = new Stack<int>();
}
this.currentIdSpace.Push(id);
}
public void PopIdSpace()
{
this.currentIdSpace.Pop();
}
public void Throw(string detail)
{
QualifiedId id = null;
if (this.currentIdSpace != null && this.currentIdSpace.Count > 0)
{
int[] idSegments = new int[this.currentIdSpace.Count];
for (int i = idSegments.Length - 1; i >= 0; i--)
{
idSegments[i] = this.currentIdSpace.Pop();
}
id = new QualifiedId(idSegments);
}
string errorMessage;
if (id == null)
{
errorMessage = SR.InvalidRootMergeMap(this.MapIndex, detail);
}
else
{
errorMessage = SR.InvalidMergeMap(this.MapIndex, id, detail);
}
throw FxTrace.Exception.Argument("maps", errorMessage);
}
}
[CollectionDataContract]
internal class EntryCollection : KeyedCollection<int, DynamicUpdateMapEntry>
{
public EntryCollection()
{
}
protected override int GetKeyForItem(DynamicUpdateMapEntry item)
{
return item.OldActivityId;
}
}
}
}
| |
// The MIT License
//
// Copyright (c) 2013 Jordan E. Terrell
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Linq;
using iSynaptic.Commons;
using iSynaptic.Commons.Linq;
namespace iSynaptic
{
internal delegate Match<T> Pattern<T>(string input);
internal struct Match<T>
{
public Maybe<T> Data;
public string Remaining;
}
internal static class Text
{
public static Pattern<string> EndOfLine = input => input == string.Empty
? new Match<string> { Data = string.Empty.ToMaybe(), Remaining = string.Empty }
: new Match<string> { Remaining = input };
public static Pattern<T> Ref<T>(Func<Pattern<T>> selector)
{
return input => selector()(input);
}
public static Pattern<T> Return<T>(T value)
{
return input => new Match<T> { Data = value.ToMaybe(), Remaining = input };
}
public static Pattern<char> Char(char expected)
{
return input =>
{
if (input != null && input.Length >= 1 && input[0] == expected)
return new Match<char> { Data = expected.ToMaybe(), Remaining = input.Substring(1) };
return new Match<char> { Remaining = input };
};
}
public static Pattern<T> LeadBy<T, R>(this Pattern<T> self, Pattern<R> pattern)
{
return input =>
{
var match = pattern(input);
if (!match.Data.HasValue) return new Match<T> { Remaining = input };
return self(match.Remaining);
};
}
public static Pattern<T> FollowedBy<T, R>(this Pattern<T> self, Pattern<R> pattern)
{
return input =>
{
var match = self(input);
if (!match.Data.HasValue) return match;
var nextMatch = pattern(match.Remaining);
if (nextMatch.Data.HasValue) return new Match<T> { Data = match.Data, Remaining = nextMatch.Remaining };
return new Match<T> { Remaining = input };
};
}
public static Pattern<IEnumerable<T>> DelimitedBy<T, R>(this Pattern<T> self, Pattern<R> delimiter)
{
return input =>
{
var list = new List<T>();
var match = self(input);
while (match.Data.HasValue)
{
list.Add(match.Data.Value);
var delimiterMatch = delimiter(match.Remaining);
if (delimiterMatch.Data.HasValue)
match = self(delimiterMatch.Remaining);
else
match = new Match<T> { Remaining = delimiterMatch.Remaining };
}
return new Match<IEnumerable<T>> { Data = list.ToMaybe<IEnumerable<T>>(), Remaining = match.Remaining };
};
}
public static Pattern<Maybe<T>> Optional<T>(this Pattern<T> self)
{
return input =>
{
var match = self(input);
return new Match<Maybe<T>> { Data = match.Data.ToMaybe(), Remaining = match.Remaining };
};
}
public static Pattern<IEnumerable<T>> Optional<T>(this Pattern<IEnumerable<T>> self)
{
return input =>
{
var match = self(input);
if (!match.Data.HasValue) return new Match<IEnumerable<T>> { Data = Enumerable.Empty<T>().ToMaybe(), Remaining = match.Remaining };
return match;
};
}
public static Pattern<string> Regex(string pattern)
{
if (string.IsNullOrWhiteSpace(pattern)) throw new ArgumentException("You must provide a pattern.", "pattern");
var regex = new Regex(pattern);
return input =>
{
var match = regex.Match(input);
if (!match.Success)
return new Match<string> { Remaining = input };
return new Match<string>
{
Data = match.Value.ToMaybe(),
Remaining = input.Substring(match.Index + match.Length)
};
};
}
public static Pattern<R> Select<T, R>(this Pattern<T> self, Func<T, R> selector)
{
return input =>
{
var match = self(input);
if (!match.Data.HasValue) return new Match<R> { Remaining = match.Remaining };
try
{
return new Match<R>
{
Data = selector(match.Data.Value).ToMaybe(),
Remaining = match.Remaining
};
}
catch
{
return new Match<R> { Remaining = match.Remaining };
}
};
}
public static Pattern<R> SelectPattern<T, R>(this Pattern<T> self, Func<T, Pattern<R>> selector)
{
return input =>
{
var match = self(input);
if (!match.Data.HasValue) return new Match<R> { Remaining = match.Remaining };
var next = selector(match.Data.Value);
var nextMatch = next(match.Remaining);
return nextMatch;
};
}
public static Pattern<R> SelectMany<T, R>(this Pattern<T> self, Func<T, Pattern<R>> selector)
{
return SelectPattern(self, selector);
}
public static Pattern<TResult> SelectMany<T, TIntermediate, TResult>(this Pattern<T> self,
Func<T, Pattern<TIntermediate>> selector,
Func<T, TIntermediate, TResult> combiner)
{
return SelectPattern(self, x => selector(x).Select(y => combiner(x, y)));
}
}
public class LogicalType : IEquatable<LogicalType>
{
private static readonly string IdentifierRegex = @"^[a-zA-Z][a-zA-Z0-9]*";
private static readonly string QualifiedIdentifierRegex = @"^([a-zA-Z][a-zA-Z0-9]*)(\.[a-zA-Z][a-zA-Z0-9]*)*";
private static readonly Pattern<string> Identifier = Text.Regex(IdentifierRegex);
private static readonly Pattern<string> QualifiedIdentifier = Text.Regex(QualifiedIdentifierRegex);
private static readonly Pattern<int> ArityPattern = Text.Regex(@"(?<=^`)\d+").Select(int.Parse);
private static readonly Pattern<int> VersionPattern = Text.Regex(@"(?<=^v)\d+").Select(int.Parse);
private static readonly Pattern<LogicalType> Pattern
= from ns in Identifier
from type in QualifiedIdentifier.LeadBy(Text.Char(':'))
from arity in ArityPattern.Optional()
let typeArgPattern = !arity.HasValue
? Text.Ref(() => Pattern).DelimitedBy(Text.Regex(@"^,\s*")).LeadBy(Text.Char('<')).FollowedBy(Text.Char('>')).Optional()
: Text.Return(Enumerable.Empty<LogicalType>())
from typeArgs in typeArgPattern
from version in VersionPattern.LeadBy(Text.Char(':')).Optional()
select arity.HasValue
? new LogicalType(ns, type, arity.Value, version)
: new LogicalType(ns, type, typeArgs, version);
private static readonly Pattern<LogicalType> TopLevelPattern = Pattern.FollowedBy(Text.EndOfLine);
private readonly string _namespaceAlias;
private readonly string _typeName;
private readonly int _arity;
private readonly LogicalType[] _typeArguments;
private readonly Maybe<int> _version;
public static LogicalType Parse(String input)
{
var result = TryParse(input);
if(!result.HasValue)
throw new ArgumentException("Input does not match the format of a logical type.", "input");
return result.Value;
}
public static Maybe<LogicalType> TryParse(String input)
{
try
{
return TopLevelPattern(input).Data;
}
catch { return Maybe.NoValue; }
}
public LogicalType(String namespaceAlias, String typeName)
: this(namespaceAlias, typeName, 0, default(Maybe<int>))
{
}
public LogicalType(String namespaceAlias, String typeName, int arity, Maybe<int> version)
: this(namespaceAlias, typeName, arity, null, version)
{
}
public LogicalType(String namespaceAlias, String typeName, IEnumerable<LogicalType> typeArguments, Maybe<int> version)
: this(namespaceAlias, typeName, 0, typeArguments, version)
{
}
private LogicalType(String namespaceAlias, String typeName, int arity, IEnumerable<LogicalType> typeArguments, Maybe<int> version)
{
_namespaceAlias = Guard.NotNullOrWhiteSpace(namespaceAlias, "namespaceAlias");
_typeName = Guard.NotNullOrWhiteSpace(typeName, "typeName");
if (!Regex.IsMatch(namespaceAlias, IdentifierRegex + "$")) throw new ArgumentOutOfRangeException("namespaceAlias", "NamespaceAlias must be an identifier.");
if (!Regex.IsMatch(typeName, QualifiedIdentifierRegex + "$")) throw new ArgumentOutOfRangeException("typeName", "TypeName must be an identifier.");
if (arity < 0) throw new ArgumentOutOfRangeException("arity", "Arity must not be negative.");
_arity = arity;
_typeArguments = typeArguments != null
? typeArguments.ToArray()
: new LogicalType[0];
if (_arity == 0 && _typeArguments.Length > 0)
_arity = _typeArguments.Length;
if (_typeArguments.Length > 0 && _arity != _typeArguments.Length)
throw new ArgumentOutOfRangeException("arity", "Arity does not match the number of provided type arguments.");
if (_typeArguments.Any(x => x.IsOpenType)) throw new ArgumentException("Type arguments cannot include open types.");
_version = version;
}
public string NamespaceAlias { get { return _namespaceAlias; } }
public string TypeName { get { return _typeName; } }
public int Arity { get { return _arity; } }
public IEnumerable<LogicalType> TypeArguments { get { return _typeArguments; } }
public Maybe<int> Version { get { return _version; } }
public bool IsOpenType { get { return Arity > 0 && TypeArguments.None(); } }
public bool IsParameterized { get { return Arity > 0; } }
public LogicalType GetOpenType()
{
if (IsOpenType) return this;
return new LogicalType(NamespaceAlias, TypeName, Arity, Version);
}
public LogicalType MakeClosedType(params LogicalType[] typeArguments)
{
return MakeClosedType((IEnumerable<LogicalType>)typeArguments);
}
public LogicalType MakeClosedType(IEnumerable<LogicalType> typeArguments)
{
var args = Guard.NotNull(typeArguments, "typeArguments").ToArray();
if (!IsOpenType) throw new InvalidOperationException("LogicalType is not an open type.");
if (args.Length != Arity) throw new ArgumentException("Incorrect number of type arguments provided.", "typeArguments");
return new LogicalType(NamespaceAlias, TypeName, typeArguments, Version);
}
public bool Equals(LogicalType other)
{
if (ReferenceEquals(other, null)) return false;
if (GetType() != other.GetType()) return false;
if (!NamespaceAlias.Equals(other.NamespaceAlias, StringComparison.OrdinalIgnoreCase)) return false;
if (!TypeName.Equals(other.TypeName, StringComparison.OrdinalIgnoreCase)) return false;
if (!Arity.Equals(other.Arity)) return false;
if (!TypeArguments.SequenceEqual(other.TypeArguments)) return false;
if (!Version.Equals(other.Version)) return false;
return true;
}
public override bool Equals(object obj)
{
return Equals(obj as LogicalType);
}
public override int GetHashCode()
{
int hash = 1;
hash = HashCode.MixJenkins32(hash + NamespaceAlias.ToLowerInvariant().GetHashCode());
hash = HashCode.MixJenkins32(hash + TypeName.ToLowerInvariant().GetHashCode());
hash = HashCode.MixJenkins32(hash + Arity);
hash = TypeArguments.Aggregate(hash, (h, lt) => HashCode.MixJenkins32(h + lt.GetHashCode()));
hash = HashCode.MixJenkins32(hash + Version.ValueOrDefault(0));
return hash;
}
public static bool operator ==(LogicalType left, LogicalType right)
{
if (ReferenceEquals(left, null) != ReferenceEquals(right, null)) return false;
return ReferenceEquals(left, null) || left.Equals(right);
}
public static bool operator !=(LogicalType left, LogicalType right)
{
return !(left == right);
}
public override string ToString()
{
string genericsPart = String.Empty;
if (TypeArguments.Any())
genericsPart = string.Format("<{0}>", string.Join(", ", TypeArguments));
else if (Arity > 0)
genericsPart = "`" + Arity.ToString();
string versionPart = Version.HasValue
? ":v" + Version.Value
: "";
return String.Format("{0}:{1}{2}{3}", NamespaceAlias, TypeName, genericsPart, versionPart);
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: Quaternion.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
/// <summary>Holder for reflection information generated from Quaternion.proto</summary>
public static partial class QuaternionReflection {
#region Descriptor
/// <summary>File descriptor for Quaternion.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static QuaternionReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChBRdWF0ZXJuaW9uLnByb3RvIjgKClF1YXRlcm5pb24SCQoBeBgBIAEoARIJ",
"CgF5GAIgASgBEgkKAXoYAyABKAESCQoBdxgEIAEoAWIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Quaternion), global::Quaternion.Parser, new[]{ "X", "Y", "Z", "W" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class Quaternion : pb::IMessage<Quaternion> {
private static readonly pb::MessageParser<Quaternion> _parser = new pb::MessageParser<Quaternion>(() => new Quaternion());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Quaternion> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::QuaternionReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Quaternion() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Quaternion(Quaternion other) : this() {
x_ = other.x_;
y_ = other.y_;
z_ = other.z_;
w_ = other.w_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Quaternion Clone() {
return new Quaternion(this);
}
/// <summary>Field number for the "x" field.</summary>
public const int XFieldNumber = 1;
private double x_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double X {
get { return x_; }
set {
x_ = value;
}
}
/// <summary>Field number for the "y" field.</summary>
public const int YFieldNumber = 2;
private double y_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double Y {
get { return y_; }
set {
y_ = value;
}
}
/// <summary>Field number for the "z" field.</summary>
public const int ZFieldNumber = 3;
private double z_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double Z {
get { return z_; }
set {
z_ = value;
}
}
/// <summary>Field number for the "w" field.</summary>
public const int WFieldNumber = 4;
private double w_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double W {
get { return w_; }
set {
w_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Quaternion);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Quaternion other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (X != other.X) return false;
if (Y != other.Y) return false;
if (Z != other.Z) return false;
if (W != other.W) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (X != 0D) hash ^= X.GetHashCode();
if (Y != 0D) hash ^= Y.GetHashCode();
if (Z != 0D) hash ^= Z.GetHashCode();
if (W != 0D) hash ^= W.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (X != 0D) {
output.WriteRawTag(9);
output.WriteDouble(X);
}
if (Y != 0D) {
output.WriteRawTag(17);
output.WriteDouble(Y);
}
if (Z != 0D) {
output.WriteRawTag(25);
output.WriteDouble(Z);
}
if (W != 0D) {
output.WriteRawTag(33);
output.WriteDouble(W);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (X != 0D) {
size += 1 + 8;
}
if (Y != 0D) {
size += 1 + 8;
}
if (Z != 0D) {
size += 1 + 8;
}
if (W != 0D) {
size += 1 + 8;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Quaternion other) {
if (other == null) {
return;
}
if (other.X != 0D) {
X = other.X;
}
if (other.Y != 0D) {
Y = other.Y;
}
if (other.Z != 0D) {
Z = other.Z;
}
if (other.W != 0D) {
W = other.W;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 9: {
X = input.ReadDouble();
break;
}
case 17: {
Y = input.ReadDouble();
break;
}
case 25: {
Z = input.ReadDouble();
break;
}
case 33: {
W = input.ReadDouble();
break;
}
}
}
}
}
#endregion
#endregion Designer generated code
| |
// 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 Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.Encryption.Rijndael.Tests
{
using Rijndael = System.Security.Cryptography.Rijndael;
/// <summary>
/// Since RijndaelImplementation (from Rijndael.Create()) and RijndaelManaged classes wrap Aes,
/// we only test minimally here.
/// </summary>
public class RijndaelTests
{
[Fact]
public static void VerifyDefaults()
{
using (var alg = Rijndael.Create())
{
// We use an internal class for the implementation, not the public RijndaelManaged
Assert.IsNotType<RijndaelManaged>(alg);
VerifyDefaults(alg);
}
using (var alg = new RijndaelManaged())
{
VerifyDefaults(alg);
}
}
private static void VerifyDefaults(Rijndael alg)
{
// The block size differs from the base
Assert.Equal(128, alg.LegalBlockSizes[0].MinSize);
Assert.Equal(128, alg.LegalBlockSizes[0].MaxSize);
Assert.Equal(128, alg.BlockSize);
// Different exception since we have different supported BlockSizes than desktop
Assert.Throws<PlatformNotSupportedException>(() => alg.BlockSize = 192);
Assert.Throws<PlatformNotSupportedException>(() => alg.BlockSize = 256);
// Normal exception for rest
Assert.Throws<CryptographicException>(() => alg.BlockSize = 111);
Assert.Equal(CipherMode.CBC, alg.Mode);
Assert.Equal(PaddingMode.PKCS7, alg.Padding);
}
[Fact]
public static void VerifyBlocksizeIVNulling()
{
using (var testIVAlg = Rijndael.Create())
{
using (var alg = Rijndael.Create())
{
alg.IV = testIVAlg.IV;
alg.BlockSize = 128;
Assert.Equal(testIVAlg.IV, alg.IV);
}
using (var alg = new RijndaelManaged())
{
alg.IV = testIVAlg.IV;
alg.BlockSize = 128;
Assert.Equal(testIVAlg.IV, alg.IV);
}
using (var alg = new RijndaelLegalSizesBreaker())
{
// This one should set IV to null on setting BlockSize since there is only one valid BlockSize
alg.IV = testIVAlg.IV;
alg.BlockSize = 1;
Assert.Throws<NotImplementedException>(() => alg.IV);
}
using (var alg = new RijndaelMinimal())
{
alg.IV = testIVAlg.IV;
alg.BlockSize = 128;
Assert.Equal(testIVAlg.IV, alg.IV);
}
}
}
[Fact]
public static void EncryptDecryptKnownECB192()
{
using (var alg = Rijndael.Create())
{
EncryptDecryptKnownECB192(alg);
}
using (var alg = new RijndaelManaged())
{
EncryptDecryptKnownECB192(alg);
}
}
private static void EncryptDecryptKnownECB192(Rijndael alg)
{
byte[] plainTextBytes =
new ASCIIEncoding().GetBytes("This is a sentence that is longer than a block, it ensures that multi-block functions work.");
byte[] encryptedBytesExpected = new byte[]
{
0xC9, 0x7F, 0xA5, 0x5B, 0xC3, 0x92, 0xDC, 0xA6,
0xE4, 0x9F, 0x2D, 0x1A, 0xEF, 0x7A, 0x27, 0x03,
0x04, 0x9C, 0xFB, 0x56, 0x63, 0x38, 0xAE, 0x4F,
0xDC, 0xF6, 0x36, 0x98, 0x28, 0x05, 0x32, 0xE9,
0xF2, 0x6E, 0xEC, 0x0C, 0x04, 0x9D, 0x12, 0x17,
0x18, 0x35, 0xD4, 0x29, 0xFC, 0x01, 0xB1, 0x20,
0xFA, 0x30, 0xAE, 0x00, 0x53, 0xD4, 0x26, 0x25,
0xA4, 0xFD, 0xD5, 0xE6, 0xED, 0x79, 0x35, 0x2A,
0xE2, 0xBB, 0x95, 0x0D, 0xEF, 0x09, 0xBB, 0x6D,
0xC5, 0xC4, 0xDB, 0x28, 0xC6, 0xF4, 0x31, 0x33,
0x9A, 0x90, 0x12, 0x36, 0x50, 0xA0, 0xB7, 0xD1,
0x35, 0xC4, 0xCE, 0x81, 0xE5, 0x2B, 0x85, 0x6B,
};
byte[] aes192Key = new byte[]
{
0xA6, 0x1E, 0xC7, 0x54, 0x37, 0x4D, 0x8C, 0xA5,
0xA4, 0xBB, 0x99, 0x50, 0x35, 0x4B, 0x30, 0x4D,
0x6C, 0xFE, 0x3B, 0x59, 0x65, 0xCB, 0x93, 0xE3,
};
// The CipherMode and KeySize are different than the default values; this ensures the type
// forwards the state properly to Aes.
alg.Mode = CipherMode.ECB;
alg.Key = aes192Key;
byte[] encryptedBytes = alg.Encrypt(plainTextBytes);
Assert.Equal(encryptedBytesExpected, encryptedBytes);
byte[] decryptedBytes = alg.Decrypt(encryptedBytes);
Assert.Equal(plainTextBytes, decryptedBytes);
}
[Fact]
public static void TestShims()
{
using (var alg = Rijndael.Create())
{
TestShims(alg);
}
using (var alg = new RijndaelManaged())
{
TestShims(alg);
}
}
private static void TestShims(Rijndael alg)
{
alg.BlockSize = 128;
Assert.Equal(128, alg.BlockSize);
var emptyIV = new byte[alg.BlockSize / 8];
alg.IV = emptyIV;
Assert.Equal(emptyIV, alg.IV);
alg.GenerateIV();
Assert.NotEqual(emptyIV, alg.IV);
var emptyKey = new byte[alg.KeySize / 8];
alg.Key = emptyKey;
Assert.Equal(emptyKey, alg.Key);
alg.GenerateKey();
Assert.NotEqual(emptyKey, alg.Key);
alg.KeySize = 128;
Assert.Equal(128, alg.KeySize);
alg.Mode = CipherMode.ECB;
Assert.Equal(CipherMode.ECB, alg.Mode);
alg.Padding = PaddingMode.PKCS7;
Assert.Equal(PaddingMode.PKCS7, alg.Padding);
}
[Fact]
public static void RijndaelKeySize_BaseClass()
{
using (Rijndael alg = new RijndaelMinimal())
{
Assert.Equal(128, alg.LegalKeySizes[0].MinSize);
Assert.Equal(256, alg.LegalKeySizes[0].MaxSize);
Assert.Equal(64, alg.LegalKeySizes[0].SkipSize);
Assert.Equal(256, alg.KeySize);
Assert.Equal(128, alg.LegalBlockSizes[0].MinSize);
Assert.Equal(256, alg.LegalBlockSizes[0].MaxSize);
Assert.Equal(64, alg.LegalBlockSizes[0].SkipSize);
Assert.Equal(128, alg.BlockSize);
}
}
[Fact]
public static void EnsureLegalSizesValuesIsolated()
{
new RijndaelLegalSizesBreaker().Dispose();
using (Rijndael alg = Rijndael.Create())
{
Assert.Equal(128, alg.LegalKeySizes[0].MinSize);
Assert.Equal(128, alg.LegalBlockSizes[0].MinSize);
alg.Key = new byte[16];
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public static void EncryptWithLargeOutputBuffer(bool blockAlignedOutput)
{
using (Rijndael alg = Rijndael.Create())
using (ICryptoTransform xform = alg.CreateEncryptor())
{
// 8 blocks, plus maybe three bytes
int outputPadding = blockAlignedOutput ? 0 : 3;
byte[] output = new byte[alg.BlockSize + outputPadding];
// 2 blocks of 0x00
byte[] input = new byte[alg.BlockSize / 4];
int outputOffset = 0;
outputOffset += xform.TransformBlock(input, 0, input.Length, output, outputOffset);
byte[] overflow = xform.TransformFinalBlock(Array.Empty<byte>(), 0, 0);
Buffer.BlockCopy(overflow, 0, output, outputOffset, overflow.Length);
outputOffset += overflow.Length;
Assert.Equal(3 * (alg.BlockSize / 8), outputOffset);
string outputAsHex = output.ByteArrayToHex();
Assert.NotEqual(new string('0', outputOffset * 2), outputAsHex.Substring(0, outputOffset * 2));
Assert.Equal(new string('0', (output.Length - outputOffset) * 2), outputAsHex.Substring(outputOffset * 2));
}
}
[Theory]
[InlineData(true, true)]
[InlineData(true, false)]
[InlineData(false, true)]
[InlineData(false, false)]
public static void TransformWithTooShortOutputBuffer(bool encrypt, bool blockAlignedOutput)
{
using (Rijndael alg = Rijndael.Create())
using (ICryptoTransform xform = encrypt ? alg.CreateEncryptor() : alg.CreateDecryptor())
{
// 1 block, plus maybe three bytes
int outputPadding = blockAlignedOutput ? 0 : 3;
byte[] output = new byte[alg.BlockSize / 8 + outputPadding];
// 3 blocks of 0x00
byte[] input = new byte[3 * (alg.BlockSize / 8)];
Assert.Throws<ArgumentOutOfRangeException>(
() => xform.TransformBlock(input, 0, input.Length, output, 0));
Assert.Equal(new byte[output.Length], output);
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public static void MultipleBlockDecryptTransform(bool blockAlignedOutput)
{
const string ExpectedOutput = "This is a 128-bit block test";
int outputPadding = blockAlignedOutput ? 0 : 3;
byte[] key = "0123456789ABCDEFFEDCBA9876543210".HexToByteArray();
byte[] iv = "0123456789ABCDEF0123456789ABCDEF".HexToByteArray();
byte[] outputBytes = new byte[iv.Length * 2 + outputPadding];
byte[] input = "D1BF87C650FCD10B758445BE0E0A99D14652480DF53423A8B727D30C8C010EDE".HexToByteArray();
int outputOffset = 0;
using (Rijndael alg = Rijndael.Create())
using (ICryptoTransform xform = alg.CreateDecryptor(key, iv))
{
Assert.Equal(2 * alg.BlockSize, (outputBytes.Length - outputPadding) * 8);
outputOffset += xform.TransformBlock(input, 0, input.Length, outputBytes, outputOffset);
byte[] overflow = xform.TransformFinalBlock(Array.Empty<byte>(), 0, 0);
Buffer.BlockCopy(overflow, 0, outputBytes, outputOffset, overflow.Length);
outputOffset += overflow.Length;
}
string decrypted = Encoding.ASCII.GetString(outputBytes, 0, outputOffset);
Assert.Equal(ExpectedOutput, decrypted);
}
private class RijndaelLegalSizesBreaker : RijndaelMinimal
{
public RijndaelLegalSizesBreaker()
{
LegalKeySizesValue[0] = new KeySizes(1, 1, 0);
LegalBlockSizesValue[0] = new KeySizes(1, 1, 0);
}
}
private class RijndaelMinimal : Rijndael
{
// If the constructor uses a virtual call to any of the property setters
// they will fail.
private readonly bool _ready;
public RijndaelMinimal()
{
// Don't set this as a field initializer, otherwise it runs before the base ctor.
_ready = true;
}
public override int KeySize
{
set
{
if (!_ready)
{
throw new InvalidOperationException();
}
base.KeySize = value;
}
}
public override int BlockSize
{
set
{
if (!_ready)
{
throw new InvalidOperationException();
}
base.BlockSize = value;
}
}
public override byte[] IV
{
set
{
if (!_ready)
{
throw new InvalidOperationException();
}
base.IV = value;
}
}
public override byte[] Key
{
set
{
if (!_ready)
{
throw new InvalidOperationException();
}
base.Key = value;
}
}
public override CipherMode Mode
{
set
{
if (!_ready)
{
throw new InvalidOperationException();
}
base.Mode = value;
}
}
public override PaddingMode Padding
{
set
{
if (!_ready)
{
throw new InvalidOperationException();
}
base.Padding = value;
}
}
public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV)
{
throw new NotImplementedException();
}
public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV)
{
throw new NotImplementedException();
}
public override void GenerateIV()
{
throw new NotImplementedException();
}
public override void GenerateKey()
{
throw new NotImplementedException();
}
}
}
}
| |
/*
* 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 NVelocity.Runtime.Parser.Node
{
using System;
using Context;
using App.Event;
using Exception;
using Util.Introspection;
/// <summary> ASTMethod.java
///
/// Method support for references : $foo.method()
///
/// NOTE :
///
/// introspection is now done at render time.
///
/// Please look at the Parser.jjt file which is
/// what controls the generation of this class.
///
/// </summary>
/// <author> <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a>
/// </author>
/// <author> <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
/// </author>
/// <version> $Id: ASTMethod.java 720228 2008-11-24 16:58:33Z nbubna $
/// </version>
public class ASTMethod : SimpleNode
{
/// <returns> Returns the methodName.
/// </returns>
/// <since> 1.5
/// </since>
virtual public string MethodName
{
get
{
return methodName;
}
}
private string methodName = "";
private int paramCount = 0;
protected internal Info uberInfo;
/// <summary> Indicates if we are running in strict reference mode.</summary>
protected internal bool strictRef = false;
/// <param name="id">
/// </param>
public ASTMethod(int id)
: base(id)
{
}
/// <param name="p">
/// </param>
/// <param name="id">
/// </param>
public ASTMethod(Parser p, int id)
: base(p, id)
{
}
/// <seealso cref="NVelocity.Runtime.Paser.Node.SimpleNode.Accept(NVelocity.Runtime.Paser.Node.IParserVisitor, System.Object)">
/// </seealso>
public override object Accept(IParserVisitor visitor, object data)
{
return visitor.Visit(this, data);
}
/// <summary> simple Init - Init our subtree and Get what we can from
/// the AST
/// </summary>
/// <param name="context">
/// </param>
/// <param name="data">
/// </param>
/// <returns> The Init result
/// </returns>
/// <throws> TemplateInitException </throws>
public override object Init(IInternalContextAdapter context, object data)
{
base.Init(context, data);
/*
* make an uberinfo - saves new's later on
*/
uberInfo = new Info(TemplateName, Line, Column);
/*
* this is about all we can do
*/
methodName = FirstToken.Image;
paramCount = GetNumChildren() - 1;
strictRef = rsvc.GetBoolean(NVelocity.Runtime.RuntimeConstants.RUNTIME_REFERENCES_STRICT, false);
return data;
}
/// <summary> invokes the method. Returns null if a problem, the
/// parameters return if the method returns something, or
/// an empty string "" if the method returns void
/// </summary>
/// <param name="instance">
/// </param>
/// <param name="context">
/// </param>
/// <returns> Result or null.
/// </returns>
/// <throws> MethodInvocationException </throws>
public override object Execute(object o, IInternalContextAdapter context)
{
/*
* new strategy (strategery!) for introspection. Since we want
* to be thread- as well as context-safe, we *must* do it now,
* at execution time. There can be no in-node caching,
* but if we are careful, we can do it in the context.
*/
IVelMethod method = null;
object[] params_Renamed = new object[paramCount];
try
{
/*
* sadly, we do need recalc the values of the args, as this can
* change from visit to visit
*/
System.Type[] paramClasses = paramCount > 0 ? new System.Type[paramCount] : new System.Collections.Generic.List<Type>().ToArray();
for (int j = 0; j < paramCount; j++)
{
params_Renamed[j] = GetChild(j + 1).Value(context);
if (params_Renamed[j] != null)
{
paramClasses[j] = params_Renamed[j].GetType();
}
}
/*
* check the cache
*/
MethodCacheKey mck = new MethodCacheKey(methodName, paramClasses);
IntrospectionCacheData icd = context.ICacheGet(mck);
/*
* like ASTIdentifier, if we have cache information, and the
* Class of Object instance is the same as that in the cache, we are
* safe.
*/
if (icd != null && (o != null && icd.ContextData == o.GetType()))
{
/*
* Get the method from the cache
*/
method = (IVelMethod)icd.Thingy;
}
else
{
/*
* otherwise, do the introspection, and then
* cache it
*/
method = rsvc.Uberspect.GetMethod(o, methodName, params_Renamed, new Info(TemplateName, Line, Column));
if ((method != null) && (o != null))
{
icd = new IntrospectionCacheData();
icd.ContextData = o.GetType();
icd.Thingy = method;
context.ICachePut(mck, icd);
}
}
/*
* if we still haven't gotten the method, either we are calling
* a method that doesn't exist (which is fine...) or I screwed
* it up.
*/
if (method == null)
{
if (strictRef)
{
// Create a parameter list for the exception Error message
System.Text.StringBuilder plist = new System.Text.StringBuilder();
for (int i = 0; i < params_Renamed.Length; i++)
{
System.Type param = paramClasses[i];
plist.Append(param == null ? "null" : param.FullName);
if (i < params_Renamed.Length - 1)
plist.Append(", ");
}
throw new MethodInvocationException("Object '" + o.GetType().FullName + "' does not contain method " + methodName + "(" + plist + ")", null, methodName, uberInfo.TemplateName, uberInfo.Line, uberInfo.Column);
}
else
{
return null;
}
}
}
catch (MethodInvocationException mie)
{
/*
* this can come from the doIntrospection(), as the arg values
* are evaluated to find the right method signature. We just
* want to propogate it here, not do anything fancy
*/
throw mie;
}
/**
* pass through application level runtime exceptions
*/
catch (System.SystemException e)
{
throw e;
}
catch (System.Exception e)
{
/*
* can come from the doIntropection() also, from Introspector
*/
string msg = "ASTMethod.Execute() : exception from introspection";
log.Error(msg, e);
throw new VelocityException(msg, e);
}
try
{
/*
* Get the returned object. It may be null, and that is
* valid for something declared with a void return type.
* Since the caller is expecting something to be returned,
* as long as things are peachy, we can return an empty
* String so ASTReference() correctly figures out that
* all is well.
*/
object obj = method.Invoke(o, params_Renamed);
if (obj == null)
{
if (method.ReturnType == System.Type.GetType("System.Void"))
{
return "";
}
}
return obj;
}
catch (System.Reflection.TargetInvocationException ite)
{
return HandleInvocationException(o, context, ite.GetBaseException());
}
/** Can also be thrown by method invocation **/
catch (System.ArgumentException t)
{
return HandleInvocationException(o, context, t);
}
/**
* pass through application level runtime exceptions
*/
catch (System.SystemException e)
{
throw e;
}
catch (System.Exception e)
{
string msg = "ASTMethod.Execute() : exception invoking method '" + methodName + "' in " + o.GetType();
log.Error(msg, e);
throw new VelocityException(msg, e);
}
}
private object HandleInvocationException(object o, IInternalContextAdapter context, System.Exception t)
{
/*
* In the event that the invocation of the method
* itself throws an exception, we want to catch that
* wrap it, and throw. We don't Log here as we want to figure
* out which reference threw the exception, so do that
* above
*/
/*
* let non-Exception Throwables go...
*/
if (t is System.Exception)
{
try
{
return EventHandlerUtil.MethodException(rsvc, context, o.GetType(), methodName, (System.Exception)t);
}
/**
* If the event handler throws an exception, then wrap it
* in a MethodInvocationException. Don't pass through RuntimeExceptions like other
* similar catchall code blocks.
*/
catch (System.Exception e)
{
throw new MethodInvocationException("Invocation of method '" + methodName + "' in " + o.GetType() + " threw exception " + e.ToString(), e, methodName, TemplateName, this.Line, this.Column);
}
}
else
{
/*
* no event cartridge to override. Just throw
*/
throw new MethodInvocationException("Invocation of method '" + methodName + "' in " + o.GetType() + " threw exception " + t.ToString(), t, methodName, TemplateName, this.Line, this.Column);
}
}
/// <summary> Internal class used as key for method cache. Combines
/// ASTMethod fields with array of parameter classes. Has
/// public access (and complete constructor) for unit test
/// purposes.
/// </summary>
/// <since> 1.5
/// </since>
public class MethodCacheKey
{
private string methodName;
private System.Type[] params_Renamed;
public MethodCacheKey(string methodName, System.Type[] params_Renamed)
{
/// <summary> Should never be initialized with nulls, but to be safe we refuse
/// to accept them.
/// </summary>
this.methodName = (methodName != null) ? methodName : string.Empty;
this.params_Renamed = (params_Renamed != null) ? params_Renamed : new System.Collections.Generic.List<Type>().ToArray();
}
/// <seealso cref="java.lang.Object.equals(java.lang.Object)">
/// </seealso>
public override bool Equals(object o)
{
/**
* note we skip the null test for methodName and params
* due to the earlier test in the constructor
*/
if (o is MethodCacheKey)
{
MethodCacheKey other = (MethodCacheKey)o;
if (params_Renamed.Length == other.params_Renamed.Length && methodName.Equals(other.methodName))
{
for (int i = 0; i < params_Renamed.Length; ++i)
{
if (params_Renamed[i] == null)
{
if (params_Renamed[i] != other.params_Renamed[i])
{
return false;
}
}
else if (!params_Renamed[i].Equals(other.params_Renamed[i]))
{
return false;
}
}
return true;
}
}
return false;
}
/// <seealso cref="java.lang.Object.hashCode()">
/// </seealso>
public override int GetHashCode()
{
int result = 17;
/**
* note we skip the null test for methodName and params
* due to the earlier test in the constructor
*/
for (int i = 0; i < params_Renamed.Length; ++i)
{
System.Type param = params_Renamed[i];
if (param != null)
{
result = result * 37 + param.GetHashCode();
}
}
result = result * 37 + methodName.GetHashCode();
return result;
}
}
}
}
| |
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 BlueYonder.MVC.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ActionDescriptor.ReturnType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace NinjaNye.SearchExtensions.Tests.SearchExtensionTests.IEnumerableTests
{
public class SearchChildrenTests
{
private ParentTestData _parent;
private List<ParentTestData> _testData;
private TestData _dataOne;
private TestData _dataFour;
private TestData _dataTwo;
private TestData _dataThree;
private ParentTestData _otherParent;
public SearchChildrenTests()
{
_dataOne = new TestData { Name = "chris", Description = "child data", Number = 1, Age = 20};
_dataTwo = new TestData { Name = "fred", Description = "child data", Number = 6, Age = 30 };
_dataThree = new TestData { Name = "teddy", Description = "child data", Number = 2, Age = 40 };
_dataFour = new TestData { Name = "josh", Description = "child data", Number = 20, Age = 50 };
_parent = new ParentTestData
{
Children = new List<TestData> {_dataOne, _dataTwo},
OtherChildren = new List<TestData> { _dataThree, _dataFour }
};
_otherParent = new ParentTestData
{
Children = new List<TestData> {_dataThree, _dataFour},
OtherChildren = new List<TestData> { _dataOne, _dataTwo }
};
_testData = new List<ParentTestData> { _parent, _otherParent };
}
[Fact]
public void SearchChild_SearchChildCollectionWithoutProperty_ReturnParent()
{
//Arrange
//Act
var result = _testData.SearchChildren(p => p.Children);
//Assert
Assert.Equal(_testData, result);
}
[Fact]
public void SearchChild_SearchChildCollection_ReturnOnlyParentWhosChildNumberIsGreaterThanTen()
{
//Arrange
//Act
var result = _testData.SearchChildren(p => p.Children)
.With(c => c.Number)
.GreaterThan(10)
.ToList();
//Assert
Assert.Single(result);
Assert.True(result.All(p => p.Children.Any(c => c.Number > 10)));
}
[Fact]
public void SearchChildren_SearchChildCollectionWithPropertyGreaterThan()
{
//Arrange
//Act
var result = _testData.SearchChildren(p => p.Children)
.With(c => c.Number)
.GreaterThan(4)
.ToList();
//Assert
Assert.Equal(2, result.Count());
Assert.Contains(_parent, result);
Assert.Contains(_otherParent, result);
Assert.True(result.All(p => p.Children.Any(c => c.Number > 4)));
}
[Fact]
public void SearchChildren_SearchChildCollectionWithPropertyGreaterThanOrEqualTo()
{
//Arrange
//Act
var result = _testData.SearchChildren(p => p.Children)
.With(c => c.Number)
.GreaterThanOrEqualTo(6)
.ToList();
//Assert
Assert.Equal(2, result.Count());
Assert.Contains(_parent, result);
Assert.Contains(_otherParent, result);
Assert.True(result.All(p => p.Children.Any(c => c.Number >= 6)));
}
[Fact]
public void SearchChildren_SearchChildCollectionWithPropertyLessThan()
{
//Arrange
//Act
var result = _testData.SearchChildren(p => p.Children)
.With(c => c.Number)
.LessThan(2)
.ToList();
//Assert
Assert.Single(result);
Assert.Contains(_parent, result);
}
[Fact]
public void SearchChildren_SearchChildCollectionWithPropertyLessThanOrEqualTo()
{
//Arrange
//Act
var result = _testData.SearchChildren(p => p.Children)
.With(c => c.Number)
.LessThanOrEqualTo(2)
.ToList();
//Assert
Assert.Equal(2, result.Count());
Assert.Contains(_parent, result);
Assert.Contains(_otherParent, result);
}
[Fact]
public void SearchChildren_SearchChildCollectionWithPropertyLessThanAndGreaterThan()
{
//Arrange
//Act
var result = _testData.SearchChildren(p => p.Children)
.With(c => c.Number)
.LessThan(10)
.GreaterThan(2)
.ToList();
//Assert
Assert.Single(result);
Assert.Contains(_parent, result);
}
[Fact]
public void SearchChildren_SearchChildCollectionWithPropertyBetween()
{
//Arrange
//Act
var result = _testData.SearchChildren(p => p.Children)
.With(c => c.Number)
.Between(2, 10)
.ToList();
//Assert
Assert.Single(result);
Assert.Contains(_parent, result);
}
[Fact]
public void SearchChildren_SearchChildCollectionWithPropertyEqualTo()
{
//Arrange
//Act
var result = _testData.SearchChildren(p => p.Children)
.With(c => c.Number)
.EqualTo(2)
.ToList();
//Assert
Assert.Single(result);
Assert.Contains(_otherParent, result);
}
[Fact]
public void SearchChildren_SearchChildCollectionWithPropertyEqualToAnyOneOfMultiple()
{
//Arrange
//Act
var result = _testData.SearchChildren(p => p.Children)
.With(c => c.Number)
.EqualTo(2, 6)
.ToList();
//Assert
Assert.Equal(2, result.Count());
Assert.Contains(_parent, result);
Assert.Contains(_otherParent, result);
}
[Fact]
public void SearchChildren_SearchChildCollectionWithMultiplePropertiesEqualTo()
{
//Arrange
//Act
var result = _testData.SearchChildren(p => p.Children)
.With(c => c.Number, c => c.Age)
.EqualTo(20)
.ToList();
//Assert
Assert.Equal(2, result.Count());
Assert.Contains(_parent, result);
Assert.Contains(_otherParent, result);
}
[Fact]
public void SearchChildren_SearchMultipleChildCollectionsWithPropertyEqualTo()
{
//Arrange
//Act
var result = _testData.SearchChildren(p => p.Children, p => p.OtherChildren)
.With(c => c.Number)
.EqualTo(20)
.ToList();
//Assert
Assert.Equal(2, result.Count());
Assert.Contains(_parent, result);
Assert.Contains(_otherParent, result);
}
[Fact]
public void SearchChildren_SearchMultipleChildCollectionsWithStringPropertyEqualTo()
{
//Arrange
//Act
var result = _testData.SearchChildren(p => p.Children, p => p.OtherChildren)
.With(c => c.Name)
.EqualTo("chris")
.ToList();
//Assert
Assert.Equal(2, result.Count());
Assert.Contains(_parent, result);
Assert.Contains(_otherParent, result);
}
}
}
| |
using System;
using System.ComponentModel;
using System.Data;
using DBSchemaInfo.Base;
namespace CslaGenerator.Metadata
{
/// <summary>
/// Summary description for DbBindColumn.
/// </summary>
[Serializable]
public class DbBindColumn : ICloneable
{
#region Fields
private ColumnOriginType _columnOriginType = ColumnOriginType.None;
// these fields are used to serialize the column name so it can be loaded from a schema
private readonly string _tableName = String.Empty;
private readonly string _viewName = String.Empty;
private readonly string _spName = String.Empty;
private int _spResultSetIndex;
private string _columnName = String.Empty;
private DbType _dataType = DbType.String;
private string _nativeType = String.Empty;
private long _size;
private bool _isPrimaryKey;
private ICatalog _catalog;
private IColumnInfo _column;
private string _objectName;
private string _catalogName;
private string _schemaName;
private IDataBaseObject _databaseObject;
private IResultSet _resultSet;
private bool _isNullable;
private bool _isIdentity;
#endregion
#region Properties
public ColumnOriginType ColumnOriginType
{
set { _columnOriginType = value; }
get { return _columnOriginType; }
}
public IColumnInfo Column
{
get { return _column; }
}
public DbType DataType
{
get
{
if (Column == null) { return _dataType; }
return Column.DbType;
}
set { _dataType = value; }
}
public string NativeType
{
get
{
if (Column == null) { return _nativeType; }
return Column.NativeType;
}
set
{
if (value != null)
_nativeType = value;
}
}
public long Size
{
get
{
if (Column == null) { return _size; }
return Column.ColumnLength;
}
set { _size = value; }
}
public int SpResultIndex
{
get { return _spResultSetIndex; }
set { _spResultSetIndex = value; }
}
[Obsolete("Use ObjectName instead")]
[Browsable(false)]
public string TableName
{
get { return _objectName; }
set
{
if (string.IsNullOrEmpty(_objectName) && !string.IsNullOrEmpty(value))
_objectName = value;
//_tableName = value;
}
}
[Obsolete("Use ObjectName instead")]
[Browsable(false)]
public string ViewName
{
get { return _objectName; }
set
{
if (string.IsNullOrEmpty(_objectName) && !string.IsNullOrEmpty(value))
_objectName = value;
//_viewName = value;
}
}
[Obsolete("Use ObjectName instead")]
[Browsable(false)]
public string SpName
{
get { return _objectName; }
set
{
if (string.IsNullOrEmpty(_objectName) && !string.IsNullOrEmpty(value))
_objectName = value;
//_spName = value;
}
}
public string ColumnName
{
get { return _columnName; }
set { _columnName = value; }
}
public bool IsPrimaryKey
{
get { return _isPrimaryKey; }
set { _isPrimaryKey = value; }
}
public string ObjectName
{
get { return _objectName; }
set
{
value = value.Trim().Replace(" ", " ").Replace(' ', '_');
_objectName = value;
}
}
public string CatalogName
{
get { return _catalogName; }
set { _catalogName = value; }
}
public string SchemaName
{
get { return _schemaName; }
set { _schemaName = value; }
}
[Browsable(false)]
public IDataBaseObject DatabaseObject
{
get { return _databaseObject; }
}
[Browsable(false)]
public IResultSet ResultSet
{
get { return _resultSet; }
}
#endregion
#region Methods
internal void LoadColumn(ICatalog catalog)
{
_catalog = catalog;
_resultSet = null;
_databaseObject = null;
_column = null;
string cat = null;
if (_catalogName != null)
{
if (string.Compare(_catalogName, _catalog.CatalogName, true) != 0)
cat = null; //When connecting to a DB with a different name
else
cat = _catalogName;
}
try
{
switch (_columnOriginType)
{
case ColumnOriginType.Table:
ITableInfo tInfo = _catalog.Tables[cat, _schemaName, _objectName];
if (tInfo != null)
{
_databaseObject = tInfo;
_resultSet = tInfo;
}
break;
case ColumnOriginType.View:
//_Column = _Catalog.Views[_CatalogName, _SchemaName, _objectName].Columns[_columnName];
IViewInfo vInfo = _catalog.Views[cat, _schemaName, _objectName];
if (vInfo != null)
{
_databaseObject = vInfo;
_resultSet = vInfo;
}
break;
case ColumnOriginType.StoredProcedure:
IStoredProcedureInfo pInfo = _catalog.Procedures[cat, _schemaName, _objectName];
if (pInfo != null)
{
_databaseObject = pInfo;
if (pInfo.ResultSets.Count > _spResultSetIndex)
_resultSet = pInfo.ResultSets[_spResultSetIndex];
}
break;
case ColumnOriginType.None:
break;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
if (_resultSet != null)
_column = _resultSet.Columns[_columnName];
ReloadColumnInfo();
}
private void ReloadColumnInfo()
{
if (_column == null)
return;
if (_catalogName == null)
_catalogName = _databaseObject.ObjectCatalog;
if (_schemaName == null)
_schemaName = _databaseObject.ObjectSchema;
_isPrimaryKey = _column.IsPrimaryKey;
_isNullable = _column.IsNullable;
_isIdentity = _column.IsIdentity;
_dataType = _column.DbType;
_nativeType = _column.NativeType;
}
public bool IsNullable
{
get { return _isNullable; }
set { _isNullable = value; }
}
public bool IsIdentity
{
get { return _isIdentity; }
set { _isIdentity = value; }
}
public object Clone()
{
var clone = (DbBindColumn)Util.ObjectCloner.CloneShallow(this);
clone.LoadColumn(_catalog);
return clone;
//DbBindColumn col = new DbBindColumn();
//col._columnName = this._columnName;
//col._columnOriginType = this._columnOriginType;
//col._spName = this._spName;
//col._spResultSetIndex = this._spResultSetIndex;
//col._spSchema = this._spSchema;
//col._tableName = this._tableName;
//col._tableSchema = this._tableSchema;
//col._viewName = this._viewName;
//col._viewSchema = this._viewSchema;
//col._dataType = this._dataType;
//col._nativeType = this._nativeType;
//return col;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Threading;
using System.Net.Sockets;
using System.Collections.Generic;
using Microsoft.Protocols.TestTools.StackSdk.Transport;
namespace Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpbcgr
{
public class RdpbcgrClientTransportStack
{
#region Fields
/// <summary>
/// the identity of stream.
/// </summary>
private static int endpointIdentity = 1;
/// <summary>
/// the identity of stream.
/// </summary>
private static int EndpointIdentity
{
get
{
return endpointIdentity++;
}
}
/// <summary>
/// a StreamConfig object that contains the config.
/// </summary>
private StreamConfig streamConfig;
/// <summary>
/// a Stream object that specifies the underlayer transport.<para/>
/// when connect to server, it will be constructed; <para/>
/// when disconnect or dispose, it will be close and set to null.
/// </summary>
private Stream stream;
/// <summary>
/// a ThreadManager object that contains the received thread.<para/>
/// when connect to server, it will be constructed;<para/>
/// when disconnect or dispose, it will be stop and set to null.
/// </summary>
private Thread thread;
/// <summary>
/// Used to stop the thread
/// </summary>
private bool stopThread = false;
/// <summary>
/// a SyncFilterQueue<TransportEvent> object that contains the event,
/// such as disconnected and exception.<para/>
/// clear event queue when connect to server. never be null.
/// </summary>
private SyncFilterQueue<TransportEvent> eventQueue;
/// <summary>
/// a DecodePacketCallback delegate that is used to decode the packet from bytes.
/// </summary>
private DecodePacketCallback decoder;
/// <summary>
/// a PacketCache to store the arrived packet.<para/>
/// clear packet list when connect to server. never be null.
/// </summary>
private SyncFilterQueue<StackPacket> packetCache;
/// <summary>
/// buffer for received data
/// </summary>
private List<byte> buffer;
/// <summary>
/// an int value that specifies the local endpoint.
/// </summary>
private int localEndPoint;
/// <summary>
/// a PacketFilter that is used to filter the packet.
/// </summary>
public PacketFilter PacketFilter;
public const int MilliSecondsToWaitStreamDataAvailable = 1;
#endregion
#region Constructors
/// <summary>
/// consturctor.
/// </summary>
/// <param name="transportConfig">
/// a TransportConfig object that contains the config.
/// </param>
/// <param name="decodePacketCallback">
/// a DecodePacketCallback delegate that is used to decode the packet from bytes.
/// </param>
/// <exception cref="ArgumentException">
/// thrown when transportConfig is not StreamConfig
/// </exception>
/// <exception cref="ArgumentNullException">
/// thrown when transportConfig is null.
/// </exception>
/// <exception cref="ArgumentNullException">
/// thrown when decodePacketCallback is null.
/// </exception>
public RdpbcgrClientTransportStack(TransportConfig transportConfig, DecodePacketCallback decodePacketCallback)
{
if (transportConfig == null)
{
throw new ArgumentNullException("transportConfig");
}
if (decodePacketCallback == null)
{
throw new ArgumentNullException("decodePacketCallback");
}
this.UpdateConfig(transportConfig);
buffer = new List<byte>();
this.eventQueue = new SyncFilterQueue<TransportEvent>();
this.packetCache = new SyncFilterQueue<StackPacket>();
this.decoder = decodePacketCallback;
}
#endregion
#region IConnectable Members
/// <summary>
/// connect to remote endpoint.<para/>
/// the underlayer transport must be TcpClient, UdpClient or NetbiosClient.
/// </summary>
/// <returns>
/// the remote endpoint of the connection.
/// </returns>
/// <exception cref="InvalidOperationException">
/// thrown when tcp client is connected to server.
/// </exception>
/// <exception cref="InvalidOperationException">
/// thrown when the received thread does not cleanup.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// thrown when this object is disposed.
/// </exception>
public object Connect()
{
if (disposed)
{
throw new ObjectDisposedException("StreamTransport");
}
if (this.thread != null)
{
throw new InvalidOperationException("stream client is connected.");
}
this.eventQueue.Clear();
this.packetCache.Clear();
this.localEndPoint = RdpbcgrClientTransportStack.EndpointIdentity;
this.stream = this.streamConfig.Stream;
this.thread = new Thread(StreamReceiveLoop);
this.thread.IsBackground = true;
this.stopThread = false;
this.thread.Start();
return localEndPoint;
}
#endregion
#region ITransport Members
/// <summary>
/// get a bool value that indicates whether there is data received from transport.
/// </summary>
/// <exception cref="ObjectDisposedException">
/// thrown when this object is disposed.
/// </exception>
public bool IsDataAvailable
{
get
{
if (disposed)
{
throw new ObjectDisposedException("StreamTransport");
}
return this.packetCache.Count > 0 || this.buffer.Count > 0;
}
}
/// <summary>
/// add transport event to transport, TSD can invoke ExpectTransportEvent to get it.
/// </summary>
/// <param name="transportEvent">
/// a TransportEvent object that contains the event to add to the queue
/// </param>
/// <exception cref="ObjectDisposedException">
/// thrown when this object is disposed.
/// </exception>
/// <exception cref="ArgumentNullException">
/// thrown when transportEvent is null.
/// </exception>
public void AddEvent(TransportEvent transportEvent)
{
if (disposed)
{
throw new ObjectDisposedException("StreamTransport");
}
if (transportEvent == null)
{
throw new ArgumentNullException("transportEvent");
}
this.eventQueue.Enqueue(transportEvent);
}
/// <summary>
/// to update the config of transport at runtime.
/// </summary>
/// <param name="config">
/// a TransportConfig object that contains the config to update
/// </param>
/// <exception cref="ArgumentException">
/// thrown when transportConfig is not StreamTransport
/// </exception>
/// <exception cref="ObjectDisposedException">
/// thrown when this object is disposed.
/// </exception>
/// <exception cref="ArgumentNullException">
/// thrown when config is null.
/// </exception>
public void UpdateConfig(TransportConfig config)
{
if (disposed)
{
throw new ObjectDisposedException("StreamTransport");
}
if (config == null)
{
throw new ArgumentNullException("config");
}
buffer = new List<byte>();
StreamConfig theStreamConfig = config as StreamConfig;
if (theStreamConfig == null)
{
throw new ArgumentException("transportConfig must be StreamConfig", "config");
}
this.streamConfig = theStreamConfig;
// if the decoder is null, the instance has not initialized
// do not terminate the thread and return directly.
if (this.decoder == null || this.packetCache == null)
{
return;
}
#region update the underlayer stream.
// abort the blocked receive thread.
if (this.thread != null)
{
this.stopThread = true;
this.thread = null;
}
// reconnect to received data from new stream.
// if the stream is null, just stop the receiver of stream.
if (this.streamConfig.Stream != null)
{
this.Connect();
}
#endregion
}
/// <summary>
/// expect transport event from transport.<para/>
/// if event arrived and packet data buffer is empty, return event directly.<para/>
/// decode packet from packet data buffer, return packet if arrived, otherwise, return event.
/// </summary>
/// <param name="timeout">
/// a TimeSpan struct that specifies the timeout of waiting for a packet or event from the transport.
/// </param>
/// <returns>
/// a TransportEvent object that contains the expected event from transport.
/// </returns>
/// <exception cref="TimeoutException">
/// thrown when timeout to wait for packet coming.
/// </exception>
/// <exception cref="TimeoutException">
/// thrown when timeout to wait for event coming.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// thrown when this object is disposed.
/// </exception>
/// <exception cref="InvalidOperationException">
/// thrown when stream client is not connected, must invoke Connect() first.
/// </exception>
public TransportEvent ExpectTransportEvent(TimeSpan timeout)
{
if (disposed)
{
throw new ObjectDisposedException("StreamTransport");
}
if (this.thread == null)
{
throw new InvalidOperationException(
"stream client is not connected, must invoke Connect() first.");
}
// decode packet
StackPacket packet = this.ExpectPacket(timeout);
// if packet is decoded, return it.
if (packet != null)
{
return new TransportEvent(
EventType.ReceivedPacket, null, this.localEndPoint, packet);
}
// if no packet, and there is event coming, return event.
// set timeout to zero, must not wait for event coming.
return eventQueue.Dequeue(new TimeSpan());
}
#endregion
#region IDisconnectable Members
/// <summary>
/// disconnect from remote host.<para/>
/// the underlayer transport must be TcpClient, NetbiosClient, TcpServer or NetbiosServer.<para/>
/// client side will disconnect the connection to server.<para/>
/// server side will disconnect all client connection.
/// </summary>
/// <exception cref="ObjectDisposedException">
/// thrown when this object is disposed.
/// </exception>
/// <exception cref="InvalidOperationException">
/// thrown when stream client is not connected, must invoke Connect() first.
/// </exception>
/// <exception cref="InvalidOperationException">
/// thrown when the received thread does not initialize.
/// </exception>
public void Disconnect()
{
if (disposed)
{
throw new ObjectDisposedException("StreamTransport");
}
if (this.stream == null)
{
throw new InvalidOperationException(
"stream client is not connected, must invoke Connect() first.");
}
if (this.thread == null)
{
throw new InvalidOperationException("the received thread does not initialize.");
}
if (this.thread.IsAlive)
{
this.stopThread = true;
}
this.thread = null;
this.stream.Dispose();
this.stream = null;
}
/// <summary>
/// expect the server to disconnect<para/>
/// the underlayer transport must be TcpClient, NetbiosClient, TcpServer or NetbiosServer.<para/>
/// client side will expect the disconnection from server.<para/>
/// server side will expect the disconnection from any client.
/// </summary>
/// <param name="timeout">
/// a TimeSpan object that specifies the timeout for this operation.
/// </param>
/// <returns>
/// return an object that is disconnected. client return null.
/// </returns>
/// <exception cref="ObjectDisposedException">
/// thrown when this object is disposed.
/// </exception>
/// <exception cref="InvalidOperationException">
/// thrown when stream client is not connected, must invoke Connect() first.
/// </exception>
public object ExpectDisconnect(TimeSpan timeout)
{
if (disposed)
{
throw new ObjectDisposedException("StreamTransport");
}
if (this.stream == null)
{
throw new InvalidOperationException(
"stream client is not connected, must invoke Connect() first.");
}
this.eventQueue.Dequeue(timeout, FilterDisconnected);
return this.localEndPoint;
}
#endregion
#region ISource Members
/// <summary>
/// Send a packet over the transport.<para/>
/// the underlayer transport must be TcpClient, Stream or NetbiosClient.
/// </summary>
/// <param name="packet">
/// a StackPacket object that contains the packet to send to target.
/// </param>
/// <exception cref="ArgumentNullException">
/// thrown when packet is null
/// </exception>
/// <exception cref="ObjectDisposedException">
/// thrown when this object is disposed.
/// </exception>
/// <exception cref="InvalidOperationException">
/// thrown when stream client is not connected, must invoke Connect() first.
/// </exception>
public void SendPacket(StackPacket packet)
{
if (disposed)
{
throw new ObjectDisposedException("StreamTransport");
}
if (packet == null)
{
throw new ArgumentNullException("packet");
}
this.SendBytes(packet.ToBytes());
}
/// <summary>
/// Send an arbitrary message over the transport.<para/>
/// the underlayer transport must be TcpClient, Stream or NetbiosClient.
/// </summary>
/// <param name="message">
/// a byte array that contains the data to send to target.
/// </param>
/// <exception cref="ArgumentNullException">
/// thrown when message is null
/// </exception>
/// <exception cref="ObjectDisposedException">
/// thrown when this object is disposed.
/// </exception>
/// <exception cref="InvalidOperationException">
/// thrown when stream client is not connected, must invoke Connect() first.
/// </exception>
public void SendBytes(byte[] message)
{
if (disposed)
{
throw new ObjectDisposedException("StreamTransport");
}
if (message == null)
{
throw new ArgumentNullException("message");
}
if (this.stream == null)
{
throw new InvalidOperationException(
"stream client is not connected, must invoke Connect() first.");
}
this.stream.Write(message, 0, message.Length);
}
/// <summary>
/// expect packet from transport.<para/>
/// the underlayer transport must be TcpClient, Stream or NetbiosClient.
/// </summary>
/// <param name="timeout">
/// a TimeSpan object that indicates the timeout to expect event.
/// </param>
/// <returns>
/// a StackPacket object that specifies the received packet.
/// </returns>
/// <exception cref="ObjectDisposedException">
/// thrown when this object is disposed.
/// </exception>
/// <exception cref="InvalidOperationException">
/// thrown when stream client is not connected, must invoke Connect() first.
/// </exception>
public StackPacket ExpectPacket(TimeSpan timeout)
{
if (disposed)
{
throw new ObjectDisposedException("StreamTransport");
}
if (this.stream == null)
{
throw new InvalidOperationException(
"stream client is not connected, must invoke Connect() first.");
}
StackPacket packet = packetCache.Dequeue(timeout);
return packet;
}
#endregion
#region IDisposable Members
/// <summary>
/// the dispose flags
/// </summary>
private bool disposed;
/// <summary>
/// Release the managed and unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
// Take this object out of the finalization queue of the GC:
GC.SuppressFinalize(this);
}
/// <summary>
/// Release resources.
/// </summary>
/// <param name = "disposing">
/// If disposing equals true, Managed and unmanaged resources are disposed. if false, Only unmanaged resources
/// can be disposed.
/// </param>
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
// If disposing equals true, dispose all managed and unmanaged resources.
if (disposing)
{
// Free managed resources & other reference types:
if (this.thread != null)
{
if(this.thread.IsAlive)
{
this.thread.Abort();
this.thread.Join();
}
this.thread = null;
}
if (this.stream != null)
{
this.stream.Dispose();
this.stream = null;
}
if (this.eventQueue != null)
{
// the SyncFilterQueue may throw exception, donot arise exception.
this.eventQueue.Dispose();
this.eventQueue = null;
}
if (this.packetCache != null)
{
this.packetCache.Dispose();
this.packetCache = null;
}
}
// Call the appropriate methods to clean up unmanaged resources.
// If disposing is false, only the following code is executed:
this.disposed = true;
}
}
/// <summary>
/// finalizer
/// </summary>
~RdpbcgrClientTransportStack()
{
Dispose(false);
}
#endregion
#region Private Methods
/// <summary>
/// the method to receive message from server.
/// </summary>
private void StreamReceiveLoop()
{
try
{
this.StreamReceiveLoopImp();
}
catch
{
// Throw no exception
}
}
/// <summary>
/// the method to receive message from server.
/// </summary>
private void StreamReceiveLoopImp()
{
byte[] data = new byte[this.streamConfig.BufferSize];
NetworkStream networkStream = this.stream as NetworkStream;
while (!this.stopThread)
{
// if the underlayer stream is network stream, using the unblock mode.
if (networkStream != null)
{
// wait for the exit event or stream data is available.
while (!this.stopThread && !networkStream.DataAvailable)
{
Thread.Sleep(MilliSecondsToWaitStreamDataAvailable);
}
// if is exit event, do not read and exit.
if (this.stopThread)
{
break;
}
}
int receivedLength = 0;
// read event
try
{
// received data from server.
receivedLength = this.stream.Read(data, 0, data.Length);
// if the server close the stream, return.
if (receivedLength == 0)
{
this.AddEvent(new TransportEvent(
EventType.Disconnected, null, this.localEndPoint, null));
break;
}
this.buffer.AddRange(ArrayUtility.SubArray<byte>(data, 0, receivedLength));
int expectedLength = 0;
int consumedLength = 0;
StackPacket[] packets = decoder(localEndPoint, buffer.ToArray(), out consumedLength, out expectedLength);
while (packets != null)
{
foreach(StackPacket packet in packets)
{
packetCache.Enqueue(packet);
}
if (consumedLength > 0)
{
buffer.RemoveRange(0, consumedLength);
}
packets = decoder(localEndPoint, buffer.ToArray(), out consumedLength, out expectedLength);
}
}
catch (Exception ex)
{
// handle exception event, return.
this.AddEvent(new TransportEvent(
EventType.Exception, null, this.localEndPoint, ex));
throw;
}
}
}
private bool FilterDisconnected(TransportEvent obj)
{
if (obj != null && obj.EventType == EventType.Disconnected)
{
return true;
}
return false;
}
#endregion
}
}
| |
/*
'===============================================================================
' Generated From - CSharp_dOOdads_View.vbgen
'
' The supporting base class SqlClientEntity is in the
' Architecture directory in "dOOdads".
'===============================================================================
*/
// Generated by MyGeneration Version # (1.0.0.4)
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Collections.Specialized;
using MyGeneration.dOOdads;
namespace dOOdad_Demo
{
public class Invoices : SqlClientEntity
{
public Invoices()
{
this.QuerySource = "Invoices";
this.MappingName = "Invoices";
}
//=================================================================
// public Function LoadAll() As Boolean
//=================================================================
// Loads all of the records in the database, and sets the currentRow to the first row
//=================================================================
public bool LoadAll()
{
return base.Query.Load();
}
public override void FlushData()
{
this._whereClause = null;
base.FlushData();
}
#region Parameters
protected class Parameters
{
public static SqlParameter ShipName
{
get
{
return new SqlParameter("@ShipName", SqlDbType.NVarChar, 40);
}
}
public static SqlParameter ShipAddress
{
get
{
return new SqlParameter("@ShipAddress", SqlDbType.NVarChar, 60);
}
}
public static SqlParameter ShipCity
{
get
{
return new SqlParameter("@ShipCity", SqlDbType.NVarChar, 15);
}
}
public static SqlParameter ShipRegion
{
get
{
return new SqlParameter("@ShipRegion", SqlDbType.NVarChar, 15);
}
}
public static SqlParameter ShipPostalCode
{
get
{
return new SqlParameter("@ShipPostalCode", SqlDbType.NVarChar, 10);
}
}
public static SqlParameter ShipCountry
{
get
{
return new SqlParameter("@ShipCountry", SqlDbType.NVarChar, 15);
}
}
public static SqlParameter CustomerID
{
get
{
return new SqlParameter("@CustomerID", SqlDbType.NChar, 5);
}
}
public static SqlParameter CustomerName
{
get
{
return new SqlParameter("@CustomerName", SqlDbType.NVarChar, 40);
}
}
public static SqlParameter Address
{
get
{
return new SqlParameter("@Address", SqlDbType.NVarChar, 60);
}
}
public static SqlParameter City
{
get
{
return new SqlParameter("@City", SqlDbType.NVarChar, 15);
}
}
public static SqlParameter Region
{
get
{
return new SqlParameter("@Region", SqlDbType.NVarChar, 15);
}
}
public static SqlParameter PostalCode
{
get
{
return new SqlParameter("@PostalCode", SqlDbType.NVarChar, 10);
}
}
public static SqlParameter Country
{
get
{
return new SqlParameter("@Country", SqlDbType.NVarChar, 15);
}
}
public static SqlParameter Salesperson
{
get
{
return new SqlParameter("@Salesperson", SqlDbType.NVarChar, 31);
}
}
public static SqlParameter OrderID
{
get
{
return new SqlParameter("@OrderID", SqlDbType.Int, 0);
}
}
public static SqlParameter OrderDate
{
get
{
return new SqlParameter("@OrderDate", SqlDbType.DateTime, 0);
}
}
public static SqlParameter RequiredDate
{
get
{
return new SqlParameter("@RequiredDate", SqlDbType.DateTime, 0);
}
}
public static SqlParameter ShippedDate
{
get
{
return new SqlParameter("@ShippedDate", SqlDbType.DateTime, 0);
}
}
public static SqlParameter ShipperName
{
get
{
return new SqlParameter("@ShipperName", SqlDbType.NVarChar, 40);
}
}
public static SqlParameter ProductID
{
get
{
return new SqlParameter("@ProductID", SqlDbType.Int, 0);
}
}
public static SqlParameter ProductName
{
get
{
return new SqlParameter("@ProductName", SqlDbType.NVarChar, 40);
}
}
public static SqlParameter UnitPrice
{
get
{
return new SqlParameter("@UnitPrice", SqlDbType.Money, 0);
}
}
public static SqlParameter Quantity
{
get
{
return new SqlParameter("@Quantity", SqlDbType.SmallInt, 0);
}
}
public static SqlParameter Discount
{
get
{
return new SqlParameter("@Discount", SqlDbType.Real, 0);
}
}
public static SqlParameter ExtendedPrice
{
get
{
return new SqlParameter("@ExtendedPrice", SqlDbType.Money, 0);
}
}
public static SqlParameter Freight
{
get
{
return new SqlParameter("@Freight", SqlDbType.Money, 0);
}
}
}
#endregion
#region ColumnNames
public class ColumnNames
{
public const string ShipName = "ShipName";
public const string ShipAddress = "ShipAddress";
public const string ShipCity = "ShipCity";
public const string ShipRegion = "ShipRegion";
public const string ShipPostalCode = "ShipPostalCode";
public const string ShipCountry = "ShipCountry";
public const string CustomerID = "CustomerID";
public const string CustomerName = "CustomerName";
public const string Address = "Address";
public const string City = "City";
public const string Region = "Region";
public const string PostalCode = "PostalCode";
public const string Country = "Country";
public const string Salesperson = "Salesperson";
public const string OrderID = "OrderID";
public const string OrderDate = "OrderDate";
public const string RequiredDate = "RequiredDate";
public const string ShippedDate = "ShippedDate";
public const string ShipperName = "ShipperName";
public const string ProductID = "ProductID";
public const string ProductName = "ProductName";
public const string UnitPrice = "UnitPrice";
public const string Quantity = "Quantity";
public const string Discount = "Discount";
public const string ExtendedPrice = "ExtendedPrice";
public const string Freight = "Freight";
static public string ToPropertyName(string columnName)
{
if(ht == null)
{
ht = new Hashtable();
ht[ShipName] = Invoices.PropertyNames.ShipName;
ht[ShipAddress] = Invoices.PropertyNames.ShipAddress;
ht[ShipCity] = Invoices.PropertyNames.ShipCity;
ht[ShipRegion] = Invoices.PropertyNames.ShipRegion;
ht[ShipPostalCode] = Invoices.PropertyNames.ShipPostalCode;
ht[ShipCountry] = Invoices.PropertyNames.ShipCountry;
ht[CustomerID] = Invoices.PropertyNames.CustomerID;
ht[CustomerName] = Invoices.PropertyNames.CustomerName;
ht[Address] = Invoices.PropertyNames.Address;
ht[City] = Invoices.PropertyNames.City;
ht[Region] = Invoices.PropertyNames.Region;
ht[PostalCode] = Invoices.PropertyNames.PostalCode;
ht[Country] = Invoices.PropertyNames.Country;
ht[Salesperson] = Invoices.PropertyNames.Salesperson;
ht[OrderID] = Invoices.PropertyNames.OrderID;
ht[OrderDate] = Invoices.PropertyNames.OrderDate;
ht[RequiredDate] = Invoices.PropertyNames.RequiredDate;
ht[ShippedDate] = Invoices.PropertyNames.ShippedDate;
ht[ShipperName] = Invoices.PropertyNames.ShipperName;
ht[ProductID] = Invoices.PropertyNames.ProductID;
ht[ProductName] = Invoices.PropertyNames.ProductName;
ht[UnitPrice] = Invoices.PropertyNames.UnitPrice;
ht[Quantity] = Invoices.PropertyNames.Quantity;
ht[Discount] = Invoices.PropertyNames.Discount;
ht[ExtendedPrice] = Invoices.PropertyNames.ExtendedPrice;
ht[Freight] = Invoices.PropertyNames.Freight;
}
return (string)ht[columnName];
}
static private Hashtable ht = null;
}
#endregion
#region PropertyNames
public class PropertyNames
{
public const string ShipName = "ShipName";
public const string ShipAddress = "ShipAddress";
public const string ShipCity = "ShipCity";
public const string ShipRegion = "ShipRegion";
public const string ShipPostalCode = "ShipPostalCode";
public const string ShipCountry = "ShipCountry";
public const string CustomerID = "CustomerID";
public const string CustomerName = "CustomerName";
public const string Address = "Address";
public const string City = "City";
public const string Region = "Region";
public const string PostalCode = "PostalCode";
public const string Country = "Country";
public const string Salesperson = "Salesperson";
public const string OrderID = "OrderID";
public const string OrderDate = "OrderDate";
public const string RequiredDate = "RequiredDate";
public const string ShippedDate = "ShippedDate";
public const string ShipperName = "ShipperName";
public const string ProductID = "ProductID";
public const string ProductName = "ProductName";
public const string UnitPrice = "UnitPrice";
public const string Quantity = "Quantity";
public const string Discount = "Discount";
public const string ExtendedPrice = "ExtendedPrice";
public const string Freight = "Freight";
static public string ToColumnName(string propertyName)
{
if(ht == null)
{
ht = new Hashtable();
ht[ShipName] = Invoices.ColumnNames.ShipName;
ht[ShipAddress] = Invoices.ColumnNames.ShipAddress;
ht[ShipCity] = Invoices.ColumnNames.ShipCity;
ht[ShipRegion] = Invoices.ColumnNames.ShipRegion;
ht[ShipPostalCode] = Invoices.ColumnNames.ShipPostalCode;
ht[ShipCountry] = Invoices.ColumnNames.ShipCountry;
ht[CustomerID] = Invoices.ColumnNames.CustomerID;
ht[CustomerName] = Invoices.ColumnNames.CustomerName;
ht[Address] = Invoices.ColumnNames.Address;
ht[City] = Invoices.ColumnNames.City;
ht[Region] = Invoices.ColumnNames.Region;
ht[PostalCode] = Invoices.ColumnNames.PostalCode;
ht[Country] = Invoices.ColumnNames.Country;
ht[Salesperson] = Invoices.ColumnNames.Salesperson;
ht[OrderID] = Invoices.ColumnNames.OrderID;
ht[OrderDate] = Invoices.ColumnNames.OrderDate;
ht[RequiredDate] = Invoices.ColumnNames.RequiredDate;
ht[ShippedDate] = Invoices.ColumnNames.ShippedDate;
ht[ShipperName] = Invoices.ColumnNames.ShipperName;
ht[ProductID] = Invoices.ColumnNames.ProductID;
ht[ProductName] = Invoices.ColumnNames.ProductName;
ht[UnitPrice] = Invoices.ColumnNames.UnitPrice;
ht[Quantity] = Invoices.ColumnNames.Quantity;
ht[Discount] = Invoices.ColumnNames.Discount;
ht[ExtendedPrice] = Invoices.ColumnNames.ExtendedPrice;
ht[Freight] = Invoices.ColumnNames.Freight;
}
return (string)ht[propertyName];
}
static private Hashtable ht = null;
}
#endregion
#region StringPropertyNames
public class StringPropertyNames
{
public const string ShipName = "s_ShipName";
public const string ShipAddress = "s_ShipAddress";
public const string ShipCity = "s_ShipCity";
public const string ShipRegion = "s_ShipRegion";
public const string ShipPostalCode = "s_ShipPostalCode";
public const string ShipCountry = "s_ShipCountry";
public const string CustomerID = "s_CustomerID";
public const string CustomerName = "s_CustomerName";
public const string Address = "s_Address";
public const string City = "s_City";
public const string Region = "s_Region";
public const string PostalCode = "s_PostalCode";
public const string Country = "s_Country";
public const string Salesperson = "s_Salesperson";
public const string OrderID = "s_OrderID";
public const string OrderDate = "s_OrderDate";
public const string RequiredDate = "s_RequiredDate";
public const string ShippedDate = "s_ShippedDate";
public const string ShipperName = "s_ShipperName";
public const string ProductID = "s_ProductID";
public const string ProductName = "s_ProductName";
public const string UnitPrice = "s_UnitPrice";
public const string Quantity = "s_Quantity";
public const string Discount = "s_Discount";
public const string ExtendedPrice = "s_ExtendedPrice";
public const string Freight = "s_Freight";
}
#endregion
#region Properties
public virtual string ShipName
{
get
{
return base.Getstring(ColumnNames.ShipName);
}
set
{
base.Setstring(ColumnNames.ShipName, value);
}
}
public virtual string ShipAddress
{
get
{
return base.Getstring(ColumnNames.ShipAddress);
}
set
{
base.Setstring(ColumnNames.ShipAddress, value);
}
}
public virtual string ShipCity
{
get
{
return base.Getstring(ColumnNames.ShipCity);
}
set
{
base.Setstring(ColumnNames.ShipCity, value);
}
}
public virtual string ShipRegion
{
get
{
return base.Getstring(ColumnNames.ShipRegion);
}
set
{
base.Setstring(ColumnNames.ShipRegion, value);
}
}
public virtual string ShipPostalCode
{
get
{
return base.Getstring(ColumnNames.ShipPostalCode);
}
set
{
base.Setstring(ColumnNames.ShipPostalCode, value);
}
}
public virtual string ShipCountry
{
get
{
return base.Getstring(ColumnNames.ShipCountry);
}
set
{
base.Setstring(ColumnNames.ShipCountry, value);
}
}
public virtual string CustomerID
{
get
{
return base.Getstring(ColumnNames.CustomerID);
}
set
{
base.Setstring(ColumnNames.CustomerID, value);
}
}
public virtual string CustomerName
{
get
{
return base.Getstring(ColumnNames.CustomerName);
}
set
{
base.Setstring(ColumnNames.CustomerName, value);
}
}
public virtual string Address
{
get
{
return base.Getstring(ColumnNames.Address);
}
set
{
base.Setstring(ColumnNames.Address, value);
}
}
public virtual string City
{
get
{
return base.Getstring(ColumnNames.City);
}
set
{
base.Setstring(ColumnNames.City, value);
}
}
public virtual string Region
{
get
{
return base.Getstring(ColumnNames.Region);
}
set
{
base.Setstring(ColumnNames.Region, value);
}
}
public virtual string PostalCode
{
get
{
return base.Getstring(ColumnNames.PostalCode);
}
set
{
base.Setstring(ColumnNames.PostalCode, value);
}
}
public virtual string Country
{
get
{
return base.Getstring(ColumnNames.Country);
}
set
{
base.Setstring(ColumnNames.Country, value);
}
}
public virtual string Salesperson
{
get
{
return base.Getstring(ColumnNames.Salesperson);
}
set
{
base.Setstring(ColumnNames.Salesperson, value);
}
}
public virtual int OrderID
{
get
{
return base.Getint(ColumnNames.OrderID);
}
set
{
base.Setint(ColumnNames.OrderID, value);
}
}
public virtual DateTime OrderDate
{
get
{
return base.GetDateTime(ColumnNames.OrderDate);
}
set
{
base.SetDateTime(ColumnNames.OrderDate, value);
}
}
public virtual DateTime RequiredDate
{
get
{
return base.GetDateTime(ColumnNames.RequiredDate);
}
set
{
base.SetDateTime(ColumnNames.RequiredDate, value);
}
}
public virtual DateTime ShippedDate
{
get
{
return base.GetDateTime(ColumnNames.ShippedDate);
}
set
{
base.SetDateTime(ColumnNames.ShippedDate, value);
}
}
public virtual string ShipperName
{
get
{
return base.Getstring(ColumnNames.ShipperName);
}
set
{
base.Setstring(ColumnNames.ShipperName, value);
}
}
public virtual int ProductID
{
get
{
return base.Getint(ColumnNames.ProductID);
}
set
{
base.Setint(ColumnNames.ProductID, value);
}
}
public virtual string ProductName
{
get
{
return base.Getstring(ColumnNames.ProductName);
}
set
{
base.Setstring(ColumnNames.ProductName, value);
}
}
public virtual decimal UnitPrice
{
get
{
return base.Getdecimal(ColumnNames.UnitPrice);
}
set
{
base.Setdecimal(ColumnNames.UnitPrice, value);
}
}
public virtual short Quantity
{
get
{
return base.Getshort(ColumnNames.Quantity);
}
set
{
base.Setshort(ColumnNames.Quantity, value);
}
}
public virtual float Discount
{
get
{
return base.Getfloat(ColumnNames.Discount);
}
set
{
base.Setfloat(ColumnNames.Discount, value);
}
}
public virtual decimal ExtendedPrice
{
get
{
return base.Getdecimal(ColumnNames.ExtendedPrice);
}
set
{
base.Setdecimal(ColumnNames.ExtendedPrice, value);
}
}
public virtual decimal Freight
{
get
{
return base.Getdecimal(ColumnNames.Freight);
}
set
{
base.Setdecimal(ColumnNames.Freight, value);
}
}
#endregion
#region String Properties
public virtual string s_ShipName
{
get
{
return this.IsColumnNull(ColumnNames.ShipName) ? string.Empty : base.GetstringAsString(ColumnNames.ShipName);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.ShipName);
else
this.ShipName = base.SetstringAsString(ColumnNames.ShipName, value);
}
}
public virtual string s_ShipAddress
{
get
{
return this.IsColumnNull(ColumnNames.ShipAddress) ? string.Empty : base.GetstringAsString(ColumnNames.ShipAddress);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.ShipAddress);
else
this.ShipAddress = base.SetstringAsString(ColumnNames.ShipAddress, value);
}
}
public virtual string s_ShipCity
{
get
{
return this.IsColumnNull(ColumnNames.ShipCity) ? string.Empty : base.GetstringAsString(ColumnNames.ShipCity);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.ShipCity);
else
this.ShipCity = base.SetstringAsString(ColumnNames.ShipCity, value);
}
}
public virtual string s_ShipRegion
{
get
{
return this.IsColumnNull(ColumnNames.ShipRegion) ? string.Empty : base.GetstringAsString(ColumnNames.ShipRegion);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.ShipRegion);
else
this.ShipRegion = base.SetstringAsString(ColumnNames.ShipRegion, value);
}
}
public virtual string s_ShipPostalCode
{
get
{
return this.IsColumnNull(ColumnNames.ShipPostalCode) ? string.Empty : base.GetstringAsString(ColumnNames.ShipPostalCode);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.ShipPostalCode);
else
this.ShipPostalCode = base.SetstringAsString(ColumnNames.ShipPostalCode, value);
}
}
public virtual string s_ShipCountry
{
get
{
return this.IsColumnNull(ColumnNames.ShipCountry) ? string.Empty : base.GetstringAsString(ColumnNames.ShipCountry);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.ShipCountry);
else
this.ShipCountry = base.SetstringAsString(ColumnNames.ShipCountry, value);
}
}
public virtual string s_CustomerID
{
get
{
return this.IsColumnNull(ColumnNames.CustomerID) ? string.Empty : base.GetstringAsString(ColumnNames.CustomerID);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.CustomerID);
else
this.CustomerID = base.SetstringAsString(ColumnNames.CustomerID, value);
}
}
public virtual string s_CustomerName
{
get
{
return this.IsColumnNull(ColumnNames.CustomerName) ? string.Empty : base.GetstringAsString(ColumnNames.CustomerName);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.CustomerName);
else
this.CustomerName = base.SetstringAsString(ColumnNames.CustomerName, value);
}
}
public virtual string s_Address
{
get
{
return this.IsColumnNull(ColumnNames.Address) ? string.Empty : base.GetstringAsString(ColumnNames.Address);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.Address);
else
this.Address = base.SetstringAsString(ColumnNames.Address, value);
}
}
public virtual string s_City
{
get
{
return this.IsColumnNull(ColumnNames.City) ? string.Empty : base.GetstringAsString(ColumnNames.City);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.City);
else
this.City = base.SetstringAsString(ColumnNames.City, value);
}
}
public virtual string s_Region
{
get
{
return this.IsColumnNull(ColumnNames.Region) ? string.Empty : base.GetstringAsString(ColumnNames.Region);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.Region);
else
this.Region = base.SetstringAsString(ColumnNames.Region, value);
}
}
public virtual string s_PostalCode
{
get
{
return this.IsColumnNull(ColumnNames.PostalCode) ? string.Empty : base.GetstringAsString(ColumnNames.PostalCode);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.PostalCode);
else
this.PostalCode = base.SetstringAsString(ColumnNames.PostalCode, value);
}
}
public virtual string s_Country
{
get
{
return this.IsColumnNull(ColumnNames.Country) ? string.Empty : base.GetstringAsString(ColumnNames.Country);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.Country);
else
this.Country = base.SetstringAsString(ColumnNames.Country, value);
}
}
public virtual string s_Salesperson
{
get
{
return this.IsColumnNull(ColumnNames.Salesperson) ? string.Empty : base.GetstringAsString(ColumnNames.Salesperson);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.Salesperson);
else
this.Salesperson = base.SetstringAsString(ColumnNames.Salesperson, value);
}
}
public virtual string s_OrderID
{
get
{
return this.IsColumnNull(ColumnNames.OrderID) ? string.Empty : base.GetintAsString(ColumnNames.OrderID);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.OrderID);
else
this.OrderID = base.SetintAsString(ColumnNames.OrderID, value);
}
}
public virtual string s_OrderDate
{
get
{
return this.IsColumnNull(ColumnNames.OrderDate) ? string.Empty : base.GetDateTimeAsString(ColumnNames.OrderDate);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.OrderDate);
else
this.OrderDate = base.SetDateTimeAsString(ColumnNames.OrderDate, value);
}
}
public virtual string s_RequiredDate
{
get
{
return this.IsColumnNull(ColumnNames.RequiredDate) ? string.Empty : base.GetDateTimeAsString(ColumnNames.RequiredDate);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.RequiredDate);
else
this.RequiredDate = base.SetDateTimeAsString(ColumnNames.RequiredDate, value);
}
}
public virtual string s_ShippedDate
{
get
{
return this.IsColumnNull(ColumnNames.ShippedDate) ? string.Empty : base.GetDateTimeAsString(ColumnNames.ShippedDate);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.ShippedDate);
else
this.ShippedDate = base.SetDateTimeAsString(ColumnNames.ShippedDate, value);
}
}
public virtual string s_ShipperName
{
get
{
return this.IsColumnNull(ColumnNames.ShipperName) ? string.Empty : base.GetstringAsString(ColumnNames.ShipperName);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.ShipperName);
else
this.ShipperName = base.SetstringAsString(ColumnNames.ShipperName, value);
}
}
public virtual string s_ProductID
{
get
{
return this.IsColumnNull(ColumnNames.ProductID) ? string.Empty : base.GetintAsString(ColumnNames.ProductID);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.ProductID);
else
this.ProductID = base.SetintAsString(ColumnNames.ProductID, value);
}
}
public virtual string s_ProductName
{
get
{
return this.IsColumnNull(ColumnNames.ProductName) ? string.Empty : base.GetstringAsString(ColumnNames.ProductName);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.ProductName);
else
this.ProductName = base.SetstringAsString(ColumnNames.ProductName, value);
}
}
public virtual string s_UnitPrice
{
get
{
return this.IsColumnNull(ColumnNames.UnitPrice) ? string.Empty : base.GetdecimalAsString(ColumnNames.UnitPrice);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.UnitPrice);
else
this.UnitPrice = base.SetdecimalAsString(ColumnNames.UnitPrice, value);
}
}
public virtual string s_Quantity
{
get
{
return this.IsColumnNull(ColumnNames.Quantity) ? string.Empty : base.GetshortAsString(ColumnNames.Quantity);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.Quantity);
else
this.Quantity = base.SetshortAsString(ColumnNames.Quantity, value);
}
}
public virtual string s_Discount
{
get
{
return this.IsColumnNull(ColumnNames.Discount) ? string.Empty : base.GetfloatAsString(ColumnNames.Discount);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.Discount);
else
this.Discount = base.SetfloatAsString(ColumnNames.Discount, value);
}
}
public virtual string s_ExtendedPrice
{
get
{
return this.IsColumnNull(ColumnNames.ExtendedPrice) ? string.Empty : base.GetdecimalAsString(ColumnNames.ExtendedPrice);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.ExtendedPrice);
else
this.ExtendedPrice = base.SetdecimalAsString(ColumnNames.ExtendedPrice, value);
}
}
public virtual string s_Freight
{
get
{
return this.IsColumnNull(ColumnNames.Freight) ? string.Empty : base.GetdecimalAsString(ColumnNames.Freight);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.Freight);
else
this.Freight = base.SetdecimalAsString(ColumnNames.Freight, value);
}
}
#endregion
#region Where Clause
public class WhereClause
{
public WhereClause(BusinessEntity entity)
{
this._entity = entity;
}
public TearOffWhereParameter TearOff
{
get
{
if(_tearOff == null)
{
_tearOff = new TearOffWhereParameter(this);
}
return _tearOff;
}
}
#region TearOff's
public class TearOffWhereParameter
{
public TearOffWhereParameter(WhereClause clause)
{
this._clause = clause;
}
public WhereParameter ShipName
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.ShipName, Parameters.ShipName);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter ShipAddress
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.ShipAddress, Parameters.ShipAddress);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter ShipCity
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.ShipCity, Parameters.ShipCity);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter ShipRegion
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.ShipRegion, Parameters.ShipRegion);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter ShipPostalCode
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.ShipPostalCode, Parameters.ShipPostalCode);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter ShipCountry
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.ShipCountry, Parameters.ShipCountry);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter CustomerID
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.CustomerID, Parameters.CustomerID);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter CustomerName
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.CustomerName, Parameters.CustomerName);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter Address
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.Address, Parameters.Address);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter City
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.City, Parameters.City);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter Region
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.Region, Parameters.Region);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter PostalCode
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.PostalCode, Parameters.PostalCode);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter Country
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.Country, Parameters.Country);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter Salesperson
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.Salesperson, Parameters.Salesperson);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter OrderID
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.OrderID, Parameters.OrderID);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter OrderDate
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.OrderDate, Parameters.OrderDate);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter RequiredDate
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.RequiredDate, Parameters.RequiredDate);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter ShippedDate
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.ShippedDate, Parameters.ShippedDate);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter ShipperName
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.ShipperName, Parameters.ShipperName);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter ProductID
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.ProductID, Parameters.ProductID);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter ProductName
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.ProductName, Parameters.ProductName);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter UnitPrice
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.UnitPrice, Parameters.UnitPrice);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter Quantity
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.Quantity, Parameters.Quantity);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter Discount
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.Discount, Parameters.Discount);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter ExtendedPrice
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.ExtendedPrice, Parameters.ExtendedPrice);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter Freight
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.Freight, Parameters.Freight);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
private WhereClause _clause;
}
#endregion
public WhereParameter ShipName
{
get
{
if(_ShipName_W == null)
{
_ShipName_W = TearOff.ShipName;
}
return _ShipName_W;
}
}
public WhereParameter ShipAddress
{
get
{
if(_ShipAddress_W == null)
{
_ShipAddress_W = TearOff.ShipAddress;
}
return _ShipAddress_W;
}
}
public WhereParameter ShipCity
{
get
{
if(_ShipCity_W == null)
{
_ShipCity_W = TearOff.ShipCity;
}
return _ShipCity_W;
}
}
public WhereParameter ShipRegion
{
get
{
if(_ShipRegion_W == null)
{
_ShipRegion_W = TearOff.ShipRegion;
}
return _ShipRegion_W;
}
}
public WhereParameter ShipPostalCode
{
get
{
if(_ShipPostalCode_W == null)
{
_ShipPostalCode_W = TearOff.ShipPostalCode;
}
return _ShipPostalCode_W;
}
}
public WhereParameter ShipCountry
{
get
{
if(_ShipCountry_W == null)
{
_ShipCountry_W = TearOff.ShipCountry;
}
return _ShipCountry_W;
}
}
public WhereParameter CustomerID
{
get
{
if(_CustomerID_W == null)
{
_CustomerID_W = TearOff.CustomerID;
}
return _CustomerID_W;
}
}
public WhereParameter CustomerName
{
get
{
if(_CustomerName_W == null)
{
_CustomerName_W = TearOff.CustomerName;
}
return _CustomerName_W;
}
}
public WhereParameter Address
{
get
{
if(_Address_W == null)
{
_Address_W = TearOff.Address;
}
return _Address_W;
}
}
public WhereParameter City
{
get
{
if(_City_W == null)
{
_City_W = TearOff.City;
}
return _City_W;
}
}
public WhereParameter Region
{
get
{
if(_Region_W == null)
{
_Region_W = TearOff.Region;
}
return _Region_W;
}
}
public WhereParameter PostalCode
{
get
{
if(_PostalCode_W == null)
{
_PostalCode_W = TearOff.PostalCode;
}
return _PostalCode_W;
}
}
public WhereParameter Country
{
get
{
if(_Country_W == null)
{
_Country_W = TearOff.Country;
}
return _Country_W;
}
}
public WhereParameter Salesperson
{
get
{
if(_Salesperson_W == null)
{
_Salesperson_W = TearOff.Salesperson;
}
return _Salesperson_W;
}
}
public WhereParameter OrderID
{
get
{
if(_OrderID_W == null)
{
_OrderID_W = TearOff.OrderID;
}
return _OrderID_W;
}
}
public WhereParameter OrderDate
{
get
{
if(_OrderDate_W == null)
{
_OrderDate_W = TearOff.OrderDate;
}
return _OrderDate_W;
}
}
public WhereParameter RequiredDate
{
get
{
if(_RequiredDate_W == null)
{
_RequiredDate_W = TearOff.RequiredDate;
}
return _RequiredDate_W;
}
}
public WhereParameter ShippedDate
{
get
{
if(_ShippedDate_W == null)
{
_ShippedDate_W = TearOff.ShippedDate;
}
return _ShippedDate_W;
}
}
public WhereParameter ShipperName
{
get
{
if(_ShipperName_W == null)
{
_ShipperName_W = TearOff.ShipperName;
}
return _ShipperName_W;
}
}
public WhereParameter ProductID
{
get
{
if(_ProductID_W == null)
{
_ProductID_W = TearOff.ProductID;
}
return _ProductID_W;
}
}
public WhereParameter ProductName
{
get
{
if(_ProductName_W == null)
{
_ProductName_W = TearOff.ProductName;
}
return _ProductName_W;
}
}
public WhereParameter UnitPrice
{
get
{
if(_UnitPrice_W == null)
{
_UnitPrice_W = TearOff.UnitPrice;
}
return _UnitPrice_W;
}
}
public WhereParameter Quantity
{
get
{
if(_Quantity_W == null)
{
_Quantity_W = TearOff.Quantity;
}
return _Quantity_W;
}
}
public WhereParameter Discount
{
get
{
if(_Discount_W == null)
{
_Discount_W = TearOff.Discount;
}
return _Discount_W;
}
}
public WhereParameter ExtendedPrice
{
get
{
if(_ExtendedPrice_W == null)
{
_ExtendedPrice_W = TearOff.ExtendedPrice;
}
return _ExtendedPrice_W;
}
}
public WhereParameter Freight
{
get
{
if(_Freight_W == null)
{
_Freight_W = TearOff.Freight;
}
return _Freight_W;
}
}
private WhereParameter _ShipName_W = null;
private WhereParameter _ShipAddress_W = null;
private WhereParameter _ShipCity_W = null;
private WhereParameter _ShipRegion_W = null;
private WhereParameter _ShipPostalCode_W = null;
private WhereParameter _ShipCountry_W = null;
private WhereParameter _CustomerID_W = null;
private WhereParameter _CustomerName_W = null;
private WhereParameter _Address_W = null;
private WhereParameter _City_W = null;
private WhereParameter _Region_W = null;
private WhereParameter _PostalCode_W = null;
private WhereParameter _Country_W = null;
private WhereParameter _Salesperson_W = null;
private WhereParameter _OrderID_W = null;
private WhereParameter _OrderDate_W = null;
private WhereParameter _RequiredDate_W = null;
private WhereParameter _ShippedDate_W = null;
private WhereParameter _ShipperName_W = null;
private WhereParameter _ProductID_W = null;
private WhereParameter _ProductName_W = null;
private WhereParameter _UnitPrice_W = null;
private WhereParameter _Quantity_W = null;
private WhereParameter _Discount_W = null;
private WhereParameter _ExtendedPrice_W = null;
private WhereParameter _Freight_W = null;
public void WhereClauseReset()
{
_ShipName_W = null;
_ShipAddress_W = null;
_ShipCity_W = null;
_ShipRegion_W = null;
_ShipPostalCode_W = null;
_ShipCountry_W = null;
_CustomerID_W = null;
_CustomerName_W = null;
_Address_W = null;
_City_W = null;
_Region_W = null;
_PostalCode_W = null;
_Country_W = null;
_Salesperson_W = null;
_OrderID_W = null;
_OrderDate_W = null;
_RequiredDate_W = null;
_ShippedDate_W = null;
_ShipperName_W = null;
_ProductID_W = null;
_ProductName_W = null;
_UnitPrice_W = null;
_Quantity_W = null;
_Discount_W = null;
_ExtendedPrice_W = null;
_Freight_W = null;
this._entity.Query.FlushWhereParameters();
}
private BusinessEntity _entity;
private TearOffWhereParameter _tearOff;
}
public WhereClause Where
{
get
{
if(_whereClause == null)
{
_whereClause = new WhereClause(this);
}
return _whereClause;
}
}
private WhereClause _whereClause = null;
#endregion
protected override IDbCommand GetInsertCommand()
{
return null;
}
protected override IDbCommand GetUpdateCommand()
{
return null;
}
protected override IDbCommand GetDeleteCommand()
{
return null;
}
}
}
| |
//// Copyright (c) .NET Foundation. All rights reserved.
///Licensed under the MIT license. See LICENSE file in the project root for details.
//
//#define DEBUG_PHOTOMAIL
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Windows.Forms;
using mshtml;
using OpenLiveWriter.Mail;
using OpenLiveWriter.BlogClient;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.CoreServices.Diagnostics;
using OpenLiveWriter.Extensibility.BlogClient;
using OpenLiveWriter.HtmlEditor;
using OpenLiveWriter.HtmlParser.Parser;
using OpenLiveWriter.Interop.Com;
using OpenLiveWriter.Interop.Com.Ribbon;
using OpenLiveWriter.Interop.Windows;
using OpenLiveWriter.Localization;
using OpenLiveWriter.Mshtml;
using OpenLiveWriter.Mshtml.Mshtml_Interop;
using OpenLiveWriter.PostEditor.Autoreplace;
using OpenLiveWriter.PostEditor.ContentSources;
using OpenLiveWriter.PostEditor.PostHtmlEditing;
using IDropTarget = OpenLiveWriter.Interop.Com.IDropTarget;
namespace OpenLiveWriter.PostEditor
{
[ClassInterface(ClassInterfaceType.None)]
[Guid("FC51FC7A-9BB1-4472-86E4-34911D298922")]
[ComVisible(true)]
public class ContentEditorFactory : IContentEditorFactory
{
private uint _globalSobitOptions;
#region IContentEditorFactory Members
private RedirectionLogger _logger;
public void Initialize(string registrySettingsPath, IContentEditorLogger logger, IContentTarget contentTarget, ISettingsProvider settingsProvider)
{
try
{
GlobalEditorOptions.Init(contentTarget, settingsProvider);
HtmlEditorControl.AllowCachedEditor();
Assembly assembly = Assembly.GetExecutingAssembly();
ApplicationEnvironment.Initialize(assembly, Path.GetDirectoryName(assembly.Location), registrySettingsPath, contentTarget.ProductName);
ContentSourceManager.Initialize(false);
Trace.Listeners.Clear();
if (logger != null)
{
_logger = new RedirectionLogger(logger);
Trace.Listeners.Add(_logger);
}
#if DEBUG
Trace.Listeners.Add(new DefaultTraceListener());
#endif
}
catch (Exception e)
{
Trace.Fail("Failed to initialize Shared Canvas: " + e);
Trace.Flush();
throw;
}
}
public void Shutdown()
{
HtmlEditorControl.DisposeCachedEditor();
TempFileManager.Instance.Dispose();
Trace.Listeners.Clear();
if (_logger != null)
_logger.Dispose();
}
public IContentEditor CreateEditor(IContentEditorSite contentEditorSite, IInternetSecurityManager internetSecurityManager, string wysiwygHtml, int dlControlFlags)
{
return new ContentEditorProxy(this, contentEditorSite, internetSecurityManager, wysiwygHtml, null, dlControlFlags);
}
public IContentEditor CreateEditorFromDraft(IContentEditorSite contentEditorSite, IInternetSecurityManager internetSecurityManager, string wysiwygHtml, string pathToDraftFile, int dlControlFlags)
{
return new ContentEditorProxy(this, contentEditorSite, internetSecurityManager, wysiwygHtml, null, pathToDraftFile, dlControlFlags);
}
public IContentEditor CreateEditorFromHtmlDocument(IContentEditorSite contentEditorSite, IInternetSecurityManager internetSecurityManager, IHTMLDocument2 htmlDocument, HtmlInsertOptions options, int dlControlFlags)
{
return new ContentEditorProxy(this, contentEditorSite, internetSecurityManager, htmlDocument, options, dlControlFlags, null, null);
}
public IContentEditor CreateEditorFromMoniker(IContentEditorSite contentEditorSite, IInternetSecurityManager internetSecurityManager, IMoniker moniker, uint codepage, HtmlInsertOptions options, string color, int dlControlFlags, string wpost)
{
codepage = EmailShim.GetCodepage(codepage);
string name;
string html = HTMLDocumentHelper.MonikerToString(moniker, codepage, out name);
if (CultureHelper.IsRtlCodepage(codepage))
{
EmailContentTarget target =
GlobalEditorOptions.ContentTarget as EmailContentTarget;
if (target != null)
{
target.EnableRtlMode();
}
}
if (string.IsNullOrEmpty(html))
html = "<html><body></body></html>";
html = EmailShim.GetContentHtml(name, html);
// Create a IHtmlDocument2 from the html which will then be loaded into the editor
IHTMLDocument2 htmlDocument;
htmlDocument = HTMLDocumentHelper.StringToHTMLDoc(html, name);
return new ContentEditorProxy(this, contentEditorSite, internetSecurityManager, htmlDocument, options, dlControlFlags, color, wpost);
}
public void SetSpellingOptions(uint sobitOptions)
{
_globalSobitOptions = sobitOptions;
if (GlobalSpellingOptionsChanged != null)
GlobalSpellingOptionsChanged(this, EventArgs.Empty);
}
#endregion
internal uint GlobalSpellingOptions
{
get
{
return _globalSobitOptions;
}
}
internal event EventHandler GlobalSpellingOptionsChanged;
#region IContentEditorFactory Members
public void DoPreloadWork()
{
ContentEditorProxy.ApplyInstalledCulture();
SimpleHtmlParser.Create();
BlogClientHelper.FormatUrl("", "", "", "");
ContentEditor contentEditor = new ContentEditor(null, new Panel(), null, new BlogPostHtmlEditorControl.BlogPostHtmlEditorSecurityManager(), new ContentEditorProxy.ContentEditorTemplateStrategy(), MshtmlOptions.DEFAULT_DLCTL);
contentEditor.Dispose();
}
#endregion
}
public class RedirectionLogger : TraceListener
{
public enum ContentEditorLoggingLevel
{
Log_Error = 0,
Log_Terse = 1,
Log_Verbose = 2,
Log_Blab = 4,
Log_Always = 6
};
private IContentEditorLogger _logger;
public RedirectionLogger(IContentEditorLogger logger)
{
_logger = logger;
}
public override void Write(string message)
{
WriteLine(message);
}
public override void WriteLine(string message)
{
WriteLine(message, null);
}
public override void WriteLine(string message, string category)
{
try
{
if (category == ErrText.FailText)
{
_logger.WriteLine(message, (int)ContentEditorLoggingLevel.Log_Error);
}
else
{
_logger.WriteLine(message, (int)ContentEditorLoggingLevel.Log_Blab);
}
}
catch (Exception)
{
// TODO: Explore our options here.
// IContentEditorLogger should not be throwing exceptions, but in the case that it does we do not want
// to make another Debug or Trace call because it could cause an infinite loop/stack overflow.
}
}
public override void Write(string message, string category)
{
WriteLine(message, category);
}
}
public class ContentEditorProxy : IContentEditor
{
private ContentEditor contentEditor;
private MainFrameWindowAdapter mainFrame;
private IBlogPostEditingContext context;
private Panel panel;
private ContentEditorAccountAdapter accountAdapter;
private IContentEditorSite _contentEditorSite;
public ContentEditorProxy(ContentEditorFactory factory, IContentEditorSite contentEditorSite, IInternetSecurityManager internetSecurityManager, string wysiwygHTML, string previewHTML, int dlControlFlags)
{
ContentEditorProxyCore(factory, contentEditorSite, internetSecurityManager, wysiwygHTML, previewHTML, new BlogPostEditingContext(ContentEditorAccountAdapter.AccountId, new BlogPost()), new ContentEditorTemplateStrategy(), dlControlFlags, null);
}
public ContentEditorProxy(ContentEditorFactory factory, IContentEditorSite contentEditorSite, IInternetSecurityManager internetSecurityManager, string wysiwygHTML, string previewHTML, string pathToFile, int dlControlFlags)
{
ContentEditorProxyCore(factory, contentEditorSite, internetSecurityManager, wysiwygHTML, previewHTML, PostEditorFile.GetExisting(new FileInfo(pathToFile)).Load(false), new ContentEditorTemplateStrategy(), dlControlFlags, null);
}
public ContentEditorProxy(ContentEditorFactory factory, IContentEditorSite contentEditorSite, IInternetSecurityManager internetSecurityManager, IHTMLDocument2 htmlDocument, HtmlInsertOptions options, int dlControlFlags, string color, string wpost)
{
string content = htmlDocument.body.innerHTML;
htmlDocument.body.innerHTML = "{post-body}";
string wysiwygHTML = HTMLDocumentHelper.HTMLDocToString(htmlDocument);
BlogPost documentToBeLoaded = null;
IBlogPostEditingContext editingContext = null;
if (string.IsNullOrEmpty(wpost) || !File.Exists(wpost))
{
documentToBeLoaded = new BlogPost();
editingContext = new BlogPostEditingContext(ContentEditorAccountAdapter.AccountId,
documentToBeLoaded);
}
else
{
PostEditorFile wpostxFile = PostEditorFile.GetExisting(new FileInfo(wpost));
editingContext = wpostxFile.Load(false);
editingContext.BlogPost.Contents = "";
}
if (!string.IsNullOrEmpty(content))
delayedInsertOperations.Enqueue(new DelayedInsert(content, options));
ContentEditorProxyCore(factory, contentEditorSite, internetSecurityManager, wysiwygHTML, null, editingContext, new ContentEditorTemplateStrategy(), dlControlFlags, color);
}
private class DelayedInsert
{
public readonly string Content;
public readonly HtmlInsertOptions Options;
public DelayedInsert(string content, HtmlInsertOptions options)
{
Content = content;
Options = options;
}
}
private Queue<DelayedInsert> delayedInsertOperations = new Queue<DelayedInsert>();
/// <summary>
/// Initializes the IContentEditor.
/// </summary>
/// <param name="factory"></param>
/// <param name="contentEditorSite"></param>
/// <param name="internetSecurityManager"></param>
/// <param name="wysiwygHTML"></param>
/// <param name="previewHTML"></param>
/// <param name="newEditingContext"></param>
/// <param name="templateStrategy"></param>
/// <param name="dlControlFlags">
/// For Mail, these flags should always include DLCTL_DLIMAGES | DLCTL_VIDEOS | DLCTL_BGSOUNDS so that local
/// images, videos and sounds are loaded. To block external content, it should also include
/// DLCTL_PRAGMA_NO_CACHE | DLCTL_FORCEOFFLINE | DLCTL_NO_CLIENTPULL so that external images are not loaded
/// and are displayed as a red X instead.
/// </param>
/// <param name="color"></param>
private void ContentEditorProxyCore(ContentEditorFactory factory, IContentEditorSite contentEditorSite, IInternetSecurityManager internetSecurityManager, string wysiwygHTML, string previewHTML, IBlogPostEditingContext newEditingContext, BlogPostHtmlEditorControl.TemplateStrategy templateStrategy, int dlControlFlags, string color)
{
try
{
Debug.Assert(contentEditorSite is IUIFramework, "IContentEditorSite must also implement IUIFramework");
Debug.Assert(contentEditorSite is IDropTarget, "IContentEditorSite must also implement IDropTarget");
ApplyInstalledCulture();
this.factory = factory;
_wysiwygHTML = wysiwygHTML;
_previewHTML = previewHTML;
_contentEditorSite = contentEditorSite;
IntPtr p = _contentEditorSite.GetWindowHandle();
WINDOWINFO info = new WINDOWINFO();
User32.GetWindowInfo(p, ref info);
panel = new Panel();
panel.Top = 0;
panel.Left = 0;
panel.Width = Math.Max(info.rcWindow.Width, 200);
panel.Height = Math.Max(info.rcWindow.Height, 200);
panel.CreateControl();
User32.SetParent(panel.Handle, p);
accountAdapter = new ContentEditorAccountAdapter();
mainFrame = new MainFrameWindowAdapter(p, panel, _contentEditorSite, accountAdapter.Id);
context = newEditingContext;
contentEditor = new ContentEditor(mainFrame, panel, mainFrame, internetSecurityManager, templateStrategy, dlControlFlags);
// Prevents asserts
contentEditor.DisableSpelling();
contentEditor.OnEditorAccountChanged(accountAdapter);
contentEditor.DocumentComplete += new EventHandler(blogPostHtmlEditor_DocumentComplete);
contentEditor.GotFocus += new EventHandler(contentEditor_GotFocus);
contentEditor.LostFocus += new EventHandler(contentEditor_LostFocus);
contentEditor.Initialize(context, accountAdapter, wysiwygHTML, previewHTML, false);
if (!string.IsNullOrEmpty(color))
{
contentEditor.IndentColor = color;
}
this.factory.GlobalSpellingOptionsChanged += GlobalSpellingOptionsChangedHandler;
}
catch (Exception ex)
{
// Something went wrong, make sure we don't reuse a cached editor
HtmlEditorControl.DisposeCachedEditor();
Trace.Fail(ex.ToString());
Trace.Flush();
throw;
}
}
private bool _inGotFocusHandler = false;
void contentEditor_GotFocus(object sender, EventArgs e)
{
_inGotFocusHandler = true;
_contentEditorSite.OnGotFocus();
_inGotFocusHandler = false;
}
void contentEditor_LostFocus(object sender, EventArgs e)
{
_contentEditorSite.OnLostFocus();
}
public static void ApplyInstalledCulture()
{
CultureHelper.ApplyUICulture(GlobalEditorOptions.GetSetting<string>(ContentEditorSetting.Language));
}
private bool _documentComplete = false;
void blogPostHtmlEditor_DocumentComplete(object sender, EventArgs e)
{
_documentComplete = true;
if (_editMode != null && _editMode.HasValue)
{
EditingMode mode = _editMode.Value;
_editMode = null;
ChangeView(mode);
return;
}
while (delayedInsertOperations.Count > 0)
{
DelayedInsert insert = delayedInsertOperations.Dequeue();
InsertHtml(insert.Content, insert.Options);
}
_contentEditorSite.OnDocumentComplete();
}
#region IContentEditor Members
public void Save(string fileName, bool preserveDirty)
{
contentEditor.SaveChanges(context.BlogPost, BlogPostSaveOptions.DefaultOptions);
context.LocalFile.SaveContentEditorFile(context, fileName, false);
}
public string Publish(IPublishOperation imageConverter)
{
return contentEditor.Publish(imageConverter);
}
public IHTMLDocument2 GetPublishDocument()
{
string body = contentEditor.Publish(null);
// Before we drop the body into the template, we wrap the whole thing in the user's default font
// This will help cover for any blocks of text that while editing had their font set by body style. We
// cannot send the body style in emails because it will get stripped by some email providers.
body = contentEditor.CurrentDefaultFont.ApplyFontToBody(body);
// We also need to wrap the email in a default direction because we support LTR/RTL per paragraph but
// we inherit the default direction from the body.
// NOTE: Now that we set the direction of the body (a few lines below) this may not be needed. It is
// currently kept to avoid possible regressions with external mail providers
string dir = contentEditor.IsRTLTemplate ? "rtl" : "ltr";
body = string.Format(CultureInfo.InvariantCulture, "<div dir=\"{0}\">{1}</div>", dir, body);
// This forms the whole html document by combining the theme and the body and then turning it into an IHTMLDocument2
// This is needed for WLM so they can reuse packaging code.
// We wrap the html document with a class that improves the representation of smart content for an email's plain text MIME part.
// In order to minimize the potential for regressions we only wrap in the case of a photomail.
IHTMLDocument2 publishDocument = HTMLDocumentHelper.StringToHTMLDoc(_wysiwygHTML.Replace("{post-body}", body), "");
// WinLive 262662: although many features work by wrapping the email in a direction div, the
// email as a whole is determined by the direction defined in the body
publishDocument.body.setAttribute("dir", dir, 1);
return publishDocument;
}
public void SetSize(int width, int height)
{
panel.Size = new Size(width, height);
}
private ContentEditorFactory factory;
private SpellingOptionState _spellingState;
private string _wysiwygHTML;
private string _previewHTML;
public void SetTheme(string wysiwygHTML)
{
// We need to track the wysiwygHTML and previewHTML so that we can use it in the Load() function
// where we have to call Initialize again which requires the theme to be passed in
_wysiwygHTML = wysiwygHTML;
_previewHTML = null;
contentEditor.SetTheme(_wysiwygHTML, null, false);
}
public void SetSpellingOptions(string dllName, ushort lcid, string[] mainLexFiles, string userLexFile, uint sobitOptions, bool useAutoCorrect)
{
_spellingState = new SpellingOptionState(
dllName, lcid, mainLexFiles, userLexFile, sobitOptions, useAutoCorrect);
_spellingState.Apply(contentEditor, factory.GlobalSpellingOptions);
if (CultureHelper.IsRtlLcid(lcid))
{
EmailContentTarget target =
GlobalEditorOptions.ContentTarget as EmailContentTarget;
if (target != null)
{
target.EnableRtlMode();
}
}
}
public void DisableSpelling()
{
_spellingState = null;
contentEditor.DisableSpelling();
}
private void GlobalSpellingOptionsChangedHandler(object sender, EventArgs e)
{
if (_spellingState != null)
_spellingState.Apply(contentEditor, factory.GlobalSpellingOptions);
}
class SpellingOptionState
{
readonly string dllName;
readonly ushort lcid;
readonly string[] mainLexFiles;
readonly string userLexFile;
readonly uint sobitOptions;
readonly bool useAutoCorrect;
public SpellingOptionState(string dllName, ushort lcid, string[] mainLexFiles, string userLexFile, uint sobitOptions, bool useAutoCorrect)
{
this.dllName = dllName;
this.lcid = lcid;
this.mainLexFiles = mainLexFiles;
this.userLexFile = userLexFile;
this.sobitOptions = sobitOptions;
this.useAutoCorrect = useAutoCorrect;
}
public void Apply(ContentEditor editor, uint globalSobitOptions)
{
editor.SetSpellingOptions(dllName, lcid, mainLexFiles, userLexFile, sobitOptions | globalSobitOptions, useAutoCorrect);
}
}
public void AutoreplaceEmoticons(bool enabled)
{
AutoreplaceSettings.EnableEmoticonsReplacement = enabled;
}
#endregion
#region IDisposable Members
public void Dispose()
{
factory.GlobalSpellingOptionsChanged -= GlobalSpellingOptionsChangedHandler;
contentEditor.DocumentComplete -= new EventHandler(blogPostHtmlEditor_DocumentComplete);
contentEditor.GotFocus -= new EventHandler(contentEditor_GotFocus);
contentEditor.LostFocus -= new EventHandler(contentEditor_LostFocus);
contentEditor.Dispose();
panel.Dispose();
accountAdapter.Dispose();
mainFrame.Dispose();
Marshal.ReleaseComObject(_contentEditorSite);
_contentEditorSite = null;
accountAdapter = null;
contentEditor = null;
panel = null;
context = null;
}
private EditingMode? _editMode;
public void ChangeView(EditingMode editingMode)
{
if (!_documentComplete)
{
_editMode = editingMode;
return;
}
try
{
switch (editingMode)
{
case EditingMode.Wysiwyg:
contentEditor.ChangeToWysiwygMode();
return;
case EditingMode.Source:
contentEditor.ChangeToCodeMode();
return;
case EditingMode.Preview:
contentEditor.ChangeToPreviewMode();
return;
case EditingMode.PlainText:
contentEditor.ChangeToPlainTextMode();
return;
}
}
catch (Exception ex)
{
Debug.Fail(ex.ToString());
throw;
}
Debug.Fail("Unknown value for editingView: " + editingMode.ToString() + "\r\nAccepted values Wysiwyg, Source, Preview, PlainText");
}
public void SetFocus()
{
if (!_inGotFocusHandler && !contentEditor.DocumentHasFocus())
contentEditor.FocusBody();
}
public void NotifyMailFocus(bool fIsPhotoAttachment)
{
contentEditor.NotifyMailFocus(fIsPhotoAttachment);
}
public void InsertHtml(string html, HtmlInsertOptions options)
{
contentEditor.InsertHtml(html, (HtmlInsertionOptions)options | HtmlInsertionOptions.ExternalContent);
}
public void ChangeSelection(SelectionPosition position)
{
contentEditor.ChangeSelection(position);
}
#endregion
#region IUICommandHandler Members
public int Execute(uint commandId, CommandExecutionVerb verb, PropertyKeyRef key, PropVariantRef currentValue, IUISimplePropertySet commandExecutionProperties)
{
return contentEditor.CommandManager.Execute(commandId, verb, key, currentValue, commandExecutionProperties);
}
public int UpdateProperty(uint commandId, ref PropertyKey key, PropVariantRef currentValue, out PropVariant newValue)
{
return contentEditor.CommandManager.UpdateProperty(commandId, ref key, currentValue, out newValue);
}
#endregion
#region Implementation of IUICommandHandlerOverride
public int OverrideProperty(uint commandId, ref PropertyKey key, PropVariantRef overrideValue)
{
return contentEditor.CommandManager.OverrideProperty(commandId, ref key, overrideValue);
}
public int CancelOverride(uint commandId, ref PropertyKey key)
{
return contentEditor.CommandManager.CancelOverride(commandId, ref key);
}
#endregion
internal class ContentEditorTemplateStrategy : BlogPostHtmlEditorControl.TemplateStrategy
{
public override string OnBodyInserted(string bodyContents)
{
return bodyContents;
}
public override string OnTitleInserted(string title)
{
return null;
}
public override void OnDocumentComplete(IHTMLDocument2 doc)
{
doc.body.style.overflow = "auto";
doc.body.id = BODY_FRAGMENT_ID;
((IHTMLElement3)doc.body).contentEditable = "true";
doc.body.style.width = "100%";
if (GlobalEditorOptions.SupportsFeature(ContentEditorFeature.RTLDirectionDefault))
doc.body.setAttribute("dir", "rtl", 0);
else
doc.body.setAttribute("dir", "ltr", 0);
IHTMLElement2 body = (IHTMLElement2)doc.body;
body.runtimeStyle.padding = "0px 0px 0px 0px";
body.runtimeStyle.borderWidth = "0px";
}
public override IHTMLElement PostBodyElement(IHTMLDocument2 doc)
{
return doc.body;
}
public override IHTMLElement TitleElement(IHTMLDocument2 doc)
{
return null;
}
}
#region IContentEditor Members
public bool GetDirtyState()
{
return contentEditor.IsDirty;
}
public void SetDirtyState(bool newState)
{
contentEditor.IsDirty = newState;
}
public void SetDefaultFont(string fontSetting)
{
contentEditor.SetDefaultFont(fontSetting);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
[ExportWorkspaceService(typeof(ISolutionCrawlerRegistrationService), ServiceLayer.Host), Shared]
internal partial class SolutionCrawlerRegistrationService : ISolutionCrawlerRegistrationService
{
private const string Default = "*";
private readonly object _gate;
private readonly SolutionCrawlerProgressReporter _progressReporter;
private readonly IAsynchronousOperationListener _listener;
private readonly Dictionary<Workspace, WorkCoordinator> _documentWorkCoordinatorMap;
private ImmutableDictionary<string, ImmutableArray<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>>> _analyzerProviders;
[ImportingConstructor]
public SolutionCrawlerRegistrationService(
[ImportMany] IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> analyzerProviders,
[ImportMany] IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> asyncListeners)
{
_gate = new object();
_analyzerProviders = analyzerProviders.GroupBy(kv => kv.Metadata.Name).ToImmutableDictionary(g => g.Key, g => g.ToImmutableArray());
AssertAnalyzerProviders(_analyzerProviders);
_documentWorkCoordinatorMap = new Dictionary<Workspace, WorkCoordinator>(ReferenceEqualityComparer.Instance);
_listener = new AggregateAsynchronousOperationListener(asyncListeners, FeatureAttribute.SolutionCrawler);
_progressReporter = new SolutionCrawlerProgressReporter(_listener);
}
public void Register(Workspace workspace)
{
var correlationId = LogAggregator.GetNextId();
lock (_gate)
{
if (_documentWorkCoordinatorMap.ContainsKey(workspace))
{
// already registered.
return;
}
var coordinator = new WorkCoordinator(
_listener,
GetAnalyzerProviders(workspace),
new Registration(correlationId, workspace, _progressReporter));
_documentWorkCoordinatorMap.Add(workspace, coordinator);
}
SolutionCrawlerLogger.LogRegistration(correlationId, workspace);
}
public void Unregister(Workspace workspace, bool blockingShutdown = false)
{
var coordinator = default(WorkCoordinator);
lock (_gate)
{
if (!_documentWorkCoordinatorMap.TryGetValue(workspace, out coordinator))
{
// already unregistered
return;
}
_documentWorkCoordinatorMap.Remove(workspace);
coordinator.Shutdown(blockingShutdown);
}
SolutionCrawlerLogger.LogUnregistration(coordinator.CorrelationId);
}
public void AddAnalyzerProvider(IIncrementalAnalyzerProvider provider, IncrementalAnalyzerProviderMetadata metadata)
{
// now update all existing work coordinator
lock (_gate)
{
var lazyProvider = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => provider, metadata);
// update existing map for future solution crawler registration - no need for interlock but this makes add or update easier
ImmutableInterlocked.AddOrUpdate(ref _analyzerProviders, metadata.Name, (n) => ImmutableArray.Create(lazyProvider), (n, v) => v.Add(lazyProvider));
// assert map integrity
AssertAnalyzerProviders(_analyzerProviders);
// find existing coordinator to update
var lazyProviders = _analyzerProviders[metadata.Name];
foreach (var kv in _documentWorkCoordinatorMap)
{
var workspace = kv.Key;
var coordinator = kv.Value;
Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata> picked;
if (!TryGetProvider(workspace.Kind, lazyProviders, out picked) || picked != lazyProvider)
{
// check whether new provider belong to current workspace
continue;
}
var analyzer = lazyProvider.Value.CreateIncrementalAnalyzer(workspace);
coordinator.AddAnalyzer(analyzer, metadata.HighPriorityForActiveFile);
}
}
}
public void Reanalyze(Workspace workspace, IIncrementalAnalyzer analyzer, IEnumerable<ProjectId> projectIds, IEnumerable<DocumentId> documentIds, bool highPriority)
{
lock (_gate)
{
var coordinator = default(WorkCoordinator);
if (!_documentWorkCoordinatorMap.TryGetValue(workspace, out coordinator))
{
// this can happen if solution crawler is already unregistered from workspace.
// one of those example will be VS shutting down so roslyn package is disposed but there is a pending
// async operation.
return;
}
// no specific projects or documents provided
if (projectIds == null && documentIds == null)
{
coordinator.Reanalyze(analyzer, workspace.CurrentSolution.Projects.SelectMany(p => p.DocumentIds).ToSet(), highPriority);
return;
}
// specific documents provided
if (projectIds == null)
{
coordinator.Reanalyze(analyzer, documentIds.ToSet(), highPriority);
return;
}
var solution = workspace.CurrentSolution;
var set = new HashSet<DocumentId>(documentIds ?? SpecializedCollections.EmptyEnumerable<DocumentId>());
set.UnionWith(projectIds.Select(id => solution.GetProject(id)).SelectMany(p => p.DocumentIds));
coordinator.Reanalyze(analyzer, set, highPriority);
}
}
internal void WaitUntilCompletion_ForTestingPurposesOnly(Workspace workspace, ImmutableArray<IIncrementalAnalyzer> workers)
{
if (_documentWorkCoordinatorMap.ContainsKey(workspace))
{
_documentWorkCoordinatorMap[workspace].WaitUntilCompletion_ForTestingPurposesOnly(workers);
}
}
internal void WaitUntilCompletion_ForTestingPurposesOnly(Workspace workspace)
{
if (_documentWorkCoordinatorMap.ContainsKey(workspace))
{
_documentWorkCoordinatorMap[workspace].WaitUntilCompletion_ForTestingPurposesOnly();
}
}
private IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> GetAnalyzerProviders(Workspace workspace)
{
Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata> lazyProvider;
foreach (var kv in _analyzerProviders)
{
var lazyProviders = kv.Value;
// try get provider for the specific workspace kind
if (TryGetProvider(workspace.Kind, lazyProviders, out lazyProvider))
{
yield return lazyProvider;
continue;
}
// try get default provider
if (TryGetProvider(Default, lazyProviders, out lazyProvider))
{
yield return lazyProvider;
}
}
}
private bool TryGetProvider(
string kind,
ImmutableArray<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> lazyProviders,
out Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata> lazyProvider)
{
// set out param
lazyProvider = null;
// try find provider for specific workspace kind
if (kind != Default)
{
foreach (var provider in lazyProviders)
{
if (provider.Metadata.WorkspaceKinds?.Any(wk => wk == kind) == true)
{
lazyProvider = provider;
return true;
}
}
return false;
}
// try find default provider
foreach (var provider in lazyProviders)
{
if (IsDefaultProvider(provider.Metadata))
{
lazyProvider = provider;
return true;
}
return false;
}
return false;
}
[Conditional("DEBUG")]
private static void AssertAnalyzerProviders(
ImmutableDictionary<string, ImmutableArray<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>>> analyzerProviders)
{
#if DEBUG
// make sure there is duplicated provider defined for same workspace.
var set = new HashSet<string>();
foreach (var kv in analyzerProviders)
{
foreach (var lazyProvider in kv.Value)
{
if (IsDefaultProvider(lazyProvider.Metadata))
{
Contract.Requires(set.Add(Default));
continue;
}
foreach (var kind in lazyProvider.Metadata.WorkspaceKinds)
{
Contract.Requires(set.Add(kind));
}
}
set.Clear();
}
#endif
}
private static bool IsDefaultProvider(IncrementalAnalyzerProviderMetadata providerMetadata)
{
return providerMetadata.WorkspaceKinds == null || providerMetadata.WorkspaceKinds.Length == 0;
}
private class Registration
{
public readonly int CorrelationId;
public readonly Workspace Workspace;
public readonly SolutionCrawlerProgressReporter ProgressReporter;
public Registration(int correlationId, Workspace workspace, SolutionCrawlerProgressReporter progressReporter)
{
CorrelationId = correlationId;
Workspace = workspace;
ProgressReporter = progressReporter;
}
public Solution CurrentSolution
{
get { return Workspace.CurrentSolution; }
}
public TService GetService<TService>() where TService : IWorkspaceService
{
return Workspace.Services.GetService<TService>();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Text;
using TestLibrary;
public class StringConcat3
{
public static int Main()
{
StringConcat3 sc3 = new StringConcat3();
TestLibrary.TestFramework.BeginTestCase("StringConcat3");
if (sc3.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
retVal = PosTest8() && retVal;
retVal = PosTest9() && retVal;
retVal = PosTest10() && retVal;
retVal = PosTest11() && retVal;
retVal = PosTest12() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
string ActualResult;
object ObjA;
object ObjB;
object ObjC;
TestLibrary.TestFramework.BeginScenario("PostTest1:Concat three objects of object ");
try
{
ObjA = new object();
ObjB = new object();
ObjC = new object();
ActualResult = string.Concat(ObjA, ObjB,ObjC);
if (ActualResult != ObjA.ToString() +ObjB.ToString() +ObjC.ToString())
{
TestLibrary.TestFramework.LogError("001", "Concat three objects ExpectResult is" + ObjA.ToString() + ObjB.ToString() + ObjC.ToString() + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
string ActualResult;
object ObjA;
object ObjB;
object ObjC;
TestLibrary.TestFramework.BeginScenario("PostTest2:Concat three null objects");
try
{
ObjA = null;
ObjB = null;
ObjC = null;
ActualResult = string.Concat(ObjA, ObjB,ObjC);
if (ActualResult != string.Empty)
{
TestLibrary.TestFramework.LogError("003", "Concat three null objects ExpectResult is" + string.Empty+ " ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
string ActualResult;
object ObjA;
object ObjB;
object ObjC;
TestLibrary.TestFramework.BeginScenario("PosTest3:Concat two null objects and a number of less than 0");
try
{
ObjA = null;
ObjB = null;
ObjC = -12314124;
ActualResult = string.Concat(ObjA, ObjB,ObjC);
if (ActualResult != ObjC.ToString())
{
TestLibrary.TestFramework.LogError("005", "Concat two null objects and a number of less than 0 ExpectResult is equel" + ObjC.ToString() + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
string ActualResult;
object ObjA;
object ObjB;
object ObjC;
TestLibrary.TestFramework.BeginScenario("PosTest4: Concat three special strings");
try
{
ObjA = new string('\t', 2);
ObjB = "\n";
ObjC = "\t";
ActualResult = string.Concat(ObjA, ObjB, ObjC);
if (ActualResult != ObjA.ToString() + ObjB.ToString() + ObjC.ToString())
{
TestLibrary.TestFramework.LogError("007", "Concat three special strings ExpectResult is" + ObjB.ToString() + ObjA.ToString() + ObjC.ToString() + " ,ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
string ActualResult;
object ObjA;
object ObjB;
object ObjC;
TestLibrary.TestFramework.BeginScenario("PosTest5:Concat three numbers of less than 0");
try
{
ObjA = -123;
ObjB = -123;
ObjC = -123;
ActualResult = string.Concat(ObjA, ObjB,ObjC);
if (ActualResult != ObjA.ToString() + ObjB.ToString() + ObjC.ToString())
{
TestLibrary.TestFramework.LogError("009", "Concat three numbers of less than 0 ExpectResult is equel" + ObjA.ToString() + ObjB.ToString() + " ,ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
string ActualResult;
object ObjA;
object ObjB;
object ObjC;
TestLibrary.TestFramework.BeginScenario("PosTest6: Concat two nulls and an object of datetime");
try
{
ObjA = null;
ObjB = new DateTime();
ObjC = null;
ActualResult = string.Concat(ObjA, ObjB,ObjC);
if (ActualResult != ObjB.ToString())
{
TestLibrary.TestFramework.LogError("011", "Concat two nulls and an object of datetime ExpectResult is equel" + ObjB.ToString() + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
string ActualResult;
object ObjA;
object ObjB;
object ObjC;
TestLibrary.TestFramework.BeginScenario("PosTest7: Concat null and an object of datetime and one space");
try
{
ObjA = null;
ObjB = new DateTime();
ObjC = " ";
ActualResult = string.Concat(ObjA, ObjB,ObjC);
if (ActualResult != ObjB.ToString() +ObjC.ToString())
{
TestLibrary.TestFramework.LogError("013", "Concat null and an object of datetime and one space ExpectResult is equel"+ ObjB.ToString() + ObjC.ToString() +",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest8()
{
bool retVal = true;
string ActualResult;
object ObjA;
object ObjB;
object ObjC;
TestLibrary.TestFramework.BeginScenario("PosTest8:Concat null and an object of random class instance and bool object");
try
{
ObjA = null;
ObjB = new StringConcat3();
ObjC = new bool();
ActualResult = string.Concat(ObjA, ObjB,ObjC);
if (ActualResult != ObjB.ToString() + ObjC.ToString())
{
TestLibrary.TestFramework.LogError("015", "Concat null and an object of random class instance and bool object ExpectResult is equel" + ObjB.ToString() + " ,ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("016", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest9()
{
bool retVal = true;
string ActualResult;
object ObjA;
object ObjB;
object ObjC;
TestLibrary.TestFramework.BeginScenario("PosTest9: Concat int and special symbol and an object of Guid");
try
{
ObjA = 123;
ObjB = "\n";
ObjC = new Guid();
ActualResult = string.Concat(ObjA, ObjB,ObjC);
if (ActualResult != ObjA.ToString() + ObjB.ToString() + ObjC.ToString())
{
TestLibrary.TestFramework.LogError("017", "Concat int and special symbol and an object of Guid ExpectResult is equel" + ObjA.ToString() + ObjB.ToString() + ObjC.ToString() + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("018", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest10()
{
bool retVal = true;
string ActualResult;
object ObjA;
object ObjB;
object ObjC;
TestLibrary.TestFramework.BeginScenario("PosTest10:Concat two guids with a \n string in middle");
try
{
ObjA = new Guid();
ObjB = "\n";
ObjC = new Guid();
ActualResult = string.Concat(ObjA, ObjB,ObjC);
if (ActualResult != ObjA.ToString() + ObjB.ToString() + ObjC.ToString())
{
TestLibrary.TestFramework.LogError("019", "Concat two guids with a \n string in middle ExpectResult is equel" + ObjA.ToString() + ObjB.ToString() + ObjC.ToString() + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("020", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest11()
{
bool retVal = true;
string ActualResult;
object ObjA;
object ObjB;
object ObjC;
TestLibrary.TestFramework.BeginScenario("PosTest11:Concat three guids");
try
{
ObjA = new Guid();
ObjB = new Guid();
ObjC = new Guid();
ActualResult = string.Concat(ObjA, ObjB, ObjC);
if (ActualResult != ObjA.ToString() + ObjB.ToString() + ObjC.ToString())
{
TestLibrary.TestFramework.LogError("021", "Concat three guids ExpectResult is equel" + ObjA.ToString() + ObjB.ToString() + ObjC.ToString() + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("022", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest12()
{
bool retVal = true;
string ActualResult;
object ObjA;
object ObjB;
object ObjC;
TestLibrary.TestFramework.BeginScenario("PosTest11:Concat guid,datetime and bool");
try
{
ObjA = new Guid();
ObjB = new bool();
ObjC = new DateTime();
ActualResult = string.Concat(ObjA, ObjB, ObjC);
if (ActualResult != ObjA.ToString() + ObjB.ToString() + ObjC.ToString())
{
TestLibrary.TestFramework.LogError("023", "Concat guid,datetiem and bool ExpectResult is equel" + ObjA.ToString() + ObjB.ToString() + ObjC.ToString() + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("024", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using Nini.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.Scripting.ScriptModuleComms;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Tests.Common;
using System;
namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests
{
/// <summary>
/// Tests for inventory functions in LSL
/// </summary>
[TestFixture]
public class JsonStoreScriptModuleTests : OpenSimTestCase
{
private Scene m_scene;
private MockScriptEngine m_engine;
private ScriptModuleCommsModule m_smcm;
private JsonStoreScriptModule m_jssm;
[TestFixtureSetUp]
public void FixtureInit()
{
// Don't allow tests to be bamboozled by asynchronous events. Execute everything on the same thread.
Util.FireAndForgetMethod = FireAndForgetMethod.RegressionTest;
}
[TestFixtureTearDown]
public void TearDown()
{
// We must set this back afterwards, otherwise later tests will fail since they're expecting multiple
// threads. Possibly, later tests should be rewritten so none of them require async stuff (which regression
// tests really shouldn't).
Util.FireAndForgetMethod = Util.DefaultFireAndForgetMethod;
}
[SetUp]
public override void SetUp()
{
base.SetUp();
IConfigSource configSource = new IniConfigSource();
IConfig jsonStoreConfig = configSource.AddConfig("JsonStore");
jsonStoreConfig.Set("Enabled", "true");
m_engine = new MockScriptEngine();
m_smcm = new ScriptModuleCommsModule();
JsonStoreModule jsm = new JsonStoreModule();
m_jssm = new JsonStoreScriptModule();
m_scene = new SceneHelpers().SetupScene();
SceneHelpers.SetupSceneModules(m_scene, configSource, m_engine, m_smcm, jsm, m_jssm);
try
{
m_smcm.RegisterScriptInvocation(this, "DummyTestMethod");
}
catch (ArgumentException)
{
Assert.Ignore("Ignoring test since running on .NET 3.5 or earlier.");
}
// XXX: Unfortunately, ICommsModule currently has no way of deregistering methods.
}
private object InvokeOp(string name, params object[] args)
{
return InvokeOpOnHost(name, UUID.Zero, args);
}
private object InvokeOpOnHost(string name, UUID hostId, params object[] args)
{
return m_smcm.InvokeOperation(hostId, UUID.Zero, name, args);
}
[Test]
public void TestJsonCreateStore()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
// Test blank store
{
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}");
Assert.That(storeId, Is.Not.EqualTo(UUID.Zero));
}
// Test single element store
{
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : 'World' }");
Assert.That(storeId, Is.Not.EqualTo(UUID.Zero));
}
// Test with an integer value
{
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : 42.15 }");
Assert.That(storeId, Is.Not.EqualTo(UUID.Zero));
string value = (string)InvokeOp("JsonGetValue", storeId, "Hello");
Assert.That(value, Is.EqualTo("42.15"));
}
// Test with an array as the root node
{
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "[ 'one', 'two', 'three' ]");
Assert.That(storeId, Is.Not.EqualTo(UUID.Zero));
string value = (string)InvokeOp("JsonGetValue", storeId, "[1]");
Assert.That(value, Is.EqualTo("two"));
}
}
[Test]
public void TestJsonDestroyStore()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : 'World' }");
int dsrv = (int)InvokeOp("JsonDestroyStore", storeId);
Assert.That(dsrv, Is.EqualTo(1));
int tprv = (int)InvokeOp("JsonGetNodeType", storeId, "Hello");
Assert.That(tprv, Is.EqualTo(JsonStoreScriptModule.JSON_NODETYPE_UNDEF));
}
[Test]
public void TestJsonDestroyStoreNotExists()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
UUID fakeStoreId = TestHelpers.ParseTail(0x500);
int dsrv = (int)InvokeOp("JsonDestroyStore", fakeStoreId);
Assert.That(dsrv, Is.EqualTo(0));
}
[Test]
public void TestJsonGetValue()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : { 'World' : 'Two' } }");
{
string value = (string)InvokeOp("JsonGetValue", storeId, "Hello.World");
Assert.That(value, Is.EqualTo("Two"));
}
// Test get of path section instead of leaf
{
string value = (string)InvokeOp("JsonGetValue", storeId, "Hello");
Assert.That(value, Is.EqualTo(""));
}
// Test get of non-existing value
{
string fakeValueGet = (string)InvokeOp("JsonGetValue", storeId, "foo");
Assert.That(fakeValueGet, Is.EqualTo(""));
}
// Test get from non-existing store
{
UUID fakeStoreId = TestHelpers.ParseTail(0x500);
string fakeStoreValueGet = (string)InvokeOp("JsonGetValue", fakeStoreId, "Hello");
Assert.That(fakeStoreValueGet, Is.EqualTo(""));
}
}
[Test]
public void TestJsonGetJson()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : { 'World' : 'Two' } }");
{
string value = (string)InvokeOp("JsonGetJson", storeId, "Hello.World");
Assert.That(value, Is.EqualTo("'Two'"));
}
// Test get of path section instead of leaf
{
string value = (string)InvokeOp("JsonGetJson", storeId, "Hello");
Assert.That(value, Is.EqualTo("{\"World\":\"Two\"}"));
}
// Test get of non-existing value
{
string fakeValueGet = (string)InvokeOp("JsonGetJson", storeId, "foo");
Assert.That(fakeValueGet, Is.EqualTo(""));
}
// Test get from non-existing store
{
UUID fakeStoreId = TestHelpers.ParseTail(0x500);
string fakeStoreValueGet = (string)InvokeOp("JsonGetJson", fakeStoreId, "Hello");
Assert.That(fakeStoreValueGet, Is.EqualTo(""));
}
}
// [Test]
// public void TestJsonTakeValue()
// {
// TestHelpers.InMethod();
//// TestHelpers.EnableLogging();
//
// UUID storeId
// = (UUID)m_smcm.InvokeOperation(
// UUID.Zero, UUID.Zero, "JsonCreateStore", new object[] { "{ 'Hello' : 'World' }" });
//
// string value
// = (string)m_smcm.InvokeOperation(
// UUID.Zero, UUID.Zero, "JsonTakeValue", new object[] { storeId, "Hello" });
//
// Assert.That(value, Is.EqualTo("World"));
//
// string value2
// = (string)m_smcm.InvokeOperation(
// UUID.Zero, UUID.Zero, "JsonGetValue", new object[] { storeId, "Hello" });
//
// Assert.That(value, Is.Null);
// }
[Test]
public void TestJsonRemoveValue()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
// Test remove of node in object pointing to a string
{
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : 'World' }");
int returnValue = (int)InvokeOp("JsonRemoveValue", storeId, "Hello");
Assert.That(returnValue, Is.EqualTo(1));
int result = (int)InvokeOp("JsonGetNodeType", storeId, "Hello");
Assert.That(result, Is.EqualTo(JsonStoreScriptModule.JSON_NODETYPE_UNDEF));
string returnValue2 = (string)InvokeOp("JsonGetValue", storeId, "Hello");
Assert.That(returnValue2, Is.EqualTo(""));
}
// Test remove of node in object pointing to another object
{
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : { 'World' : 'Wally' } }");
int returnValue = (int)InvokeOp("JsonRemoveValue", storeId, "Hello");
Assert.That(returnValue, Is.EqualTo(1));
int result = (int)InvokeOp("JsonGetNodeType", storeId, "Hello");
Assert.That(result, Is.EqualTo(JsonStoreScriptModule.JSON_NODETYPE_UNDEF));
string returnValue2 = (string)InvokeOp("JsonGetJson", storeId, "Hello");
Assert.That(returnValue2, Is.EqualTo(""));
}
// Test remove of node in an array
{
UUID storeId
= (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : [ 'value1', 'value2' ] }");
int returnValue = (int)InvokeOp("JsonRemoveValue", storeId, "Hello[0]");
Assert.That(returnValue, Is.EqualTo(1));
int result = (int)InvokeOp("JsonGetNodeType", storeId, "Hello[0]");
Assert.That(result, Is.EqualTo(JsonStoreScriptModule.JSON_NODETYPE_VALUE));
result = (int)InvokeOp("JsonGetNodeType", storeId, "Hello[1]");
Assert.That(result, Is.EqualTo(JsonStoreScriptModule.JSON_NODETYPE_UNDEF));
string stringReturnValue = (string)InvokeOp("JsonGetValue", storeId, "Hello[0]");
Assert.That(stringReturnValue, Is.EqualTo("value2"));
stringReturnValue = (string)InvokeOp("JsonGetJson", storeId, "Hello[1]");
Assert.That(stringReturnValue, Is.EqualTo(""));
}
// Test remove of non-existing value
{
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : 'World' }");
int fakeValueRemove = (int)InvokeOp("JsonRemoveValue", storeId, "Cheese");
Assert.That(fakeValueRemove, Is.EqualTo(0));
}
{
// Test get from non-existing store
UUID fakeStoreId = TestHelpers.ParseTail(0x500);
int fakeStoreValueRemove = (int)InvokeOp("JsonRemoveValue", fakeStoreId, "Hello");
Assert.That(fakeStoreValueRemove, Is.EqualTo(0));
}
}
// [Test]
// public void TestJsonTestPath()
// {
// TestHelpers.InMethod();
//// TestHelpers.EnableLogging();
//
// UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : { 'World' : 'One' } }");
//
// {
// int result = (int)InvokeOp("JsonTestPath", storeId, "Hello.World");
// Assert.That(result, Is.EqualTo(1));
// }
//
// // Test for path which does not resolve to a value.
// {
// int result = (int)InvokeOp("JsonTestPath", storeId, "Hello");
// Assert.That(result, Is.EqualTo(0));
// }
//
// {
// int result2 = (int)InvokeOp("JsonTestPath", storeId, "foo");
// Assert.That(result2, Is.EqualTo(0));
// }
//
// // Test with fake store
// {
// UUID fakeStoreId = TestHelpers.ParseTail(0x500);
// int fakeStoreValueRemove = (int)InvokeOp("JsonTestPath", fakeStoreId, "Hello");
// Assert.That(fakeStoreValueRemove, Is.EqualTo(0));
// }
// }
// [Test]
// public void TestJsonTestPathJson()
// {
// TestHelpers.InMethod();
//// TestHelpers.EnableLogging();
//
// UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : { 'World' : 'One' } }");
//
// {
// int result = (int)InvokeOp("JsonTestPathJson", storeId, "Hello.World");
// Assert.That(result, Is.EqualTo(1));
// }
//
// // Test for path which does not resolve to a value.
// {
// int result = (int)InvokeOp("JsonTestPathJson", storeId, "Hello");
// Assert.That(result, Is.EqualTo(1));
// }
//
// {
// int result2 = (int)InvokeOp("JsonTestPathJson", storeId, "foo");
// Assert.That(result2, Is.EqualTo(0));
// }
//
// // Test with fake store
// {
// UUID fakeStoreId = TestHelpers.ParseTail(0x500);
// int fakeStoreValueRemove = (int)InvokeOp("JsonTestPathJson", fakeStoreId, "Hello");
// Assert.That(fakeStoreValueRemove, Is.EqualTo(0));
// }
// }
[Test]
public void TestJsonGetArrayLength()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : { 'World' : [ 'one', 2 ] } }");
{
int result = (int)InvokeOp("JsonGetArrayLength", storeId, "Hello.World");
Assert.That(result, Is.EqualTo(2));
}
// Test path which is not an array
{
int result = (int)InvokeOp("JsonGetArrayLength", storeId, "Hello");
Assert.That(result, Is.EqualTo(-1));
}
// Test fake path
{
int result = (int)InvokeOp("JsonGetArrayLength", storeId, "foo");
Assert.That(result, Is.EqualTo(-1));
}
// Test fake store
{
UUID fakeStoreId = TestHelpers.ParseTail(0x500);
int result = (int)InvokeOp("JsonGetArrayLength", fakeStoreId, "Hello.World");
Assert.That(result, Is.EqualTo(-1));
}
}
[Test]
public void TestJsonGetNodeType()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : { 'World' : [ 'one', 2 ] } }");
{
int result = (int)InvokeOp("JsonGetNodeType", storeId, ".");
Assert.That(result, Is.EqualTo(JsonStoreScriptModule.JSON_NODETYPE_OBJECT));
}
{
int result = (int)InvokeOp("JsonGetNodeType", storeId, "Hello");
Assert.That(result, Is.EqualTo(JsonStoreScriptModule.JSON_NODETYPE_OBJECT));
}
{
int result = (int)InvokeOp("JsonGetNodeType", storeId, "Hello.World");
Assert.That(result, Is.EqualTo(JsonStoreScriptModule.JSON_NODETYPE_ARRAY));
}
{
int result = (int)InvokeOp("JsonGetNodeType", storeId, "Hello.World[0]");
Assert.That(result, Is.EqualTo(JsonStoreScriptModule.JSON_NODETYPE_VALUE));
}
{
int result = (int)InvokeOp("JsonGetNodeType", storeId, "Hello.World[1]");
Assert.That(result, Is.EqualTo(JsonStoreScriptModule.JSON_NODETYPE_VALUE));
}
// Test for non-existant path
{
int result = (int)InvokeOp("JsonGetNodeType", storeId, "foo");
Assert.That(result, Is.EqualTo(JsonStoreScriptModule.JSON_NODETYPE_UNDEF));
}
// Test for non-existant store
{
UUID fakeStoreId = TestHelpers.ParseTail(0x500);
int result = (int)InvokeOp("JsonGetNodeType", fakeStoreId, ".");
Assert.That(result, Is.EqualTo(JsonStoreScriptModule.JSON_NODETYPE_UNDEF));
}
}
[Test]
public void TestJsonList2Path()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
// Invoking these methods directly since I just couldn't get comms module invocation to work for some reason
// - some confusion with the methods that take a params object[] invocation.
{
string result = m_jssm.JsonList2Path(UUID.Zero, UUID.Zero, new object[] { "foo" });
Assert.That(result, Is.EqualTo("{foo}"));
}
{
string result = m_jssm.JsonList2Path(UUID.Zero, UUID.Zero, new object[] { "foo", "bar" });
Assert.That(result, Is.EqualTo("{foo}.{bar}"));
}
{
string result = m_jssm.JsonList2Path(UUID.Zero, UUID.Zero, new object[] { "foo", 1, "bar" });
Assert.That(result, Is.EqualTo("{foo}.[1].{bar}"));
}
}
[Test]
public void TestJsonSetValue()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
{
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}");
int result = (int)InvokeOp("JsonSetValue", storeId, "Fun", "Times");
Assert.That(result, Is.EqualTo(1));
string value = (string)InvokeOp("JsonGetValue", storeId, "Fun");
Assert.That(value, Is.EqualTo("Times"));
}
// Test setting a key containing periods with delineation
{
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}");
int result = (int)InvokeOp("JsonSetValue", storeId, "{Fun.Circus}", "Times");
Assert.That(result, Is.EqualTo(1));
string value = (string)InvokeOp("JsonGetValue", storeId, "{Fun.Circus}");
Assert.That(value, Is.EqualTo("Times"));
}
// *** Test [] ***
// Test setting a key containing unbalanced ] without delineation. Expecting failure
{
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}");
int result = (int)InvokeOp("JsonSetValue", storeId, "Fun]Circus", "Times");
Assert.That(result, Is.EqualTo(0));
string value = (string)InvokeOp("JsonGetValue", storeId, "Fun]Circus");
Assert.That(value, Is.EqualTo(""));
}
// Test setting a key containing unbalanced [ without delineation. Expecting failure
{
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}");
int result = (int)InvokeOp("JsonSetValue", storeId, "Fun[Circus", "Times");
Assert.That(result, Is.EqualTo(0));
string value = (string)InvokeOp("JsonGetValue", storeId, "Fun[Circus");
Assert.That(value, Is.EqualTo(""));
}
// Test setting a key containing unbalanced [] without delineation. Expecting failure
{
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}");
int result = (int)InvokeOp("JsonSetValue", storeId, "Fun[]Circus", "Times");
Assert.That(result, Is.EqualTo(0));
string value = (string)InvokeOp("JsonGetValue", storeId, "Fun[]Circus");
Assert.That(value, Is.EqualTo(""));
}
// Test setting a key containing unbalanced ] with delineation
{
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}");
int result = (int)InvokeOp("JsonSetValue", storeId, "{Fun]Circus}", "Times");
Assert.That(result, Is.EqualTo(1));
string value = (string)InvokeOp("JsonGetValue", storeId, "{Fun]Circus}");
Assert.That(value, Is.EqualTo("Times"));
}
// Test setting a key containing unbalanced [ with delineation
{
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}");
int result = (int)InvokeOp("JsonSetValue", storeId, "{Fun[Circus}", "Times");
Assert.That(result, Is.EqualTo(1));
string value = (string)InvokeOp("JsonGetValue", storeId, "{Fun[Circus}");
Assert.That(value, Is.EqualTo("Times"));
}
// Test setting a key containing empty balanced [] with delineation
{
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}");
int result = (int)InvokeOp("JsonSetValue", storeId, "{Fun[]Circus}", "Times");
Assert.That(result, Is.EqualTo(1));
string value = (string)InvokeOp("JsonGetValue", storeId, "{Fun[]Circus}");
Assert.That(value, Is.EqualTo("Times"));
}
// // Commented out as this currently unexpectedly fails.
// // Test setting a key containing brackets around an integer with delineation
// {
// UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}");
//
// int result = (int)InvokeOp("JsonSetValue", storeId, "{Fun[0]Circus}", "Times");
// Assert.That(result, Is.EqualTo(1));
//
// string value = (string)InvokeOp("JsonGetValue", storeId, "{Fun[0]Circus}");
// Assert.That(value, Is.EqualTo("Times"));
// }
// *** Test {} ***
// Test setting a key containing unbalanced } without delineation. Expecting failure (?)
{
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}");
int result = (int)InvokeOp("JsonSetValue", storeId, "Fun}Circus", "Times");
Assert.That(result, Is.EqualTo(0));
string value = (string)InvokeOp("JsonGetValue", storeId, "Fun}Circus");
Assert.That(value, Is.EqualTo(""));
}
// Test setting a key containing unbalanced { without delineation. Expecting failure (?)
{
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}");
int result = (int)InvokeOp("JsonSetValue", storeId, "Fun{Circus", "Times");
Assert.That(result, Is.EqualTo(0));
string value = (string)InvokeOp("JsonGetValue", storeId, "Fun}Circus");
Assert.That(value, Is.EqualTo(""));
}
// // Commented out as this currently unexpectedly fails.
// // Test setting a key containing unbalanced }
// {
// UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}");
//
// int result = (int)InvokeOp("JsonSetValue", storeId, "{Fun}Circus}", "Times");
// Assert.That(result, Is.EqualTo(0));
// }
// Test setting a key containing unbalanced { with delineation
{
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}");
int result = (int)InvokeOp("JsonSetValue", storeId, "{Fun{Circus}", "Times");
Assert.That(result, Is.EqualTo(1));
string value = (string)InvokeOp("JsonGetValue", storeId, "{Fun{Circus}");
Assert.That(value, Is.EqualTo("Times"));
}
// Test setting a key containing balanced {} with delineation. This should fail.
{
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}");
int result = (int)InvokeOp("JsonSetValue", storeId, "{Fun{Filled}Circus}", "Times");
Assert.That(result, Is.EqualTo(0));
string value = (string)InvokeOp("JsonGetValue", storeId, "{Fun{Filled}Circus}");
Assert.That(value, Is.EqualTo(""));
}
// Test setting to location that does not exist. This should fail.
{
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}");
int result = (int)InvokeOp("JsonSetValue", storeId, "Fun.Circus", "Times");
Assert.That(result, Is.EqualTo(0));
string value = (string)InvokeOp("JsonGetValue", storeId, "Fun.Circus");
Assert.That(value, Is.EqualTo(""));
}
// Test with fake store
{
UUID fakeStoreId = TestHelpers.ParseTail(0x500);
int fakeStoreValueSet = (int)InvokeOp("JsonSetValue", fakeStoreId, "Hello", "World");
Assert.That(fakeStoreValueSet, Is.EqualTo(0));
}
}
[Test]
public void TestJsonSetJson()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
// Single quoted token case
{
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ }");
int result = (int)InvokeOp("JsonSetJson", storeId, "Fun", "'Times'");
Assert.That(result, Is.EqualTo(1));
string value = (string)InvokeOp("JsonGetValue", storeId, "Fun");
Assert.That(value, Is.EqualTo("Times"));
}
// Sub-tree case
{
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ }");
int result = (int)InvokeOp("JsonSetJson", storeId, "Fun", "{ 'Filled' : 'Times' }");
Assert.That(result, Is.EqualTo(1));
string value = (string)InvokeOp("JsonGetValue", storeId, "Fun.Filled");
Assert.That(value, Is.EqualTo("Times"));
}
// If setting single strings in JsonSetValueJson, these must be single quoted tokens, not bare strings.
{
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ }");
int result = (int)InvokeOp("JsonSetJson", storeId, "Fun", "Times");
Assert.That(result, Is.EqualTo(0));
string value = (string)InvokeOp("JsonGetValue", storeId, "Fun");
Assert.That(value, Is.EqualTo(""));
}
// Test setting to location that does not exist. This should fail.
{
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ }");
int result = (int)InvokeOp("JsonSetJson", storeId, "Fun.Circus", "'Times'");
Assert.That(result, Is.EqualTo(0));
string value = (string)InvokeOp("JsonGetValue", storeId, "Fun.Circus");
Assert.That(value, Is.EqualTo(""));
}
// Test with fake store
{
UUID fakeStoreId = TestHelpers.ParseTail(0x500);
int fakeStoreValueSet = (int)InvokeOp("JsonSetJson", fakeStoreId, "Hello", "'World'");
Assert.That(fakeStoreValueSet, Is.EqualTo(0));
}
}
/// <summary>
/// Test for writing json to a notecard
/// </summary>
/// <remarks>
/// TODO: Really needs to test correct receipt of the link_message event. Could do this by directly fetching
/// it via the MockScriptEngine or perhaps by a dummy script instance.
/// </remarks>
[Test]
public void TestJsonWriteNotecard()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, TestHelpers.ParseTail(0x1));
m_scene.AddSceneObject(so);
UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello':'World' }");
{
string notecardName = "nc1";
// Write notecard
UUID writeNotecardRequestId = (UUID)InvokeOpOnHost("JsonWriteNotecard", so.UUID, storeId, "", notecardName);
Assert.That(writeNotecardRequestId, Is.Not.EqualTo(UUID.Zero));
TaskInventoryItem nc1Item = so.RootPart.Inventory.GetInventoryItem(notecardName);
Assert.That(nc1Item, Is.Not.Null);
// TODO: Should independently check the contents.
}
// TODO: Write partial test
{
// Try to write notecard for a bad path
// In this case we do get a request id but no notecard is written.
string badPathNotecardName = "badPathNotecardName";
UUID writeNotecardBadPathRequestId
= (UUID)InvokeOpOnHost("JsonWriteNotecard", so.UUID, storeId, "flibble", badPathNotecardName);
Assert.That(writeNotecardBadPathRequestId, Is.Not.EqualTo(UUID.Zero));
TaskInventoryItem badPathItem = so.RootPart.Inventory.GetInventoryItem(badPathNotecardName);
Assert.That(badPathItem, Is.Null);
}
{
// Test with fake store
// In this case we do get a request id but no notecard is written.
string fakeStoreNotecardName = "fakeStoreNotecardName";
UUID fakeStoreId = TestHelpers.ParseTail(0x500);
UUID fakeStoreWriteNotecardValue
= (UUID)InvokeOpOnHost("JsonWriteNotecard", so.UUID, fakeStoreId, "", fakeStoreNotecardName);
Assert.That(fakeStoreWriteNotecardValue, Is.Not.EqualTo(UUID.Zero));
TaskInventoryItem fakeStoreItem = so.RootPart.Inventory.GetInventoryItem(fakeStoreNotecardName);
Assert.That(fakeStoreItem, Is.Null);
}
}
/// <summary>
/// Test for reading json from a notecard
/// </summary>
/// <remarks>
/// TODO: Really needs to test correct receipt of the link_message event. Could do this by directly fetching
/// it via the MockScriptEngine or perhaps by a dummy script instance.
/// </remarks>
[Test]
public void TestJsonReadNotecard()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
string notecardName = "nc1";
SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, TestHelpers.ParseTail(0x1));
m_scene.AddSceneObject(so);
UUID creatingStoreId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello':'World' }");
// Write notecard
InvokeOpOnHost("JsonWriteNotecard", so.UUID, creatingStoreId, "", notecardName);
{
// Read notecard
UUID receivingStoreId = (UUID)InvokeOp("JsonCreateStore", "{}");
UUID readNotecardRequestId = (UUID)InvokeOpOnHost("JsonReadNotecard", so.UUID, receivingStoreId, "", notecardName);
Assert.That(readNotecardRequestId, Is.Not.EqualTo(UUID.Zero));
string value = (string)InvokeOp("JsonGetValue", receivingStoreId, "Hello");
Assert.That(value, Is.EqualTo("World"));
}
{
// Read notecard to new single component path
UUID receivingStoreId = (UUID)InvokeOp("JsonCreateStore", "{}");
UUID readNotecardRequestId = (UUID)InvokeOpOnHost("JsonReadNotecard", so.UUID, receivingStoreId, "make", notecardName);
Assert.That(readNotecardRequestId, Is.Not.EqualTo(UUID.Zero));
string value = (string)InvokeOp("JsonGetValue", receivingStoreId, "Hello");
Assert.That(value, Is.EqualTo(""));
value = (string)InvokeOp("JsonGetValue", receivingStoreId, "make.Hello");
Assert.That(value, Is.EqualTo("World"));
}
{
// Read notecard to new multi-component path. This should not work.
UUID receivingStoreId = (UUID)InvokeOp("JsonCreateStore", "{}");
UUID readNotecardRequestId = (UUID)InvokeOpOnHost("JsonReadNotecard", so.UUID, receivingStoreId, "make.it", notecardName);
Assert.That(readNotecardRequestId, Is.Not.EqualTo(UUID.Zero));
string value = (string)InvokeOp("JsonGetValue", receivingStoreId, "Hello");
Assert.That(value, Is.EqualTo(""));
value = (string)InvokeOp("JsonGetValue", receivingStoreId, "make.it.Hello");
Assert.That(value, Is.EqualTo(""));
}
{
// Read notecard to existing multi-component path. This should work
UUID receivingStoreId = (UUID)InvokeOp("JsonCreateStore", "{ 'make' : { 'it' : 'so' } }");
UUID readNotecardRequestId = (UUID)InvokeOpOnHost("JsonReadNotecard", so.UUID, receivingStoreId, "make.it", notecardName);
Assert.That(readNotecardRequestId, Is.Not.EqualTo(UUID.Zero));
string value = (string)InvokeOp("JsonGetValue", receivingStoreId, "Hello");
Assert.That(value, Is.EqualTo(""));
value = (string)InvokeOp("JsonGetValue", receivingStoreId, "make.it.Hello");
Assert.That(value, Is.EqualTo("World"));
}
{
// Read notecard to invalid path. This should not work.
UUID receivingStoreId = (UUID)InvokeOp("JsonCreateStore", "{ 'make' : { 'it' : 'so' } }");
UUID readNotecardRequestId = (UUID)InvokeOpOnHost("JsonReadNotecard", so.UUID, receivingStoreId, "/", notecardName);
Assert.That(readNotecardRequestId, Is.Not.EqualTo(UUID.Zero));
string value = (string)InvokeOp("JsonGetValue", receivingStoreId, "Hello");
Assert.That(value, Is.EqualTo(""));
}
{
// Try read notecard to fake store.
UUID fakeStoreId = TestHelpers.ParseTail(0x500);
UUID readNotecardRequestId = (UUID)InvokeOpOnHost("JsonReadNotecard", so.UUID, fakeStoreId, "", notecardName);
Assert.That(readNotecardRequestId, Is.Not.EqualTo(UUID.Zero));
string value = (string)InvokeOp("JsonGetValue", fakeStoreId, "Hello");
Assert.That(value, Is.EqualTo(""));
}
}
public object DummyTestMethod(object o1, object o2, object o3, object o4, object o5)
{
return null;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.