context
stringlengths
2.52k
185k
gt
stringclasses
1 value
#region license // Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // // DO NOT EDIT THIS FILE! // // This file was generated automatically by astgen.boo. // namespace Boo.Lang.Compiler.Ast { using System.Collections; using System.Runtime.Serialization; [System.Serializable] public partial class TryStatement : Statement { protected Block _protectedBlock; protected ExceptionHandlerCollection _exceptionHandlers; protected Block _failureBlock; protected Block _ensureBlock; [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public TryStatement CloneNode() { return (TryStatement)Clone(); } /// <summary> /// <see cref="Node.CleanClone"/> /// </summary> [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public TryStatement CleanClone() { return (TryStatement)base.CleanClone(); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public NodeType NodeType { get { return NodeType.TryStatement; } } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public void Accept(IAstVisitor visitor) { visitor.OnTryStatement(this); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Matches(Node node) { if (node == null) return false; if (NodeType != node.NodeType) return false; var other = ( TryStatement)node; if (!Node.Matches(_modifier, other._modifier)) return NoMatch("TryStatement._modifier"); if (!Node.Matches(_protectedBlock, other._protectedBlock)) return NoMatch("TryStatement._protectedBlock"); if (!Node.AllMatch(_exceptionHandlers, other._exceptionHandlers)) return NoMatch("TryStatement._exceptionHandlers"); if (!Node.Matches(_failureBlock, other._failureBlock)) return NoMatch("TryStatement._failureBlock"); if (!Node.Matches(_ensureBlock, other._ensureBlock)) return NoMatch("TryStatement._ensureBlock"); return true; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Replace(Node existing, Node newNode) { if (base.Replace(existing, newNode)) { return true; } if (_modifier == existing) { this.Modifier = (StatementModifier)newNode; return true; } if (_protectedBlock == existing) { this.ProtectedBlock = (Block)newNode; return true; } if (_exceptionHandlers != null) { ExceptionHandler item = existing as ExceptionHandler; if (null != item) { ExceptionHandler newItem = (ExceptionHandler)newNode; if (_exceptionHandlers.Replace(item, newItem)) { return true; } } } if (_failureBlock == existing) { this.FailureBlock = (Block)newNode; return true; } if (_ensureBlock == existing) { this.EnsureBlock = (Block)newNode; return true; } return false; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public object Clone() { TryStatement clone = (TryStatement)FormatterServices.GetUninitializedObject(typeof(TryStatement)); clone._lexicalInfo = _lexicalInfo; clone._endSourceLocation = _endSourceLocation; clone._documentation = _documentation; clone._entity = _entity; if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone(); if (null != _modifier) { clone._modifier = _modifier.Clone() as StatementModifier; clone._modifier.InitializeParent(clone); } if (null != _protectedBlock) { clone._protectedBlock = _protectedBlock.Clone() as Block; clone._protectedBlock.InitializeParent(clone); } if (null != _exceptionHandlers) { clone._exceptionHandlers = _exceptionHandlers.Clone() as ExceptionHandlerCollection; clone._exceptionHandlers.InitializeParent(clone); } if (null != _failureBlock) { clone._failureBlock = _failureBlock.Clone() as Block; clone._failureBlock.InitializeParent(clone); } if (null != _ensureBlock) { clone._ensureBlock = _ensureBlock.Clone() as Block; clone._ensureBlock.InitializeParent(clone); } return clone; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override internal void ClearTypeSystemBindings() { _annotations = null; _entity = null; if (null != _modifier) { _modifier.ClearTypeSystemBindings(); } if (null != _protectedBlock) { _protectedBlock.ClearTypeSystemBindings(); } if (null != _exceptionHandlers) { _exceptionHandlers.ClearTypeSystemBindings(); } if (null != _failureBlock) { _failureBlock.ClearTypeSystemBindings(); } if (null != _ensureBlock) { _ensureBlock.ClearTypeSystemBindings(); } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public Block ProtectedBlock { get { if (_protectedBlock == null) { _protectedBlock = new Block(); _protectedBlock.InitializeParent(this); } return _protectedBlock; } set { if (_protectedBlock != value) { _protectedBlock = value; if (null != _protectedBlock) { _protectedBlock.InitializeParent(this); } } } } [System.Xml.Serialization.XmlArray] [System.Xml.Serialization.XmlArrayItem(typeof(ExceptionHandler))] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public ExceptionHandlerCollection ExceptionHandlers { get { return _exceptionHandlers ?? (_exceptionHandlers = new ExceptionHandlerCollection(this)); } set { if (_exceptionHandlers != value) { _exceptionHandlers = value; if (null != _exceptionHandlers) { _exceptionHandlers.InitializeParent(this); } } } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public Block FailureBlock { get { return _failureBlock; } set { if (_failureBlock != value) { _failureBlock = value; if (null != _failureBlock) { _failureBlock.InitializeParent(this); } } } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public Block EnsureBlock { get { return _ensureBlock; } set { if (_ensureBlock != value) { _ensureBlock = value; if (null != _ensureBlock) { _ensureBlock.InitializeParent(this); } } } } } }
/* * Comparers - Various Comparer classes used within ObjectListView * * Author: Phillip Piper * Date: 25/11/2008 17:15 * * Change log: * v2.8.1 * 2014-12-03 JPP - Added StringComparer * v2.3 * 2009-08-24 JPP - Added OLVGroupComparer * 2009-06-01 JPP - ModelObjectComparer would crash if secondary sort column was null. * 2008-12-20 JPP - Fixed bug with group comparisons when a group key was null (SF#2445761) * 2008-11-25 JPP Initial version * * TO DO: * * Copyright (C) 2006-2014 Phillip Piper * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. */ using System; using System.Collections; using System.Collections.Generic; using System.Windows.Forms; namespace BrightIdeasSoftware { /// <summary> /// ColumnComparer is the workhorse for all comparison between two values of a particular column. /// If the column has a specific comparer, use that to compare the values. Otherwise, do /// a case insensitive string compare of the string representations of the values. /// </summary> /// <remarks><para>This class inherits from both IComparer and its generic counterpart /// so that it can be used on untyped and typed collections.</para> /// <para>This is used by normal (non-virtual) ObjectListViews. Virtual lists use /// ModelObjectComparer</para> /// </remarks> public class ColumnComparer : IComparer, IComparer<OLVListItem> { /// <summary> /// Gets or sets the method that will be used to compare two strings. /// The default is to compare on the current culture, case-insensitive /// </summary> public static StringCompareDelegate StringComparer { get { return stringComparer; } set { stringComparer = value; } } private static StringCompareDelegate stringComparer; /// <summary> /// Create a ColumnComparer that will order the rows in a list view according /// to the values in a given column /// </summary> /// <param name="col">The column whose values will be compared</param> /// <param name="order">The ordering for column values</param> public ColumnComparer(OLVColumn col, SortOrder order) { this.column = col; this.sortOrder = order; } /// <summary> /// Create a ColumnComparer that will order the rows in a list view according /// to the values in a given column, and by a secondary column if the primary /// column is equal. /// </summary> /// <param name="col">The column whose values will be compared</param> /// <param name="order">The ordering for column values</param> /// <param name="col2">The column whose values will be compared for secondary sorting</param> /// <param name="order2">The ordering for secondary column values</param> public ColumnComparer(OLVColumn col, SortOrder order, OLVColumn col2, SortOrder order2) : this(col, order) { // There is no point in secondary sorting on the same column if (col != col2) this.secondComparer = new ColumnComparer(col2, order2); } /// <summary> /// Compare two rows /// </summary> /// <param name="x">row1</param> /// <param name="y">row2</param> /// <returns>An ordering indication: -1, 0, 1</returns> public int Compare(object x, object y) { return this.Compare((OLVListItem)x, (OLVListItem)y); } /// <summary> /// Compare two rows /// </summary> /// <param name="x">row1</param> /// <param name="y">row2</param> /// <returns>An ordering indication: -1, 0, 1</returns> public int Compare(OLVListItem x, OLVListItem y) { if (this.sortOrder == SortOrder.None) return 0; int result = 0; object x1 = this.column.GetValue(x.RowObject); object y1 = this.column.GetValue(y.RowObject); // Handle nulls. Null values come last bool xIsNull = (x1 == null || x1 == System.DBNull.Value); bool yIsNull = (y1 == null || y1 == System.DBNull.Value); if (xIsNull || yIsNull) { if (xIsNull && yIsNull) result = 0; else result = (xIsNull ? -1 : 1); } else { result = this.CompareValues(x1, y1); } if (this.sortOrder == SortOrder.Descending) result = 0 - result; // If the result was equality, use the secondary comparer to resolve it if (result == 0 && this.secondComparer != null) result = this.secondComparer.Compare(x, y); return result; } /// <summary> /// Compare the actual values to be used for sorting /// </summary> /// <param name="x">The aspect extracted from the first row</param> /// <param name="y">The aspect extracted from the second row</param> /// <returns>An ordering indication: -1, 0, 1</returns> public int CompareValues(object x, object y) { // Force case insensitive compares on strings if (x is string xAsString) return CompareStrings(xAsString, y as String); return x is IComparable comparable ? comparable.CompareTo(y) : 0; } private static int CompareStrings(string x, string y) { if (StringComparer == null) return String.Compare(x, y, StringComparison.CurrentCultureIgnoreCase); else return StringComparer(x, y); } private OLVColumn column; private SortOrder sortOrder; private ColumnComparer secondComparer; } /// <summary> /// This comparer sort list view groups. OLVGroups have a "SortValue" property, /// which is used if present. Otherwise, the titles of the groups will be compared. /// </summary> public class OLVGroupComparer : IComparer<OLVGroup> { /// <summary> /// Create a group comparer /// </summary> /// <param name="order">The ordering for column values</param> public OLVGroupComparer(SortOrder order) { this.sortOrder = order; } /// <summary> /// Compare the two groups. OLVGroups have a "SortValue" property, /// which is used if present. Otherwise, the titles of the groups will be compared. /// </summary> /// <param name="x">group1</param> /// <param name="y">group2</param> /// <returns>An ordering indication: -1, 0, 1</returns> public int Compare(OLVGroup x, OLVGroup y) { // If we can compare the sort values, do that. // Otherwise do a case insensitive compare on the group header. int result; if (x.SortValue != null && y.SortValue != null) result = x.SortValue.CompareTo(y.SortValue); else result = String.Compare(x.Header, y.Header, StringComparison.CurrentCultureIgnoreCase); if (this.sortOrder == SortOrder.Descending) result = 0 - result; return result; } private SortOrder sortOrder; } /// <summary> /// This comparer can be used to sort a collection of model objects by a given column /// </summary> /// <remarks> /// <para>This is used by virtual ObjectListViews. Non-virtual lists use /// ColumnComparer</para> /// </remarks> public class ModelObjectComparer : IComparer, IComparer<object> { /// <summary> /// Gets or sets the method that will be used to compare two strings. /// The default is to compare on the current culture, case-insensitive /// </summary> public static StringCompareDelegate StringComparer { get { return stringComparer; } set { stringComparer = value; } } private static StringCompareDelegate stringComparer; /// <summary> /// Create a model object comparer /// </summary> /// <param name="col"></param> /// <param name="order"></param> public ModelObjectComparer(OLVColumn col, SortOrder order) { this.column = col; this.sortOrder = order; } /// <summary> /// Create a model object comparer with a secondary sorting column /// </summary> /// <param name="col"></param> /// <param name="order"></param> /// <param name="col2"></param> /// <param name="order2"></param> public ModelObjectComparer(OLVColumn col, SortOrder order, OLVColumn col2, SortOrder order2) : this(col, order) { // There is no point in secondary sorting on the same column if (col != col2 && col2 != null && order2 != SortOrder.None) this.secondComparer = new ModelObjectComparer(col2, order2); } /// <summary> /// Compare the two model objects /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public int Compare(object x, object y) { int result = 0; object x1 = this.column.GetValue(x); object y1 = this.column.GetValue(y); if (this.sortOrder == SortOrder.None) return 0; // Handle nulls. Null values come last bool xIsNull = (x1 == null || x1 == System.DBNull.Value); bool yIsNull = (y1 == null || y1 == System.DBNull.Value); if (xIsNull || yIsNull) { if (xIsNull && yIsNull) result = 0; else result = (xIsNull ? -1 : 1); } else { result = this.CompareValues(x1, y1); } if (this.sortOrder == SortOrder.Descending) result = 0 - result; // If the result was equality, use the secondary comparer to resolve it if (result == 0 && this.secondComparer != null) result = this.secondComparer.Compare(x, y); return result; } /// <summary> /// Compare the actual values /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public int CompareValues(object x, object y) { // Force case insensitive compares on strings if (x is string xStr) return CompareStrings(xStr, y as String); return x is IComparable comparable ? comparable.CompareTo(y) : 0; } private static int CompareStrings(string x, string y) { if (StringComparer == null) return String.Compare(x, y, StringComparison.CurrentCultureIgnoreCase); else return StringComparer(x, y); } private OLVColumn column; private SortOrder sortOrder; private ModelObjectComparer secondComparer; #region IComparer<object> Members #endregion } }
// <copyright file="SparseMatrixTests.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-2013 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 System.Collections.Generic; using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Single; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Single { /// <summary> /// Sparse matrix tests. /// </summary> public class SparseMatrixTests : MatrixTests { /// <summary> /// Creates a matrix for the given number of rows and columns. /// </summary> /// <param name="rows">The number of rows.</param> /// <param name="columns">The number of columns.</param> /// <returns>A matrix with the given dimensions.</returns> protected override Matrix<float> CreateMatrix(int rows, int columns) { return new SparseMatrix(rows, columns); } /// <summary> /// Creates a matrix from a 2D array. /// </summary> /// <param name="data">The 2D array to create this matrix from.</param> /// <returns>A matrix with the given values.</returns> protected override Matrix<float> CreateMatrix(float[,] data) { return SparseMatrix.OfArray(data); } /// <summary> /// Can create a matrix form array. /// </summary> [Test] public void CanCreateMatrixFrom1DArray() { var testData = new Dictionary<string, Matrix<float>> { {"Singular3x3", SparseMatrix.OfColumnMajor(3, 3, new float[] {1, 1, 1, 1, 1, 1, 2, 2, 2})}, {"Square3x3", SparseMatrix.OfColumnMajor(3, 3, new[] {-1.1f, 0.0f, -4.4f, -2.2f, 1.1f, 5.5f, -3.3f, 2.2f, 6.6f})}, {"Square4x4", SparseMatrix.OfColumnMajor(4, 4, new[] {-1.1f, 0.0f, 1.0f, -4.4f, -2.2f, 1.1f, 2.1f, 5.5f, -3.3f, 2.2f, 6.2f, 6.6f, -4.4f, 3.3f, 4.3f, -7.7f})}, {"Tall3x2", SparseMatrix.OfColumnMajor(3, 2, new[] {-1.1f, 0.0f, -4.4f, -2.2f, 1.1f, 5.5f})}, {"Wide2x3", SparseMatrix.OfColumnMajor(2, 3, new[] {-1.1f, 0.0f, -2.2f, 1.1f, -3.3f, 2.2f})} }; foreach (var name in testData.Keys) { Assert.AreEqual(TestMatrices[name], testData[name]); } } /// <summary> /// Matrix from array is a copy. /// </summary> [Test] public void MatrixFrom1DArrayIsCopy() { // Sparse Matrix copies values from float[], but no remember reference. var data = new float[] {1, 1, 1, 1, 1, 1, 2, 2, 2}; var matrix = SparseMatrix.OfColumnMajor(3, 3, data); matrix[0, 0] = 10.0f; Assert.AreNotEqual(10.0f, data[0]); } /// <summary> /// Matrix from two-dimensional array is a copy. /// </summary> [Test] public void MatrixFrom2DArrayIsCopy() { var matrix = SparseMatrix.OfArray(TestData2D["Singular3x3"]); matrix[0, 0] = 10.0f; Assert.AreEqual(1.0f, TestData2D["Singular3x3"][0, 0]); } /// <summary> /// Can create a matrix from two-dimensional array. /// </summary> /// <param name="name">Matrix name.</param> [TestCase("Singular3x3")] [TestCase("Singular4x4")] [TestCase("Square3x3")] [TestCase("Square4x4")] [TestCase("Tall3x2")] [TestCase("Wide2x3")] public void CanCreateMatrixFrom2DArray(string name) { var matrix = SparseMatrix.OfArray(TestData2D[name]); for (var i = 0; i < TestData2D[name].GetLength(0); i++) { for (var j = 0; j < TestData2D[name].GetLength(1); j++) { Assert.AreEqual(TestData2D[name][i, j], matrix[i, j]); } } } /// <summary> /// Can create an identity matrix. /// </summary> [Test] public void CanCreateIdentity() { var matrix = SparseMatrix.CreateIdentity(5); for (var i = 0; i < matrix.RowCount; i++) { for (var j = 0; j < matrix.ColumnCount; j++) { Assert.AreEqual(i == j ? 1.0f : 0.0f, matrix[i, j]); } } } /// <summary> /// Identity with wrong order throws <c>ArgumentOutOfRangeException</c>. /// </summary> /// <param name="order">The size of the square matrix</param> [TestCase(0)] [TestCase(-1)] public void IdentityWithWrongOrderThrowsArgumentOutOfRangeException(int order) { Assert.That(() => SparseMatrix.CreateIdentity(order), Throws.TypeOf<ArgumentOutOfRangeException>()); } /// <summary> /// Can create a large sparse matrix /// </summary> [Test] public void CanCreateLargeSparseMatrix() { var matrix = new SparseMatrix(500, 1000); var nonzero = 0; var rnd = new System.Random(0); for (var i = 0; i < matrix.RowCount; i++) { for (var j = 0; j < matrix.ColumnCount; j++) { var value = rnd.Next(10)*rnd.Next(10)*rnd.Next(10)*rnd.Next(10)*rnd.Next(10); if (value != 0) { nonzero++; } matrix[i, j] = value; } } Assert.AreEqual(matrix.NonZerosCount, nonzero); } /// <summary> /// Test whether order matters when adding sparse matrices. /// </summary> [Test] public void CanAddSparseMatricesBothWays() { var m1 = new SparseMatrix(1, 3); var m2 = SparseMatrix.OfArray(new float[,] { { 0, 1, 1 } }); var sum1 = m1 + m2; var sum2 = m2 + m1; Assert.IsTrue(sum1.Equals(m2)); Assert.IsTrue(sum1.Equals(sum2)); var sparseResult = new SparseMatrix(1, 3); sparseResult.Add(m2, sparseResult); Assert.IsTrue(sparseResult.Equals(sum1)); sparseResult = SparseMatrix.OfArray(new float[,] { { 0, 1, 1 } }); sparseResult.Add(m1, sparseResult); Assert.IsTrue(sparseResult.Equals(sum1)); sparseResult = SparseMatrix.OfArray(new float[,] { { 0, 1, 1 } }); m1.Add(sparseResult, sparseResult); Assert.IsTrue(sparseResult.Equals(sum1)); sparseResult = SparseMatrix.OfArray(new float[,] { { 0, 1, 1 } }); sparseResult.Add(sparseResult, sparseResult); Assert.IsTrue(sparseResult.Equals(2*sum1)); var denseResult = new DenseMatrix(1, 3); denseResult.Add(m2, denseResult); Assert.IsTrue(denseResult.Equals(sum1)); denseResult = DenseMatrix.OfArray(new float[,] {{0, 1, 1}}); denseResult.Add(m1, denseResult); Assert.IsTrue(denseResult.Equals(sum1)); var m3 = DenseMatrix.OfArray(new float[,] {{0, 1, 1}}); var sum3 = m1 + m3; var sum4 = m3 + m1; Assert.IsTrue(sum3.Equals(m3)); Assert.IsTrue(sum3.Equals(sum4)); } /// <summary> /// Test whether order matters when subtracting sparse matrices. /// </summary> [Test] public void CanSubtractSparseMatricesBothWays() { var m1 = new SparseMatrix(1, 3); var m2 = SparseMatrix.OfArray(new float[,] { { 0, 1, 1 } }); var diff1 = m1 - m2; var diff2 = m2 - m1; Assert.IsTrue(diff1.Equals(m2.Negate())); Assert.IsTrue(diff1.Equals(diff2.Negate())); var sparseResult = new SparseMatrix(1, 3); sparseResult.Subtract(m2, sparseResult); Assert.IsTrue(sparseResult.Equals(diff1)); sparseResult = SparseMatrix.OfArray(new float[,] { { 0, 1, 1 } }); sparseResult.Subtract(m1, sparseResult); Assert.IsTrue(sparseResult.Equals(diff2)); sparseResult = SparseMatrix.OfArray(new float[,] { { 0, 1, 1 } }); m1.Subtract(sparseResult, sparseResult); Assert.IsTrue(sparseResult.Equals(diff1)); sparseResult = SparseMatrix.OfArray(new float[,] { { 0, 1, 1 } }); sparseResult.Subtract(sparseResult, sparseResult); Assert.IsTrue(sparseResult.Equals(0*diff1)); var denseResult = new DenseMatrix(1, 3); denseResult.Subtract(m2, denseResult); Assert.IsTrue(denseResult.Equals(diff1)); denseResult = DenseMatrix.OfArray(new float[,] {{0, 1, 1}}); denseResult.Subtract(m1, denseResult); Assert.IsTrue(denseResult.Equals(diff2)); var m3 = DenseMatrix.OfArray(new float[,] {{0, 1, 1}}); var diff3 = m1 - m3; var diff4 = m3 - m1; Assert.IsTrue(diff3.Equals(m3.Negate())); Assert.IsTrue(diff3.Equals(diff4.Negate())); } /// <summary> /// Test whether we can create a large sparse matrix /// </summary> [Test] public void CanCreateLargeMatrix() { const int Order = 1000000; var matrix = new SparseMatrix(Order); Assert.AreEqual(Order, matrix.RowCount); Assert.AreEqual(Order, matrix.ColumnCount); Assert.DoesNotThrow(() => matrix[0, 0] = 1); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using Xunit; namespace System.Linq.Tests { public class ToLookupTests : EnumerableTests { private static void AssertMatches<K, T>(IEnumerable<K> keys, IEnumerable<T> elements, System.Linq.ILookup<K, T> lookup) { Assert.NotNull(lookup); Assert.NotNull(keys); Assert.NotNull(elements); int num = 0; using (IEnumerator<K> keyEnumerator = keys.GetEnumerator()) using (IEnumerator<T> elEnumerator = elements.GetEnumerator()) { while (keyEnumerator.MoveNext()) { Assert.True(lookup.Contains(keyEnumerator.Current)); foreach (T e in lookup[keyEnumerator.Current]) { Assert.True(elEnumerator.MoveNext()); Assert.Equal(e, elEnumerator.Current); } ++num; } Assert.False(elEnumerator.MoveNext()); } Assert.Equal(num, lookup.Count); } [Fact] public void SameResultsRepeatCall() { var q1 = from x1 in new string[] { "Alen", "Felix", null, null, "X", "Have Space", "Clinton", "" } select x1; ; var q2 = from x2 in new int[] { 55, 49, 9, -100, 24, 25, -1, 0 } select x2; var q = from x3 in q1 from x4 in q2 select new { a1 = x3, a2 = x4 }; Assert.Equal(q.ToLookup(e => e.a1), q.ToLookup(e => e.a1)); } [Fact] public void NullKeyIncluded() { string[] key = { "Chris", "Bob", null, "Tim" }; int[] element = { 50, 95, 55, 90 }; var source = key.Zip(element, (k, e) => new { Name = k, Score = e }); AssertMatches(key, source, source.ToLookup(e => e.Name)); } [Fact] public void OneElementCustomComparer() { string[] key = { "Chris" }; int[] element = { 50 }; var source = new [] { new {Name = "risCh", Score = 50} }; AssertMatches(key, source, source.ToLookup(e => e.Name, new AnagramEqualityComparer())); } [Fact] public void UniqueElementsElementSelector() { string[] key = { "Chris", "Prakash", "Tim", "Robert", "Brian" }; int[] element = { 50, 100, 95, 60, 80 }; var source = new [] { new { Name = key[0], Score = element[0] }, new { Name = key[1], Score = element[1] }, new { Name = key[2], Score = element[2] }, new { Name = key[3], Score = element[3] }, new { Name = key[4], Score = element[4] } }; AssertMatches(key, element, source.ToLookup(e => e.Name, e => e.Score)); } [Fact] public void DuplicateKeys() { string[] key = { "Chris", "Prakash", "Robert" }; int[] element = { 50, 80, 100, 95, 99, 56 }; var source = new[] { new { Name = key[0], Score = element[0] }, new { Name = key[1], Score = element[2] }, new { Name = key[2], Score = element[5] }, new { Name = key[1], Score = element[3] }, new { Name = key[0], Score = element[1] }, new { Name = key[1], Score = element[4] } }; AssertMatches(key, element, source.ToLookup(e => e.Name, e => e.Score, new AnagramEqualityComparer())); } [Fact] public void RunOnce() { string[] key = { "Chris", "Prakash", "Robert" }; int[] element = { 50, 80, 100, 95, 99, 56 }; var source = new[] { new { Name = key[0], Score = element[0] }, new { Name = key[1], Score = element[2] }, new { Name = key[2], Score = element[5] }, new { Name = key[1], Score = element[3] }, new { Name = key[0], Score = element[1] }, new { Name = key[1], Score = element[4] } }; AssertMatches(key, element, source.RunOnce().ToLookup(e => e.Name, e => e.Score, new AnagramEqualityComparer())); } [Fact] public void Count() { string[] key = { "Chris", "Prakash", "Robert" }; int[] element = { 50, 80, 100, 95, 99, 56 }; var source = new[] { new { Name = key[0], Score = element[0] }, new { Name = key[1], Score = element[2] }, new { Name = key[2], Score = element[5] }, new { Name = key[1], Score = element[3] }, new { Name = key[0], Score = element[1] }, new { Name = key[1], Score = element[4] } }; Assert.Equal(3, source.ToLookup(e => e.Name, e => e.Score).Count()); } [Fact] public void EmptySource() { string[] key = { }; int[] element = { }; var source = key.Zip(element, (k, e) => new { Name = k, Score = e }); AssertMatches(key, element, source.ToLookup(e => e.Name, e => e.Score, new AnagramEqualityComparer())); } [Fact] public void SingleNullKeyAndElement() { string[] key = { null }; string[] element = { null }; string[] source = new string[] { null }; AssertMatches(key, element, source.ToLookup(e => e, e => e, EqualityComparer<string>.Default)); } [Fact] public void NullSource() { IEnumerable<int> source = null; Assert.Throws<ArgumentNullException>("source", () => source.ToLookup(i => i / 10)); } [Fact] public void NullSourceExplicitComparer() { IEnumerable<int> source = null; Assert.Throws<ArgumentNullException>("source", () => source.ToLookup(i => i / 10, EqualityComparer<int>.Default)); } [Fact] public void NullSourceElementSelector() { IEnumerable<int> source = null; Assert.Throws<ArgumentNullException>("source", () => source.ToLookup(i => i / 10, i => i + 2)); } [Fact] public void NullSourceElementSelectorExplicitComparer() { IEnumerable<int> source = null; Assert.Throws<ArgumentNullException>("source", () => source.ToLookup(i => i / 10, i => i + 2, EqualityComparer<int>.Default)); } [Fact] public void NullKeySelector() { Func<int, int> keySelector = null; Assert.Throws<ArgumentNullException>("keySelector", () => Enumerable.Range(0, 1000).ToLookup(keySelector)); } [Fact] public void NullKeySelectorExplicitComparer() { Func<int, int> keySelector = null; Assert.Throws<ArgumentNullException>("keySelector", () => Enumerable.Range(0, 1000).ToLookup(keySelector, EqualityComparer<int>.Default)); } [Fact] public void NullKeySelectorElementSelector() { Func<int, int> keySelector = null; Assert.Throws<ArgumentNullException>("keySelector", () => Enumerable.Range(0, 1000).ToLookup(keySelector, i => i + 2)); } [Fact] public void NullKeySelectorElementSelectorExplicitComparer() { Func<int, int> keySelector = null; Assert.Throws<ArgumentNullException>("keySelector", () => Enumerable.Range(0, 1000).ToLookup(keySelector, i => i + 2, EqualityComparer<int>.Default)); } [Fact] public void NullElementSelector() { Func<int, int> elementSelector = null; Assert.Throws<ArgumentNullException>("elementSelector", () => Enumerable.Range(0, 1000).ToLookup(i => i / 10, elementSelector)); } [Fact] public void NullElementSelectorExplicitComparer() { Func<int, int> elementSelector = null; Assert.Throws<ArgumentNullException>("elementSelector", () => Enumerable.Range(0, 1000).ToLookup(i => i / 10, elementSelector, EqualityComparer<int>.Default)); } [Theory] [InlineData(1)] [InlineData(2)] [InlineData(3)] public void ApplyResultSelectorForGroup(int enumType) { //Create test data var roles = new List<Role> { new Role { Id = 1 }, new Role { Id = 2 }, new Role { Id = 3 }, }; var memberships = Enumerable.Range(0, 50).Select(i => new Membership { Id = i, Role = roles[i % 3], CountMe = i % 3 == 0 }); //Run actual test var grouping = memberships.GroupBy( m => m.Role, (role, mems) => new RoleMetadata { Role = role, CountA = mems.Count(m => m.CountMe), CountrB = mems.Count(m => !m.CountMe) }); IEnumerable<RoleMetadata> result; switch (enumType) { case 1: result = grouping.ToList(); break; case 2: result = grouping.ToArray(); break; default: result = grouping; break; } var expected = new[] { new RoleMetadata {Role = new Role {Id = 1}, CountA = 17, CountrB = 0 }, new RoleMetadata {Role = new Role {Id = 2}, CountA = 0, CountrB = 17 }, new RoleMetadata {Role = new Role {Id = 3}, CountA = 0, CountrB = 16 } }; Assert.Equal(expected, result); } [Theory] [MemberData(nameof(DebuggerAttributesValid_Data))] public void DebuggerAttributesValid<TKey, TElement>(ILookup<TKey, TElement> lookup, TKey dummy1, TElement dummy2) { // The dummy parameters can be removed once https://github.com/dotnet/buildtools/pull/1300 is brought in. Assert.Equal($"Count = {lookup.Count}", DebuggerAttributes.ValidateDebuggerDisplayReferences(lookup)); object proxyObject = DebuggerAttributes.GetProxyObject(lookup); // Validate proxy fields Assert.Empty(DebuggerAttributes.GetDebuggerVisibleFields(proxyObject)); // Validate proxy properties IDictionary<string, PropertyInfo> properties = DebuggerAttributes.GetDebuggerVisibleProperties(proxyObject); Assert.Equal(1, properties.Count); // Groupings PropertyInfo groupingsProperty = properties["Groupings"]; Assert.Equal(DebuggerBrowsableState.RootHidden, DebuggerAttributes.GetDebuggerBrowsableState(groupingsProperty)); var groupings = (IGrouping<TKey, TElement>[])groupingsProperty.GetValue(proxyObject); Assert.IsType<IGrouping<TKey, TElement>[]>(groupings); // Arrays can be covariant / of assignment-compatible types Assert.All(groupings.Zip(lookup, (l, r) => Tuple.Create(l, r)), tuple => { Assert.Same(tuple.Item1, tuple.Item2); }); Assert.Same(groupings, groupingsProperty.GetValue(proxyObject)); // The result should be cached, as Lookup is immutable. } public static IEnumerable<object[]> DebuggerAttributesValid_Data() { IEnumerable<int> source = new[] { 1 }; yield return new object[] { source.ToLookup(i => i), 0, 0 }; yield return new object[] { source.ToLookup(i => i.ToString(), i => i), string.Empty, 0 }; yield return new object[] { source.ToLookup(i => TimeSpan.FromSeconds(i), i => i), TimeSpan.Zero, 0 }; yield return new object[] { new string[] { null }.ToLookup(x => x), string.Empty, string.Empty }; // This test won't even work with the work-around because nullables lose their type once boxed, so xUnit sees an `int` and thinks // we're trying to pass an ILookup<int, int> rather than an ILookup<int?, int?>. // However, it should also be fixed once that PR is brought in, so leaving in this comment. // yield return new object[] { new int?[] { null }.ToLookup(x => x), new int?(0), new int?(0) }; } public class Membership { public int Id { get; set; } public Role Role { get; set; } public bool CountMe { get; set; } } public class Role : IEquatable<Role> { public int Id { get; set; } public bool Equals(Role other) => other != null && Id == other.Id; public override bool Equals(object obj) => Equals(obj as Role); public override int GetHashCode() => Id; } public class RoleMetadata : IEquatable<RoleMetadata> { public Role Role { get; set; } public int CountA { get; set; } public int CountrB { get; set; } public bool Equals(RoleMetadata other) => other != null && Role.Equals(other.Role) && CountA == other.CountA && CountrB == other.CountrB; public override bool Equals(object obj) => Equals(obj as RoleMetadata); public override int GetHashCode() => Role.GetHashCode() * 31 + CountA + CountrB; } } }
// 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; using Microsoft.Win32.SafeHandles; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security.Principal; using Xunit; using System.Text; using System.ComponentModel; using System.Security; namespace System.Diagnostics.Tests { public partial class ProcessStartInfoTests : ProcessTestBase { [Fact] public void TestEnvironmentProperty() { Assert.NotEqual(0, new Process().StartInfo.Environment.Count); ProcessStartInfo psi = new ProcessStartInfo(); // Creating a detached ProcessStartInfo will pre-populate the environment // with current environmental variables. IDictionary<string, string> environment = psi.Environment; Assert.NotEqual(0, environment.Count); int countItems = environment.Count; environment.Add("NewKey", "NewValue"); environment.Add("NewKey2", "NewValue2"); Assert.Equal(countItems + 2, environment.Count); environment.Remove("NewKey"); Assert.Equal(countItems + 1, environment.Count); environment.Add("NewKey2", "NewValue2Overridden"); Assert.Equal("NewValue2Overridden", environment["NewKey2"]); //Clear environment.Clear(); Assert.Equal(0, environment.Count); //ContainsKey environment.Add("NewKey", "NewValue"); environment.Add("NewKey2", "NewValue2"); Assert.True(environment.ContainsKey("NewKey")); Assert.Equal(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), environment.ContainsKey("newkey")); Assert.False(environment.ContainsKey("NewKey99")); //Iterating string result = null; int index = 0; foreach (string e1 in environment.Values.OrderBy(p => p)) { index++; result += e1; } Assert.Equal(2, index); Assert.Equal("NewValueNewValue2", result); result = null; index = 0; foreach (string e1 in environment.Keys.OrderBy(p => p)) { index++; result += e1; } Assert.Equal("NewKeyNewKey2", result); Assert.Equal(2, index); result = null; index = 0; foreach (KeyValuePair<string, string> e1 in environment.OrderBy(p => p.Key)) { index++; result += e1.Key; } Assert.Equal("NewKeyNewKey2", result); Assert.Equal(2, index); //Contains Assert.True(environment.Contains(new KeyValuePair<string, string>("NewKey", "NewValue"))); Assert.Equal(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), environment.Contains(new KeyValuePair<string, string>("nEwKeY", "NewValue"))); Assert.False(environment.Contains(new KeyValuePair<string, string>("NewKey99", "NewValue99"))); //Exception not thrown with invalid key Assert.Throws<ArgumentNullException>(() => environment.Contains(new KeyValuePair<string, string>(null, "NewValue99"))); environment.Add(new KeyValuePair<string, string>("NewKey98", "NewValue98")); //Indexed string newIndexItem = environment["NewKey98"]; Assert.Equal("NewValue98", newIndexItem); //TryGetValue string stringout = null; Assert.True(environment.TryGetValue("NewKey", out stringout)); Assert.Equal("NewValue", stringout); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.True(environment.TryGetValue("NeWkEy", out stringout)); Assert.Equal("NewValue", stringout); } stringout = null; Assert.False(environment.TryGetValue("NewKey99", out stringout)); Assert.Equal(null, stringout); //Exception not thrown with invalid key Assert.Throws<ArgumentNullException>(() => { string stringout1 = null; environment.TryGetValue(null, out stringout1); }); //Exception not thrown with invalid key Assert.Throws<ArgumentNullException>(() => environment.Add(null, "NewValue2")); environment.Add("NewKey2", "NewValue2OverriddenAgain"); Assert.Equal("NewValue2OverriddenAgain", environment["NewKey2"]); //Remove Item environment.Remove("NewKey98"); environment.Remove("NewKey98"); //2nd occurrence should not assert //Exception not thrown with null key Assert.Throws<ArgumentNullException>(() => { environment.Remove(null); }); //"Exception not thrown with null key" Assert.Throws<KeyNotFoundException>(() => environment["1bB"]); Assert.True(environment.Contains(new KeyValuePair<string, string>("NewKey2", "NewValue2OverriddenAgain"))); Assert.Equal(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), environment.Contains(new KeyValuePair<string, string>("NEWKeY2", "NewValue2OverriddenAgain"))); Assert.False(environment.Contains(new KeyValuePair<string, string>("NewKey2", "newvalue2Overriddenagain"))); Assert.False(environment.Contains(new KeyValuePair<string, string>("newkey2", "newvalue2Overriddenagain"))); //Use KeyValuePair Enumerator string[] results = new string[2]; var x = environment.GetEnumerator(); x.MoveNext(); results[0] = x.Current.Key + " " + x.Current.Value; x.MoveNext(); results[1] = x.Current.Key + " " + x.Current.Value; Assert.Equal(new string[] { "NewKey NewValue", "NewKey2 NewValue2OverriddenAgain" }, results.OrderBy(s => s)); //IsReadonly Assert.False(environment.IsReadOnly); environment.Add(new KeyValuePair<string, string>("NewKey3", "NewValue3")); environment.Add(new KeyValuePair<string, string>("NewKey4", "NewValue4")); //CopyTo - the order is undefined. KeyValuePair<string, string>[] kvpa = new KeyValuePair<string, string>[10]; environment.CopyTo(kvpa, 0); KeyValuePair<string, string>[] kvpaOrdered = kvpa.OrderByDescending(k => k.Value).ToArray(); Assert.Equal("NewKey4", kvpaOrdered[0].Key); Assert.Equal("NewKey2", kvpaOrdered[2].Key); environment.CopyTo(kvpa, 6); Assert.Equal(default(KeyValuePair<string, string>), kvpa[5]); Assert.StartsWith("NewKey", kvpa[6].Key); Assert.NotEqual(kvpa[6].Key, kvpa[7].Key); Assert.StartsWith("NewKey", kvpa[7].Key); Assert.NotEqual(kvpa[7].Key, kvpa[8].Key); Assert.StartsWith("NewKey", kvpa[8].Key); //Exception not thrown with null key Assert.Throws<ArgumentOutOfRangeException>(() => { environment.CopyTo(kvpa, -1); }); //Exception not thrown with null key Assert.Throws<ArgumentException>(() => { environment.CopyTo(kvpa, 9); }); //Exception not thrown with null key Assert.Throws<ArgumentNullException>(() => { KeyValuePair<string, string>[] kvpanull = null; environment.CopyTo(kvpanull, 0); }); } [Fact] public void TestEnvironmentOfChildProcess() { const string ItemSeparator = "CAFF9451396B4EEF8A5155A15BDC2080"; // random string that shouldn't be in any env vars; used instead of newline to separate env var strings const string ExtraEnvVar = "TestEnvironmentOfChildProcess_SpecialStuff"; Environment.SetEnvironmentVariable(ExtraEnvVar, "\x1234" + Environment.NewLine + "\x5678"); // ensure some Unicode characters and newlines are in the output try { // Schedule a process to see what env vars it gets. Have it write out those variables // to its output stream so we can read them. Process p = CreateProcess(() => { Console.Write(string.Join(ItemSeparator, Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().Select(e => Convert.ToBase64String(Encoding.UTF8.GetBytes(e.Key + "=" + e.Value))))); return SuccessExitCode; }); p.StartInfo.StandardOutputEncoding = Encoding.UTF8; p.StartInfo.RedirectStandardOutput = true; p.Start(); string output = p.StandardOutput.ReadToEnd(); Assert.True(p.WaitForExit(WaitInMS)); // Parse the env vars from the child process var actualEnv = new HashSet<string>(output.Split(new[] { ItemSeparator }, StringSplitOptions.None).Select(s => Encoding.UTF8.GetString(Convert.FromBase64String(s)))); // Validate against StartInfo.Environment. var startInfoEnv = new HashSet<string>(p.StartInfo.Environment.Select(e => e.Key + "=" + e.Value)); Assert.True(startInfoEnv.SetEquals(actualEnv), string.Format("Expected: {0}{1}Actual: {2}", string.Join(", ", startInfoEnv.Except(actualEnv)), Environment.NewLine, string.Join(", ", actualEnv.Except(startInfoEnv)))); // Validate against current process. (Profilers / code coverage tools can add own environment variables // but we start child process without them. Thus the set of variables from the child process could // be a subset of variables from current process.) var envEnv = new HashSet<string>(Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().Select(e => e.Key + "=" + e.Value)); Assert.True(envEnv.IsSupersetOf(actualEnv), string.Format("Expected: {0}{1}Actual: {2}", string.Join(", ", envEnv.Except(actualEnv)), Environment.NewLine, string.Join(", ", actualEnv.Except(envEnv)))); } finally { Environment.SetEnvironmentVariable(ExtraEnvVar, null); } } [PlatformSpecific(TestPlatforms.Windows)] // UseShellExecute currently not supported on Windows on .NET Core [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Desktop UseShellExecute is set to true by default but UseShellExecute=true is not supported on Core")] public void UseShellExecute_GetSetWindows_Success_Netcore() { ProcessStartInfo psi = new ProcessStartInfo(); Assert.False(psi.UseShellExecute); // Calling the setter Assert.Throws<PlatformNotSupportedException>(() => { psi.UseShellExecute = true; }); psi.UseShellExecute = false; // Calling the getter Assert.False(psi.UseShellExecute, "UseShellExecute=true is not supported on onecore."); } [PlatformSpecific(TestPlatforms.Windows)] [Fact] [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "Desktop UseShellExecute is set to true by default but UseShellExecute=true is not supported on Core")] public void UseShellExecute_GetSetWindows_Success_Netfx() { ProcessStartInfo psi = new ProcessStartInfo(); Assert.True(psi.UseShellExecute); psi.UseShellExecute = false; Assert.False(psi.UseShellExecute); psi.UseShellExecute = true; Assert.True(psi.UseShellExecute); } [PlatformSpecific(TestPlatforms.AnyUnix)] // UseShellExecute currently not supported on Windows [Fact] public void TestUseShellExecuteProperty_SetAndGet_Unix() { ProcessStartInfo psi = new ProcessStartInfo(); Assert.False(psi.UseShellExecute); psi.UseShellExecute = true; Assert.True(psi.UseShellExecute); psi.UseShellExecute = false; Assert.False(psi.UseShellExecute); } [PlatformSpecific(TestPlatforms.AnyUnix)] // UseShellExecute currently not supported on Windows [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] public void TestUseShellExecuteProperty_Redirects_NotSupported(int std) { Process p = CreateProcessLong(); p.StartInfo.UseShellExecute = true; switch (std) { case 0: p.StartInfo.RedirectStandardInput = true; break; case 1: p.StartInfo.RedirectStandardOutput = true; break; case 2: p.StartInfo.RedirectStandardError = true; break; } Assert.Throws<InvalidOperationException>(() => p.Start()); } [Fact] public void TestArgumentsProperty() { ProcessStartInfo psi = new ProcessStartInfo(); Assert.Equal(string.Empty, psi.Arguments); psi = new ProcessStartInfo("filename", "-arg1 -arg2"); Assert.Equal("-arg1 -arg2", psi.Arguments); psi.Arguments = "-arg3 -arg4"; Assert.Equal("-arg3 -arg4", psi.Arguments); } [Theory, InlineData(true), InlineData(false)] public void TestCreateNoWindowProperty(bool value) { Process testProcess = CreateProcessLong(); try { testProcess.StartInfo.CreateNoWindow = value; testProcess.Start(); Assert.Equal(value, testProcess.StartInfo.CreateNoWindow); } finally { if (!testProcess.HasExited) testProcess.Kill(); Assert.True(testProcess.WaitForExit(WaitInMS)); } } [Fact] public void TestWorkingDirectoryProperty() { CreateDefaultProcess(); // check defaults Assert.Equal(string.Empty, _process.StartInfo.WorkingDirectory); Process p = CreateProcessLong(); p.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory(); try { p.Start(); Assert.Equal(Directory.GetCurrentDirectory(), p.StartInfo.WorkingDirectory); } finally { if (!p.HasExited) p.Kill(); Assert.True(p.WaitForExit(WaitInMS)); } } [ActiveIssue(12696)] [Fact, PlatformSpecific(TestPlatforms.Windows), OuterLoop] // Uses P/Invokes, Requires admin privileges public void TestUserCredentialsPropertiesOnWindows() { string username = "test", password = "PassWord123!!"; try { Interop.NetUserAdd(username, password); } catch (Exception exc) { Console.Error.WriteLine("TestUserCredentialsPropertiesOnWindows: NetUserAdd failed: {0}", exc.Message); return; // test is irrelevant if we can't add a user } bool hasStarted = false; SafeProcessHandle handle = null; Process p = null; try { p = CreateProcessLong(); p.StartInfo.LoadUserProfile = true; p.StartInfo.UserName = username; p.StartInfo.PasswordInClearText = password; hasStarted = p.Start(); if (Interop.OpenProcessToken(p.SafeHandle, 0x8u, out handle)) { SecurityIdentifier sid; if (Interop.ProcessTokenToSid(handle, out sid)) { string actualUserName = sid.Translate(typeof(NTAccount)).ToString(); int indexOfDomain = actualUserName.IndexOf('\\'); if (indexOfDomain != -1) actualUserName = actualUserName.Substring(indexOfDomain + 1); bool isProfileLoaded = GetNamesOfUserProfiles().Any(profile => profile.Equals(username)); Assert.Equal(username, actualUserName); Assert.True(isProfileLoaded); } } } finally { IEnumerable<uint> collection = new uint[] { 0 /* NERR_Success */, 2221 /* NERR_UserNotFound */ }; Assert.Contains<uint>(Interop.NetUserDel(null, username), collection); if (handle != null) handle.Dispose(); if (hasStarted) { if (!p.HasExited) p.Kill(); Assert.True(p.WaitForExit(WaitInMS)); } } } private static List<string> GetNamesOfUserProfiles() { List<string> userNames = new List<string>(); string[] names = Registry.Users.GetSubKeyNames(); for (int i = 1; i < names.Length; i++) { try { SecurityIdentifier sid = new SecurityIdentifier(names[i]); string userName = sid.Translate(typeof(NTAccount)).ToString(); int indexofDomain = userName.IndexOf('\\'); if (indexofDomain != -1) { userName = userName.Substring(indexofDomain + 1); userNames.Add(userName); } } catch (Exception) { } } return userNames; } [Fact] public void TestEnvironmentVariables_Environment_DataRoundTrips() { ProcessStartInfo psi = new ProcessStartInfo(); // Creating a detached ProcessStartInfo will pre-populate the environment // with current environmental variables. psi.Environment.Clear(); psi.EnvironmentVariables.Add("NewKey", "NewValue"); psi.Environment.Add("NewKey2", "NewValue2"); Assert.Equal(psi.Environment["NewKey"], psi.EnvironmentVariables["NewKey"]); Assert.Equal(psi.Environment["NewKey2"], psi.EnvironmentVariables["NewKey2"]); Assert.Equal(2, psi.EnvironmentVariables.Count); Assert.Equal(psi.Environment.Count, psi.EnvironmentVariables.Count); Assert.Throws<ArgumentException>(null, () => psi.EnvironmentVariables.Add("NewKey2", "NewValue2")); psi.EnvironmentVariables.Add("NewKey3", "NewValue3"); psi.Environment.Add("NewKey3", "NewValue3Overridden"); Assert.Equal("NewValue3Overridden", psi.Environment["NewKey3"]); psi.EnvironmentVariables.Clear(); Assert.Equal(0, psi.Environment.Count); psi.EnvironmentVariables.Add("NewKey", "NewValue"); psi.EnvironmentVariables.Add("NewKey2", "NewValue2"); // Environment and EnvironmentVariables should be equal, but have different enumeration types. IEnumerable<KeyValuePair<string, string>> allEnvironment = psi.Environment.OrderBy(k => k.Key); IEnumerable<DictionaryEntry> allDictionary = psi.EnvironmentVariables.Cast<DictionaryEntry>().OrderBy(k => k.Key); Assert.Equal(allEnvironment.Select(k => new DictionaryEntry(k.Key, k.Value)), allDictionary); psi.EnvironmentVariables.Add("NewKey3", "NewValue3"); KeyValuePair<string, string>[] kvpa = new KeyValuePair<string, string>[5]; psi.Environment.CopyTo(kvpa, 0); KeyValuePair<string, string>[] kvpaOrdered = kvpa.OrderByDescending(k => k.Key).ToArray(); Assert.Equal("NewKey", kvpaOrdered[2].Key); Assert.Equal("NewValue", kvpaOrdered[2].Value); psi.EnvironmentVariables.Remove("NewKey3"); Assert.False(psi.Environment.Contains(new KeyValuePair<string,string>("NewKey3", "NewValue3"))); } [PlatformSpecific(TestPlatforms.Windows)] // Test case is specific to Windows [Fact] public void Verbs_GetWithExeExtension_ReturnsExpected() { var psi = new ProcessStartInfo { FileName = $"{Process.GetCurrentProcess().ProcessName}.exe" }; Assert.Contains("open", psi.Verbs, StringComparer.OrdinalIgnoreCase); if (PlatformDetection.IsNotWindowsNanoServer) { Assert.Contains("runas", psi.Verbs, StringComparer.OrdinalIgnoreCase); Assert.Contains("runasuser", psi.Verbs, StringComparer.OrdinalIgnoreCase); } Assert.DoesNotContain("printto", psi.Verbs, StringComparer.OrdinalIgnoreCase); Assert.DoesNotContain("closed", psi.Verbs, StringComparer.OrdinalIgnoreCase); } [Theory] [InlineData("")] [InlineData("nofileextension")] [PlatformSpecific(TestPlatforms.Windows)] public void Verbs_GetWithNoExtension_ReturnsEmpty(string fileName) { var info = new ProcessStartInfo { FileName = fileName }; Assert.Empty(info.Verbs); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void Verbs_GetWithNoRegisteredExtension_ReturnsEmpty() { var info = new ProcessStartInfo { FileName = "file.nosuchextension" }; Assert.Empty(info.Verbs); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void Verbs_GetWithNoEmptyStringKey_ReturnsEmpty() { const string Extension = ".noemptykeyextension"; const string FileName = "file" + Extension; using (TempRegistryKey tempKey = new TempRegistryKey(Registry.ClassesRoot, Extension)) { if (tempKey.Key == null) { // Skip this test if the user doesn't have permission to // modify the registry. return; } var info = new ProcessStartInfo { FileName = FileName }; Assert.Empty(info.Verbs); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void Verbs_GetWithEmptyStringValue_ReturnsEmpty() { const string Extension = ".emptystringextension"; const string FileName = "file" + Extension; using (TempRegistryKey tempKey = new TempRegistryKey(Registry.ClassesRoot, Extension)) { if (tempKey.Key == null) { // Skip this test if the user doesn't have permission to // modify the registry. return; } tempKey.Key.SetValue("", ""); var info = new ProcessStartInfo { FileName = FileName }; Assert.Empty(info.Verbs); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "The full .NET Framework throws an InvalidCastException for non-string keys. See https://github.com/dotnet/corefx/issues/18187.")] [PlatformSpecific(TestPlatforms.Windows)] public void Verbs_GetWithNonStringValue_ReturnsEmpty() { const string Extension = ".nonstringextension"; const string FileName = "file" + Extension; using (TempRegistryKey tempKey = new TempRegistryKey(Registry.ClassesRoot, Extension)) { if (tempKey.Key == null) { // Skip this test if the user doesn't have permission to // modify the registry. return; } tempKey.Key.SetValue("", 123); var info = new ProcessStartInfo { FileName = FileName }; Assert.Empty(info.Verbs); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void Verbs_GetWithNoShellSubKey_ReturnsEmpty() { const string Extension = ".noshellsubkey"; const string FileName = "file" + Extension; using (TempRegistryKey tempKey = new TempRegistryKey(Registry.ClassesRoot, Extension)) { if (tempKey.Key == null) { // Skip this test if the user doesn't have permission to // modify the registry. return; } tempKey.Key.SetValue("", "nosuchshell"); var info = new ProcessStartInfo { FileName = FileName }; Assert.Empty(info.Verbs); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void Verbs_GetWithSubkeys_ReturnsEmpty() { const string Extension = ".customregistryextension"; const string FileName = "file" + Extension; const string SubKeyValue = "customregistryextensionshell"; using (TempRegistryKey extensionKey = new TempRegistryKey(Registry.ClassesRoot, Extension)) using (TempRegistryKey shellKey = new TempRegistryKey(Registry.ClassesRoot, SubKeyValue + "\\shell")) { if (extensionKey.Key == null) { // Skip this test if the user doesn't have permission to // modify the registry. return; } extensionKey.Key.SetValue("", SubKeyValue); shellKey.Key.CreateSubKey("verb1"); shellKey.Key.CreateSubKey("NEW"); shellKey.Key.CreateSubKey("new"); shellKey.Key.CreateSubKey("verb2"); var info = new ProcessStartInfo { FileName = FileName }; Assert.Equal(new string[] { "verb1", "verb2" }, info.Verbs); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void Verbs_GetUnix_ReturnsEmpty() { var info = new ProcessStartInfo(); Assert.Empty(info.Verbs); } [PlatformSpecific(TestPlatforms.AnyUnix)] // Test case is specific to Unix [Fact] public void TestEnvironmentVariablesPropertyUnix(){ ProcessStartInfo psi = new ProcessStartInfo(); // Creating a detached ProcessStartInfo will pre-populate the environment // with current environmental variables. StringDictionary environmentVariables = psi.EnvironmentVariables; Assert.NotEqual(0, environmentVariables.Count); int CountItems = environmentVariables.Count; environmentVariables.Add("NewKey", "NewValue"); environmentVariables.Add("NewKey2", "NewValue2"); Assert.Equal(CountItems + 2, environmentVariables.Count); environmentVariables.Remove("NewKey"); Assert.Equal(CountItems + 1, environmentVariables.Count); //Exception not thrown with invalid key Assert.Throws<ArgumentException>(() => { environmentVariables.Add("NewKey2", "NewValue2"); }); Assert.False(environmentVariables.ContainsKey("NewKey")); environmentVariables.Add("newkey2", "newvalue2"); Assert.True(environmentVariables.ContainsKey("newkey2")); Assert.Equal("newvalue2", environmentVariables["newkey2"]); Assert.Equal("NewValue2", environmentVariables["NewKey2"]); environmentVariables.Clear(); Assert.Equal(0, environmentVariables.Count); environmentVariables.Add("NewKey", "newvalue"); environmentVariables.Add("newkey2", "NewValue2"); Assert.False(environmentVariables.ContainsKey("newkey")); Assert.False(environmentVariables.ContainsValue("NewValue")); string result = null; int index = 0; foreach (string e1 in environmentVariables.Values) { index++; result += e1; } Assert.Equal(2, index); Assert.Equal("newvalueNewValue2", result); result = null; index = 0; foreach (string e1 in environmentVariables.Keys) { index++; result += e1; } Assert.Equal("NewKeynewkey2", result); Assert.Equal(2, index); result = null; index = 0; foreach (DictionaryEntry e1 in environmentVariables) { index++; result += e1.Key; } Assert.Equal("NewKeynewkey2", result); Assert.Equal(2, index); //Key not found Assert.Throws<KeyNotFoundException>(() => { string stringout = environmentVariables["NewKey99"]; }); //Exception not thrown with invalid key Assert.Throws<ArgumentNullException>(() => { string stringout = environmentVariables[null]; }); //Exception not thrown with invalid key Assert.Throws<ArgumentNullException>(() => environmentVariables.Add(null, "NewValue2")); Assert.Throws<ArgumentException>(() => environmentVariables.Add("newkey2", "NewValue2")); //Use DictionaryEntry Enumerator var x = environmentVariables.GetEnumerator() as IEnumerator; x.MoveNext(); var y1 = (DictionaryEntry)x.Current; Assert.Equal("NewKey newvalue", y1.Key + " " + y1.Value); x.MoveNext(); y1 = (DictionaryEntry)x.Current; Assert.Equal("newkey2 NewValue2", y1.Key + " " + y1.Value); environmentVariables.Add("newkey3", "newvalue3"); KeyValuePair<string, string>[] kvpa = new KeyValuePair<string, string>[10]; environmentVariables.CopyTo(kvpa, 0); Assert.Equal("NewKey", kvpa[0].Key); Assert.Equal("newkey3", kvpa[2].Key); Assert.Equal("newvalue3", kvpa[2].Value); string[] kvp = new string[10]; Assert.Throws<ArgumentException>(() => { environmentVariables.CopyTo(kvp, 6); }); environmentVariables.CopyTo(kvpa, 6); Assert.Equal("NewKey", kvpa[6].Key); Assert.Equal("newvalue", kvpa[6].Value); Assert.Throws<ArgumentOutOfRangeException>(() => { environmentVariables.CopyTo(kvpa, -1); }); Assert.Throws<ArgumentException>(() => { environmentVariables.CopyTo(kvpa, 9); }); Assert.Throws<ArgumentNullException>(() => { KeyValuePair<string, string>[] kvpanull = null; environmentVariables.CopyTo(kvpanull, 0); }); } [Theory] [InlineData(null)] [InlineData("")] [InlineData("domain")] [PlatformSpecific(TestPlatforms.Windows)] public void Domain_SetWindows_GetReturnsExpected(string domain) { var info = new ProcessStartInfo { Domain = domain }; Assert.Equal(domain ?? string.Empty, info.Domain); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void Domain_GetSetUnix_ThrowsPlatformNotSupportedException() { var info = new ProcessStartInfo(); Assert.Throws<PlatformNotSupportedException>(() => info.Domain); Assert.Throws<PlatformNotSupportedException>(() => info.Domain = "domain"); } [Theory] [InlineData(null)] [InlineData("")] [InlineData("filename")] public void FileName_Set_GetReturnsExpected(string fileName) { var info = new ProcessStartInfo { FileName = fileName }; Assert.Equal(fileName ?? string.Empty, info.FileName); } [Theory] [InlineData(true)] [InlineData(false)] [PlatformSpecific(TestPlatforms.Windows)] public void LoadUserProfile_SetWindows_GetReturnsExpected(bool loadUserProfile) { var info = new ProcessStartInfo { LoadUserProfile = loadUserProfile }; Assert.Equal(loadUserProfile, info.LoadUserProfile); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void LoadUserProfile_GetSetUnix_ThrowsPlatformNotSupportedException() { var info = new ProcessStartInfo(); Assert.Throws<PlatformNotSupportedException>(() => info.LoadUserProfile); Assert.Throws<PlatformNotSupportedException>(() => info.LoadUserProfile = false); } [Theory] [InlineData(null)] [InlineData("")] [InlineData("passwordInClearText")] [PlatformSpecific(TestPlatforms.Windows)] public void PasswordInClearText_SetWindows_GetReturnsExpected(string passwordInClearText) { var info = new ProcessStartInfo { PasswordInClearText = passwordInClearText }; Assert.Equal(passwordInClearText, info.PasswordInClearText); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void PasswordInClearText_GetSetUnix_ThrowsPlatformNotSupportedException() { var info = new ProcessStartInfo(); Assert.Throws<PlatformNotSupportedException>(() => info.PasswordInClearText); Assert.Throws<PlatformNotSupportedException>(() => info.PasswordInClearText = "passwordInClearText"); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void Password_SetWindows_GetReturnsExpected() { using (SecureString password = new SecureString()) { password.AppendChar('a'); var info = new ProcessStartInfo { Password = password }; Assert.Equal(password, info.Password); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void Password_GetSetUnix_ThrowsPlatformNotSupportedException() { var info = new ProcessStartInfo(); Assert.Throws<PlatformNotSupportedException>(() => info.Password); Assert.Throws<PlatformNotSupportedException>(() => info.Password = new SecureString()); } [Theory] [InlineData(null)] [InlineData("")] [InlineData("domain")] [PlatformSpecific(TestPlatforms.Windows)] public void UserName_SetWindows_GetReturnsExpected(string userName) { var info = new ProcessStartInfo { UserName = userName }; Assert.Equal(userName ?? string.Empty, info.UserName); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void UserName_GetSetUnix_ThrowsPlatformNotSupportedException() { var info = new ProcessStartInfo(); Assert.Throws<PlatformNotSupportedException>(() => info.UserName); Assert.Throws<PlatformNotSupportedException>(() => info.UserName = "username"); } [Theory] [InlineData(null)] [InlineData("")] [InlineData("verb")] public void Verb_Set_GetReturnsExpected(string verb) { var info = new ProcessStartInfo { Verb = verb }; Assert.Equal(verb ?? string.Empty, info.Verb); } [Theory] [InlineData(ProcessWindowStyle.Normal - 1)] [InlineData(ProcessWindowStyle.Maximized + 1)] public void WindowStyle_SetNoSuchWindowStyle_ThrowsInvalidEnumArgumentException(ProcessWindowStyle style) { var info = new ProcessStartInfo(); Assert.Throws<InvalidEnumArgumentException>(() => info.WindowStyle = style); } [Theory] [InlineData(ProcessWindowStyle.Hidden)] [InlineData(ProcessWindowStyle.Maximized)] [InlineData(ProcessWindowStyle.Minimized)] [InlineData(ProcessWindowStyle.Normal)] public void WindowStyle_Set_GetReturnsExpected(ProcessWindowStyle style) { var info = new ProcessStartInfo { WindowStyle = style }; Assert.Equal(style, info.WindowStyle); } [Theory] [InlineData(null)] [InlineData("")] [InlineData("workingdirectory")] public void WorkingDirectory_Set_GetReturnsExpected(string workingDirectory) { var info = new ProcessStartInfo { WorkingDirectory = workingDirectory }; Assert.Equal(workingDirectory ?? string.Empty, info.WorkingDirectory); } } }
// 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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void TestZUInt64() { var test = new BooleanBinaryOpTest__TestZUInt64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class BooleanBinaryOpTest__TestZUInt64 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(UInt64[] inArray1, UInt64[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt64>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt64, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<UInt64> _fld1; public Vector128<UInt64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); return testStruct; } public void RunStructFldScenario(BooleanBinaryOpTest__TestZUInt64 testClass) { var result = Sse41.TestZ(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } public void RunStructFldScenario_Load(BooleanBinaryOpTest__TestZUInt64 testClass) { fixed (Vector128<UInt64>* pFld1 = &_fld1) fixed (Vector128<UInt64>* pFld2 = &_fld2) { var result = Sse41.TestZ( Sse2.LoadVector128((UInt64*)(pFld1)), Sse2.LoadVector128((UInt64*)(pFld2)) ); testClass.ValidateResult(_fld1, _fld2, result); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static UInt64[] _data1 = new UInt64[Op1ElementCount]; private static UInt64[] _data2 = new UInt64[Op2ElementCount]; private static Vector128<UInt64> _clsVar1; private static Vector128<UInt64> _clsVar2; private Vector128<UInt64> _fld1; private Vector128<UInt64> _fld2; private DataTable _dataTable; static BooleanBinaryOpTest__TestZUInt64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); } public BooleanBinaryOpTest__TestZUInt64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.TestZ( Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse41.TestZ( Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.TestZ( Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse41).GetMethod(nameof(Sse41.TestZ), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.TestZ), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.TestZ), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.TestZ( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt64>* pClsVar1 = &_clsVar1) fixed (Vector128<UInt64>* pClsVar2 = &_clsVar2) { var result = Sse41.TestZ( Sse2.LoadVector128((UInt64*)(pClsVar1)), Sse2.LoadVector128((UInt64*)(pClsVar2)) ); ValidateResult(_clsVar1, _clsVar2, result); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr); var result = Sse41.TestZ(op1, op2); ValidateResult(op1, op2, result); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)); var result = Sse41.TestZ(op1, op2); ValidateResult(op1, op2, result); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr)); var result = Sse41.TestZ(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new BooleanBinaryOpTest__TestZUInt64(); var result = Sse41.TestZ(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new BooleanBinaryOpTest__TestZUInt64(); fixed (Vector128<UInt64>* pFld1 = &test._fld1) fixed (Vector128<UInt64>* pFld2 = &test._fld2) { var result = Sse41.TestZ( Sse2.LoadVector128((UInt64*)(pFld1)), Sse2.LoadVector128((UInt64*)(pFld2)) ); ValidateResult(test._fld1, test._fld2, result); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.TestZ(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt64>* pFld1 = &_fld1) fixed (Vector128<UInt64>* pFld2 = &_fld2) { var result = Sse41.TestZ( Sse2.LoadVector128((UInt64*)(pFld1)), Sse2.LoadVector128((UInt64*)(pFld2)) ); ValidateResult(_fld1, _fld2, result); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.TestZ(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse41.TestZ( Sse2.LoadVector128((UInt64*)(&test._fld1)), Sse2.LoadVector128((UInt64*)(&test._fld2)) ); ValidateResult(test._fld1, test._fld2, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt64> op1, Vector128<UInt64> op2, bool result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(UInt64[] left, UInt64[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= ((left[i] & right[i]) == 0); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.TestZ)}<UInt64>(Vector128<UInt64>, Vector128<UInt64>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
//#define PRE_V2_4 using System; using System.Collections.Generic; using System.Text; using System.ComponentModel; using System.Threading; using InTheHand.Net.Sockets; using System.Diagnostics; #if NETCF using SendOrPostCallback = System.Threading.WaitCallback; #endif namespace InTheHand.Net.Bluetooth { /// <summary> /// Provides simple access to asynchronous methods on Bluetooth features, for /// instance to background device discovery. /// </summary> /// - /// <example> /// <code lang="VB.NET"> /// Public Sub DiscoDevicesAsync() /// Dim bco As New BluetoothComponent() /// AddHandler bco.DiscoverDevicesProgress, AddressOf HandleDiscoDevicesProgress /// AddHandler bco.DiscoverDevicesComplete, AddressOf HandleDiscoDevicesComplete /// bco.DiscoverDevicesAsync(255, True, True, True, False, 99) /// End Sub /// /// Private Sub HandleDiscoDevicesProgress(ByVal sender As Object, ByVal e As DiscoverDevicesEventArgs) /// Console.WriteLine("DiscoDevicesAsync Progress found {0} devices.", e.Devices.Length) /// End Sub /// /// Private Sub HandleDiscoDevicesComplete(ByVal sender As Object, ByVal e As DiscoverDevicesEventArgs) /// Debug.Assert(CInt(e.UserState) = 99) /// If e.Cancelled Then /// Console.WriteLine("DiscoDevicesAsync cancelled.") /// ElseIf e.Error IsNot Nothing Then /// Console.WriteLine("DiscoDevicesAsync error: {0}.", e.Error.Message) /// Else /// Console.WriteLine("DiscoDevicesAsync complete found {0} devices.", e.Devices.Length) /// End If /// End Sub /// </code> /// </example> public class BluetoothComponent : Component { readonly BluetoothClient m_cli; //---- /// <summary> /// Initializes a new instance of the <see cref="T:InTheHand.Net.Bluetooth.BluetoothComponent"/> class. /// </summary> public BluetoothComponent() : this(new BluetoothClient()) { } //TODO !!!! Add to public stack factory /// <summary> /// Initializes a new instance of the <see cref="T:InTheHand.Net.Bluetooth.BluetoothComponent"/> class. /// </summary> /// - /// <param name="cli">A <see cref="T:InTheHand.Net.Sockets.BluetoothClient"/> /// instance to use to run discovery on. Must be non-null. /// </param> public BluetoothComponent(BluetoothClient cli) { if (cli == null) throw new ArgumentNullException("cli"); m_cli = cli; } /// <summary> /// Optionally disposes of the managed resources used by the /// <see cref="T:InTheHand.Net.Bluetooth.BluetoothComponent"/> class. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged /// resources; <c>false</c> to release only unmanaged resources. /// </param> protected override void Dispose(bool disposing) { try { if (disposing) { m_cli.Dispose(); } } finally { base.Dispose(disposing); } } //---- /// <summary> /// Occurs when an device discovery operation completes. /// </summary> /// - /// <remarks> /// <para>This event is raised at the end of the discovery process /// and lists all the discovered devices. /// </para> /// </remarks> /// - /// <seealso cref="E:InTheHand.Net.Bluetooth.BluetoothComponent.DiscoverDevicesProgress"/> public event EventHandler<DiscoverDevicesEventArgs> DiscoverDevicesComplete; /// <summary> /// Raises the <see cref="E:InTheHand.Net.Bluetooth.BluetoothComponent.DiscoverDevicesComplete"/> event. /// </summary> /// <param name="e">A <see cref="T:InTheHand.Net.Bluetooth.DiscoverDevicesEventArgs"/> /// object that contains event data. /// </param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", Justification = "It it /not/ visible!")] protected void OnDiscoveryComplete(DiscoverDevicesEventArgs e) { EventHandler<DiscoverDevicesEventArgs> eh = DiscoverDevicesComplete; if (eh != null) { eh(this, e); } } /// <summary> /// Occurs during an device discovery operation /// to show one or more new devices. /// </summary> /// - /// <remarks> /// <para>This event is raised for all discovered devices, both the /// known devices which are presented first, if requested, /// as well as newly discovery device found by the inquiry process, /// again if requested. /// </para> /// <para>Note that any event instance may include one or more devices. Note /// also that a particular device may be presented more than one time; /// including once from the &#x2018;known&#x2019; list, once when a /// device is dicovered, and possibly another time when the discovery /// process retrieves the new device&#x2019;s Device Name. /// </para> /// </remarks> /// - /// <seealso cref="E:InTheHand.Net.Bluetooth.BluetoothComponent.DiscoverDevicesComplete"/> public event EventHandler<DiscoverDevicesEventArgs> DiscoverDevicesProgress; /// <summary> /// Raises the <see cref="E:InTheHand.Net.Bluetooth.BluetoothComponent.DiscoverDevicesProgress"/> event. /// </summary> /// <param name="e">A <see cref="T:InTheHand.Net.Bluetooth.DiscoverDevicesEventArgs"/> /// object that contains event data. /// </param> protected void OnDiscoveryProgress(DiscoverDevicesEventArgs e) { var eh = DiscoverDevicesProgress; if (eh != null) { eh(this, e); } } /// <summary> /// Discovers accessible Bluetooth devices and returns their names and addresses. /// This method does not block the calling thread. /// </summary> /// - /// <remarks> /// <para>See <see cref="M:InTheHand.Net.Sockets.BluetoothClient.DiscoverDevices(System.Int32,System.Boolean,System.Boolean,System.Boolean,System.Boolean)"/> /// for more information. /// </para> /// <para>The devices are presented in the <see cref="E:InTheHand.Net.Bluetooth.BluetoothComponent.DiscoverDevicesComplete"/> /// and <see cref="E:InTheHand.Net.Bluetooth.BluetoothComponent.DiscoverDevicesProgress"/> events. /// </para> /// </remarks> /// - /// <param name="maxDevices">The maximum number of devices to get information about. /// </param> /// <param name="authenticated">True to return previously authenticated/paired devices. /// </param> /// <param name="remembered">True to return remembered devices. /// </param> /// <param name="unknown">True to return previously unknown devices. /// </param> /// <param name="discoverableOnly">True to return only the devices that /// are in range, and in discoverable mode. See the remarks section. /// </param> /// <param name="state">A user-defined object that is passed to the method /// invoked when the asynchronous operation completes. /// </param> /// - /// <returns>An array of BluetoothDeviceInfo objects describing the devices discovered.</returns> public void DiscoverDevicesAsync(int maxDevices, bool authenticated, bool remembered, bool unknown, bool discoverableOnly, object state) { AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(state); // Provide the remembered devices immediately DoRemembered(authenticated, remembered, discoverableOnly, asyncOp); // #if PRE_V2_4 if (discoverableOnly) throw new ArgumentException("Flag 'discoverableOnly' is not supported in this version.", "discoverableOnly"); FuncDiscoDevs dlgt = new FuncDiscoDevs(m_cli.DiscoverDevices); FuncDiscoDevs exist = Interlocked.CompareExchange(ref m_dlgt, dlgt, null); if (exist != null) throw new InvalidOperationException("Only support one concurrent operation."); dlgt.BeginInvoke(maxDevices, authenticated, remembered, unknown, //discoverableOnly, HandleDiscoComplete, asyncOp); #else m_cli.BeginDiscoverDevices(maxDevices, authenticated, remembered, unknown, discoverableOnly, HandleDiscoComplete, asyncOp, HandleDiscoNewDevice, asyncOp); #endif } private void DoRemembered(bool authenticated, bool remembered, bool discoverableOnly, AsyncOperation asyncOp) { if ((authenticated || remembered) && !discoverableOnly) { var rmbd = m_cli.DiscoverDevices(255, authenticated, remembered, false, false); if (rmbd.Length != 0) { var e = new DiscoverDevicesEventArgs(rmbd, asyncOp.UserSuppliedState); SendOrPostCallback cb = delegate(object args) { OnDiscoveryProgress((DiscoverDevicesEventArgs)args); }; asyncOp.Post(cb, e); } } } #if PRE_V2_4 delegate BluetoothDeviceInfo[] FuncDiscoDevs(int maxDevices, bool authenticated, bool remembered, bool unknown/*, bool discoverableOnly*/); FuncDiscoDevs m_dlgt; #endif [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void HandleDiscoComplete(IAsyncResult ar) { AsyncOperation asyncOp = (AsyncOperation)ar.AsyncState; DiscoverDevicesEventArgs e; try { #if PRE_V2_4 FuncDiscoDevs dlgt = Interlocked.Exchange(ref m_dlgt, null); BluetoothDeviceInfo[] arr = dlgt.EndInvoke(ar); #else BluetoothDeviceInfo[] arr = m_cli.EndDiscoverDevices(ar); #endif e = new DiscoverDevicesEventArgs(arr, asyncOp.UserSuppliedState); } catch (Exception ex) { e = new DiscoverDevicesEventArgs(ex, asyncOp.UserSuppliedState); // TO-DO ?? Set Cancelled if disposed? } // SendOrPostCallback cb = delegate(object args) { OnDiscoveryComplete((DiscoverDevicesEventArgs)args); }; asyncOp.PostOperationCompleted(cb, e); } private void HandleDiscoNewDevice(InTheHand.Net.Bluetooth.Factory.IBluetoothDeviceInfo newDevice, object state) { Debug.WriteLine(DateTime.UtcNow.TimeOfDay.ToString() + ": HandleDiscoNewDevice."); AsyncOperation asyncOp = (AsyncOperation)state; Debug.Assert(newDevice != null); var rslt = new BluetoothDeviceInfo[] { new BluetoothDeviceInfo(newDevice) }; Debug.Assert(rslt.Length > 0, "NOT rslt.Length > 0"); var e = new DiscoverDevicesEventArgs(rslt, asyncOp.UserSuppliedState); SendOrPostCallback cb = delegate(object args) { OnDiscoveryProgress((DiscoverDevicesEventArgs)args); }; asyncOp.Post(cb, e); } } }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using System; using System.Collections.Generic; using System.Linq; using Glass.Mapper.Configuration; using Glass.Mapper.Pipelines.ConfigurationResolver.Tasks.OnDemandResolver; using Glass.Mapper.Pipelines.DataMapperResolver; using System.Collections.Concurrent; using Castle.Core.Logging; namespace Glass.Mapper { /// <summary> /// The context contains the configuration of Glass.Mapper /// </summary> public class Context { /// <summary> /// The default context name /// </summary> public const string DefaultContextName = "Default"; #region STATICS /// <summary> /// The default Context. Used by services if no Context is specified. /// </summary> /// <value>The default.</value> public static Context Default { get; private set; } /// <summary> /// Contains the list of Contexts currently loaded. /// </summary> /// <value>The contexts.</value> public static IDictionary<string, Context> Contexts { get; private set; } /// <summary> /// Initializes static members of the <see cref="Context"/> class. /// </summary> static Context() { Contexts = new Dictionary<string, Context>(); } /// <summary> /// Creates a Context and creates it as the default Context. This is assigned to the Default static property. /// </summary> /// <param name="resolver">The resolver.</param> /// <returns>Context.</returns> public static Context Create(IDependencyResolver resolver) { return Context.Create(resolver, DefaultContextName, true); } /// <summary> /// Creates a new context and adds it to the Contexts dictionary. /// </summary> /// <param name="resolver">The resolver.</param> /// <param name="contextName">The context name, used as the key in the Contexts dictionary.</param> /// <param name="isDefault">Indicates if this is the default context. If it is the context is assigned to the Default static property.</param> /// <returns>Context.</returns> /// <exception cref="System.NullReferenceException">No dependency resolver set.</exception> public static Context Create(IDependencyResolver resolver, string contextName, bool isDefault = false) { if (resolver == null) throw new NullReferenceException("No dependency resolver set."); var context = new Context(); context.DependencyResolver = resolver; context.Name = contextName; Contexts[contextName] = context; if (isDefault) Default = context; return context; } /// <summary> /// Clears all static and default contexts /// </summary> public static void Clear() { Default = null; Contexts = new Dictionary<string, Context>(); } #endregion public string Name { get; private set; } /// <summary> /// List of the type configurations loaded by this context /// </summary> /// <value>The type configurations.</value> public ConcurrentDictionary<Type, AbstractTypeConfiguration> TypeConfigurations { get; private set; } /// <summary> /// The dependency resolver used by services using the context /// </summary> /// <value>The dependency resolver.</value> public IDependencyResolver DependencyResolver { get; set; } public ILogger Log { get; set; } /// <summary> /// Prevents a default instance of the <see cref="Context"/> class from being created. /// </summary> private Context() { TypeConfigurations = new ConcurrentDictionary<Type, AbstractTypeConfiguration>(); Log = new NullLogger(); } /// <summary> /// Gets a type configuration based on type /// </summary> /// <param name="type">The type.</param> /// <returns>AbstractTypeConfiguration.</returns> public AbstractTypeConfiguration this[Type type] { get { if (TypeConfigurations.ContainsKey(type)) return TypeConfigurations[type]; else return null; } } /// <summary> /// Loads the specified loaders. /// </summary> /// <param name="loaders">The list of configuration loaders to load into the context.</param> public void Load(params IConfigurationLoader[] loaders) { if (loaders.Any()) { var typeConfigurations = loaders .Select(loader => loader.Load()).Aggregate((x, y) => x.Union(y)); //first we have to add each type config to the collection foreach (var typeConfig in typeConfigurations) { if(TypeConfigurations.ContainsKey(typeConfig.Type)){ Log.Warn("Tried to add type {0} to TypeConfigurationDictioary twice".Formatted(typeConfig.Type)); continue; } typeConfig.PerformAutoMap(); if (!TypeConfigurations.TryAdd(typeConfig.Type, typeConfig)) { Log.Warn("Failed to add type {0} to TypeConfigurationDictionary".Formatted(typeConfig.Type)); } } //then process the properties. //this stops the problem of types not existing for certain data handlers foreach (var typeConfig in typeConfigurations) { ProcessProperties(typeConfig.Properties); } } } /// <summary> /// Processes the properties. /// </summary> /// <param name="properties">The properties.</param> /// <exception cref="System.NullReferenceException">Could not find data mapper for property {0} on type {1} /// .Formatted(property.PropertyInfo.Name,property.PropertyInfo.ReflectedType.FullName)</exception> private void ProcessProperties(IEnumerable<AbstractPropertyConfiguration> properties ) { DataMapperResolver runner = new DataMapperResolver(DependencyResolver.ResolveAll<IDataMapperResolverTask>()); foreach(var property in properties) { DataMapperResolverArgs args = new DataMapperResolverArgs(this, property); args.PropertyConfiguration = property; args.DataMappers = DependencyResolver.ResolveAll<AbstractDataMapper>(); runner.Run(args); if(args.Result == null) { throw new NullReferenceException( "Could not find data mapper for property {0} on type {1}" .Formatted(property.PropertyInfo.Name,property.PropertyInfo.ReflectedType.FullName)); } property.Mapper = args.Result; } } /// <summary> /// Gets the type configuration. /// </summary> /// <param name="obj">The obj.</param> /// <returns>AbstractTypeConfiguration.</returns> public T GetTypeConfiguration<T>(object obj, bool doNotLoad = false, bool checkBase = true) where T: AbstractTypeConfiguration, new() { return GetTypeConfiguration<T>(obj.GetType(), doNotLoad, checkBase); } /// <summary> /// Gets the type configuration. /// </summary> /// <param name="obj">The obj.</param> /// <returns>AbstractTypeConfiguration.</returns> public T GetTypeConfiguration<T>(Type type, bool doNotLoad = false, bool checkBase = true) where T : AbstractTypeConfiguration, new() { var config = TypeConfigurations.ContainsKey(type) ? TypeConfigurations[type] : null; if (config != null) return config as T; if (checkBase) { //check base type encase of proxy if (type.BaseType != null) { config = TypeConfigurations.ContainsKey(type.BaseType) ? TypeConfigurations[type.BaseType] : null; } if (config != null) return config as T; //check interfaces encase this is an interface proxy string name = type.Name; //ME - I added the OrderByDescending in response to issue 53 // raised on the Glass.Sitecore.Mapper project. Longest name should be compared first // to get the most specific interface var interfaceType = type.GetInterfaces() .OrderByDescending(x => x.Name.Length) .FirstOrDefault(x => name.Contains(x.Name)); if (interfaceType != null) config = TypeConfigurations.ContainsKey(interfaceType) ? TypeConfigurations[interfaceType] : null; } if (config == null && !doNotLoad) { Load(new OnDemandLoader<T>(type)); return GetTypeConfiguration<T>(type, true); } return config as T; } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using Newtonsoft.Json; using System.Threading; using QuantConnect.Data; using QuantConnect.Orders; using QuantConnect.Logging; using System.Threading.Tasks; using QuantConnect.Interfaces; using QuantConnect.Securities; using System.Collections.Generic; namespace QuantConnect.Brokerages { /// <summary> /// Represents the base Brokerage implementation. This provides logging on brokerage events. /// </summary> public abstract class Brokerage : IBrokerage { // 7:45 AM (New York time zone) private static readonly TimeSpan LiveBrokerageCashSyncTime = new TimeSpan(7, 45, 0); private readonly object _performCashSyncReentranceGuard = new object(); private bool _syncedLiveBrokerageCashToday = true; private long _lastSyncTimeTicks = DateTime.UtcNow.Ticks; /// <summary> /// Event that fires each time an order is filled /// </summary> public event EventHandler<OrderEvent> OrderStatusChanged; /// <summary> /// Event that fires each time a short option position is assigned /// </summary> public event EventHandler<OrderEvent> OptionPositionAssigned; /// <summary> /// Event that fires each time a user's brokerage account is changed /// </summary> public event EventHandler<AccountEvent> AccountChanged; /// <summary> /// Event that fires when an error is encountered in the brokerage /// </summary> public event EventHandler<BrokerageMessageEvent> Message; /// <summary> /// Gets the name of the brokerage /// </summary> public string Name { get; } /// <summary> /// Returns true if we're currently connected to the broker /// </summary> public abstract bool IsConnected { get; } /// <summary> /// Creates a new Brokerage instance with the specified name /// </summary> /// <param name="name">The name of the brokerage</param> protected Brokerage(string name) { Name = name; } /// <summary> /// Places a new order and assigns a new broker ID to the order /// </summary> /// <param name="order">The order to be placed</param> /// <returns>True if the request for a new order has been placed, false otherwise</returns> public abstract bool PlaceOrder(Order order); /// <summary> /// Updates the order with the same id /// </summary> /// <param name="order">The new order information</param> /// <returns>True if the request was made for the order to be updated, false otherwise</returns> public abstract bool UpdateOrder(Order order); /// <summary> /// Cancels the order with the specified ID /// </summary> /// <param name="order">The order to cancel</param> /// <returns>True if the request was made for the order to be canceled, false otherwise</returns> public abstract bool CancelOrder(Order order); /// <summary> /// Connects the client to the broker's remote servers /// </summary> public abstract void Connect(); /// <summary> /// Disconnects the client from the broker's remote servers /// </summary> public abstract void Disconnect(); /// <summary> /// Dispose of the brokerage instance /// </summary> public virtual void Dispose() { // NOP } /// <summary> /// Event invocator for the OrderFilled event /// </summary> /// <param name="e">The OrderEvent</param> protected virtual void OnOrderEvent(OrderEvent e) { try { OrderStatusChanged?.Invoke(this, e); if (Log.DebuggingEnabled) { // log after calling the OrderStatusChanged event, the BrokerageTransactionHandler will set the order quantity Log.Debug("Brokerage.OnOrderEvent(): " + e); } } catch (Exception err) { Log.Error(err); } } /// <summary> /// Event invocator for the OptionPositionAssigned event /// </summary> /// <param name="e">The OrderEvent</param> protected virtual void OnOptionPositionAssigned(OrderEvent e) { try { Log.Debug("Brokerage.OptionPositionAssigned(): " + e); OptionPositionAssigned?.Invoke(this, e); } catch (Exception err) { Log.Error(err); } } /// <summary> /// Event invocator for the AccountChanged event /// </summary> /// <param name="e">The AccountEvent</param> protected virtual void OnAccountChanged(AccountEvent e) { try { Log.Trace($"Brokerage.OnAccountChanged(): {e}"); AccountChanged?.Invoke(this, e); } catch (Exception err) { Log.Error(err); } } /// <summary> /// Event invocator for the Message event /// </summary> /// <param name="e">The error</param> protected virtual void OnMessage(BrokerageMessageEvent e) { try { if (e.Type == BrokerageMessageType.Error) { Log.Error("Brokerage.OnMessage(): " + e); } else { Log.Trace("Brokerage.OnMessage(): " + e); } Message?.Invoke(this, e); } catch (Exception err) { Log.Error(err); } } /// <summary> /// Helper method that will try to get the live holdings from the provided brokerage data collection else will default to the algorithm state /// </summary> /// <remarks>Holdings will removed from the provided collection on the first call, since this method is expected to be called only /// once on initialize, after which the algorithm should use Lean accounting</remarks> protected virtual List<Holding> GetAccountHoldings(Dictionary<string, string> brokerageData, IEnumerable<Security> securities) { if (Log.DebuggingEnabled) { Log.Debug("Brokerage.GetAccountHoldings(): starting..."); } if (brokerageData != null && brokerageData.Remove("live-holdings", out var value) && !string.IsNullOrEmpty(value)) { // remove the key, we really only want to return the cached value on the first request var result = JsonConvert.DeserializeObject<List<Holding>>(value); Log.Trace($"Brokerage.GetAccountHoldings(): sourcing holdings from provided brokerage data, found {result.Count} entries"); return result; } return securities?.Where(security => security.Holdings.AbsoluteQuantity > 0) .OrderBy(security => security.Symbol) .Select(security => new Holding(security)).ToList() ?? new List<Holding>(); } /// <summary> /// Helper method that will try to get the live cash balance from the provided brokerage data collection else will default to the algorithm state /// </summary> /// <remarks>Cash balance will removed from the provided collection on the first call, since this method is expected to be called only /// once on initialize, after which the algorithm should use Lean accounting</remarks> protected virtual List<CashAmount> GetCashBalance(Dictionary<string, string> brokerageData, CashBook cashBook) { if (Log.DebuggingEnabled) { Log.Debug("Brokerage.GetCashBalance(): starting..."); } if (brokerageData != null && brokerageData.Remove("live-cash-balance", out var value) && !string.IsNullOrEmpty(value)) { // remove the key, we really only want to return the cached value on the first request var result = JsonConvert.DeserializeObject<List<CashAmount>>(value); Log.Trace($"Brokerage.GetCashBalance(): sourcing cash balance from provided brokerage data, found {result.Count} entries"); return result; } return cashBook?.Select(x => new CashAmount(x.Value.Amount, x.Value.Symbol)).ToList() ?? new List<CashAmount>(); } /// <summary> /// Gets all open orders on the account. /// NOTE: The order objects returned do not have QC order IDs. /// </summary> /// <returns>The open orders returned from IB</returns> public abstract List<Order> GetOpenOrders(); /// <summary> /// Gets all holdings for the account /// </summary> /// <returns>The current holdings from the account</returns> public abstract List<Holding> GetAccountHoldings(); /// <summary> /// Gets the current cash balance for each currency held in the brokerage account /// </summary> /// <returns>The current cash balance for each currency available for trading</returns> public abstract List<CashAmount> GetCashBalance(); /// <summary> /// Specifies whether the brokerage will instantly update account balances /// </summary> public virtual bool AccountInstantlyUpdated => false; /// <summary> /// Returns the brokerage account's base currency /// </summary> public virtual string AccountBaseCurrency { get; protected set; } /// <summary> /// Gets the history for the requested security /// </summary> /// <param name="request">The historical data request</param> /// <returns>An enumerable of bars covering the span specified in the request</returns> public virtual IEnumerable<BaseData> GetHistory(HistoryRequest request) { return Enumerable.Empty<BaseData>(); } #region IBrokerageCashSynchronizer implementation /// <summary> /// Gets the date of the last sync (New York time zone) /// </summary> protected DateTime LastSyncDate => LastSyncDateTimeUtc.ConvertFromUtc(TimeZones.NewYork).Date; /// <summary> /// Gets the datetime of the last sync (UTC) /// </summary> public DateTime LastSyncDateTimeUtc => new DateTime(Interlocked.Read(ref _lastSyncTimeTicks)); /// <summary> /// Returns whether the brokerage should perform the cash synchronization /// </summary> /// <param name="currentTimeUtc">The current time (UTC)</param> /// <returns>True if the cash sync should be performed</returns> public virtual bool ShouldPerformCashSync(DateTime currentTimeUtc) { // every morning flip this switch back var currentTimeNewYork = currentTimeUtc.ConvertFromUtc(TimeZones.NewYork); if (_syncedLiveBrokerageCashToday && currentTimeNewYork.Date != LastSyncDate) { _syncedLiveBrokerageCashToday = false; } return !_syncedLiveBrokerageCashToday && currentTimeNewYork.TimeOfDay >= LiveBrokerageCashSyncTime; } /// <summary> /// Synchronizes the cashbook with the brokerage account /// </summary> /// <param name="algorithm">The algorithm instance</param> /// <param name="currentTimeUtc">The current time (UTC)</param> /// <param name="getTimeSinceLastFill">A function which returns the time elapsed since the last fill</param> /// <returns>True if the cash sync was performed successfully</returns> public virtual bool PerformCashSync(IAlgorithm algorithm, DateTime currentTimeUtc, Func<TimeSpan> getTimeSinceLastFill) { try { // prevent reentrance in this method if (!Monitor.TryEnter(_performCashSyncReentranceGuard)) { Log.Trace("Brokerage.PerformCashSync(): Reentrant call, cash sync not performed"); return false; } Log.Trace("Brokerage.PerformCashSync(): Sync cash balance"); var balances = new List<CashAmount>(); try { balances = GetCashBalance(); } catch (Exception err) { Log.Error(err, "Error in GetCashBalance:"); } if (balances.Count == 0) { Log.Trace("Brokerage.PerformCashSync(): No cash balances available, cash sync not performed"); return false; } // Adds currency to the cashbook that the user might have deposited foreach (var balance in balances) { if (!algorithm.Portfolio.CashBook.ContainsKey(balance.Currency)) { Log.Trace($"Brokerage.PerformCashSync(): Unexpected cash found {balance.Currency} {balance.Amount}", true); algorithm.Portfolio.SetCash(balance.Currency, balance.Amount, 0); } } // if we were returned our balances, update everything and flip our flag as having performed sync today foreach (var kvp in algorithm.Portfolio.CashBook) { var cash = kvp.Value; //update the cash if the entry if found in the balances var balanceCash = balances.Find(balance => balance.Currency == cash.Symbol); if (balanceCash != default(CashAmount)) { // compare in account currency var delta = cash.Amount - balanceCash.Amount; if (Math.Abs(algorithm.Portfolio.CashBook.ConvertToAccountCurrency(delta, cash.Symbol)) > 5) { // log the delta between Log.Trace($"Brokerage.PerformCashSync(): {balanceCash.Currency} Delta: {delta:0.00}", true); } algorithm.Portfolio.CashBook[cash.Symbol].SetAmount(balanceCash.Amount); } else { //Set the cash amount to zero if cash entry not found in the balances Log.Trace($"Brokerage.PerformCashSync(): {cash.Symbol} was not found in brokerage cash balance, setting the amount to 0", true); algorithm.Portfolio.CashBook[cash.Symbol].SetAmount(0); } } _syncedLiveBrokerageCashToday = true; _lastSyncTimeTicks = currentTimeUtc.Ticks; } finally { Monitor.Exit(_performCashSyncReentranceGuard); } // fire off this task to check if we've had recent fills, if we have then we'll invalidate the cash sync // and do it again until we're confident in it Task.Delay(TimeSpan.FromSeconds(10)).ContinueWith(_ => { // we want to make sure this is a good value, so check for any recent fills if (getTimeSinceLastFill() <= TimeSpan.FromSeconds(20)) { // this will cause us to come back in and reset cash again until we // haven't processed a fill for +- 10 seconds of the set cash time _syncedLiveBrokerageCashToday = false; //_failedCashSyncAttempts = 0; Log.Trace("Brokerage.PerformCashSync(): Unverified cash sync - resync required."); } else { Log.Trace("Brokerage.PerformCashSync(): Verified cash sync."); algorithm.Portfolio.LogMarginInformation(); } }); return true; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void CompareLessThanScalarSingle() { var test = new SimpleBinaryOpTest__CompareLessThanScalarSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareLessThanScalarSingle { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Single); private const int Op2ElementCount = VectorSize / sizeof(Single); private const int RetElementCount = VectorSize / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private SimpleBinaryOpTest__DataTable<Single, Single, Single> _dataTable; static SimpleBinaryOpTest__CompareLessThanScalarSingle() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__CompareLessThanScalarSingle() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Single, Single, Single>(_data1, _data2, new Single[RetElementCount], VectorSize); } public bool IsSupported => Sse.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse.CompareLessThanScalar( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse.CompareLessThanScalar( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse.CompareLessThanScalar( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse).GetMethod(nameof(Sse.CompareLessThanScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse).GetMethod(nameof(Sse.CompareLessThanScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse).GetMethod(nameof(Sse.CompareLessThanScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse.CompareLessThanScalar( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse.CompareLessThanScalar(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareLessThanScalar(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareLessThanScalar(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__CompareLessThanScalarSingle(); var result = Sse.CompareLessThanScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse.CompareLessThanScalar(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { if (BitConverter.SingleToInt32Bits(result[0]) != ((left[0] < right[0]) ? -1 : 0)) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(left[i]) != BitConverter.SingleToInt32Bits(result[i])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse)}.{nameof(Sse.CompareLessThanScalar)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Bond.Expressions.Xml { using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq.Expressions; using System.Runtime.CompilerServices; using System.Xml; using Bond.Expressions; using Bond.Expressions.Pull; using Bond.Protocols; public class SimpleXmlParser<R> : XmlParser<R> where R : IXmlReader { static readonly Expression<Action<byte, XmlNodeType, string, string>> parsingError = (s, t, n, v) => ParsingError(s, t, n, v); static readonly Expression<Action<XmlNodeType>> unexpectedNodeError = n => UnexpectedNodeError(n); delegate Expression ContainerItemHandler(Expression nextItem); public SimpleXmlParser(RuntimeSchema schema) : base(schema, flatten: true) {} public SimpleXmlParser(Type type) : base(Bond.Schema.GetRuntimeSchema(type), flatten: true) {} SimpleXmlParser(XmlParser<R> that, RuntimeSchema schema) : base(that, schema, flatten: true) {} protected override IStateMachine<XmlNodeType> CreateStateMachine( IEnumerable<TransformSchemaPair> transforms, ParameterExpression requiredFields) { return new StateMachine<XmlNodeType> { InitialState = State.AtStructElement, FinalState = State.Finished, IgnoredTokens = new[] { XmlNodeType.Comment, XmlNodeType.Text, XmlNodeType.Whitespace, XmlNodeType.XmlDeclaration, }, Default = state => Expression.Invoke(unexpectedNodeError, Reader.NodeType), TokenTransitions = new[] { new TokenTransition<XmlNodeType> { Token = XmlNodeType.Element, StateTransitions = new[] { new StateTransition(State.AtStructElement, ProcessStructElement), new StateTransition(State.InsideStructElement, state => ProcessFieldElement(state, requiredFields, transforms)), new StateTransition(State.AtFieldEndElement, State.InsideStructElement, state => Reader.Read()) }, Default = state => ParsingError(state), }, new TokenTransition<XmlNodeType> { Token = XmlNodeType.EndElement, StateTransitions = new[] { new StateTransition(State.AtFieldEndElement, State.InsideStructElement, state => Reader.Read()), new StateTransition(State.InsideStructElement, State.Finished, state => Reader.Read()) }, Default = state => ParsingError(state), } } }; } Expression ProcessStructElement(Expression state) { return Expression.Block( Expression.IfThenElse( Reader.IsEmptyElement, Expression.Assign(state, Expression.Constant(State.Finished)), Expression.Assign(state, Expression.Constant(State.InsideStructElement))), Reader.Read()); } Expression ProcessFieldElement( Expression state, ParameterExpression requiredFields, IEnumerable<TransformSchemaPair> transforms) { var requiredIndex = 0; // start from the expression to handle unknown element (will be executed at the end of the if/else chain) Expression body = Expression.Block( Reader.Skip(), Expression.Assign(state, Expression.Constant(State.InsideStructElement))); // if there are transform/schema pairs for base structs, process their fields as well into the expression foreach (var pair in transforms) { var index = 0; var structDef = pair.Schema.StructDef; foreach (var field in pair.Transform.Fields) { var fieldDef = structDef.fields[index++]; Debug.Assert(field.Id == fieldDef.id); var parser = new SimpleXmlParser<R>(this, pair.Schema.GetFieldSchema(fieldDef)); // process field - and set the state to expect to see the field element's end var handleField = new List<Expression> { field.Value(parser, Expression.Constant(fieldDef.type.id)), Expression.Assign(state, Expression.Constant(State.AtFieldEndElement)) }; if (fieldDef.metadata.modifier == Modifier.Required) { handleField.Add(RequiredFields.Mark(requiredFields, requiredIndex++)); } body = Expression.IfThenElse( NodeNameEquals(fieldDef.metadata.name, structDef.metadata.GetXmlNamespace()), Expression.Block(handleField), body); } } return body; } public override Expression Apply(ITransform transform) { // in SimpleXml protocol, the parser is expecting to read one step in order to get to the actual // element that represents the struct return Expression.Block( Read(), base.Apply(transform)); } public override Expression Blob(Expression count) { // TODO: for now handle blob as array of bytes; consider CDATA return null; } public override Expression Scalar(Expression valueType, BondDataType expectedType, ValueHandler handler) { var stringValue = Expression.Variable(typeof(string), "valueAsString"); // Reading primitive field of a struct, or a primitive list item - value is in Xml element text. // If we have an empty element, parse it as if it has an empty text. // Otherwise: read once to get to the text, handle the text, read once more to get to the end element. return Expression.Block( new[] { stringValue }, Expression.IfThenElse( Reader.IsEmptyElement, Expression.Assign(stringValue, StringExpression.Empty()), Expression.Block( Reader.Read(), Expression.IfThenElse( Expression.Equal(Reader.NodeType, Expression.Constant(XmlNodeType.EndElement)), Expression.Assign(stringValue, Expression.Constant(string.Empty)), Expression.Block( IfNotNodeType(XmlNodeType.Text, IfNotNodeType(XmlNodeType.Whitespace, ParsingError())), Expression.Assign(stringValue, Reader.Value), Reader.Read(), IfNotNodeType(XmlNodeType.EndElement, ParsingError()))))), handler(StringExpression.Convert(stringValue, expectedType))); } public override Expression Container(BondDataType? expectedType, ContainerHandler handler) { return Items(nextItem => handler( new SimpleXmlParser<R>(this, Schema.GetElementSchema()), Expression.Constant(Schema.TypeDef.element.id), nextItem, Expression.Constant(0), null)); } public override Expression Map(BondDataType? expectedKeyType, BondDataType? expectedValueType, MapHandler handler) { return Items(nextItem => handler( new SimpleXmlParser<R>(this, Schema.GetKeySchema()), new SimpleXmlParser<R>(this, Schema.GetElementSchema()), Expression.Constant(Schema.TypeDef.key.id), Expression.Constant(Schema.TypeDef.element.id), nextItem, nextItem, Expression.Constant(0))); } Expression Items(ContainerItemHandler handler) { // If the list is an empty element we won't read anything var isEmpty = Expression.Variable(typeof(bool), "isEmpty"); // Generate the following code for the "next" expression: // if (isEmpty) // { // return false; // } // else // { // while (reader.NodeType == XmlNodeType.Whitespace) reader.Read; // do { reader.Read(); } while (reader.NodeType == XmlNodeType.Whitespace; // // if (reader.NodeType == XmlNodeType.Element) && // reader.LocalName != "Item") // { // throw new InvalidDataException(); // } // // return reader.XmlNode != XmlNodeType.EndElement; // } var whitespace = Expression.Equal(Reader.NodeType, Expression.Constant(XmlNodeType.Whitespace)); var next = Expression.Condition(isEmpty, Expression.Constant(false), Expression.Block( ControlExpression.While(whitespace, Reader.Read()), ControlExpression.DoWhile(Reader.Read(), whitespace), Expression.IfThen( Expression.AndAlso( Expression.Equal(Reader.NodeType, Expression.Constant(XmlNodeType.Element)), Expression.NotEqual(Reader.LocalName, Expression.Constant("Item"))), ParsingError()), Expression.NotEqual(Reader.NodeType, Expression.Constant(XmlNodeType.EndElement)))); return Expression.Block( new[] { isEmpty }, Expression.Assign(isEmpty, Reader.IsEmptyElement), handler(next)); } Expression IfNotNodeType(XmlNodeType type, Expression then) { return Expression.IfThen( Expression.NotEqual(Reader.NodeType, Expression.Constant(type)), then); } Expression NodeNameEquals(string localName, string namespaceUri) { if (string.IsNullOrEmpty(namespaceUri)) { return StringExpression.Equals(Reader.LocalName, localName, StringComparison.OrdinalIgnoreCase); } return Expression.AndAlso( StringExpression.Equals(Reader.LocalName, localName, StringComparison.OrdinalIgnoreCase), Expression.OrElse( StringExpression.Equals(Reader.NamespaceURI, StringExpression.Empty(), StringComparison.OrdinalIgnoreCase), StringExpression.Equals(Reader.NamespaceURI, namespaceUri, StringComparison.OrdinalIgnoreCase))); } static void UnexpectedNodeError(XmlNodeType type) { throw new InvalidDataException(string.Format(CultureInfo.InvariantCulture, "Unexpected node type: {0}", type)); } Expression ParsingError(Expression state) { return Expression.Invoke(parsingError, state, Reader.NodeType, Reader.LocalName, Reader.Value); } Expression ParsingError() { return Expression.Invoke(parsingError, Expression.Constant((byte)0), Reader.NodeType, Reader.LocalName, Reader.Value); } [MethodImpl(MethodImplOptions.NoInlining)] static void ParsingError(byte state, XmlNodeType type, string name, string value) { throw new InvalidDataException(string.Format(CultureInfo.InvariantCulture, "Parsing error: state '{0}', (Xml node type='{1}', name='{2}', value='{3}')", state, type, name, value)); } static class State { public const byte AtStructElement = 1; public const byte InsideStructElement = 2; public const byte AtFieldEndElement = 3; public const byte Finished = 4; } } }
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 TodoList_Service.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; } } }
// SF API version v50.0 // Custom fields included: False // Relationship objects included: True using System; using NetCoreForce.Client.Models; using NetCoreForce.Client.Attributes; using Newtonsoft.Json; namespace NetCoreForce.Models { ///<summary> /// Process Instance ///<para>SObject Name: ProcessInstance</para> ///<para>Custom Object: False</para> ///</summary> public class SfProcessInstance : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "ProcessInstance"; } } ///<summary> /// Process Instance ID /// <para>Name: Id</para> /// <para>SF Type: id</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "id")] [Updateable(false), Createable(false)] public string Id { get; set; } ///<summary> /// Approval Process ID /// <para>Name: ProcessDefinitionId</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "processDefinitionId")] [Updateable(false), Createable(false)] public string ProcessDefinitionId { get; set; } ///<summary> /// ReferenceTo: ProcessDefinition /// <para>RelationshipName: ProcessDefinition</para> ///</summary> [JsonProperty(PropertyName = "processDefinition")] [Updateable(false), Createable(false)] public SfProcessDefinition ProcessDefinition { get; set; } ///<summary> /// Target Object ID /// <para>Name: TargetObjectId</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "targetObjectId")] [Updateable(false), Createable(false)] public string TargetObjectId { get; set; } ///<summary> /// Status /// <para>Name: Status</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "status")] [Updateable(false), Createable(false)] public string Status { get; set; } ///<summary> /// Completed Date /// <para>Name: CompletedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "completedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? CompletedDate { get; set; } ///<summary> /// User ID /// <para>Name: LastActorId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "lastActorId")] [Updateable(false), Createable(false)] public string LastActorId { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: LastActor</para> ///</summary> [JsonProperty(PropertyName = "lastActor")] [Updateable(false), Createable(false)] public SfUser LastActor { get; set; } ///<summary> /// Elapsed Time in Days /// <para>Name: ElapsedTimeInDays</para> /// <para>SF Type: double</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "elapsedTimeInDays")] [Updateable(false), Createable(false)] public double? ElapsedTimeInDays { get; set; } ///<summary> /// Elapsed Time in Hours /// <para>Name: ElapsedTimeInHours</para> /// <para>SF Type: double</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "elapsedTimeInHours")] [Updateable(false), Createable(false)] public double? ElapsedTimeInHours { get; set; } ///<summary> /// Elapsed Time in Minutes /// <para>Name: ElapsedTimeInMinutes</para> /// <para>SF Type: double</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "elapsedTimeInMinutes")] [Updateable(false), Createable(false)] public double? ElapsedTimeInMinutes { get; set; } ///<summary> /// User ID /// <para>Name: SubmittedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "submittedById")] [Updateable(false), Createable(false)] public string SubmittedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: SubmittedBy</para> ///</summary> [JsonProperty(PropertyName = "submittedBy")] [Updateable(false), Createable(false)] public SfUser SubmittedBy { get; set; } ///<summary> /// Deleted /// <para>Name: IsDeleted</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isDeleted")] [Updateable(false), Createable(false)] public bool? IsDeleted { get; set; } ///<summary> /// Created Date /// <para>Name: CreatedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdDate")] [Updateable(false), Createable(false)] public DateTimeOffset? CreatedDate { get; set; } ///<summary> /// Created By ID /// <para>Name: CreatedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdById")] [Updateable(false), Createable(false)] public string CreatedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: CreatedBy</para> ///</summary> [JsonProperty(PropertyName = "createdBy")] [Updateable(false), Createable(false)] public SfUser CreatedBy { get; set; } ///<summary> /// Last Modified Date /// <para>Name: LastModifiedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastModifiedDate { get; set; } ///<summary> /// Last Modified By ID /// <para>Name: LastModifiedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedById")] [Updateable(false), Createable(false)] public string LastModifiedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: LastModifiedBy</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedBy")] [Updateable(false), Createable(false)] public SfUser LastModifiedBy { get; set; } ///<summary> /// System Modstamp /// <para>Name: SystemModstamp</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "systemModstamp")] [Updateable(false), Createable(false)] public DateTimeOffset? SystemModstamp { get; set; } } }
// **************************************************************** // Copyright 2008, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org // **************************************************************** using System; using System.Collections; using System.Collections.Specialized; namespace NUnit.Constraints { /// <summary> /// The TestCaseData class represents a set of arguments /// and other parameter info to be used for a parameterized /// test case. It provides a number of instance modifiers /// for use in initializing the test case. /// /// Note: Instance modifiers are getters that return /// the same instance after modifying it's state. /// </summary> public class TestCaseData : ITestCaseData { #region Constants //private static readonly string DESCRIPTION = "_DESCRIPTION"; //private static readonly string IGNOREREASON = "_IGNOREREASON"; private static readonly string CATEGORIES = "_CATEGORIES"; #endregion #region Instance Fields /// <summary> /// The argument list to be provided to the test /// </summary> private object[] arguments; /// <summary> /// The expected result to be returned /// </summary> private object result; /// <summary> /// The expected exception Type /// </summary> private Type expectedExceptionType; /// <summary> /// The FullName of the expected exception /// </summary> private string expectedExceptionName; /// <summary> /// The name to be used for the test /// </summary> private string testName; /// <summary> /// The description of the test /// </summary> private string description; /// <summary> /// A dictionary of properties, used to add information /// to tests without requiring the class to change. /// </summary> private IDictionary properties; /// <summary> /// If true, indicates that the test case is to be ignored /// </summary> bool isIgnored; /// <summary> /// The reason for ignoring a test case /// </summary> string ignoreReason; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="T:TestCaseData"/> class. /// </summary> /// <param name="args">The arguments.</param> public TestCaseData(params object[] args) { if (args == null) this.arguments = new object[] { null }; else this.arguments = args; } /// <summary> /// Initializes a new instance of the <see cref="T:TestCaseData"/> class. /// </summary> /// <param name="arg">The argument.</param> public TestCaseData(object arg) { this.arguments = new object[] { arg }; } /// <summary> /// Initializes a new instance of the <see cref="T:TestCaseData"/> class. /// </summary> /// <param name="arg1">The first argument.</param> /// <param name="arg2">The second argument.</param> public TestCaseData(object arg1, object arg2) { this.arguments = new object[] { arg1, arg2 }; } /// <summary> /// Initializes a new instance of the <see cref="T:TestCaseData"/> class. /// </summary> /// <param name="arg1">The first argument.</param> /// <param name="arg2">The second argument.</param> /// <param name="arg3">The third argument.</param> public TestCaseData(object arg1, object arg2, object arg3) { this.arguments = new object[] { arg1, arg2, arg3 }; } #endregion #region ITestCaseData Members /// <summary> /// Gets the argument list to be provided to the test /// </summary> public object[] Arguments { get { return arguments; } } /// <summary> /// Gets the expected result /// </summary> public object Result { get { return result; } } /// <summary> /// Gets the expected exception Type /// </summary> public Type ExpectedException { get { return expectedExceptionType; } } /// <summary> /// Gets the FullName of the expected exception /// </summary> public string ExpectedExceptionName { get { return expectedExceptionName; } } /// <summary> /// Gets the name to be used for the test /// </summary> public string TestName { get { return testName; } } /// <summary> /// Gets the description of the test /// </summary> public string Description { get { return description; } } /// <summary> /// Gets a value indicating whether this <see cref="ITestCaseData"/> is ignored. /// </summary> /// <value><c>true</c> if ignored; otherwise, <c>false</c>.</value> public bool Ignored { get { return isIgnored; } } /// <summary> /// Gets the ignore reason. /// </summary> /// <value>The ignore reason.</value> public string IgnoreReason { get { return ignoreReason; } } #endregion #region Additional Public Properties /// <summary> /// Gets a list of categories associated with this test. /// </summary> public IList Categories { get { if (Properties[CATEGORIES] == null) Properties[CATEGORIES] = new ArrayList(); return (IList)Properties[CATEGORIES]; } } /// <summary> /// Gets the property dictionary for this test /// </summary> public IDictionary Properties { get { if (properties == null) properties = new ListDictionary(); return properties; } } #endregion #region Fluent Instance Modifiers /// <summary> /// Sets the expected result for the test /// </summary> /// <param name="result">The expected result</param> /// <returns>A modified TestCaseData</returns> public TestCaseData Returns(object result) { this.result = result; return this; } /// <summary> /// Sets the expected exception type for the test /// </summary> /// <param name="exceptionType">Type of the expected exception.</param> /// <returns>The modified TestCaseData instance</returns> public TestCaseData Throws(Type exceptionType) { this.expectedExceptionType = exceptionType; this.expectedExceptionName = exceptionType.FullName; return this; } /// <summary> /// Sets the expected exception type for the test /// </summary> /// <param name="exceptionName">FullName of the expected exception.</param> /// <returns>The modified TestCaseData instance</returns> public TestCaseData Throws(string exceptionName) { this.expectedExceptionName = exceptionName; return this; } /// <summary> /// Sets the name of the test case /// </summary> /// <returns>The modified TestCaseData instance</returns> public TestCaseData SetName(string name) { this.testName = name; return this; } /// <summary> /// Sets the description for the test case /// being constructed. /// </summary> /// <param name="description">The description.</param> /// <returns>The modified TestCaseData instance.</returns> public TestCaseData SetDescription(string description) { this.description = description; return this; } /// <summary> /// Applies a category to the test /// </summary> /// <param name="category"></param> /// <returns></returns> public TestCaseData SetCategory(string category) { this.Categories.Add(category); return this; } /// <summary> /// Applies a named property to the test /// </summary> /// <param name="propName"></param> /// <param name="propValue"></param> /// <returns></returns> public TestCaseData SetProperty(string propName, string propValue) { this.Properties.Add(propName, propValue); return this; } /// <summary> /// Applies a named property to the test /// </summary> /// <param name="propName"></param> /// <param name="propValue"></param> /// <returns></returns> public TestCaseData SetProperty(string propName, int propValue) { this.Properties.Add(propName, propValue); return this; } /// <summary> /// Applies a named property to the test /// </summary> /// <param name="propName"></param> /// <param name="propValue"></param> /// <returns></returns> public TestCaseData SetProperty(string propName, double propValue) { this.Properties.Add(propName, propValue); return this; } /// <summary> /// Ignores this TestCase. /// </summary> /// <returns></returns> public TestCaseData Ignore() { isIgnored = true; return this; } /// <summary> /// Ignores this TestCase, specifying the reason. /// </summary> /// <param name="reason">The reason.</param> /// <returns></returns> public TestCaseData Ignore(string reason) { isIgnored = true; ignoreReason = reason; return this; } #endregion } }
#region LGPL License /* Axiom Game Engine Library Copyright (C) 2003 Axiom Project Team The overall design, and a majority of the core engine and rendering code contained within this library is a derivative of the open source Object Oriented Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net. Many thanks to the OGRE team for maintaining such a high quality project. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion using System; using System.Collections; using System.Collections.Generic; using Axiom.Core; using Axiom.Controllers.Canned; using Axiom.Graphics; namespace Axiom.Controllers { /// <summary> /// Summary description for ControllerManager. /// </summary> public sealed class ControllerManager : IDisposable { #region Singleton implementation /// <summary> /// Singleton instance of this class. /// </summary> private static ControllerManager instance; /// <summary> /// Internal constructor. This class cannot be instantiated externally. /// </summary> internal ControllerManager() { if (instance == null) { instance = this; } } /// <summary> /// Gets the singleton instance of this class. /// </summary> public static ControllerManager Instance { get { return instance; } } #endregion Singleton implementation #region Member variables /// <summary> /// List of references to controllers in a scene. /// </summary> private List<Controller<float>> controllers = new List<Controller<float>>(); /// <summary> /// Local instance of a FrameTimeControllerValue to be used for time based controllers. /// </summary> private IControllerValue<float> frameTimeController = new FrameTimeControllerValue(); private IControllerFunction<float> passthroughFunction = new PassthroughControllerFunction(); private ulong lastFrameNumber = 0; #endregion #region Methods /// <summary> /// Overloaded method. Creates a new controller, using a reference to a FrameTimeControllerValue as /// the source. /// </summary> /// <param name="destination">Controller value to use as the destination.</param> /// <param name="function">Controller funcion that will use the source value to set the destination.</param> /// <returns>A newly created controller object that will be updated during the main render loop.</returns> public Controller<float> CreateController(IControllerValue<float> destination, IControllerFunction<float> function) { // call the overloaded method passing in our precreated frame time controller value as the source return CreateController(frameTimeController, destination, function); } /// <summary> /// Factory method for creating an instance of a controller based on the input provided. /// </summary> /// <param name="source">Controller value to use as the source.</param> /// <param name="destination">Controller value to use as the destination.</param> /// <param name="function">Controller funcion that will use the source value to set the destination.</param> /// <returns>A newly created controller object that will be updated during the main render loop.</returns> public Controller<float> CreateController(IControllerValue<float> source, IControllerValue<float> destination, IControllerFunction<float> function) { // create a new controller object Controller<float> controller = new Controller<float>(source, destination, function); // add the new controller to our list controllers.Add(controller); return controller; } public void DestroyController(Controller<float> controller) { controllers.Remove(controller); } public Controller<float> CreateFrameTimePassthroughController(IControllerValue<float> dest) { return CreateController(frameTimeController, dest, passthroughFunction); } public float GetElapsedTime() { return ((FrameTimeControllerValue)frameTimeController).ElapsedTime; } /// <summary> /// Creates a texture layer animator controller. /// </summary> /// <remarks> /// This helper method creates the Controller, IControllerValue and IControllerFunction classes required /// to animate a texture. /// </remarks> /// <param name="texUnit">The texture unit to animate.</param> /// <param name="sequenceTime">Length of the animation (in seconds).</param> /// <returns>A newly created controller object that will be updated during the main render loop.</returns> public Controller<float> CreateTextureAnimator(TextureUnitState texUnit, float sequenceTime) { IControllerValue<float> val = new TextureFrameControllerValue(texUnit); IControllerFunction<float> func = new AnimationControllerFunction(sequenceTime); return CreateController(val, func); } /// <summary> /// Creates a basic time-based texture coordinate modifier designed for creating rotating textures. /// </summary> /// <remarks> /// This simple method allows you to easily create constant-speed rotating textures. If you want more /// control, look up the ControllerManager.CreateTextureWaveTransformer for more complex wave-based /// scrollers / stretchers / rotaters. /// </remarks> /// <param name="layer">The texture unit to animate.</param> /// <param name="speed">Speed of the rotation, in counter-clockwise revolutions per second.</param> /// <returns>A newly created controller object that will be updated during the main render loop.</returns> public Controller<float> CreateTextureRotator(TextureUnitState layer, float speed) { IControllerValue<float> val = new TexCoordModifierControllerValue(layer, false, false, false, false, true); IControllerFunction<float> func = new MultipyControllerFunction(-speed, true); return CreateController(val, func); } /// <summary> /// Predefined controller value for setting a single floating- /// point value in a constant paramter of a vertex or fragment program. /// </summary> /// <remarks> /// Any value is accepted, it is propagated into the 'x' /// component of the constant register identified by the index. If you /// need to use named parameters, retrieve the index from the param /// object before setting this controller up. /// </remarks> /// <param name="parms"></param> /// <param name="index"></param> /// <param name="timeFactor"></param> /// <returns></returns> public Controller<float> CreateGpuProgramTimerParam(GpuProgramParameters parms, int index, float timeFactor) { IControllerValue<float> val = new FloatGpuParamControllerValue(parms, index); IControllerFunction<float> func = new MultipyControllerFunction(timeFactor, true); return CreateController(val, func); } /// <summary> /// Creates a basic time-based texture coordinate modifier designed for creating rotating textures. /// </summary> /// <remarks> /// This simple method allows you to easily create constant-speed scrolling textures. If you want more /// control, look up the ControllerManager.CreateTextureWaveTransformer for more complex wave-based /// scrollers / stretchers / rotaters. /// </remarks> /// <param name="layer">The texture unit to animate.</param> /// <param name="speedU">Horizontal speed, in wraps per second.</param> /// <param name="speedV">Vertical speed, in wraps per second.</param> /// <returns>A newly created controller object that will be updated during the main render loop.</returns> public Controller<float> CreateTextureScroller(TextureUnitState layer, float speedU, float speedV) { IControllerValue<float> val = null; IControllerFunction<float> func = null; Controller<float> controller = null; // if both u and v speeds are the same, we can use a single controller for it if(speedU != 0 && (speedU == speedV)) { // create the value and function val = new TexCoordModifierControllerValue(layer, true, true); func = new MultipyControllerFunction(-speedU, true); // create the controller (uses FrameTime for source by default) controller = CreateController(val, func); } else { // create seperate for U if(speedU != 0) { // create the value and function val = new TexCoordModifierControllerValue(layer, true, false); func = new MultipyControllerFunction(-speedU, true); // create the controller (uses FrameTime for source by default) controller = CreateController(val, func); } // create seperate for V if(speedV != 0) { // create the value and function val = new TexCoordModifierControllerValue(layer, false, true); func = new MultipyControllerFunction(-speedV, true); // create the controller (uses FrameTime for source by default) controller = CreateController(val, func); } } // TODO: Revisit, since we can't return 2 controllers in the case of non equal U and V speeds return controller; } /// <summary> /// Creates a very flexible time-based texture transformation which can alter the scale, position or /// rotation of a texture based on a wave function. /// </summary> /// <param name="layer">The texture unit to effect.</param> /// <param name="transformType">The type of transform, either translate (scroll), scale (stretch) or rotate (spin).</param> /// <param name="waveType">The shape of the wave, see WaveformType enum for details.</param> /// <param name="baseVal">The base value of the output.</param> /// <param name="frequency">The speed of the wave in cycles per second.</param> /// <param name="phase">The offset of the start of the wave, e.g. 0.5 to start half-way through the wave.</param> /// <param name="amplitude">Scales the output so that instead of lying within 0..1 it lies within 0..(1 * amplitude) for exaggerated effects</param> /// <returns>A newly created controller object that will be updated during the main render loop.</returns> public Controller<float> CreateTextureWaveTransformer(TextureUnitState layer, TextureTransform type, WaveformType waveType, float baseVal, float frequency, float phase, float amplitude) { IControllerValue<float> val = null; IControllerFunction<float> function = null; // determine which type of controller value this layer needs switch(type) { case TextureTransform.TranslateU: val = new TexCoordModifierControllerValue(layer, true, false); break; case TextureTransform.TranslateV: val = new TexCoordModifierControllerValue(layer, false, true); break; case TextureTransform.ScaleU: val = new TexCoordModifierControllerValue(layer, false, false, true, false, false); break; case TextureTransform.ScaleV: val = new TexCoordModifierControllerValue(layer, false, false, false, true, false); break; case TextureTransform.Rotate: val = new TexCoordModifierControllerValue(layer, false, false, false, false, true); break; } // switch // create a new waveform controller function function = new WaveformControllerFunction(waveType, baseVal, frequency, phase, amplitude, true); // finally, create the controller using frame time as the source value return CreateController(frameTimeController, val, function); } /// <summary> /// Causes all registered controllers to execute. This will depend on RenderSystem.BeginScene already /// being called so that the time since last frame can be obtained for calculations. /// </summary> public void UpdateAll() { ulong thisFrameNumber = Root.Instance.CurrentFrameCount; if (thisFrameNumber != lastFrameNumber) { // loop through each controller and tell it to update for (int i = 0; i < controllers.Count; i++) { Controller<float> controller = controllers[i]; controller.Update(); } lastFrameNumber = thisFrameNumber; } } #endregion #region IDisposable Implementation /// <summary> /// Called when the engine is shutting down. /// </summary> public void Dispose() { controllers.Clear(); instance = null; } #endregion IDisposable Implementation } }
//------------------------------------------------------------------------------ // <copyright file="ExpressionBindingCollection.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI { using System; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.ComponentModel.Design; using System.Data; using System.Web.Util; using System.Security.Permissions; /// <devdoc> /// </devdoc> public sealed class ExpressionBindingCollection : ICollection { private EventHandler changedEvent; private Hashtable bindings; private Hashtable removedBindings; /// <devdoc> /// </devdoc> public ExpressionBindingCollection() { this.bindings = new Hashtable(StringComparer.OrdinalIgnoreCase); } /// <devdoc> /// </devdoc> public int Count { get { return bindings.Count; } } /// <devdoc> /// </devdoc> public bool IsReadOnly { get { return false; } } /// <devdoc> /// </devdoc> public bool IsSynchronized { get { return false; } } /// <devdoc> /// </devdoc> public ICollection RemovedBindings { get { int bindingCount = 0; ICollection keys = null; if (removedBindings != null) { keys = removedBindings.Keys; bindingCount = keys.Count; string[] removedNames = new string[bindingCount]; int i = 0; foreach (string s in keys) { removedNames[i++] = s; } removedBindings.Clear(); return removedNames; } else { return new string[0]; } } } /// <devdoc> /// </devdoc> private Hashtable RemovedBindingsTable { get { if (removedBindings == null) { removedBindings = new Hashtable(StringComparer.OrdinalIgnoreCase); } return removedBindings; } } /// <devdoc> /// </devdoc> public object SyncRoot { get { return this; } } /// <devdoc> /// </devdoc> public ExpressionBinding this[string propertyName] { get { object o = bindings[propertyName]; if (o != null) return(ExpressionBinding)o; return null; } } public event EventHandler Changed { add { changedEvent = (EventHandler)Delegate.Combine(changedEvent, value); } remove { changedEvent = (EventHandler)Delegate.Remove(changedEvent, value); } } /// <devdoc> /// </devdoc> public void Add(ExpressionBinding binding) { bindings[binding.PropertyName] = binding; RemovedBindingsTable.Remove(binding.PropertyName); OnChanged(); } /// <devdoc> /// </devdoc> public bool Contains(string propName) { return bindings.Contains(propName); } /// <devdoc> /// </devdoc> public void Clear() { ICollection keys = bindings.Keys; if ((keys.Count != 0) && (removedBindings == null)) { // ensure the removedBindings hashtable is created Hashtable h = RemovedBindingsTable; } foreach (string s in keys) { removedBindings[s] = String.Empty; } bindings.Clear(); OnChanged(); } /// <devdoc> /// </devdoc> public void CopyTo(Array array, int index) { for (IEnumerator e = this.GetEnumerator(); e.MoveNext();) array.SetValue(e.Current, index++); } /// <devdoc> /// </devdoc> public void CopyTo(ExpressionBinding[] array, int index) { for (IEnumerator e = this.GetEnumerator(); e.MoveNext();) array.SetValue(e.Current, index++); } /// <devdoc> /// </devdoc> public IEnumerator GetEnumerator() { return bindings.Values.GetEnumerator(); } private void OnChanged() { if (changedEvent != null) { changedEvent(this, EventArgs.Empty); } } /// <devdoc> /// </devdoc> public void Remove(string propertyName) { Remove(propertyName, true); } /// <devdoc> /// </devdoc> public void Remove(ExpressionBinding binding) { Remove(binding.PropertyName, true); } /// <devdoc> /// </devdoc> public void Remove(string propertyName, bool addToRemovedList) { if (Contains(propertyName)) { if (addToRemovedList && bindings.Contains(propertyName)) { RemovedBindingsTable[propertyName] = String.Empty; } bindings.Remove(propertyName); OnChanged(); } } } }
// 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.ComponentModel.Composition; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.SymbolMapping; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.MetadataAsSource { [Export(typeof(IMetadataAsSourceFileService))] internal class MetadataAsSourceFileService : IMetadataAsSourceFileService { /// <summary> /// A lock to guard parallel accesses to this type. In practice, we presume that it's not /// an important scenario that we can be generating multiple documents in parallel, and so /// we simply take this lock around all public entrypoints to enforce sequential access. /// </summary> private readonly SemaphoreSlim _gate = new SemaphoreSlim(initialCount: 1); /// <summary> /// For a description of the key, see GetKeyAsync. /// </summary> private readonly Dictionary<UniqueDocumentKey, MetadataAsSourceGeneratedFileInfo> _keyToInformation = new Dictionary<UniqueDocumentKey, MetadataAsSourceGeneratedFileInfo>(); private readonly Dictionary<string, MetadataAsSourceGeneratedFileInfo> _generatedFilenameToInformation = new Dictionary<string, MetadataAsSourceGeneratedFileInfo>(StringComparer.OrdinalIgnoreCase); private IBidirectionalMap<MetadataAsSourceGeneratedFileInfo, DocumentId> _openedDocumentIds = BidirectionalMap<MetadataAsSourceGeneratedFileInfo, DocumentId>.Empty; private MetadataAsSourceWorkspace _workspace; /// <summary> /// We create a mutex so other processes can see if our directory is still alive. We destroy the mutex when /// we purge our generated files. /// </summary> private Mutex _mutex; private string _rootTemporaryPathWithGuid; private readonly string _rootTemporaryPath; public MetadataAsSourceFileService() { _rootTemporaryPath = Path.Combine(Path.GetTempPath(), "MetadataAsSource"); } private static string CreateMutexName(string directoryName) { return "MetadataAsSource-" + directoryName; } private string GetRootPathWithGuid_NoLock() { if (_rootTemporaryPathWithGuid == null) { var guidString = Guid.NewGuid().ToString("N"); _rootTemporaryPathWithGuid = Path.Combine(_rootTemporaryPath, guidString); _mutex = new Mutex(initiallyOwned: true, name: CreateMutexName(guidString)); } return _rootTemporaryPathWithGuid; } public async Task<MetadataAsSourceFile> GetGeneratedFileAsync(Project project, ISymbol symbol, CancellationToken cancellationToken = default(CancellationToken)) { if (project == null) { throw new ArgumentNullException(nameof(project)); } if (symbol == null) { throw new ArgumentNullException(nameof(symbol)); } if (symbol.Kind == SymbolKind.Namespace) { throw new ArgumentException(EditorFeaturesResources.SymbolCannotBeNamespace, "symbol"); } symbol = symbol.GetOriginalUnreducedDefinition(); MetadataAsSourceGeneratedFileInfo fileInfo; Location navigateLocation = null; var topLevelNamedType = MetadataAsSourceHelpers.GetTopLevelContainingNamedType(symbol); var symbolId = SymbolKey.Create(symbol, await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false), cancellationToken); using (await _gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { InitializeWorkspace(project); var infoKey = await GetUniqueDocumentKey(project, topLevelNamedType, cancellationToken).ConfigureAwait(false); fileInfo = _keyToInformation.GetOrAdd(infoKey, _ => new MetadataAsSourceGeneratedFileInfo(GetRootPathWithGuid_NoLock(), project, topLevelNamedType)); _generatedFilenameToInformation[fileInfo.TemporaryFilePath] = fileInfo; if (!File.Exists(fileInfo.TemporaryFilePath)) { // We need to generate this. First, we'll need a temporary project to do the generation into. We // avoid loading the actual file from disk since it doesn't exist yet. var temporaryProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: false); var temporaryDocument = _workspace.CurrentSolution.AddProject(temporaryProjectInfoAndDocumentId.Item1) .GetDocument(temporaryProjectInfoAndDocumentId.Item2); var sourceFromMetadataService = temporaryDocument.Project.LanguageServices.GetService<IMetadataAsSourceService>(); temporaryDocument = await sourceFromMetadataService.AddSourceToAsync(temporaryDocument, symbol, cancellationToken).ConfigureAwait(false); // We have the content, so write it out to disk var text = await temporaryDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); // Create the directory. It's possible a parallel deletion is happening in another process, so we may have // to retry this a few times. var directoryToCreate = Path.GetDirectoryName(fileInfo.TemporaryFilePath); while (!Directory.Exists(directoryToCreate)) { try { Directory.CreateDirectory(directoryToCreate); } catch (DirectoryNotFoundException) { } catch (UnauthorizedAccessException) { } } using (var textWriter = new StreamWriter(fileInfo.TemporaryFilePath, append: false, encoding: fileInfo.Encoding)) { text.Write(textWriter); } // Mark read-only new FileInfo(fileInfo.TemporaryFilePath).IsReadOnly = true; // Locate the target in the thing we just created navigateLocation = await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, temporaryDocument, cancellationToken).ConfigureAwait(false); } // If we don't have a location yet, then that means we're re-using an existing file. In this case, we'll want to relocate the symbol. if (navigateLocation == null) { navigateLocation = await RelocateSymbol_NoLock(fileInfo, symbolId, cancellationToken).ConfigureAwait(false); } } var documentName = string.Format( "{0} [{1}]", topLevelNamedType.Name, EditorFeaturesResources.FromMetadata); var documentTooltip = topLevelNamedType.ToDisplayString(new SymbolDisplayFormat(typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces)); return new MetadataAsSourceFile(fileInfo.TemporaryFilePath, navigateLocation, documentName, documentTooltip); } private async Task<Location> RelocateSymbol_NoLock(MetadataAsSourceGeneratedFileInfo fileInfo, SymbolKey symbolId, CancellationToken cancellationToken) { // We need to relocate the symbol in the already existing file. If the file is open, we can just // reuse that workspace. Otherwise, we have to go spin up a temporary project to do the binding. DocumentId openDocumentId; if (_openedDocumentIds.TryGetValue(fileInfo, out openDocumentId)) { // Awesome, it's already open. Let's try to grab a document for it var document = _workspace.CurrentSolution.GetDocument(openDocumentId); return await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, document, cancellationToken).ConfigureAwait(false); } // Annoying case: the file is still on disk. Only real option here is to spin up a fake project to go and bind in. var temporaryProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: true); var temporaryDocument = _workspace.CurrentSolution.AddProject(temporaryProjectInfoAndDocumentId.Item1) .GetDocument(temporaryProjectInfoAndDocumentId.Item2); return await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, temporaryDocument, cancellationToken).ConfigureAwait(false); } public bool TryAddDocumentToWorkspace(string filePath, ITextBuffer buffer) { using (_gate.DisposableWait()) { MetadataAsSourceGeneratedFileInfo fileInfo; if (_generatedFilenameToInformation.TryGetValue(filePath, out fileInfo)) { Contract.ThrowIfTrue(_openedDocumentIds.ContainsKey(fileInfo)); // We do own the file, so let's open it up in our workspace var newProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: true); _workspace.OnProjectAdded(newProjectInfoAndDocumentId.Item1); _workspace.OnDocumentOpened(newProjectInfoAndDocumentId.Item2, buffer.AsTextContainer()); _openedDocumentIds = _openedDocumentIds.Add(fileInfo, newProjectInfoAndDocumentId.Item2); return true; } } return false; } public bool TryRemoveDocumentFromWorkspace(string filePath) { using (_gate.DisposableWait()) { MetadataAsSourceGeneratedFileInfo fileInfo; if (_generatedFilenameToInformation.TryGetValue(filePath, out fileInfo)) { if (_openedDocumentIds.ContainsKey(fileInfo)) { RemoveDocumentFromWorkspace_NoLock(fileInfo); return true; } } } return false; } private void RemoveDocumentFromWorkspace_NoLock(MetadataAsSourceGeneratedFileInfo fileInfo) { var documentId = _openedDocumentIds.GetValueOrDefault(fileInfo); Contract.ThrowIfNull(documentId); _workspace.OnDocumentClosed(documentId, new FileTextLoader(fileInfo.TemporaryFilePath, fileInfo.Encoding)); _workspace.OnProjectRemoved(documentId.ProjectId); _openedDocumentIds = _openedDocumentIds.RemoveKey(fileInfo); } private async Task<UniqueDocumentKey> GetUniqueDocumentKey(Project project, INamedTypeSymbol topLevelNamedType, CancellationToken cancellationToken) { var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var peMetadataReference = compilation.GetMetadataReference(topLevelNamedType.ContainingAssembly) as PortableExecutableReference; if (peMetadataReference.FilePath != null) { return new UniqueDocumentKey(peMetadataReference.FilePath, project.Language, SymbolKey.Create(topLevelNamedType, compilation, cancellationToken)); } else { return new UniqueDocumentKey(topLevelNamedType.ContainingAssembly.Identity, project.Language, SymbolKey.Create(topLevelNamedType, compilation, cancellationToken)); } } private void InitializeWorkspace(Project project) { if (_workspace == null) { _workspace = new MetadataAsSourceWorkspace(this, project.Solution.Workspace.Services.HostServices); } } internal async Task<SymbolMappingResult> MapSymbolAsync(Document document, SymbolKey symbolId, CancellationToken cancellationToken) { MetadataAsSourceGeneratedFileInfo fileInfo; using (await _gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { if (!_openedDocumentIds.TryGetKey(document.Id, out fileInfo)) { return null; } } // WARANING: do not touch any state fields outside the lock. var solution = fileInfo.Workspace.CurrentSolution; var project = solution.GetProject(fileInfo.SourceProjectId); if (project == null) { return null; } var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var resolutionResult = symbolId.Resolve(compilation, ignoreAssemblyKey: true, cancellationToken: cancellationToken); if (resolutionResult.Symbol == null) { return null; } return new SymbolMappingResult(project, resolutionResult.Symbol); } public void CleanupGeneratedFiles() { using (_gate.DisposableWait()) { // Release our mutex to indicate we're no longer using our directory and reset state if (_mutex != null) { _mutex.Dispose(); _mutex = null; _rootTemporaryPathWithGuid = null; } // Clone the list so we don't break our own enumeration var generatedFileInfoList = _generatedFilenameToInformation.Values.ToList(); foreach (var generatedFileInfo in generatedFileInfoList) { if (_openedDocumentIds.ContainsKey(generatedFileInfo)) { RemoveDocumentFromWorkspace_NoLock(generatedFileInfo); } } _generatedFilenameToInformation.Clear(); _keyToInformation.Clear(); Contract.ThrowIfFalse(_openedDocumentIds.IsEmpty); try { if (Directory.Exists(_rootTemporaryPath)) { bool deletedEverything = true; // Let's look through directories to delete. foreach (var directoryInfo in new DirectoryInfo(_rootTemporaryPath).EnumerateDirectories()) { Mutex acquiredMutex; // Is there a mutex for this one? if (Mutex.TryOpenExisting(CreateMutexName(directoryInfo.Name), out acquiredMutex)) { acquiredMutex.Dispose(); deletedEverything = false; continue; } TryDeleteFolderWhichContainsReadOnlyFiles(directoryInfo.FullName); } if (deletedEverything) { Directory.Delete(_rootTemporaryPath); } } } catch (Exception) { } } } private static void TryDeleteFolderWhichContainsReadOnlyFiles(string directoryPath) { try { foreach (var fileInfo in new DirectoryInfo(directoryPath).EnumerateFiles("*", SearchOption.AllDirectories)) { fileInfo.IsReadOnly = false; } Directory.Delete(directoryPath, recursive: true); } catch (Exception) { } } public bool IsNavigableMetadataSymbol(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Event: case SymbolKind.Field: case SymbolKind.Method: case SymbolKind.NamedType: case SymbolKind.Property: case SymbolKind.Parameter: return true; } return false; } private class UniqueDocumentKey : IEquatable<UniqueDocumentKey> { private static readonly IEqualityComparer<SymbolKey> s_symbolIdComparer = SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true); /// <summary> /// The path to the assembly. Null in the case of in-memory assemblies, where we then use assembly identity. /// </summary> private readonly string _filePath; /// <summary> /// Assembly identity. Only non-null if filePath is null, where it's an in-memory assembly. /// </summary> private readonly AssemblyIdentity _assemblyIdentity; private readonly string _language; private readonly SymbolKey _symbolId; public UniqueDocumentKey(string filePath, string language, SymbolKey symbolId) { Contract.ThrowIfNull(filePath); _filePath = filePath; _language = language; _symbolId = symbolId; } public UniqueDocumentKey(AssemblyIdentity assemblyIdentity, string language, SymbolKey symbolId) { Contract.ThrowIfNull(assemblyIdentity); _assemblyIdentity = assemblyIdentity; _language = language; _symbolId = symbolId; } public bool Equals(UniqueDocumentKey other) { if (other == null) { return false; } return StringComparer.OrdinalIgnoreCase.Equals(_filePath, other._filePath) && object.Equals(_assemblyIdentity, other._assemblyIdentity) && _language == other._language && s_symbolIdComparer.Equals(_symbolId, other._symbolId); } public override bool Equals(object obj) { return Equals(obj as UniqueDocumentKey); } public override int GetHashCode() { return Hash.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(_filePath ?? string.Empty), Hash.Combine(_assemblyIdentity != null ? _assemblyIdentity.GetHashCode() : 0, Hash.Combine(_language.GetHashCode(), s_symbolIdComparer.GetHashCode(_symbolId)))); } } } }
/* FluorineFx open source library Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; using System.Collections; using System.Threading; #if !(NET_1_1) using System.Collections.Generic; #endif namespace FluorineFx.Collections.Generic { /// <summary> /// A thread-safe version of IDictionary in which all operations that change the dictionary are implemented by /// making a new copy of the underlying Hashtable. /// </summary> public class CopyOnWriteDictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection, IDictionary { Dictionary<TKey, TValue> _dictionary; /// <summary> /// Initializes a new instance of CopyOnWriteDictionary. /// </summary> public CopyOnWriteDictionary() { _dictionary = new Dictionary<TKey, TValue>(); } /// <summary> /// Initializes a new, empty instance of the CopyOnWriteDictionary class using the specified initial capacity. /// </summary> /// <param name="capacity">The approximate number of elements that the CopyOnWriteDictionary object can initially contain.</param> public CopyOnWriteDictionary(int capacity) { _dictionary = new Dictionary<TKey, TValue>(capacity); } /// <summary> /// Initializes a new instance of the CopyOnWriteDictionary class by copying the elements from the specified dictionary to the new CopyOnWriteDictionary object. The new CopyOnWriteDictionary object has an initial capacity equal to the number of elements copied. /// </summary> /// <param name="d">The IDictionary object to copy to a new CopyOnWriteDictionary object.</param> public CopyOnWriteDictionary(IDictionary<TKey, TValue> d) { _dictionary = new Dictionary<TKey, TValue>(d); } #if !(NET_1_1) /// <summary> /// Initializes a new, empty instance of the CopyOnWriteDictionary class using the default initial capacity and load factor, and the specified IEqualityComparer object. /// </summary> /// <param name="equalityComparer">The IEqualityComparer object that defines the hash code provider and the comparer to use with the CopyOnWriteDictionary object.</param> public CopyOnWriteDictionary(IEqualityComparer<TKey> equalityComparer) { _dictionary = new Dictionary<TKey, TValue>(equalityComparer); } #endif #region IDictionary<TKey,TValue> Members /// <summary> /// Adds an element with the specified key and value into the CopyOnWriteDictionary. /// </summary> /// <param name="key">The key of the element to add.</param> /// <param name="value">The value of the element to add. The value can be null reference (Nothing in Visual Basic).</param> public void Add(TKey key, TValue value) { lock (this.SyncRoot) { Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>(_dictionary); dictionary.Add(key, value); _dictionary = dictionary; } } /// <summary> /// Determines whether the CopyOnWriteDictionary contains a specific key. /// </summary> /// <param name="key">The key to locate in the CopyOnWriteDictionary.</param> /// <returns>true if the CopyOnWriteDictionary contains an element with the specified key; otherwise, false.</returns> public bool ContainsKey(TKey key) { return _dictionary.ContainsKey(key); } /// <summary> /// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the <see cref="T:CopyOnWriteDictionary"/>. /// </summary> /// <value></value> /// <returns> /// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the object that implements <see cref="T:CopyOnWriteDictionary"/>. /// </returns> public ICollection<TKey> Keys { get { return _dictionary.Keys; } } /// <summary> /// Removes the element with the specified key from the CopyOnWriteDictionary. /// </summary> /// <param name="key">The key of the element to remove.</param> /// <returns> /// true if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key"/> was not found in the original <see cref="T:CopyOnWriteDictionary"/>. /// </returns> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="key"/> is null. /// </exception> public bool Remove(TKey key) { lock (this.SyncRoot) { if (ContainsKey(key)) { Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>(_dictionary); dictionary.Remove(key); _dictionary = dictionary; return true; } } return false; } /// <summary> /// Gets the value associated with the specified key. /// </summary> /// <param name="key">The key whose value to get.</param> /// <param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the <paramref name="value"/> parameter. This parameter is passed uninitialized.</param> /// <returns> /// true if the CopyOnWriteDictionary contains an element with the specified key; otherwise, false. /// </returns> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="key"/> is null. /// </exception> public bool TryGetValue(TKey key, out TValue value) { return _dictionary.TryGetValue(key, out value); } /// <summary> /// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the <see cref="T:CopyOnWriteDictionary"/>. /// </summary> /// <value></value> /// <returns> /// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the object that implements <see cref="T:CopyOnWriteDictionary"/>. /// </returns> public ICollection<TValue> Values { get { return _dictionary.Values; } } /// <summary> /// Gets or sets the value with the specified key. /// </summary> /// <value>The value associated with the specified key.</value> public TValue this[TKey key] { get { return _dictionary[key]; } set { lock (this.SyncRoot) { Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>(_dictionary); dictionary[key] = value; _dictionary = dictionary; } } } #endregion #region ICollection<KeyValuePair<TKey,TValue>> Members /// <summary> /// Adds an item to the CopyOnWriteDictionary. /// </summary> /// <param name="item">The object to add to the CopyOnWriteDictionary.</param> public void Add(KeyValuePair<TKey, TValue> item) { Add(item.Key, item.Value); } /// <summary> /// Removes all elements from the CopyOnWriteDictionary. /// </summary> public void Clear() { lock (this.SyncRoot) { _dictionary = new Dictionary<TKey, TValue>(); } } /// <summary> /// Determines whether the CopyOnWriteDictionary contains a specific key. /// </summary> /// <param name="item"></param> /// <returns>true if the CopyOnWriteDictionary contains an element with the specified key; otherwise, false.</returns> public bool Contains(KeyValuePair<TKey, TValue> item) { return (_dictionary as ICollection<KeyValuePair<TKey, TValue>>).Contains(item); } /// <summary> /// Copies the elements of the <see cref="T:CopyOnWriteDictionary"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:CopyOnWriteDictionary"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="array"/> is null. /// </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="arrayIndex"/> is less than 0. /// </exception> /// <exception cref="T:System.ArgumentException"> /// <paramref name="array"/> is multidimensional. /// -or- /// <paramref name="arrayIndex"/> is equal to or greater than the length of <paramref name="array"/>. /// -or- /// The number of elements in the source <see cref="T:CopyOnWriteDictionary"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>. /// -or- /// Type <paramref name="T"/> cannot be cast automatically to the type of the destination <paramref name="array"/>. /// </exception> public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { (_dictionary as ICollection<KeyValuePair<TKey, TValue>>).CopyTo(array, arrayIndex); } /// <summary> /// Gets the number of elements contained in the <see cref="T:CopyOnWriteDictionary"/>. /// </summary> /// <value></value> /// <returns> /// The number of elements contained in the <see cref="T:CopyOnWriteDictionary"/>. /// </returns> public int Count { get { return _dictionary.Count; } } /// <summary> /// Gets a value indicating whether the <see cref="T:CopyOnWriteDictionary"/> is read-only. /// </summary> /// <value></value> /// <returns>true if the <see cref="T:CopyOnWriteDictionary"/> is read-only; otherwise, false. /// </returns> public bool IsReadOnly { get { return (_dictionary as ICollection<KeyValuePair<TKey, TValue>>).IsReadOnly; } } /// <summary> /// Removes the first occurrence of a specific object from the <see cref="T:CopyOnWriteDictionary"/>. /// </summary> /// <param name="item">The object to remove from the <see cref="T:CopyOnWriteDictionary"/>.</param> /// <returns> /// true if <paramref name="item"/> was successfully removed from the <see cref="T:CopyOnWriteDictionary"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:CopyOnWriteDictionary"/>. /// </returns> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:CopyOnWriteDictionary"/> is read-only. /// </exception> public bool Remove(KeyValuePair<TKey, TValue> item) { return Remove(item.Key); } #endregion #region IEnumerable<KeyValuePair<TKey,TValue>> Members /// <summary> /// Returns an enumerator that iterates through the CopyOnWriteDictionary. /// </summary> /// <returns>An enumerator for the CopyOnWriteDictionary.</returns> public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return _dictionary.GetEnumerator(); } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return _dictionary.GetEnumerator(); } #endregion #region ICollection Members /// <summary> /// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="array"/> is null. /// </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="index"/> is less than zero. /// </exception> /// <exception cref="T:System.ArgumentException"> /// <paramref name="array"/> is multidimensional. /// -or- /// <paramref name="index"/> is equal to or greater than the length of <paramref name="array"/>. /// -or- /// The number of elements in the source <see cref="T:System.Collections.ICollection"/> is greater than the available space from <paramref name="index"/> to the end of the destination <paramref name="array"/>. /// </exception> /// <exception cref="T:System.ArgumentException"> /// The type of the source <see cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the destination <paramref name="array"/>. /// </exception> public void CopyTo(Array array, int index) { (_dictionary as ICollection).CopyTo(array, index); } /// <summary> /// Gets a value indicating whether access to the <see cref="T:CopyOnWriteDictionary"/> is synchronized (thread safe). /// </summary> /// <value></value> /// <returns>true if access to the <see cref="T:CopyOnWriteDictionary"/> is synchronized (thread safe); otherwise, false. /// </returns> public bool IsSynchronized { get { return true; } } /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="T:CopyOnWriteDictionary"/>. /// </summary> /// <value></value> /// <returns> /// An object that can be used to synchronize access to the <see cref="T:CopyOnWriteDictionary"/>. /// </returns> public object SyncRoot { get { return (_dictionary as ICollection).SyncRoot; } } #endregion /// <summary> /// Adds an item to the dictionary if this CopyOnWriteDictionary does not yet contain this item. /// </summary> ///<param name="key">The <see cref="T:System.Object"></see> to use as the key of the element to add. </param> ///<param name="value">The <see cref="T:System.Object"></see> to use as the value of the element to add. </param> /// <returns>The value if added, otherwise the old value in the dictionary.</returns> public TValue AddIfAbsent(TKey key, TValue value) { lock (SyncRoot) { if (!_dictionary.ContainsKey(key)) { _dictionary.Add(key, value); return value; } else { return _dictionary[key]; } } } /// <summary> /// Removes and returns the item with the provided key. /// </summary> /// <param name="key">The key to locate.</param> /// <returns>The item if the <see cref="T:CopyOnWriteDictionary"></see> contains an element with the key; otherwise, null.</returns> public object RemoveAndGet(TKey key) { lock (this.SyncRoot) { if (ContainsKey(key)) { Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>(_dictionary); dictionary.Remove(key); object value = _dictionary[key]; _dictionary = dictionary; return value; } } return null; } #region IDictionary Members ///<summary> ///Adds an element with the provided key and value to the <see cref="T:CopyOnWriteDictionary"></see> object. ///</summary> ///<param name="value">The <see cref="T:System.Object"></see> to use as the value of the element to add. </param> ///<param name="key">The <see cref="T:System.Object"></see> to use as the key of the element to add. </param> ///<exception cref="T:System.ArgumentException">An element with the same key already exists in the <see cref="T:CopyOnWriteDictionary"></see> object. </exception> ///<exception cref="T:System.ArgumentNullException">key is null. </exception> ///<exception cref="T:System.NotSupportedException">The <see cref="T:CopyOnWriteDictionary"></see> is read-only.-or- The <see cref="T:CopyOnWriteDictionary"></see> has a fixed size. </exception><filterpriority>2</filterpriority> public void Add(object key, object value) { Add((TKey)key, (TValue)value); } ///<summary> ///Determines whether the <see cref="T:CopyOnWriteDictionary"></see> object contains an element with the specified key. ///</summary> ///<returns> ///true if the <see cref="T:CopyOnWriteDictionary"></see> contains an element with the key; otherwise, false. ///</returns> ///<param name="key">The key to locate in the <see cref="T:CopyOnWriteDictionary"></see> object.</param> ///<exception cref="T:System.ArgumentNullException">key is null. </exception><filterpriority>2</filterpriority> public bool Contains(object key) { return ContainsKey((TKey)key); } ///<summary> ///Returns an <see cref="T:CopyOnWriteDictionaryEnumerator"></see> object for the <see cref="T:CopyOnWriteDictionary"></see> object. ///</summary> ///<returns> ///An <see cref="T:CopyOnWriteDictionaryEnumerator"></see> object for the <see cref="T:CopyOnWriteDictionary"></see> object. ///</returns> IDictionaryEnumerator IDictionary.GetEnumerator() { return (_dictionary as IDictionary).GetEnumerator(); } ///<summary> ///Gets a value indicating whether the <see cref="T:CopyOnWriteDictionary"></see> object has a fixed size. ///</summary> ///<returns> ///true if the <see cref="T:CopyOnWriteDictionary"></see> object has a fixed size; otherwise, false. ///</returns> public bool IsFixedSize { get { return false; } } ///<summary> ///Gets an <see cref="T:System.Collections.ICollection"></see> object containing the keys of the <see cref="T:CopyOnWriteDictionary"></see> object. ///</summary> ///<returns> ///An <see cref="T:System.Collections.ICollection"></see> object containing the keys of the <see cref="T:CopyOnWriteDictionary"></see> object. ///</returns> ICollection IDictionary.Keys { get { return (_dictionary as IDictionary).Keys; } } ///<summary> ///Removes the element with the specified key from the <see cref="T:CopyOnWriteDictionary"></see> object. ///</summary> ///<param name="key">The key of the element to remove. </param> ///<exception cref="T:System.NotSupportedException">The <see cref="T:CopyOnWriteDictionary"></see> object is read-only.-or- The <see cref="T:CopyOnWriteDictionary"></see> has a fixed size. </exception> ///<exception cref="T:System.ArgumentNullException">key is null. </exception><filterpriority>2</filterpriority> public void Remove(object key) { Remove((TKey)key); } ///<summary> ///Gets an <see cref="T:System.Collections.ICollection"></see> object containing the values in the <see cref="T:CopyOnWriteDictionary"></see> object. ///</summary> ///<returns> ///An <see cref="T:System.Collections.ICollection"></see> object containing the values in the <see cref="T:CopyOnWriteDictionary"></see> object. ///</returns> ICollection IDictionary.Values { get { return (_dictionary as IDictionary).Values; } } ///<summary> ///Gets or sets the element with the specified key. ///</summary> ///<returns> ///The element with the specified key. ///</returns> ///<param name="key">The key of the element to get or set. </param> ///<exception cref="T:System.NotSupportedException">The property is set and the <see cref="T:CopyOnWriteDictionary"></see> object is read-only.-or- The property is set, key does not exist in the collection, and the <see cref="T:CopyOnWriteDictionary"></see> has a fixed size. </exception> ///<exception cref="T:System.ArgumentNullException">key is null. </exception><filterpriority>2</filterpriority> public object this[object key] { get { return this[(TKey)key]; } set { this[(TKey)key] = (TValue)value; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // using System; using System.Runtime.InteropServices; using System.Threading.Tasks; using System.Collections.Generic; using System.Runtime.CompilerServices; public static class Assert { public static bool HasAssertFired; public static void AreEqual(Object actual, Object expected) { if (!(actual == null && expected == null) && !actual.Equals(expected)) { Console.WriteLine("Not equal!"); Console.WriteLine("actual = " + actual.ToString()); Console.WriteLine("expected = " + expected.ToString()); HasAssertFired = true; } } } public interface IMyInterface { #if V2 // Adding new methods to interfaces is incompatible change, but we will make sure that it works anyway void NewInterfaceMethod(); #endif string InterfaceMethod(string s); } public class MyClass : IMyInterface { #if V2 public int _field1; public int _field2; public int _field3; #endif public int InstanceField; #if V2 public static Object StaticObjectField2; [ThreadStatic] public static String ThreadStaticStringField2; [ThreadStatic] public static int ThreadStaticIntField; public static Nullable<Guid> StaticNullableGuidField; public static Object StaticObjectField; [ThreadStatic] public static int ThreadStaticIntField2; public static long StaticLongField; [ThreadStatic] public static DateTime ThreadStaticDateTimeField2; public static long StaticLongField2; [ThreadStatic] public static DateTime ThreadStaticDateTimeField; public static Nullable<Guid> StaticNullableGuidField2; [ThreadStatic] public static String ThreadStaticStringField; #else public static Object StaticObjectField; public static long StaticLongField; public static Nullable<Guid> StaticNullableGuidField; [ThreadStatic] public static String ThreadStaticStringField; [ThreadStatic] public static int ThreadStaticIntField; [ThreadStatic] public static DateTime ThreadStaticDateTimeField; #endif public MyClass() { } #if V2 public virtual void NewVirtualMethod() { } public virtual void NewInterfaceMethod() { throw new Exception(); } #endif public virtual string VirtualMethod() { return "Virtual method result"; } public virtual string InterfaceMethod(string s) { return "Interface" + s + "result"; } public static string TestInterfaceMethod(IMyInterface i, string s) { return i.InterfaceMethod(s); } public static void TestStaticFields() { StaticObjectField = (int)StaticObjectField + 12345678; StaticLongField *= 456; Assert.AreEqual(StaticNullableGuidField, new Guid("0D7E505F-E767-4FEF-AEEC-3243A3005673")); StaticNullableGuidField = null; ThreadStaticStringField += "World"; ThreadStaticIntField /= 78; ThreadStaticDateTimeField = ThreadStaticDateTimeField + new TimeSpan(123); MyGeneric<int,int>.ThreadStatic = new Object(); #if false // TODO: Enable once LDFTN is supported // Do some operations on static fields on a different thread to verify that we are not mixing thread-static and non-static Task.Run(() => { StaticObjectField = (int)StaticObjectField + 1234; StaticLongField *= 45; ThreadStaticStringField = "Garbage"; ThreadStaticIntField = 0xBAAD; ThreadStaticDateTimeField = DateTime.Now; }).Wait(); #endif } [DllImport("api-ms-win-core-sysinfo-l1-1-0.dll")] public extern static int GetTickCount(); [DllImport("libcoreclr")] public extern static int GetCurrentThreadId(); static public void TestInterop() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { GetTickCount(); } else { GetCurrentThreadId(); } } #if V2 public string MovedToBaseClass() { return "MovedToBaseClass"; } #endif #if V2 public virtual string ChangedToVirtual() { return null; } #else public string ChangedToVirtual() { return "ChangedToVirtual"; } #endif } public class MyChildClass : MyClass { public MyChildClass() { } #if !V2 public string MovedToBaseClass() { return "MovedToBaseClass"; } #endif #if V2 public override string ChangedToVirtual() { return "ChangedToVirtual"; } #endif } public struct MyStruct : IDisposable { int x; #if V2 void IDisposable.Dispose() { } #else public void Dispose() { } #endif } public class MyGeneric<T,U> { [ThreadStatic] public static Object ThreadStatic; public MyGeneric() { } public virtual string GenericVirtualMethod<V,W>() { return typeof(T).ToString() + typeof(U).ToString() + typeof(V).ToString() + typeof(W).ToString(); } #if V2 public string MovedToBaseClass<W>() { typeof(Dictionary<W,W>).ToString(); return typeof(List<W>).ToString(); } #endif #if V2 public virtual string ChangedToVirtual<W>() { return null; } #else public string ChangedToVirtual<W>() { return typeof(List<W>).ToString(); } #endif public string NonVirtualMethod() { return "MyGeneric.NonVirtualMethod"; } } public class MyChildGeneric<T> : MyGeneric<T,T> { public MyChildGeneric() { } #if !V2 public string MovedToBaseClass<W>() { return typeof(List<W>).ToString(); } #endif #if V2 public override string ChangedToVirtual<W>() { typeof(Dictionary<Int32, W>).ToString(); return typeof(List<W>).ToString(); } #endif } [StructLayout(LayoutKind.Sequential)] public class MyClassWithLayout { #if V2 public int _field1; public int _field2; public int _field3; #endif } public struct MyGrowingStruct { int x; int y; #if V2 Object o1; Object o2; #endif static public MyGrowingStruct Construct() { return new MyGrowingStruct() { x = 111, y = 222 }; } public static void Check(ref MyGrowingStruct s) { Assert.AreEqual(s.x, 111); Assert.AreEqual(s.y, 222); } } public struct MyChangingStruct { #if V2 public int y; public int x; #else public int x; public int y; #endif static public MyChangingStruct Construct() { return new MyChangingStruct() { x = 111, y = 222 }; } public static void Check(ref MyChangingStruct s) { Assert.AreEqual(s.x, 112); Assert.AreEqual(s.y, 222); } } public struct MyChangingHFAStruct { #if V2 float x; float y; #else int x; int y; #endif static public MyChangingHFAStruct Construct() { return new MyChangingHFAStruct() { x = 12, y = 23 }; } public static void Check(MyChangingHFAStruct s) { #if V2 Assert.AreEqual(s.x, 12.0f); Assert.AreEqual(s.y, 23.0f); #else Assert.AreEqual(s.x, 12); Assert.AreEqual(s.y, 23); #endif } } public class ByteBaseClass : List<byte> { public byte BaseByte; } public class ByteChildClass : ByteBaseClass { public byte ChildByte; [MethodImplAttribute(MethodImplOptions.NoInlining)] public ByteChildClass(byte value) { ChildByte = 67; } }
using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; namespace Org.OpenAPITools.Model { /// <summary> /// /// </summary> [DataContract] public class FreeStyleProject { /// <summary> /// Gets or Sets Class /// </summary> [DataMember(Name="_class", EmitDefaultValue=false)] [JsonProperty(PropertyName = "_class")] public string Class { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name="name", EmitDefaultValue=false)] [JsonProperty(PropertyName = "name")] public string Name { get; set; } /// <summary> /// Gets or Sets Url /// </summary> [DataMember(Name="url", EmitDefaultValue=false)] [JsonProperty(PropertyName = "url")] public string Url { get; set; } /// <summary> /// Gets or Sets Color /// </summary> [DataMember(Name="color", EmitDefaultValue=false)] [JsonProperty(PropertyName = "color")] public string Color { get; set; } /// <summary> /// Gets or Sets Actions /// </summary> [DataMember(Name="actions", EmitDefaultValue=false)] [JsonProperty(PropertyName = "actions")] public List<FreeStyleProjectactions> Actions { get; set; } /// <summary> /// Gets or Sets Description /// </summary> [DataMember(Name="description", EmitDefaultValue=false)] [JsonProperty(PropertyName = "description")] public string Description { get; set; } /// <summary> /// Gets or Sets DisplayName /// </summary> [DataMember(Name="displayName", EmitDefaultValue=false)] [JsonProperty(PropertyName = "displayName")] public string DisplayName { get; set; } /// <summary> /// Gets or Sets DisplayNameOrNull /// </summary> [DataMember(Name="displayNameOrNull", EmitDefaultValue=false)] [JsonProperty(PropertyName = "displayNameOrNull")] public string DisplayNameOrNull { get; set; } /// <summary> /// Gets or Sets FullDisplayName /// </summary> [DataMember(Name="fullDisplayName", EmitDefaultValue=false)] [JsonProperty(PropertyName = "fullDisplayName")] public string FullDisplayName { get; set; } /// <summary> /// Gets or Sets FullName /// </summary> [DataMember(Name="fullName", EmitDefaultValue=false)] [JsonProperty(PropertyName = "fullName")] public string FullName { get; set; } /// <summary> /// Gets or Sets Buildable /// </summary> [DataMember(Name="buildable", EmitDefaultValue=false)] [JsonProperty(PropertyName = "buildable")] public bool? Buildable { get; set; } /// <summary> /// Gets or Sets Builds /// </summary> [DataMember(Name="builds", EmitDefaultValue=false)] [JsonProperty(PropertyName = "builds")] public List<FreeStyleBuild> Builds { get; set; } /// <summary> /// Gets or Sets FirstBuild /// </summary> [DataMember(Name="firstBuild", EmitDefaultValue=false)] [JsonProperty(PropertyName = "firstBuild")] public FreeStyleBuild FirstBuild { get; set; } /// <summary> /// Gets or Sets HealthReport /// </summary> [DataMember(Name="healthReport", EmitDefaultValue=false)] [JsonProperty(PropertyName = "healthReport")] public List<FreeStyleProjecthealthReport> HealthReport { get; set; } /// <summary> /// Gets or Sets InQueue /// </summary> [DataMember(Name="inQueue", EmitDefaultValue=false)] [JsonProperty(PropertyName = "inQueue")] public bool? InQueue { get; set; } /// <summary> /// Gets or Sets KeepDependencies /// </summary> [DataMember(Name="keepDependencies", EmitDefaultValue=false)] [JsonProperty(PropertyName = "keepDependencies")] public bool? KeepDependencies { get; set; } /// <summary> /// Gets or Sets LastBuild /// </summary> [DataMember(Name="lastBuild", EmitDefaultValue=false)] [JsonProperty(PropertyName = "lastBuild")] public FreeStyleBuild LastBuild { get; set; } /// <summary> /// Gets or Sets LastCompletedBuild /// </summary> [DataMember(Name="lastCompletedBuild", EmitDefaultValue=false)] [JsonProperty(PropertyName = "lastCompletedBuild")] public FreeStyleBuild LastCompletedBuild { get; set; } /// <summary> /// Gets or Sets LastFailedBuild /// </summary> [DataMember(Name="lastFailedBuild", EmitDefaultValue=false)] [JsonProperty(PropertyName = "lastFailedBuild")] public string LastFailedBuild { get; set; } /// <summary> /// Gets or Sets LastStableBuild /// </summary> [DataMember(Name="lastStableBuild", EmitDefaultValue=false)] [JsonProperty(PropertyName = "lastStableBuild")] public FreeStyleBuild LastStableBuild { get; set; } /// <summary> /// Gets or Sets LastSuccessfulBuild /// </summary> [DataMember(Name="lastSuccessfulBuild", EmitDefaultValue=false)] [JsonProperty(PropertyName = "lastSuccessfulBuild")] public FreeStyleBuild LastSuccessfulBuild { get; set; } /// <summary> /// Gets or Sets LastUnstableBuild /// </summary> [DataMember(Name="lastUnstableBuild", EmitDefaultValue=false)] [JsonProperty(PropertyName = "lastUnstableBuild")] public string LastUnstableBuild { get; set; } /// <summary> /// Gets or Sets LastUnsuccessfulBuild /// </summary> [DataMember(Name="lastUnsuccessfulBuild", EmitDefaultValue=false)] [JsonProperty(PropertyName = "lastUnsuccessfulBuild")] public string LastUnsuccessfulBuild { get; set; } /// <summary> /// Gets or Sets NextBuildNumber /// </summary> [DataMember(Name="nextBuildNumber", EmitDefaultValue=false)] [JsonProperty(PropertyName = "nextBuildNumber")] public int? NextBuildNumber { get; set; } /// <summary> /// Gets or Sets QueueItem /// </summary> [DataMember(Name="queueItem", EmitDefaultValue=false)] [JsonProperty(PropertyName = "queueItem")] public string QueueItem { get; set; } /// <summary> /// Gets or Sets ConcurrentBuild /// </summary> [DataMember(Name="concurrentBuild", EmitDefaultValue=false)] [JsonProperty(PropertyName = "concurrentBuild")] public bool? ConcurrentBuild { get; set; } /// <summary> /// Gets or Sets Scm /// </summary> [DataMember(Name="scm", EmitDefaultValue=false)] [JsonProperty(PropertyName = "scm")] public NullSCM Scm { get; set; } /// <summary> /// Get 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 FreeStyleProject {\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Url: ").Append(Url).Append("\n"); sb.Append(" Color: ").Append(Color).Append("\n"); sb.Append(" Actions: ").Append(Actions).Append("\n"); sb.Append(" Description: ").Append(Description).Append("\n"); sb.Append(" DisplayName: ").Append(DisplayName).Append("\n"); sb.Append(" DisplayNameOrNull: ").Append(DisplayNameOrNull).Append("\n"); sb.Append(" FullDisplayName: ").Append(FullDisplayName).Append("\n"); sb.Append(" FullName: ").Append(FullName).Append("\n"); sb.Append(" Buildable: ").Append(Buildable).Append("\n"); sb.Append(" Builds: ").Append(Builds).Append("\n"); sb.Append(" FirstBuild: ").Append(FirstBuild).Append("\n"); sb.Append(" HealthReport: ").Append(HealthReport).Append("\n"); sb.Append(" InQueue: ").Append(InQueue).Append("\n"); sb.Append(" KeepDependencies: ").Append(KeepDependencies).Append("\n"); sb.Append(" LastBuild: ").Append(LastBuild).Append("\n"); sb.Append(" LastCompletedBuild: ").Append(LastCompletedBuild).Append("\n"); sb.Append(" LastFailedBuild: ").Append(LastFailedBuild).Append("\n"); sb.Append(" LastStableBuild: ").Append(LastStableBuild).Append("\n"); sb.Append(" LastSuccessfulBuild: ").Append(LastSuccessfulBuild).Append("\n"); sb.Append(" LastUnstableBuild: ").Append(LastUnstableBuild).Append("\n"); sb.Append(" LastUnsuccessfulBuild: ").Append(LastUnsuccessfulBuild).Append("\n"); sb.Append(" NextBuildNumber: ").Append(NextBuildNumber).Append("\n"); sb.Append(" QueueItem: ").Append(QueueItem).Append("\n"); sb.Append(" ConcurrentBuild: ").Append(ConcurrentBuild).Append("\n"); sb.Append(" Scm: ").Append(Scm).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Get the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading; using PWLib.FileSyncLib; namespace AutoUSBBackup.GUI { public partial class MainForm : Form { static MainForm sInstance = null; public static MainForm Instance { get { return sInstance; } } SpineThread mSpineThread = null; Thread mShutdownThread; MainFormEventController mEventController; bool mClosing = false; bool mSystemShutdown = false; bool mHideOnLoad = true; public Spine Spine { get { return mSpineThread != null ? mSpineThread.Spine : null; } } public MainFormEventController EventController { get { return mEventController; } } public UserControlSwitcher ControlSwitcher { get { return mUserControlSwitcher; } } public Shared.LogTextBox LogBox { get { return ( ( WelcomeControl )mUserControlSwitcher.GetUserControl( FormControlType.Welcome ) ).LogBox; } } public static void StartApp( bool block, string[] args ) { try { bool hideOnLoad = false; bool verboseLogging = false; foreach ( string arg in args ) { string lowerArg = arg.ToLower(); if ( lowerArg == "/hide" ) hideOnLoad = true; else if ( lowerArg == "/verbose" ) verboseLogging = true; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault( false ); GUI.MainForm m = new GUI.MainForm( hideOnLoad ); Config.CreateInstance(); PWLib.UsbDrive.UsbDriveList.CreateInstance( m ); m.ControlSwitcher.SwitchUserControl( FormControlType.Welcome, FormControlSwitchType.Start ); Log.Init( verboseLogging ); Log.WriteLine( LogType.TextLog, "******************* Starting application *******************" ); m.StartSpineThread(); if ( block ) Application.Run( m ); else m.Show(); } catch ( System.Exception ex ) { Log.WriteException( "Fatal exception caught", ex ); } } public static void StopApp() { try { PWLib.UsbDrive.UsbDriveList.Instance.Dispose(); Log.WriteLine( LogType.TextLog, "******************* Exiting application *******************" ); Log.Close(); } catch ( System.Exception ) { } } public new void Dispose() { CloseApplication(); base.Dispose(); } public MainForm( bool hideOnLoad ) { System.Diagnostics.Debug.Assert( sInstance == null ); sInstance = this; mShutdownThread = new Thread( new ThreadStart( ShutdownThread ) ); mHideOnLoad = hideOnLoad; InitializeComponent(); CreateControl(); Shown += new EventHandler( MainForm_Shown ); mSpineThread = new SpineThread(); VolumeDescriptorList.CreateInstance( mSpineThread.EventController ); mEventController = new MainFormEventController( this, mProgressBar, mTrayIcon ); mUserControlSwitcher.BuildUserControlList(); } public void StartSpineThread() { mEventController.HookSpineEvents( mSpineThread.EventController ); mSpineThread.Start(); } protected override void WndProc( ref Message m ) { bool callBaseWndProc = true; // const int WM_ENDSESSION = 0x16; const int WM_QUERYENDSESSION = 0x11; if ( m.Msg.Equals( WM_QUERYENDSESSION ) ) mSystemShutdown = true; if ( mSpineThread != null ) callBaseWndProc = mSpineThread.WndProc( ref m ); if ( callBaseWndProc ) base.WndProc( ref m ); } #region Closing / showing / hiding form methods void ShutdownThread() { while ( mSpineThread != null && !mSpineThread.Disposed ) { Thread.Sleep( 100 ); } if ( this.Created ) this.Invoke( new ThreadStart( delegate() { Close(); } ) ); } public void CloseApplication() { if ( !mClosing ) { Config.Active.Save(); if ( mSpineThread != null ) mSpineThread.CancelOperation(); ShowForm( false ); mClosing = true; if ( mSpineThread != null ) mSpineThread.Dispose(); mTrayIcon.Dispose(); mShutdownThread.Start(); } } public void ShowForm( bool show ) { if ( show ) { Show(); Activate(); BringToFront(); WindowState = FormWindowState.Normal; } else { Hide(); WindowState = FormWindowState.Minimized; } } private void MainForm_FormClosing( object sender, FormClosingEventArgs e ) { if ( mSystemShutdown ) { CloseApplication(); e.Cancel = false; ShowForm( false ); } else if ( !mClosing ) { e.Cancel = true; ShowForm( false ); } } #endregion #region Methods called by inside the GUI (mainly from the UserControls describing the GUI) public void RemoveVolume( VolumeDescriptor desc, bool removeAllData ) { mSpineThread.RemoveVolume( desc, removeAllData ); } public bool VolumeNameExists( string name ) { return VolumeDescriptorList.Instance.VolumeNameExists( name ); } public string TakeNameAndMakeItUnique( string defaultName ) { string name = defaultName; for ( int attempts = 1; true; ++attempts ) { if ( VolumeNameExists( name ) ) { name = defaultName + " (" + attempts + ")"; } else if ( attempts >= 1000 ) { name = ""; } else break; } return name; } public void RestoreVolume( VolumeDescriptor vid, VolumeSnapshotRevision revision, string onDiskPath ) { mSpineThread.RestoreVolume( vid, revision, onDiskPath ); } public void TransferVolume( VolumeDescriptor vid, PWLib.UsbDrive.UsbDriveInfo newDrive ) { mSpineThread.TransferVolume( vid, newDrive ); } public void SetDefaultStatusText() { SetStatusText("Ready"); } public void SetTitleText( string text, int percentComplete ) { if ( text.Length > 0 && percentComplete >= 0 ) this.Text = text + "... [" + percentComplete.ToString() + "%]"; else this.Text = "AutoUSBBackup"; } public void SetStatusText(string text) { mStatusLabel.Text = text; } public void CancelOperation() { mSpineThread.CancelOperation(); } public void FormatUsbDrive( PWLib.UsbDrive.UsbDriveInfo drive ) { mSpineThread.FormatUsbDrive( drive ); } public void ForceFullBackup() { mSpineThread.ForceFullBackup(); } public void BackupVolume( VolumeDescriptor vdesc ) { if ( vdesc.Volume != null ) mSpineThread.ForceBackup( vdesc.Volume ); } #endregion #region Tray icon events private void mTrayIcon_DoubleClick( object sender, EventArgs e ) { ShowForm( true ); } private void showToolStripMenuItem_Click( object sender, EventArgs e ) { mTrayIcon_DoubleClick( sender, e ); } private void exitToolStripMenuItem_Click( object sender, EventArgs e ) { CloseApplication(); } #endregion void MainForm_Shown( object sender, EventArgs e ) { if ( mHideOnLoad ) { ShowForm( false ); } RecalculateProgressBarSize(); } private void MainForm_Resize(object sender, EventArgs e) { if ( FormWindowState.Minimized == WindowState ) { Hide(); // leave only the sys tray icon } RecalculateProgressBarSize(); } private void mStatusLabel_TextChanged(object sender, EventArgs e) { RecalculateProgressBarSize(); } void RecalculateProgressBarSize() { mProgressBar.Width = this.Size.Width - this.mStatusLabel.Width - 50; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using ServiceStack.Common.Support; using ServiceStack.Logging; namespace ServiceStack.Common.Utils { public class ReflectionUtils { public static readonly ILog Log = LogManager.GetLogger(typeof(ReflectionUtils)); /// <summary> /// Populate an object with Example data. /// </summary> /// <param name="obj"></param> /// <returns></returns> public static object PopulateObject(object obj) { if (obj == null) return null; var members = obj.GetType().GetMembers(BindingFlags.Public | BindingFlags.Instance); foreach (var info in members) { var fieldInfo = info as FieldInfo; var propertyInfo = info as PropertyInfo; if (fieldInfo != null || propertyInfo != null) { var memberType = fieldInfo != null ? fieldInfo.FieldType : propertyInfo.PropertyType; var value = CreateDefaultValue(memberType); SetValue(fieldInfo, propertyInfo, obj, value); } } return obj; } private static readonly Dictionary<Type, object> DefaultValueTypes = new Dictionary<Type, object>(); public static object GetDefaultValue(Type type) { if (!type.IsValueType) return null; object defaultValue; lock (DefaultValueTypes) { if (!DefaultValueTypes.TryGetValue(type, out defaultValue)) { defaultValue = Activator.CreateInstance(type); DefaultValueTypes[type] = defaultValue; } } return defaultValue; } private static readonly Dictionary<string, AssignmentDefinition> AssignmentDefinitionCache = new Dictionary<string, AssignmentDefinition>(); public static AssignmentDefinition GetAssignmentDefinition(Type toType, Type fromType) { var cacheKey = toType.FullName + "<" + fromType.FullName; lock (AssignmentDefinitionCache) { AssignmentDefinition definition; if (AssignmentDefinitionCache.TryGetValue(cacheKey, out definition)) { return definition; } definition = new AssignmentDefinition { ToType = toType, FromType = fromType, }; var members = fromType.GetMembers(BindingFlags.Public | BindingFlags.Instance); foreach (var info in members) { var fromPropertyInfo = info as PropertyInfo; if (fromPropertyInfo != null) { var toPropertyInfo = GetPropertyInfo(toType, fromPropertyInfo.Name); if (toPropertyInfo == null) continue; if (!fromPropertyInfo.CanRead) continue; if (!toPropertyInfo.CanWrite) continue; definition.AddMatch(fromPropertyInfo, toPropertyInfo); } var fromFieldInfo = info as FieldInfo; if (fromFieldInfo != null) { var toFieldInfo = GetFieldInfo(toType, fromFieldInfo.Name); if (toFieldInfo == null) continue; definition.AddMatch(fromFieldInfo, toFieldInfo); } } AssignmentDefinitionCache[cacheKey] = definition; return definition; } } public static To PopulateObject<To, From>(To to, From from) { if (Equals(to, default(To)) || Equals(from, default(From))) return default(To); var assignmentDefinition = GetAssignmentDefinition(to.GetType(), from.GetType()); assignmentDefinition.Populate(to, from); return to; } public static To PopulateWithNonDefaultValues<To, From>(To to, From from) { if (Equals(to, default(To)) || Equals(from, default(From))) return default(To); var assignmentDefinition = GetAssignmentDefinition(to.GetType(), from.GetType()); assignmentDefinition.PopulateWithNonDefaultValues(to, from); return to; } public static To PopulateFromPropertiesWithAttribute<To, From>(To to, From from, Type attributeType) { if (Equals(to, default(To)) || Equals(from, default(From))) return default(To); var assignmentDefinition = GetAssignmentDefinition(to.GetType(), from.GetType()); assignmentDefinition.PopulateFromPropertiesWithAttribute(to, from, attributeType); return to; } /// <summary> /// Populate an instance of the type with Example data. /// </summary> /// <param name="type"></param> /// <returns></returns> public static object PopulateType(Type type) { var obj = Activator.CreateInstance(type); return PopulateObject(obj); } public static void SetProperty(object obj, PropertyInfo propertyInfo, object value) { if (!propertyInfo.CanWrite) { Log.WarnFormat("Attempted to set read only property '{0}'", propertyInfo.Name); return; } var propertySetMetodInfo = propertyInfo.GetSetMethod(); if (propertySetMetodInfo != null) { propertySetMetodInfo.Invoke(obj, new[] { value }); } } public static void SetValue(FieldInfo fieldInfo, PropertyInfo propertyInfo, object obj, object value) { try { if (IsUnsettableValue(fieldInfo, propertyInfo)) return; if (fieldInfo != null && !fieldInfo.IsLiteral) { fieldInfo.SetValue(obj, value); } else { SetProperty(obj, propertyInfo, value); } PopulateObject(value); } catch (Exception ex) { var name = (fieldInfo != null) ? fieldInfo.Name : propertyInfo.Name; Log.DebugFormat("Could not set member: {0}. Error: {1}", name, ex.Message); } } public static bool IsUnsettableValue(FieldInfo fieldInfo, PropertyInfo propertyInfo) { if (propertyInfo != null && propertyInfo.ReflectedType != null) { // Properties on non-user defined classes should not be set // Currently we define those properties as properties declared on // types defined in mscorlib if (propertyInfo.DeclaringType.Assembly == typeof(object).Assembly) { return true; } } return false; } public static object[] CreateDefaultValues(IEnumerable<Type> types) { var values = new List<object>(); foreach (var type in types) { values.Add(CreateDefaultValue(type)); } return values.ToArray(); } public static object CreateDefaultValue(Type type) { if (type == typeof(string)) { return type.Name; } if (type.IsValueType) { return Activator.CreateInstance(type); } if (type.IsArray) { return PopulateArray(type); } var constructorInfo = type.GetConstructor(Type.EmptyTypes); var hasEmptyConstructor = constructorInfo != null; if (hasEmptyConstructor) { var value = constructorInfo.Invoke(new object[0]); Type[] interfaces = type.FindInterfaces((t, critera) => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(ICollection<>) , null); bool isGenericCollection = interfaces.Length > 0; if (isGenericCollection) { SetGenericCollection(interfaces[0], type, value); } return value; } return null; } public static void SetGenericCollection(Type realisedListType, Type type, object genericObj) { var args = realisedListType.GetGenericArguments(); if (args.Length != 1) { Log.ErrorFormat("Found a generic list that does not take one generic argument: {0}", realisedListType); return; } var methodInfo = type.GetMethod("Add"); if (methodInfo != null) { var argValues = CreateDefaultValues(args); methodInfo.Invoke(genericObj, argValues); Log.DebugFormat("Added value '{0}' to type '{1}", argValues, genericObj.GetType()); } } public static Array PopulateArray(Type type) { var objArray = Array.CreateInstance(type, 1); var elementType = objArray.GetType().GetElementType(); var objElementType = PopulateType(elementType); objArray.SetValue(objElementType, 0); PopulateObject(objElementType); return objArray; } //TODO: replace with InAssignableFrom public static bool CanCast(Type toType, Type fromType) { if (toType.IsInterface) { var interfaceList = fromType.GetInterfaces().ToList(); if (interfaceList.Contains(toType)) return true; } else { Type baseType = fromType; bool areSameTypes; do { areSameTypes = baseType == toType; } while (!areSameTypes && (baseType = fromType.BaseType) != null); if (areSameTypes) return true; } return false; } public static MemberInfo GetMemberInfo(Type fromType, string memberName) { var baseType = fromType; do { var members = baseType.GetMembers(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); foreach (var memberInfo in members) { if (memberInfo.Name == memberName) return memberInfo; } } while ((baseType = baseType.BaseType) != null); return null; } public static FieldInfo GetFieldInfo(Type fromType, string fieldName) { var baseType = fromType; do { var fieldInfos = baseType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); foreach (var fieldInfo in fieldInfos) { if (fieldInfo.Name == fieldName) return fieldInfo; } } while ((baseType = baseType.BaseType) != null); return null; } public static PropertyInfo GetPropertyInfo(Type fromType, string propertyName) { var baseType = fromType; do { var propertyInfos = baseType.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); foreach (var propertyInfo in propertyInfos) { if (propertyInfo.Name == propertyName) return propertyInfo; } } while ((baseType = baseType.BaseType) != null); return null; } public static IEnumerable<KeyValuePair<PropertyInfo, T>> GetPropertyAttributes<T>(Type fromType) where T : Attribute { var attributeType = typeof(T); var baseType = fromType; do { var propertyInfos = baseType.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); foreach (var propertyInfo in propertyInfos) { var attributes = propertyInfo.GetCustomAttributes(attributeType, true); foreach (T attribute in attributes) { yield return new KeyValuePair<PropertyInfo, T>(propertyInfo, attribute); } } } while ((baseType = baseType.BaseType) != null); } public delegate object CtorDelegate(); static readonly Dictionary<Type, Func<object>> ConstructorMethods = new Dictionary<Type, Func<object>>(); public static Func<object> GetConstructorMethod(Type type) { lock (ConstructorMethods) { Func<object> ctorFn; if (!ConstructorMethods.TryGetValue(type, out ctorFn)) { ctorFn = GetConstructorMethodToCache(type); ConstructorMethods[type] = ctorFn; } return ctorFn; } } public static Func<object> GetConstructorMethodToCache(Type type) { var emptyCtor = type.GetConstructor(Type.EmptyTypes); if (emptyCtor == null) throw new ArgumentException(type.FullName + " does not have an empty constructor"); var dm = new DynamicMethod("MyCtor", type, Type.EmptyTypes, typeof(ReflectionUtils).Module, true); var ilgen = dm.GetILGenerator(); ilgen.Emit(OpCodes.Nop); ilgen.Emit(OpCodes.Newobj, emptyCtor); ilgen.Emit(OpCodes.Ret); Func<object> ctorFn = ((CtorDelegate) dm.CreateDelegate(typeof (CtorDelegate))).Invoke; return ctorFn; } public static object CreateInstance(Type type) { #if NO_EMIT return Activator.CreateInstance(type); #else var ctorFn = GetConstructorMethod(type); return ctorFn(); #endif } } }
#region Copyright notice and license // Copyright 2015, Google 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. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Grpc.Core; using Grpc.Core.Internal; using Grpc.Core.Utils; using NUnit.Framework; namespace Grpc.Core.Tests { public class ClientServerTest { const string Host = "localhost"; const string ServiceName = "/tests.Test"; static readonly Method<string, string> EchoMethod = new Method<string, string>( MethodType.Unary, "/tests.Test/Echo", Marshallers.StringMarshaller, Marshallers.StringMarshaller); static readonly Method<string, string> ConcatAndEchoMethod = new Method<string, string>( MethodType.ClientStreaming, "/tests.Test/ConcatAndEcho", Marshallers.StringMarshaller, Marshallers.StringMarshaller); static readonly Method<string, string> NonexistentMethod = new Method<string, string>( MethodType.Unary, "/tests.Test/NonexistentMethod", Marshallers.StringMarshaller, Marshallers.StringMarshaller); static readonly ServerServiceDefinition ServiceDefinition = ServerServiceDefinition.CreateBuilder(ServiceName) .AddMethod(EchoMethod, EchoHandler) .AddMethod(ConcatAndEchoMethod, ConcatAndEchoHandler) .Build(); Server server; Channel channel; [TestFixtureSetUp] public void InitClass() { GrpcEnvironment.Initialize(); } [SetUp] public void Init() { server = new Server(); server.AddServiceDefinition(ServiceDefinition); int port = server.AddListeningPort(Host, Server.PickUnusedPort); server.Start(); channel = new Channel(Host, port); } [TearDown] public void Cleanup() { channel.Dispose(); server.ShutdownAsync().Wait(); } [TestFixtureTearDown] public void CleanupClass() { GrpcEnvironment.Shutdown(); } [Test] public void UnaryCall() { var call = new Call<string, string>(ServiceName, EchoMethod, channel, Metadata.Empty); Assert.AreEqual("ABC", Calls.BlockingUnaryCall(call, "ABC", CancellationToken.None)); } [Test] public void UnaryCall_ServerHandlerThrows() { var call = new Call<string, string>(ServiceName, EchoMethod, channel, Metadata.Empty); try { Calls.BlockingUnaryCall(call, "THROW", CancellationToken.None); Assert.Fail(); } catch (RpcException e) { Assert.AreEqual(StatusCode.Unknown, e.Status.StatusCode); } } [Test] public void AsyncUnaryCall() { var call = new Call<string, string>(ServiceName, EchoMethod, channel, Metadata.Empty); var result = Calls.AsyncUnaryCall(call, "ABC", CancellationToken.None).Result; Assert.AreEqual("ABC", result); } [Test] public void AsyncUnaryCall_ServerHandlerThrows() { Task.Run(async () => { var call = new Call<string, string>(ServiceName, EchoMethod, channel, Metadata.Empty); try { await Calls.AsyncUnaryCall(call, "THROW", CancellationToken.None); Assert.Fail(); } catch (RpcException e) { Assert.AreEqual(StatusCode.Unknown, e.Status.StatusCode); } }).Wait(); } [Test] public void ClientStreamingCall() { Task.Run(async () => { var call = new Call<string, string>(ServiceName, ConcatAndEchoMethod, channel, Metadata.Empty); var callResult = Calls.AsyncClientStreamingCall(call, CancellationToken.None); await callResult.RequestStream.WriteAll(new string[] { "A", "B", "C" }); Assert.AreEqual("ABC", await callResult.Result); }).Wait(); } [Test] public void ClientStreamingCall_CancelAfterBegin() { Task.Run(async () => { var call = new Call<string, string>(ServiceName, ConcatAndEchoMethod, channel, Metadata.Empty); var cts = new CancellationTokenSource(); var callResult = Calls.AsyncClientStreamingCall(call, cts.Token); // TODO(jtattermusch): we need this to ensure call has been initiated once we cancel it. await Task.Delay(1000); cts.Cancel(); try { await callResult.Result; } catch (RpcException e) { Assert.AreEqual(StatusCode.Cancelled, e.Status.StatusCode); } }).Wait(); } [Test] public void UnaryCall_DisposedChannel() { channel.Dispose(); var call = new Call<string, string>(ServiceName, EchoMethod, channel, Metadata.Empty); Assert.Throws(typeof(ObjectDisposedException), () => Calls.BlockingUnaryCall(call, "ABC", CancellationToken.None)); } [Test] public void UnaryCallPerformance() { var call = new Call<string, string>(ServiceName, EchoMethod, channel, Metadata.Empty); BenchmarkUtil.RunBenchmark(100, 100, () => { Calls.BlockingUnaryCall(call, "ABC", default(CancellationToken)); }); } [Test] public void UnknownMethodHandler() { var call = new Call<string, string>(ServiceName, NonexistentMethod, channel, Metadata.Empty); try { Calls.BlockingUnaryCall(call, "ABC", default(CancellationToken)); Assert.Fail(); } catch (RpcException e) { Assert.AreEqual(StatusCode.Unimplemented, e.Status.StatusCode); } } private static async Task<string> EchoHandler(ServerCallContext context, string request) { if (request == "THROW") { throw new Exception("This was thrown on purpose by a test"); } return request; } private static async Task<string> ConcatAndEchoHandler(ServerCallContext context, IAsyncStreamReader<string> requestStream) { string result = ""; await requestStream.ForEach(async (request) => { if (request == "THROW") { throw new Exception("This was thrown on purpose by a test"); } result += request; }); // simulate processing takes some time. await Task.Delay(250); return result; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.FileProviders.Internal; using Microsoft.Extensions.FileProviders.Physical; using Microsoft.Extensions.Primitives; using OrchardCore.Modules; namespace OrchardCore.Mvc { /// <summary> /// This custom <see cref="IFileProvider"/> implementation provides the file contents /// of Module Project Razor files while in a development environment. /// </summary> public class ModuleProjectRazorFileProvider : IFileProvider { private static IList<IFileProvider> _pageFileProviders; private static Dictionary<string, string> _roots; private static object _synLock = new object(); public ModuleProjectRazorFileProvider(IApplicationContext applicationContext) { if (_roots != null) { return; } lock (_synLock) { if (_roots == null) { var application = applicationContext.Application; _pageFileProviders = new List<IFileProvider>(); var roots = new Dictionary<string, string>(); // Resolve all module projects roots. foreach (var module in application.Modules) { // If the module and the application assemblies are not at the same location, // this means that the module is referenced as a package, not as a project in dev. if (module.Assembly == null || Path.GetDirectoryName(module.Assembly.Location) != Path.GetDirectoryName(application.Assembly.Location)) { continue; } // Get module assets which are razor files. var assets = module.Assets.Where(a => a.ModuleAssetPath .EndsWith(".cshtml", StringComparison.Ordinal)); if (assets.Any()) { var asset = assets.First(); var index = asset.ModuleAssetPath.IndexOf(module.Root, StringComparison.Ordinal); // Resolve the physical "{ModuleProjectDirectory}" from the project asset. var filePath = asset.ModuleAssetPath.Substring(index + module.Root.Length); var root = asset.ProjectAssetPath.Substring(0, asset.ProjectAssetPath.Length - filePath.Length); // Get the first module project asset which is under a "Pages" folder. var page = assets.FirstOrDefault(a => a.ProjectAssetPath.Contains("/Pages/")); // Check if the module project may have a razor page. if (page != null && Directory.Exists(root)) { // Razor pages are not watched in the same way as other razor views. // We need a physical file provider on the "{ModuleProjectDirectory}". _pageFileProviders.Add(new PhysicalFileProvider(root)); } // Add the module project root. roots[module.Name] = root; } } _roots = roots; } } } public IDirectoryContents GetDirectoryContents(string subpath) { // 'GetDirectoryContents()' is used to discover shapes templates and build fixed binding tables. // So the embedded file provider can always provide the structure under modules "Views" folders. // The razor view engine also uses 'GetDirectoryContents()' to find razor pages (not mvc views). // So here, we only need to serve the directory contents under modules projects "Pages" folders. // Note: This provider is not used in production where all modules precompiled views are used. // Note: See 'ApplicationRazorFileProvider' for the specific case of the application's module. if (subpath == null) { return NotFoundDirectoryContents.Singleton; } var folder = NormalizePath(subpath); // Under "Areas/{ModuleId}" or "Areas/{ModuleId}/**". if (folder.StartsWith(Application.ModulesRoot, StringComparison.Ordinal)) { // Remove "Areas/" from the folder path. folder = folder.Substring(Application.ModulesRoot.Length); var index = folder.IndexOf('/'); // "{ModuleId}/**". if (index != -1) { // Resolve the module id. var module = folder.Substring(0, index); // Try to get the module project root and if (_roots.TryGetValue(module, out var root) && // check for a final or an intermadiate "Pages" segment. (folder.EndsWith("/Pages", StringComparison.Ordinal) || folder.Contains("/Pages/"))) { // Resolve the subpath relative to "{ModuleProjectDirectory}". folder = root + folder.Substring(module.Length + 1); if (Directory.Exists(folder)) { // Serve the contents from the file system. return new PhysicalDirectoryContents(folder); } } } } return NotFoundDirectoryContents.Singleton; } public IFileInfo GetFileInfo(string subpath) { if (subpath == null) { return new NotFoundFileInfo(subpath); } var path = NormalizePath(subpath); // "Areas/**/*.*". if (path.StartsWith(Application.ModulesRoot, StringComparison.Ordinal)) { // Skip the "Areas/" root folder. path = path.Substring(Application.ModulesRoot.Length); var index = path.IndexOf('/'); // "{ModuleId}/**/*.*". if (index != -1) { // Resolve the module id. var module = path.Substring(0, index); // Get the module root folder. if (_roots.TryGetValue(module, out var root)) { // Resolve "{ModuleProjectDirectory}**/*.*" var filePath = root + path.Substring(module.Length + 1); if (File.Exists(filePath)) { //Serve the file from the physical file system. return new PhysicalFileInfo(new FileInfo(filePath)); } } } } return new NotFoundFileInfo(subpath); } public IChangeToken Watch(string filter) { if (filter == null) { return NullChangeToken.Singleton; } var path = NormalizePath(filter); // "Areas/**/*.*". if (path.StartsWith(Application.ModulesRoot, StringComparison.Ordinal) && !path.Contains('*')) { // Skip the "Areas/" root folder. path = path.Substring(Application.ModulesRoot.Length); var index = path.IndexOf('/'); // "{ModuleId}/**/*.*". if (index != -1) { // Resolve the module id. var module = path.Substring(0, index); // Get the module root folder. if (_roots.TryGetValue(module, out var root)) { // Resolve "{ModuleProjectDirectory}**/*.*" var filePath = root + path.Substring(module.Length + 1); var directory = Path.GetDirectoryName(filePath); var fileName = Path.GetFileNameWithoutExtension(filePath); if (Directory.Exists(directory)) { // Watch the project asset from the physical file system. // Note: Here a wildcard is used on the file extension // so that removing and re-adding a file is detected. return new PollingWildCardChangeToken(directory, fileName + ".*"); } } } } // The view engine uses a watch on "Pages/**/*.cshtml" but only for razor pages. // So here, we only use file providers for modules which have a "Pages" folder. else if (path.Equals("Pages/**/*.cshtml")) { var changeTokens = new List<IChangeToken>(); // For each module which might have pages. foreach (var provider in _pageFileProviders) { // Watch all razor files under its "Pages" folder. var changeToken = provider.Watch("Pages/**/*.cshtml"); if (changeToken != null) { changeTokens.Add(changeToken); } } if (changeTokens.Count == 1) { return changeTokens.First(); } if (changeTokens.Count > 0) { // Use a composite of all provider tokens. return new CompositeChangeToken(changeTokens); } } return NullChangeToken.Singleton; } private string NormalizePath(string path) { return path.Replace('\\', '/').Trim('/'); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // <OWNER>[....]</OWNER> // /*============================================================ * * Class: IsolatedStorage * * * Purpose: Provides access to Persisted Application / Assembly data * * Date: Feb 15, 2000 * ===========================================================*/ namespace System.IO.IsolatedStorage { using System; using System.IO; using System.Text; using System.Threading; using System.Reflection; using System.Collections; using System.Security; using System.Security.Policy; using System.Security.Permissions; using System.Security.Cryptography; using System.Runtime.Serialization; using System.Runtime.CompilerServices; #if FEATURE_SERIALIZATION using System.Runtime.Serialization.Formatters.Binary; #endif // FEATURE_SERIALIZATION using System.Runtime.InteropServices; using System.Runtime.Versioning; using Microsoft.Win32; using System.Diagnostics.Contracts; [Serializable] [Flags] [System.Runtime.InteropServices.ComVisible(true)] public enum IsolatedStorageScope { // Dependency in native : COMIsolatedStorage.h None = 0x00, User = 0x01, #if !FEATURE_ISOSTORE_LIGHT Domain = 0x02, Assembly = 0x04, Roaming = 0x08, Machine = 0x10, #endif // FEATURE_ISOSTORE_LIGHT Application = 0x20 } #if !FEATURE_ISOSTORE_LIGHT // not serializable [System.Runtime.InteropServices.ComVisible(true)] public abstract class IsolatedStorage : MarshalByRefObject { // Helper constants internal const IsolatedStorageScope c_Assembly = (IsolatedStorageScope.User | IsolatedStorageScope.Assembly); internal const IsolatedStorageScope c_Domain = (IsolatedStorageScope.User | IsolatedStorageScope.Assembly | IsolatedStorageScope.Domain); internal const IsolatedStorageScope c_AssemblyRoaming = (IsolatedStorageScope.Roaming | IsolatedStorageScope.User | IsolatedStorageScope.Assembly); internal const IsolatedStorageScope c_DomainRoaming = (IsolatedStorageScope.Roaming | IsolatedStorageScope.User | IsolatedStorageScope.Assembly | IsolatedStorageScope.Domain); internal const IsolatedStorageScope c_MachineAssembly = (IsolatedStorageScope.Machine | IsolatedStorageScope.Assembly); internal const IsolatedStorageScope c_MachineDomain = (IsolatedStorageScope.Machine | IsolatedStorageScope.Assembly | IsolatedStorageScope.Domain); internal const IsolatedStorageScope c_AppUser = (IsolatedStorageScope.Application | IsolatedStorageScope.User); internal const IsolatedStorageScope c_AppMachine = (IsolatedStorageScope.Application | IsolatedStorageScope.Machine); internal const IsolatedStorageScope c_AppUserRoaming = (IsolatedStorageScope.Roaming | IsolatedStorageScope.Application | IsolatedStorageScope.User); #if !FEATURE_PAL private const String s_Publisher = "Publisher"; #endif // !FEATURE_PAL private const String s_StrongName = "StrongName"; private const String s_Site = "Site"; private const String s_Url = "Url"; private const String s_Zone = "Zone"; private ulong m_Quota; private bool m_ValidQuota; private Object m_DomainIdentity; private Object m_AssemIdentity; private Object m_AppIdentity; private String m_DomainName; private String m_AssemName; private String m_AppName; private IsolatedStorageScope m_Scope; private static volatile IsolatedStorageFilePermission s_PermDomain; private static volatile IsolatedStorageFilePermission s_PermMachineDomain; private static volatile IsolatedStorageFilePermission s_PermDomainRoaming; private static volatile IsolatedStorageFilePermission s_PermAssem; private static volatile IsolatedStorageFilePermission s_PermMachineAssem; private static volatile IsolatedStorageFilePermission s_PermAssemRoaming; private static volatile IsolatedStorageFilePermission s_PermAppUser; private static volatile IsolatedStorageFilePermission s_PermAppMachine; private static volatile IsolatedStorageFilePermission s_PermAppUserRoaming; private static volatile SecurityPermission s_PermControlEvidence; private static volatile PermissionSet s_PermUnrestricted; #if _DEBUG private static bool s_fDebug = false; private static int s_iDebug = 0; #endif // This one should be a macro, expecting JIT to inline this. internal static bool IsRoaming(IsolatedStorageScope scope) { return ((scope & IsolatedStorageScope.Roaming) != 0); } internal bool IsRoaming() { return ((m_Scope & IsolatedStorageScope.Roaming) != 0); } // This one should be a macro, expecting JIT to inline this. internal static bool IsDomain(IsolatedStorageScope scope) { return ((scope & IsolatedStorageScope.Domain) != 0); } internal bool IsDomain() { return ((m_Scope & IsolatedStorageScope.Domain) != 0); } #if false // Not currently used // This one should be a macro, expecting JIT to inline this. internal static bool IsUser(IsolatedStorageScope scope) { return ((scope & IsolatedStorageScope.User) != 0); } #endif // This one should be a macro, expecting JIT to inline this. internal static bool IsMachine(IsolatedStorageScope scope) { return ((scope & IsolatedStorageScope.Machine) != 0); } internal bool IsAssembly() { return ((m_Scope & IsolatedStorageScope.Assembly) != 0); } // This one should be a macro, expecting JIT to inline this. internal static bool IsApp(IsolatedStorageScope scope) { return ((scope & IsolatedStorageScope.Application) != 0); } internal bool IsApp() { return ((m_Scope & IsolatedStorageScope.Application) != 0); } private String GetNameFromID(String typeID, String instanceID) { return typeID + SeparatorInternal + instanceID; } private static String GetPredefinedTypeName(Object o) { #if !FEATURE_PAL if (o is Publisher) return s_Publisher; else if (o is StrongName) return s_StrongName; #else if (o is StrongName) return s_StrongName; #endif // !FEATURE_PAL else if (o is Url) return s_Url; else if (o is Site) return s_Site; else if (o is Zone) return s_Zone; return null; } #if !FEATURE_PAL internal static String GetHash(Stream s) { using (SHA1 sha1 = new SHA1CryptoServiceProvider()) { byte[] b = sha1.ComputeHash(s); return Path.ToBase32StringSuitableForDirName(b); } } #else internal static String GetHash(Stream s) { const int MAX_BUFFER_SIZE = 1024; byte[] buffer = new byte[MAX_BUFFER_SIZE]; // 160 bits SHA1 output as defined in the Secure Hash Standard const int MESSAGE_DIGEST_LENGTH = 20; int digestLength = 0; byte[] digest = new byte[MESSAGE_DIGEST_LENGTH]; IntPtr hProv = (IntPtr) 0; IntPtr hHash = (IntPtr) 0; if( Win32Native.CryptAcquireContext(out hProv, null, null, 0, 0) == false) throw new IsolatedStorageException(Environment.GetResourceString("IsolatedStorage_Exception")); if( Win32Native.CryptCreateHash(hProv, Win32Native.CALG_SHA1,(IntPtr) 0, 0, out hHash) == false) throw new IsolatedStorageException(Environment.GetResourceString("IsolatedStorage_Exception")); int bytesRead; do { bytesRead = s.Read(buffer,0,MAX_BUFFER_SIZE); if (bytesRead > 0) { if(Win32Native.CryptHashData(hHash, buffer, bytesRead, 0) == false) { throw new IsolatedStorageException(Environment.GetResourceString("IsolatedStorage_Exception")); } } } while (bytesRead > 0); // perform a sanity check to make sure the digest size equals MESSAGE_DIGEST_LENGTH int fourBytes = 4; if( Win32Native.CryptGetHashParam(hHash, Win32Native.HP_HASHSIZE, out digestLength, ref fourBytes, 0) == false || (digestLength != MESSAGE_DIGEST_LENGTH) ) { throw new IsolatedStorageException(Environment.GetResourceString("IsolatedStorage_Exception")); } if( Win32Native.CryptGetHashParam(hHash, Win32Native.HP_HASHVAL, digest, ref digestLength, 0) == false) throw new IsolatedStorageException(Environment.GetResourceString("IsolatedStorage_Exception")); if( Win32Native.CryptDestroyHash(hHash) == false) throw new IsolatedStorageException(Environment.GetResourceString("IsolatedStorage_Exception")); if( Win32Native.CryptReleaseContext(hProv, 0) == false ) throw new IsolatedStorageException(Environment.GetResourceString("IsolatedStorage_Exception")); return Path.ToBase32StringSuitableForDirName(digest); } #endif // !FEATURE_PAL #if false // This is not used. private static String ToBase64StringSuitableForDirName(byte[] buff) { String s = Convert.ToBase64String(buff); StringBuilder sb = new StringBuilder(); // Remove certain chars not suited for file names for (int i=0; i<s.Length; ++i) { Char c = s[i]; if (Char.IsUpper(s[i])) { // NT file system is case in-sensitive. This will // weaken the hash. Preserve the streangth of the // hash by adding a new "special char" before all caps sb.Append("O"); sb.Append(s[i]); } else if (c == '/') // replace '/' with '-' sb.Append("-"); else if (c != '=') // ignore padding sb.Append(s[i]); } return sb.ToString(); } #endif private static bool IsValidName(String s) { for (int i=0; i<s.Length; ++i) { if (!Char.IsLetter(s[i]) && !Char.IsDigit(s[i])) return false; } return true; } private static SecurityPermission GetControlEvidencePermission() { // Don't [....]. OK to create this object more than once. if (s_PermControlEvidence == null) s_PermControlEvidence = new SecurityPermission( SecurityPermissionFlag.ControlEvidence); return s_PermControlEvidence; } private static PermissionSet GetUnrestricted() { // Don't [....]. OK to create this object more than once. if (s_PermUnrestricted == null) s_PermUnrestricted = new PermissionSet( PermissionState.Unrestricted); return s_PermUnrestricted; } protected virtual char SeparatorExternal { #if !FEATURE_PAL get { return '\\'; } #else get { return System.IO.Path.DirectorySeparatorChar; } #endif //!FEATURE_PAL } protected virtual char SeparatorInternal { get { return '.'; } } // gets "amount of space / resource used" [CLSCompliant(false)] [Obsolete("IsolatedStorage.MaximumSize has been deprecated because it is not CLS Compliant. To get the maximum size use IsolatedStorage.Quota")] public virtual ulong MaximumSize { get { if (m_ValidQuota) return m_Quota; throw new InvalidOperationException( Environment.GetResourceString( "IsolatedStorage_QuotaIsUndefined", "MaximumSize")); } } [CLSCompliant(false)] [Obsolete("IsolatedStorage.CurrentSize has been deprecated because it is not CLS Compliant. To get the current size use IsolatedStorage.UsedSize")] public virtual ulong CurrentSize { get { throw new InvalidOperationException( Environment.GetResourceString( "IsolatedStorage_CurrentSizeUndefined", "CurrentSize")); } } [ComVisible(false)] public virtual long UsedSize { get { throw new InvalidOperationException( Environment.GetResourceString( "IsolatedStorage_CurrentSizeUndefined", "UsedSize")); } } [ComVisible(false)] public virtual long Quota { get { if (m_ValidQuota) return (long) m_Quota; throw new InvalidOperationException( Environment.GetResourceString( "IsolatedStorage_QuotaIsUndefined", "Quota")); } internal set { m_Quota = (ulong) value; m_ValidQuota = true; } } [ComVisible(false)] public virtual long AvailableFreeSpace { get { throw new InvalidOperationException( Environment.GetResourceString( "IsolatedStorage_QuotaIsUndefined", "AvailableFreeSpace")); } } public Object DomainIdentity { [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPolicy)] get { if (IsDomain()) return m_DomainIdentity; throw new InvalidOperationException( Environment.GetResourceString( "IsolatedStorage_DomainUndefined")); } } [ComVisible(false)] public Object ApplicationIdentity { [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPolicy)] get { if (IsApp()) return m_AppIdentity; throw new InvalidOperationException( Environment.GetResourceString( "IsolatedStorage_ApplicationUndefined")); } } public Object AssemblyIdentity { [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPolicy)] get { if (IsAssembly()) return m_AssemIdentity; throw new InvalidOperationException( Environment.GetResourceString( "IsolatedStorage_AssemblyUndefined")); } } [ComVisible(false)] public virtual Boolean IncreaseQuotaTo(Int64 newQuotaSize) { return false; } // Returns the AppDomain Stream (if present). // Sets assem stream [System.Security.SecurityCritical] // auto-generated internal MemoryStream GetIdentityStream(IsolatedStorageScope scope) { BinaryFormatter bSer; MemoryStream ms; Object o; GetUnrestricted().Assert(); bSer = new BinaryFormatter(); ms = new MemoryStream(); if (IsApp(scope)) o = m_AppIdentity; else if (IsDomain(scope)) o = m_DomainIdentity; else { o = m_AssemIdentity; } if (o != null) bSer.Serialize(ms, o); ms.Position = 0; return ms; } public IsolatedStorageScope Scope { get { return m_Scope; } } internal String DomainName { get { if (IsDomain()) return m_DomainName; throw new InvalidOperationException( Environment.GetResourceString( "IsolatedStorage_DomainUndefined")); } } internal String AssemName { get { if (IsAssembly()) return m_AssemName; throw new InvalidOperationException( Environment.GetResourceString( "IsolatedStorage_AssemblyUndefined")); } } internal String AppName { get { if (IsApp()) return m_AppName; throw new InvalidOperationException( Environment.GetResourceString( "IsolatedStorage_ApplicationUndefined")); } } [System.Security.SecuritySafeCritical] // auto-generated protected void InitStore(IsolatedStorageScope scope, Type domainEvidenceType, Type assemblyEvidenceType) { RuntimeAssembly assem; AppDomain domain; PermissionSet psAllowed, psDenied; psAllowed = null; psDenied = null; assem = GetCaller(); GetControlEvidencePermission().Assert(); if (IsDomain(scope)) { domain = Thread.GetDomain(); if (!IsRoaming(scope)) // No quota for roaming { psAllowed = domain.PermissionSet; if (psAllowed == null) throw new IsolatedStorageException( Environment.GetResourceString( "IsolatedStorage_DomainGrantSet")); } _InitStore(scope, domain.Evidence, domainEvidenceType, assem.Evidence, assemblyEvidenceType, null,null); } else { if (!IsRoaming(scope)) // No quota for roaming { assem.GetGrantSet(out psAllowed, out psDenied); if (psAllowed == null) throw new IsolatedStorageException( Environment.GetResourceString( "IsolatedStorage_AssemblyGrantSet")); } _InitStore(scope, null, null, assem.Evidence, assemblyEvidenceType, null,null); } SetQuota(psAllowed, psDenied); } [System.Security.SecuritySafeCritical] // auto-generated protected void InitStore(IsolatedStorageScope scope, Type appEvidenceType) { Assembly assem; AppDomain domain; PermissionSet psAllowed, psDenied; psAllowed = null; psDenied = null; assem = GetCaller(); GetControlEvidencePermission().Assert(); if (IsApp(scope)) { domain = Thread.GetDomain(); if (!IsRoaming(scope)) // No quota for roaming { psAllowed = domain.PermissionSet; if (psAllowed == null) throw new IsolatedStorageException( Environment.GetResourceString( "IsolatedStorage_DomainGrantSet")); } #if !FEATURE_PAL ActivationContext activationContext = AppDomain.CurrentDomain.ActivationContext; if (activationContext == null) throw new IsolatedStorageException( Environment.GetResourceString( "IsolatedStorage_ApplicationMissingIdentity")); ApplicationSecurityInfo asi = new ApplicationSecurityInfo(activationContext); _InitStore(scope, null, null, null,null, asi.ApplicationEvidence, appEvidenceType); #else throw new IsolatedStorageException( Environment.GetResourceString( "IsolatedStorage_ApplicationMissingIdentity")); #endif // !FEATURE_PAL } SetQuota(psAllowed, psDenied); } [System.Security.SecuritySafeCritical] // auto-generated internal void InitStore(IsolatedStorageScope scope, Object domain, Object assem, Object app) { RuntimeAssembly callerAssembly; PermissionSet psAllowed = null, psDenied = null; Evidence domainEv = null, assemEv = null, appEv = null; if (IsApp(scope)) { EvidenceBase applicationEvidenceObject = app as EvidenceBase; if (applicationEvidenceObject == null) { applicationEvidenceObject = new LegacyEvidenceWrapper(app); } appEv = new Evidence(); appEv.AddHostEvidence(applicationEvidenceObject); } else { EvidenceBase assemblyEvidenceObject = assem as EvidenceBase; if (assemblyEvidenceObject == null) { assemblyEvidenceObject = new LegacyEvidenceWrapper(assem); } assemEv = new Evidence(); assemEv.AddHostEvidence(assemblyEvidenceObject); if (IsDomain(scope)) { EvidenceBase domainEvidenceObject = domain as EvidenceBase; if (domainEvidenceObject == null) { domainEvidenceObject = new LegacyEvidenceWrapper(domain); } domainEv = new Evidence(); domainEv.AddHostEvidence(domainEvidenceObject); } } _InitStore(scope, domainEv, null, assemEv, null, appEv, null); // Set the quota based on the caller, not the evidence supplied if (!IsRoaming(scope)) // No quota for roaming { callerAssembly = GetCaller(); GetControlEvidencePermission().Assert(); callerAssembly.GetGrantSet(out psAllowed, out psDenied); if (psAllowed == null) throw new IsolatedStorageException( Environment.GetResourceString( "IsolatedStorage_AssemblyGrantSet")); } // This can be called only by trusted assemblies. // This quota really does not correspond to the permissions // granted for this evidence. SetQuota(psAllowed, psDenied); } [System.Security.SecurityCritical] // auto-generated internal void InitStore(IsolatedStorageScope scope, Evidence domainEv, Type domainEvidenceType, Evidence assemEv, Type assemEvidenceType, Evidence appEv, Type appEvidenceType) { PermissionSet psAllowed = null; if (!IsRoaming(scope)) { if (IsApp(scope)) { psAllowed = SecurityManager.GetStandardSandbox(appEv); } else if (IsDomain(scope)) { psAllowed = SecurityManager.GetStandardSandbox(domainEv); } else { psAllowed = SecurityManager.GetStandardSandbox(assemEv); } } _InitStore(scope, domainEv, domainEvidenceType, assemEv, assemEvidenceType, appEv, appEvidenceType); SetQuota(psAllowed, null); } [System.Security.SecuritySafeCritical] // auto-generated internal bool InitStore(IsolatedStorageScope scope, Stream domain, Stream assem, Stream app, String domainName, String assemName, String appName) { BinaryFormatter bSer; try { GetUnrestricted().Assert(); bSer = new BinaryFormatter(); if (IsApp(scope)) { // Get the Application Info m_AppIdentity = bSer.Deserialize(app); m_AppName = appName; } else { // Get the Assem Info m_AssemIdentity = bSer.Deserialize(assem); m_AssemName = assemName; if (IsDomain(scope)) { // Get the AppDomain Info m_DomainIdentity = bSer.Deserialize(domain); m_DomainName = domainName; } } } catch { return false; } Contract.Assert(m_ValidQuota == false, "Quota should be invalid here"); m_Scope = scope; return true; } [System.Security.SecurityCritical] // auto-generated private void _InitStore(IsolatedStorageScope scope, Evidence domainEv, Type domainEvidenceType, Evidence assemEv, Type assemblyEvidenceType, Evidence appEv, Type appEvidenceType) { VerifyScope(scope); // If its app-scoped, we only use the appId and appName. Else assume assembly evidence present // and check if we need domain scoping too // Input arg checks if (IsApp(scope)) { if (appEv == null) throw new IsolatedStorageException( Environment.GetResourceString( "IsolatedStorage_ApplicationMissingIdentity")); } else { if (assemEv == null) throw new IsolatedStorageException( Environment.GetResourceString( "IsolatedStorage_AssemblyMissingIdentity")); if (IsDomain(scope) && (domainEv == null)) throw new IsolatedStorageException( Environment.GetResourceString( "IsolatedStorage_DomainMissingIdentity")); } // Security checks DemandPermission(scope); String typeHash = null, instanceHash = null; if (IsApp(scope)) { m_AppIdentity = GetAccountingInfo(appEv, appEvidenceType, IsolatedStorageScope.Application, out typeHash, out instanceHash); m_AppName = GetNameFromID(typeHash, instanceHash); } else { m_AssemIdentity = GetAccountingInfo( assemEv, assemblyEvidenceType, IsolatedStorageScope.Assembly, out typeHash, out instanceHash); m_AssemName = GetNameFromID(typeHash, instanceHash); if (IsDomain(scope)) { m_DomainIdentity = GetAccountingInfo(domainEv, domainEvidenceType, IsolatedStorageScope.Domain, out typeHash, out instanceHash); m_DomainName = GetNameFromID(typeHash, instanceHash); } } m_Scope = scope; } [System.Security.SecurityCritical] // auto-generated private static Object GetAccountingInfo( Evidence evidence, Type evidenceType, IsolatedStorageScope fAssmDomApp, out String typeName, out String instanceName) { Object o, oNormalized = null; MemoryStream ms; BinaryWriter bw; BinaryFormatter bSer; o = _GetAccountingInfo(evidence, evidenceType, fAssmDomApp, out oNormalized); // Get the type name typeName = GetPredefinedTypeName(o); if (typeName == null) { // This is not a predefined type. Serialize the type // and get a hash for the serialized stream GetUnrestricted().Assert(); ms = new MemoryStream(); bSer = new BinaryFormatter(); bSer.Serialize(ms, o.GetType()); ms.Position = 0; typeName = GetHash(ms); #if _DEBUG DebugLog(o.GetType(), ms); #endif CodeAccessPermission.RevertAssert(); } instanceName = null; // Get the normalized instance name if present. if (oNormalized != null) { if (oNormalized is Stream) { instanceName = GetHash((Stream)oNormalized); } else if (oNormalized is String) { if (IsValidName((String)oNormalized)) { instanceName = (String)oNormalized; } else { // The normalized name has illegal chars // serialize and get the hash. ms = new MemoryStream(); bw = new BinaryWriter(ms); bw.Write((String)oNormalized); ms.Position = 0; instanceName = GetHash(ms); #if _DEBUG DebugLog(oNormalized, ms); #endif } } } else { oNormalized = o; } if (instanceName == null) { // Serialize the instance and get the hash for the // serialized stream GetUnrestricted().Assert(); ms = new MemoryStream(); bSer = new BinaryFormatter(); bSer.Serialize(ms, oNormalized); ms.Position = 0; instanceName = GetHash(ms); #if _DEBUG DebugLog(oNormalized, ms); #endif CodeAccessPermission.RevertAssert(); } return o; } private static Object _GetAccountingInfo( Evidence evidence, Type evidenceType, IsolatedStorageScope fAssmDomApp, out Object oNormalized) { Object o = null; Contract.Assert(evidence != null, "evidence != null"); if (evidenceType == null) { // Caller does not have any preference // Order of preference is Publisher, Strong Name, Url, Site #if !FEATURE_PAL o = evidence.GetHostEvidence<Publisher>(); if (o == null) o = evidence.GetHostEvidence<StrongName>(); #endif // !FEATURE_PAL if (o == null) o = evidence.GetHostEvidence<Url>(); if (o == null) o = evidence.GetHostEvidence<Site>(); if (o == null) o = evidence.GetHostEvidence<Zone>(); if (o == null) { // The evidence object can have tons of other objects // creatd by the policy system. Ignore those. if (fAssmDomApp == IsolatedStorageScope.Domain) throw new IsolatedStorageException( Environment.GetResourceString( "IsolatedStorage_DomainNoEvidence")); else if (fAssmDomApp == IsolatedStorageScope.Application) throw new IsolatedStorageException( Environment.GetResourceString( "IsolatedStorage_ApplicationNoEvidence")); else throw new IsolatedStorageException( Environment.GetResourceString( "IsolatedStorage_AssemblyNoEvidence")); } } else { o = evidence.GetHostEvidence(evidenceType); if (o == null) { if (fAssmDomApp == IsolatedStorageScope.Domain) throw new IsolatedStorageException( Environment.GetResourceString( "IsolatedStorage_DomainNoEvidence")); else if (fAssmDomApp == IsolatedStorageScope.Application) throw new IsolatedStorageException( Environment.GetResourceString( "IsolatedStorage_ApplicationNoEvidence")); else throw new IsolatedStorageException( Environment.GetResourceString( "IsolatedStorage_AssemblyNoEvidence")); } } // For startup Perf, Url, Site, StrongName types don't implement // INormalizeForIsolatedStorage interface, instead they have // Normalize() method. if (o is INormalizeForIsolatedStorage) { oNormalized = ((INormalizeForIsolatedStorage)o).Normalize(); } #if !FEATURE_PAL else if (o is Publisher) { oNormalized = ((Publisher)o).Normalize(); } #endif // !FEATURE_PAL else if (o is StrongName) { oNormalized = ((StrongName)o).Normalize(); } else if (o is Url) { oNormalized = ((Url)o).Normalize(); } else if (o is Site) { oNormalized = ((Site)o).Normalize(); } else if (o is Zone) { oNormalized = ((Zone)o).Normalize(); } else { oNormalized = null; } return o; } [System.Security.SecurityCritical] // auto-generated private static void DemandPermission(IsolatedStorageScope scope) { IsolatedStorageFilePermission ip = null; // Ok to create more than one instnace of s_PermXXX, the last one // will be shared. No need to synchronize. // First check for permissions switch (scope) { case c_Domain: if (s_PermDomain == null) s_PermDomain = new IsolatedStorageFilePermission( IsolatedStorageContainment.DomainIsolationByUser, 0, false); ip = s_PermDomain; break; case c_Assembly: if (s_PermAssem == null) s_PermAssem = new IsolatedStorageFilePermission( IsolatedStorageContainment.AssemblyIsolationByUser, 0, false); ip = s_PermAssem; break; case c_DomainRoaming: if (s_PermDomainRoaming == null) s_PermDomainRoaming = new IsolatedStorageFilePermission( IsolatedStorageContainment.DomainIsolationByRoamingUser, 0, false); ip = s_PermDomainRoaming; break; case c_AssemblyRoaming: if (s_PermAssemRoaming == null) s_PermAssemRoaming = new IsolatedStorageFilePermission( IsolatedStorageContainment.AssemblyIsolationByRoamingUser, 0, false); ip = s_PermAssemRoaming; break; case c_MachineDomain: if (s_PermMachineDomain == null) s_PermMachineDomain = new IsolatedStorageFilePermission( IsolatedStorageContainment.DomainIsolationByMachine, 0, false); ip = s_PermMachineDomain; break; case c_MachineAssembly: if (s_PermMachineAssem == null) s_PermMachineAssem = new IsolatedStorageFilePermission( IsolatedStorageContainment.AssemblyIsolationByMachine, 0, false); ip = s_PermMachineAssem; break; case c_AppUser: if (s_PermAppUser == null) s_PermAppUser = new IsolatedStorageFilePermission( IsolatedStorageContainment.ApplicationIsolationByUser, 0, false); ip = s_PermAppUser; break; case c_AppMachine: if (s_PermAppMachine == null) s_PermAppMachine = new IsolatedStorageFilePermission( IsolatedStorageContainment.ApplicationIsolationByMachine, 0, false); ip = s_PermAppMachine; break; case c_AppUserRoaming: if (s_PermAppUserRoaming== null) s_PermAppUserRoaming= new IsolatedStorageFilePermission( IsolatedStorageContainment.ApplicationIsolationByRoamingUser, 0, false); ip = s_PermAppUserRoaming; break; #if _DEBUG default: Contract.Assert(false, "Invalid scope"); break; #endif } ip.Demand(); } internal static void VerifyScope(IsolatedStorageScope scope) { // The only valid ones are the ones that have a helper constant defined above (c_*) if ((scope == c_Domain) || (scope == c_Assembly) || (scope == c_DomainRoaming) || (scope == c_AssemblyRoaming) || (scope == c_MachineDomain) || (scope == c_MachineAssembly) || (scope == c_AppUser) || (scope == c_AppMachine) || (scope == c_AppUserRoaming)) return; throw new ArgumentException( Environment.GetResourceString( "IsolatedStorage_Scope_Invalid")); } [System.Security.SecurityCritical] internal virtual void SetQuota(PermissionSet psAllowed, PermissionSet psDenied) { IsolatedStoragePermission ispAllowed, ispDenied; ispAllowed = GetPermission(psAllowed); m_Quota = 0; if (ispAllowed != null) { if (ispAllowed.IsUnrestricted()) m_Quota = Int64.MaxValue; else m_Quota = (ulong) ispAllowed.UserQuota; } if (psDenied != null) { ispDenied = GetPermission(psDenied); if (ispDenied != null) { if (ispDenied.IsUnrestricted()) { m_Quota = 0; } else { ulong denied = (ulong) ispDenied.UserQuota; if (denied > m_Quota) m_Quota = 0; else m_Quota -= denied; } } } m_ValidQuota = true; #if _DEBUG if (s_fDebug) { if (s_iDebug >= 1) { if (psAllowed != null) Console.WriteLine("Allowed PS : " + psAllowed); if (psDenied != null) Console.WriteLine("Denied PS : " + psDenied); } } #endif } #if _DEBUG private static void DebugLog(Object o, MemoryStream ms) { if (s_fDebug) { if (s_iDebug >= 1) Console.WriteLine(o.ToString()); if (s_iDebug >= 10) { byte[] p = ms.GetBuffer(); for (int _i=0; _i<ms.Length; ++_i) { Console.Write(" "); Console.Write(p[_i]); } Console.WriteLine(""); } } } #endif public abstract void Remove(); protected abstract IsolatedStoragePermission GetPermission(PermissionSet ps); [System.Security.SecuritySafeCritical] // auto-generated internal static RuntimeAssembly GetCaller() { RuntimeAssembly retAssembly = null; GetCaller(JitHelpers.GetObjectHandleOnStack(ref retAssembly)); return retAssembly; } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] private static extern void GetCaller(ObjectHandleOnStack retAssembly); } #endif // FEATURE_ISOSTORE_LIGHT }
#region License // // Copyright (c) 2007-2018, Sean Chambers <schambers80@gmail.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections.Generic; using System.Data; using FluentMigrator.Expressions; using FluentMigrator.Runner.Generators; using FluentMigrator.Runner.Generators.DB2; using FluentMigrator.Runner.Helpers; using FluentMigrator.Runner.Initialization; using JetBrains.Annotations; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace FluentMigrator.Runner.Processors.DB2 { public class Db2Processor : GenericProcessorBase { [Obsolete] public Db2Processor(IDbConnection connection, IMigrationGenerator generator, IAnnouncer announcer, IMigrationProcessorOptions options, IDbFactory factory) : base(connection, factory, generator, announcer, options) { Quoter = new Db2Quoter(); } public Db2Processor( [NotNull] Db2DbFactory factory, [NotNull] Db2Generator generator, [NotNull] Db2Quoter quoter, [NotNull] ILogger<Db2Processor> logger, [NotNull] IOptionsSnapshot<ProcessorOptions> options, [NotNull] IConnectionStringAccessor connectionStringAccessor) : base(() => factory.Factory, generator, logger, options.Value, connectionStringAccessor) { Quoter = quoter; } public override string DatabaseType => "DB2"; public override IList<string> DatabaseTypeAliases { get; } = new List<string> { "IBM DB2" }; public IQuoter Quoter { get; set; } public override bool ColumnExists(string schemaName, string tableName, string columnName) { var conditions = new List<string> { BuildEqualityComparison("TABNAME", tableName), BuildEqualityComparison("COLNAME", columnName), }; if (!string.IsNullOrEmpty(schemaName)) conditions.Add(BuildEqualityComparison("TABSCHEMA", schemaName)); var condition = string.Join(" AND ", conditions); var doesExist = Exists("SELECT COLNAME FROM SYSCAT.COLUMNS WHERE {0}", condition); return doesExist; } public override bool ConstraintExists(string schemaName, string tableName, string constraintName) { var conditions = new List<string> { BuildEqualityComparison("TABNAME", tableName), BuildEqualityComparison("CONSTNAME", constraintName), }; if (!string.IsNullOrEmpty(schemaName)) conditions.Add(BuildEqualityComparison("TABSCHEMA", schemaName)); var condition = string.Join(" AND ", conditions); return Exists("SELECT CONSTNAME FROM SYSCAT.TABCONST WHERE {0}", condition); } public override bool DefaultValueExists(string schemaName, string tableName, string columnName, object defaultValue) { var defaultValueAsString = string.Format("%{0}%", FormatHelper.FormatSqlEscape(defaultValue.ToString())); var conditions = new List<string> { BuildEqualityComparison("TABNAME", tableName), BuildEqualityComparison("COLNAME", columnName), $"\"DEFAULT\" LIKE '{defaultValueAsString}'", }; if (!string.IsNullOrEmpty(schemaName)) conditions.Add(BuildEqualityComparison("TABSCHEMA", schemaName)); var condition = string.Join(" AND ", conditions); return Exists("SELECT \"DEFAULT\" FROM SYSCAT.COLUMNS WHERE {0}", condition); } public override void Execute(string template, params object[] args) { Process(string.Format(template, args)); } public override bool Exists(string template, params object[] args) { EnsureConnectionIsOpen(); using (var command = CreateCommand(string.Format(template, args))) using (var reader = command.ExecuteReader()) { return reader.Read(); } } public override bool IndexExists(string schemaName, string tableName, string indexName) { var conditions = new List<string> { BuildEqualityComparison("TABNAME", tableName), BuildEqualityComparison("INDNAME", indexName), }; if (!string.IsNullOrEmpty(schemaName)) conditions.Add(BuildEqualityComparison("INDSCHEMA", schemaName)); var condition = string.Join(" AND ", conditions); var doesExist = Exists("SELECT INDNAME FROM SYSCAT.INDEXES WHERE {0}", condition); return doesExist; } public override void Process(PerformDBOperationExpression expression) { Logger.LogSay("Performing DB Operation"); if (Options.PreviewOnly) { return; } EnsureConnectionIsOpen(); expression.Operation?.Invoke(Connection, Transaction); } public override DataSet Read(string template, params object[] args) { EnsureConnectionIsOpen(); using (var command = CreateCommand(string.Format(template, args))) using (var reader = command.ExecuteReader()) { return reader.ReadDataSet(); } } public override DataSet ReadTableData(string schemaName, string tableName) { return Read("SELECT * FROM {0}", Quoter.QuoteTableName(tableName, schemaName)); } public override bool SchemaExists(string schemaName) { var conditions = new List<string> { BuildEqualityComparison("SCHEMANAME", schemaName), }; var condition = string.Join(" AND ", conditions); return Exists("SELECT SCHEMANAME FROM SYSCAT.SCHEMATA WHERE {0}", condition); } public override bool SequenceExists(string schemaName, string sequenceName) { return false; } public override bool TableExists(string schemaName, string tableName) { var conditions = new List<string> { BuildEqualityComparison("TABNAME", tableName), }; if (!string.IsNullOrEmpty(schemaName)) conditions.Add(BuildEqualityComparison("TABSCHEMA", schemaName)); var condition = string.Join(" AND ", conditions); return Exists("SELECT TABNAME FROM SYSCAT.TABLES WHERE {0}", condition); } protected override void Process(string sql) { Logger.LogSql(sql); if (Options.PreviewOnly || string.IsNullOrEmpty(sql)) { return; } EnsureConnectionIsOpen(); using (var command = CreateCommand(sql)) { command.ExecuteNonQuery(); } } private string BuildEqualityComparison(string columnName, string value) { if (Quoter.IsQuoted(value)) { return $"{Quoter.QuoteColumnName(columnName)}='{FormatHelper.FormatSqlEscape(Quoter.UnQuote(value))}'"; } return $"LCASE({Quoter.QuoteColumnName(columnName)})=LCASE('{FormatHelper.FormatSqlEscape(Quoter.UnQuote(value))}')"; } } }
// // Copyright (c) 2004-2018 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System.Collections.Generic; using System.Globalization; using NLog.Config; using NLog.Targets; using NLog.UnitTests.Common; namespace NLog.UnitTests.Fluent { using System; using System.IO; using Xunit; using NLog.Fluent; public class LogBuilderTests : NLogTestBase { private static readonly ILogger _logger = LogManager.GetLogger("logger1"); public LogBuilderTests() { var configuration = new LoggingConfiguration(); var t1 = new LastLogEventListTarget { Name = "t1" }; var t2 = new DebugTarget { Name = "t2", Layout = "${message}" }; configuration.AddTarget(t1); configuration.AddTarget(t2); configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, t1)); configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, t2)); LogManager.Configuration = configuration; } [Fact] public void TraceWrite() { TraceWrite_internal(() => _logger.Trace()); } #if NET4_5 [Fact] public void TraceWrite_static_builder() { TraceWrite_internal(() => Log.Trace(), true); } #endif ///<remarks> /// func because 1 logbuilder creates 1 message /// /// Caution: don't use overloading, that will break xUnit: /// CATASTROPHIC ERROR OCCURRED: /// System.ArgumentException: Ambiguous method named TraceWrite in type NLog.UnitTests.Fluent.LogBuilderTests /// </remarks> private void TraceWrite_internal(Func<LogBuilder> logBuilder, bool isStatic = false) { logBuilder() .Message("This is a test fluent message.") .Property("Test", "TraceWrite") .Write(); var loggerName = isStatic ? "LogBuilderTests" : "logger1"; { var expectedEvent = new LogEventInfo(LogLevel.Trace, loggerName, "This is a test fluent message."); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); } var ticks = DateTime.Now.Ticks; logBuilder() .Message("This is a test fluent message '{0}'.", ticks) .Property("Test", "TraceWrite") .Write(); { var rendered = $"This is a test fluent message '{ticks}'."; var expectedEvent = new LogEventInfo(LogLevel.Trace, loggerName, "This is a test fluent message '{0}'."); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessage("t2", rendered); } } [Fact] public void TraceWriteProperties() { var props = new Dictionary<string, object> { {"prop1", "1"}, {"prop2", "2"}, }; _logger.Trace() .Message("This is a test fluent message.") .Properties(props).Write(); { var expectedEvent = new LogEventInfo(LogLevel.Trace, "logger1", "This is a test fluent message."); expectedEvent.Properties["prop1"] = "1"; expectedEvent.Properties["prop2"] = "2"; AssertLastLogEventTarget(expectedEvent); } } [Fact] public void WarnWriteProperties() { var props = new Dictionary<string, object> { {"prop1", "1"}, {"prop2", "2"}, }; _logger.Warn() .Message("This is a test fluent message.") .Properties(props).Write(); { var expectedEvent = new LogEventInfo(LogLevel.Warn, "logger1", "This is a test fluent message."); expectedEvent.Properties["prop1"] = "1"; expectedEvent.Properties["prop2"] = "2"; AssertLastLogEventTarget(expectedEvent); } } [Fact] public void LogWriteProperties() { var props = new Dictionary<string, object> { {"prop1", "1"}, {"prop2", "2"}, }; _logger.Log(LogLevel.Fatal) .Message("This is a test fluent message.") .Properties(props).Write(); { var expectedEvent = new LogEventInfo(LogLevel.Fatal, "logger1", "This is a test fluent message."); expectedEvent.Properties["prop1"] = "1"; expectedEvent.Properties["prop2"] = "2"; AssertLastLogEventTarget(expectedEvent); } } [Fact] public void LogOffWriteProperties() { var props = new Dictionary<string, object> { {"prop1", "1"}, {"prop2", "2"}, }; var props2 = new Dictionary<string, object> { {"prop1", "4"}, {"prop2", "5"}, }; _logger.Log(LogLevel.Fatal) .Message("This is a test fluent message.") .Properties(props).Write(); _logger.Log(LogLevel.Off) .Message("dont log this.") .Properties(props2).Write(); { var expectedEvent = new LogEventInfo(LogLevel.Fatal, "logger1", "This is a test fluent message."); expectedEvent.Properties["prop1"] = "1"; expectedEvent.Properties["prop2"] = "2"; AssertLastLogEventTarget(expectedEvent); } } #if NET4_5 [Fact] public void LevelWriteProperties() { var props = new Dictionary<string, object> { {"prop1", "1"}, {"prop2", "2"}, }; Log.Level(LogLevel.Fatal) .Message("This is a test fluent message.") .Properties(props).Write(); { var expectedEvent = new LogEventInfo(LogLevel.Fatal, "LogBuilderTests", "This is a test fluent message."); expectedEvent.Properties["prop1"] = "1"; expectedEvent.Properties["prop2"] = "2"; AssertLastLogEventTarget(expectedEvent); } } #endif [Fact] public void TraceIfWrite() { _logger.Trace() .Message("This is a test fluent message.1") .Property("Test", "TraceWrite") .Write(); { var expectedEvent = new LogEventInfo(LogLevel.Trace, "logger1", "This is a test fluent message.1"); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); } int v = 1; _logger.Trace() .Message("This is a test fluent WriteIf message '{0}'.", DateTime.Now.Ticks) .Property("Test", "TraceWrite") .WriteIf(() => v == 1); { var expectedEvent = new LogEventInfo(LogLevel.Trace, "logger1", "This is a test fluent WriteIf message '{0}'."); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessageContains("t2", "This is a test fluent WriteIf message "); } _logger.Trace() .Message("dont write this! '{0}'.", DateTime.Now.Ticks) .Property("Test", "TraceWrite") .WriteIf(() => { return false; }); { var expectedEvent = new LogEventInfo(LogLevel.Trace, "logger1", "This is a test fluent WriteIf message '{0}'."); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessageContains("t2", "This is a test fluent WriteIf message "); } _logger.Trace() .Message("This is a test fluent WriteIf message '{0}'.", DateTime.Now.Ticks) .Property("Test", "TraceWrite") .WriteIf(v == 1); { var expectedEvent = new LogEventInfo(LogLevel.Trace, "logger1", "This is a test fluent WriteIf message '{0}'."); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessageContains("t2", "This is a test fluent WriteIf message "); } _logger.Trace() .Message("Should Not WriteIf message '{0}'.", DateTime.Now.Ticks) .Property("Test", "TraceWrite") .WriteIf(v > 1); { //previous var expectedEvent = new LogEventInfo(LogLevel.Trace, "logger1", "This is a test fluent WriteIf message '{0}'."); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessageContains("t2", "This is a test fluent WriteIf message "); } } [Fact] public void InfoWrite() { InfoWrite_internal(() => _logger.Info()); } #if NET4_5 [Fact] public void InfoWrite_static_builder() { InfoWrite_internal(() => Log.Info(), true); } #endif ///<remarks> /// func because 1 logbuilder creates 1 message /// /// Caution: don't use overloading, that will break xUnit: /// CATASTROPHIC ERROR OCCURRED: /// System.ArgumentException: Ambiguous method named TraceWrite in type NLog.UnitTests.Fluent.LogBuilderTests /// </remarks> private void InfoWrite_internal(Func<LogBuilder> logBuilder, bool isStatic = false) { logBuilder() .Message("This is a test fluent message.") .Property("Test", "InfoWrite") .Write(); var loggerName = isStatic ? "LogBuilderTests" : "logger1"; { //previous var expectedEvent = new LogEventInfo(LogLevel.Info, loggerName, "This is a test fluent message."); expectedEvent.Properties["Test"] = "InfoWrite"; AssertLastLogEventTarget(expectedEvent); } logBuilder() .Message("This is a test fluent message '{0}'.", DateTime.Now.Ticks) .Property("Test", "InfoWrite") .Write(); { //previous var expectedEvent = new LogEventInfo(LogLevel.Info, loggerName, "This is a test fluent message '{0}'."); expectedEvent.Properties["Test"] = "InfoWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessageContains("t2", "This is a test fluent message '"); } } [Fact] public void DebugWrite() { ErrorWrite_internal(() => _logger.Debug(), LogLevel.Debug); } #if NET4_5 [Fact] public void DebugWrite_static_builder() { ErrorWrite_internal(() => Log.Debug(), LogLevel.Debug, true); } #endif [Fact] public void FatalWrite() { ErrorWrite_internal(() => _logger.Fatal(), LogLevel.Fatal); } #if NET4_5 [Fact] public void FatalWrite_static_builder() { ErrorWrite_internal(() => Log.Fatal(), LogLevel.Fatal, true); } #endif [Fact] public void ErrorWrite() { ErrorWrite_internal(() => _logger.Error(), LogLevel.Error); } #if NET4_5 [Fact] public void ErrorWrite_static_builder() { ErrorWrite_internal(() => Log.Error(), LogLevel.Error, true); } #endif [Fact] public void LogBuilder_null_lead_to_ArgumentNullException() { var logger = LogManager.GetLogger("a"); Assert.Throws<ArgumentNullException>(() => new LogBuilder(null, LogLevel.Debug)); Assert.Throws<ArgumentNullException>(() => new LogBuilder(null)); Assert.Throws<ArgumentNullException>(() => new LogBuilder(logger, null)); var logBuilder = new LogBuilder(logger); Assert.Throws<ArgumentNullException>(() => logBuilder.Properties(null)); Assert.Throws<ArgumentNullException>(() => logBuilder.Property(null, "b")); } [Fact] public void LogBuilder_nLogEventInfo() { var d = new DateTime(2015, 01, 30, 14, 30, 5); var logEventInfo = new LogBuilder(LogManager.GetLogger("a")).LoggerName("b").Level(LogLevel.Fatal).TimeStamp(d).LogEventInfo; Assert.Equal("b", logEventInfo.LoggerName); Assert.Equal(LogLevel.Fatal, logEventInfo.Level); Assert.Equal(d, logEventInfo.TimeStamp); } [Fact] public void LogBuilder_exception_only() { var ex = new Exception("Exception message1"); _logger.Error() .Exception(ex) .Write(); var expectedEvent = new LogEventInfo(LogLevel.Error, "logger1", null) { Exception = ex }; AssertLastLogEventTarget(expectedEvent); } [Fact] public void LogBuilder_null_logLevel() { Assert.Throws<ArgumentNullException>(() => _logger.Error().Level(null)); } [Fact] public void LogBuilder_message_overloadsTest() { LogManager.ThrowExceptions = true; _logger.Debug() .Message("Message with {0} arg", 1) .Write(); AssertDebugLastMessage("t2", "Message with 1 arg"); _logger.Debug() .Message("Message with {0} args. {1}", 2, "YES") .Write(); AssertDebugLastMessage("t2", "Message with 2 args. YES"); _logger.Debug() .Message("Message with {0} args. {1} {2}", 3, ":) ", 2) .Write(); AssertDebugLastMessage("t2", "Message with 3 args. :) 2"); _logger.Debug() .Message("Message with {0} args. {1} {2}{3}", "more", ":) ", 2, "b") .Write(); AssertDebugLastMessage("t2", "Message with more args. :) 2b"); } [Fact] public void LogBuilder_message_cultureTest() { if (IsTravis()) { Console.WriteLine("[SKIP] LogBuilderTests.LogBuilder_message_cultureTest because we are running in Travis"); return; } LogManager.Configuration.DefaultCultureInfo = GetCultureInfo("en-US"); _logger.Debug() .Message("Message with {0} {1} {2} {3}", 4.1, 4.001, new DateTime(2016, 12, 31), true) .Write(); AssertDebugLastMessage("t2", "Message with 4.1 4.001 12/31/2016 12:00:00 AM True"); _logger.Debug() .Message(GetCultureInfo("nl-nl"), "Message with {0} {1} {2} {3}", 4.1, 4.001, new DateTime(2016, 12, 31), true) .Write(); AssertDebugLastMessage("t2", "Message with 4,1 4,001 31-12-2016 00:00:00 True"); } ///<remarks> /// func because 1 logbuilder creates 1 message /// /// Caution: don't use overloading, that will break xUnit: /// CATASTROPHIC ERROR OCCURRED: /// System.ArgumentException: Ambiguous method named TraceWrite in type NLog.UnitTests.Fluent.LogBuilderTests /// </remarks> private void ErrorWrite_internal(Func<LogBuilder> logBuilder, LogLevel logLevel, bool isStatic = false) { Exception catchedException = null; string path = "blah.txt"; try { string text = File.ReadAllText(path); } catch (Exception ex) { catchedException = ex; logBuilder() .Message("Error reading file '{0}'.", path) .Exception(ex) .Property("Test", "ErrorWrite") .Write(); } var loggerName = isStatic ? "LogBuilderTests" : "logger1"; { var expectedEvent = new LogEventInfo(logLevel, loggerName, "Error reading file '{0}'."); expectedEvent.Properties["Test"] = "ErrorWrite"; expectedEvent.Exception = catchedException; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessageContains("t2", "Error reading file '"); } logBuilder() .Message("This is a test fluent message.") .Property("Test", "ErrorWrite") .Write(); { var expectedEvent = new LogEventInfo(logLevel, loggerName, "This is a test fluent message."); expectedEvent.Properties["Test"] = "ErrorWrite"; AssertLastLogEventTarget(expectedEvent); } logBuilder() .Message("This is a test fluent message '{0}'.", DateTime.Now.Ticks) .Property("Test", "ErrorWrite") .Write(); { var expectedEvent = new LogEventInfo(logLevel, loggerName, "This is a test fluent message '{0}'."); expectedEvent.Properties["Test"] = "ErrorWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessageContains("t2", "This is a test fluent message '"); } } /// <summary> /// Test the written logevent /// </summary> /// <param name="expected">exptected event to be logged.</param> static void AssertLastLogEventTarget(LogEventInfo expected) { var target = LogManager.Configuration.FindTargetByName<LastLogEventListTarget>("t1"); Assert.NotNull(target); var lastLogEvent = target.LastLogEvent; Assert.NotNull(lastLogEvent); Assert.Equal(expected.Message, lastLogEvent.Message); Assert.NotNull(lastLogEvent.Properties); // TODO NLog ver. 5 - Remove these properties lastLogEvent.Properties.Remove("CallerMemberName"); lastLogEvent.Properties.Remove("CallerLineNumber"); lastLogEvent.Properties.Remove("CallerFilePath"); Assert.Equal(expected.Properties, lastLogEvent.Properties); Assert.Equal(expected.LoggerName, lastLogEvent.LoggerName); Assert.Equal(expected.Level, lastLogEvent.Level); Assert.Equal(expected.Exception, lastLogEvent.Exception); Assert.Equal(expected.FormatProvider, lastLogEvent.FormatProvider); } } }
// 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. #pragma warning disable 169 // There is no defined ordering between fields in multiple declarations of partial class or struct #pragma warning disable 282 using System; using System.IO; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using Internal.NativeFormat; namespace Internal.Metadata.NativeFormat { // This Enum matches CorMethodSemanticsAttr defined in CorHdr.h [Flags] public enum MethodSemanticsAttributes { Setter = 0x0001, Getter = 0x0002, Other = 0x0004, AddOn = 0x0008, RemoveOn = 0x0010, Fire = 0x0020, } // This Enum matches CorPInvokeMap defined in CorHdr.h [Flags] public enum PInvokeAttributes { NoMangle = 0x0001, CharSetMask = 0x0006, CharSetNotSpec = 0x0000, CharSetAnsi = 0x0002, CharSetUnicode = 0x0004, CharSetAuto = 0x0006, BestFitUseAssem = 0x0000, BestFitEnabled = 0x0010, BestFitDisabled = 0x0020, BestFitMask = 0x0030, ThrowOnUnmappableCharUseAssem = 0x0000, ThrowOnUnmappableCharEnabled = 0x1000, ThrowOnUnmappableCharDisabled = 0x2000, ThrowOnUnmappableCharMask = 0x3000, SupportsLastError = 0x0040, CallConvMask = 0x0700, CallConvWinapi = 0x0100, CallConvCdecl = 0x0200, CallConvStdcall = 0x0300, CallConvThiscall = 0x0400, CallConvFastcall = 0x0500, MaxValue = 0xFFFF, } public partial struct Handle { public override bool Equals(Object obj) { if (obj is Handle) return _value == ((Handle)obj)._value; else return false; } public bool Equals(Handle handle) { return _value == handle._value; } public override int GetHashCode() { return (int)_value; } internal Handle(int value) { _value = value; } internal void Validate(params HandleType[] permittedTypes) { var myHandleType = (HandleType)(_value >> 24); foreach (var hType in permittedTypes) { if (myHandleType == hType) { return; } } if (myHandleType == HandleType.Null) { return; } throw new ArgumentException("Invalid handle type"); } public Handle(HandleType type, int offset) { _value = (int)type << 24 | (int)offset; } public HandleType HandleType { get { return (HandleType)(_value >> 24); } } internal int Offset { get { return (this._value & 0x00FFFFFF); } } public bool IsNull(MetadataReader reader) { return reader.IsNull(this); } public int ToIntToken() { return _value; } public static Handle FromIntToken(int value) { return new Handle(value); } internal int _value; public override string ToString() { return String.Format("{1} : {0,8:X8}", _value, Enum.GetName(typeof(HandleType), this.HandleType)); } } public static class NativeFormatReaderExtensions { public static string GetString(this MetadataReader reader, ConstantStringValueHandle handle) { return reader.GetConstantStringValue(handle).Value; } } /// <summary> /// ConstantReferenceValue can only be used to encapsulate null reference values, /// and therefore does not actually store the value. /// </summary> public partial struct ConstantReferenceValue { /// Always returns null value. public Object Value { get { return null; } } } // ConstantReferenceValue public partial struct ConstantStringValueHandle { public bool StringEquals(string value, MetadataReader reader) { return reader.StringEquals(this, value); } } public sealed partial class MetadataReader { private MetadataHeader _header; internal NativeReader _streamReader; // Creates a metadata reader on a memory-mapped file block public unsafe MetadataReader(IntPtr pBuffer, int cbBuffer) { _streamReader = new NativeReader((byte*)pBuffer, (uint)cbBuffer); _header = new MetadataHeader(); _header.Decode(_streamReader); } /// <summary> /// Used as the root entrypoint for metadata, this is where all top-down /// structural walks of metadata must start. /// </summary> public ScopeDefinitionHandleCollection ScopeDefinitions { get { return _header.ScopeDefinitions; } } /// <summary> /// Returns a Handle value representing the null value. Can be used /// to test handle values of all types for null. /// </summary> public Handle NullHandle { get { return new Handle() { _value = ((int)HandleType.Null) << 24 }; } } /// <summary> /// Returns true if handle is null. /// </summary> public bool IsNull(Handle handle) { return handle._value == NullHandle._value; } /// <summary> /// Idempotent - simply returns the provided handle value. Exists for /// consistency so that generated code does not need to handle this /// as a special case. /// </summary> public Handle ToHandle(Handle handle) { return handle; } internal bool StringEquals(ConstantStringValueHandle handle, string value) { return _streamReader.StringEquals((uint)handle.Offset, value); } } internal partial class MetadataHeader { /// <todo> /// Signature should be updated every time the metadata schema changes. /// </todo> public const uint Signature = 0xDEADDFFD; /// <summary> /// The set of ScopeDefinitions contained within this metadata resource. /// </summary> public ScopeDefinitionHandleCollection ScopeDefinitions; public void Decode(NativeReader reader) { if (reader.ReadUInt32(0) != Signature) reader.ThrowBadImageFormatException(); reader.Read(4, out ScopeDefinitions); } } }
using EdiEngine.Common.Enums; using EdiEngine.Common.Definitions; using EdiEngine.Standards.X12_004010.Segments; namespace EdiEngine.Standards.X12_004010.Maps { public class M_841 : MapLoop { public M_841() : base(null) { Content.AddRange(new MapBaseEntity[] { new L_SPI(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 }, new L_HL(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 }, }); } //1000 public class L_SPI : MapLoop { public L_SPI(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new SPI() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new RDT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new NTE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new X1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new X2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new X7() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_REF(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_N1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //1100 public class L_REF : MapLoop { public L_REF(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new REF() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //1200 public class L_N1 : MapLoop { public L_N1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2000 public class L_HL : MapLoop { public L_HL(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new HL() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new L_SPI_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_PID(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_REF_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_LX(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_EFI(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_CID(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2100 public class L_SPI_1 : MapLoop { public L_SPI_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new SPI() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new RDT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PRR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PRT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PRS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new LIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_N1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2110 public class L_N1_1 : MapLoop { public L_N1_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new N9() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2200 public class L_PID : MapLoop { public L_PID(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new PID() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new PKD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new UIT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new LOC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new PWK() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_PKG(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2210 public class L_PKG : MapLoop { public L_PKG(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new PKG() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2300 public class L_REF_1 : MapLoop { public L_REF_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new REF() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2400 public class L_LX : MapLoop { public L_LX(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new LIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new TMD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PSD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new SPS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2500 public class L_EFI : MapLoop { public L_EFI(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new EFI() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new BIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //2600 public class L_CID : MapLoop { public L_CID(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new CID() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new UIT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new TMD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PSD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new CSS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new SPS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_MEA(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_STA(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_CSF(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_EFI_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2610 public class L_MEA : MapLoop { public L_MEA(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new MEA() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2620 public class L_STA : MapLoop { public L_STA(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new STA() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2630 public class L_CSF : MapLoop { public L_CSF(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new CSF() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new LS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_CID_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new LE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //2631 public class L_CID_1 : MapLoop { public L_CID_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new CID() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new STA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //2640 public class L_EFI_1 : MapLoop { public L_EFI_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new EFI() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new BIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } } }
#define GoogleCodeJam #define DEBUG using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; namespace CodingChallenge { // Test public class Program { #if CodeForces private static object solve() { return null; } #endif #if GoogleCodeJam static List<int[]> path; static List<int[]>[][] graph; static bool[][][][] used; static bool[][][][] golden; static int[][] visited; static int[] ringOrientation; static int n, m, k; static int len; static int gold, goldgoal; private static string solveCase() { Read(out n, out m, out k); len = m * (n * k - k + 2 + n); goldgoal = n * m / 2; n += 1; /*int[][][]*/ graph = new List<int[]>[n+1][]; graph[0] = new[] { new List<int[]>() }; graph[n] = new[] { new List<int[]>() }; for (int i = 1; i < n; i++) { graph[i] = new List<int[]>[m]; for (int j = 0; j < m; j++) { graph[i][j] = new List<int[]>() { new[] { i, (j - 1) >= 0 ? j - 1 : m - 1 }, new[] { i, (j + 1) % m } }; } } //Console.WriteLine($"n: {n}, m: {m}, k: {k}"); for (int i = 1; i < n - 1; i++) { for (int j = 0; j < m; j++) { int[] conn = ReadMany<int>(); for (int l = 0; l < k; l++) { //Console.WriteLine($"{i}, {j}, {l}"); graph[i][j].Add(new[] { i+1, conn[l] - 1 }); graph[i+1][conn[l] - 1].Add(new[] { i, j }); } } } for (int i = 0; i < m; i++) { graph[0][0].Add(new[] { 1, i }); graph[1][i].Add(new[] { 0, 0 }); graph[n][0].Add(new[] { n-1, i }); graph[n-1][i].Add(new[] { n, 0 }); } //for (int i = 0; i <= n; i++) { // for (int j = 0; j < graph[i].Length; j++) { // //Console.Write($"({i}, {j}): [ "); // //Console.Write(String.Join(", ", graph[i][j].Select(lst => String.Join(" ", lst)))); // //Console.WriteLine(" ]"); // } //} // Did I visit this node? // If yes, how often? visited = new int[n+1][]; for (int l = 0; l < visited.Length; l++) { visited[l] = new int[m]; } // Did I use that edge? used = new bool[n][][][]; for (int i = 0; i < n; i++) { used[i] = new bool[m][][]; for (int j = 0; j < m; j++) { used[i][j] = new bool[n+1][]; for (int l = 0; l < n+1; l++) { used[i][j][l] = new bool[m]; } } } // GOGOGOGOOOGOGOOGOGOGOGOGOOGOGOOGOGOOGOGOOOGOGOGOGOGOGOOG // Holds whether the rings goes from (0 to 1) (1) or // (1 to 2) (-1) or // not spec (0) ringOrientation = new int[n]; path = new List<int[]>(); gold = 0; DFS(new[] { 0, 0 }); //return "WTH"; string number1 = String.Join("\n", path.Select(x => x[0] + " " + (x[0] == 0 || x[0] == n ? 0 : (x[1] + 1)))); // Did I visit this node? // If yes, how often? visited = new int[n+1][]; for (int l = 0; l < visited.Length; l++) { visited[l] = new int[m]; } // Did I use that edge? used = new bool[n][][][]; golden = new bool[n][][][]; for (int i = 0; i < n; i++) { used[i] = new bool[m][][]; golden[i] = new bool[m][][]; for (int j = 0; j < m; j++) { used[i][j] = new bool[n+1][]; golden[i][j] = new bool[n+1][]; for (int l = 0; l < n+1; l++) { used[i][j][l] = new bool[m]; golden[i][j][l] = new bool[m]; } } } for (int i = 0; i < n; i++) { ringOrientation[i] = -ringOrientation[i]; } bool[][] seen = new bool[n+1][]; seen[0] = new[] { true }; seen[n] = new[] { false }; for (int i = 1; i <= n; i++) { seen[i] = new bool[m]; } int[] prev = new[] { 0, 0 }; for (int i = 0; i < path.Count; i++) { int[] node = path[i]; Console.WriteLine($"Looking at: ({node[0]}, {node[1] + 1})"); if (seen[node[0]][node[1]]) { // do nothing } else { int[] smaller = smallerArr(node, prev); int[] larger = node[0] == smaller[0] && node[1] == smaller[1] ? prev : node; golden[smaller[0]][smaller[1]][larger[0]][larger[1]] = true; Console.WriteLine($"{node[0] == prev[0] ? "---------------------------" : ""}marked: ({prev[0]}, {prev[1] + 1}) to ({node[0]}, {node[1] + 1}) as golden"); seen[node[0]][node[1]] = true; } prev = node; } path = new List<int[]>(); gold = 0; Console.WriteLine("START 2"); modifiedDFS(new[] { 0, 0 }); //Console.WriteLine(path.Count); string number2 = String.Join("\n", path.Select(x => x[0] + " " + (x[0] == 0 || x[0] == n ? 0 : (x[1] + 1)))); return number1 + "\n" + number2; } static int[] smallerArr(int[] a, int[] b) { if (a[0] < b[0]) return a; else if (b[0] < a[0]) return b; else if (a[1] < b[1]) return a; else return b; } #endif static void DFS(int[] pos) { if (path.Count == len) return; if (path.Count == len - 1 && gold == goldgoal) { if (pos[0] == 1) { path.Add(new[] { 0, 0 }); return; } } //Console.WriteLine($"Inspecting current position: ({pos[0]}, {pos[1]}). Depth: {path.Count}"); foreach (Tuple<int[], bool> nn in ValidNeighbors(pos)) { int[] neighbor = nn.Item1; bool setOrient = nn.Item2; int[] smaller = smallerArr(pos, neighbor); int[] larger = smaller[0] == pos[0] && smaller[1] == pos[1] ? neighbor : pos; //if (used[smaller[0]][smaller[1]][larger[0]][larger[1]]) { // continue; //} visited[neighbor[0]][neighbor[1]]++; path.Add(neighbor); used[smaller[0]][smaller[1]][larger[0]][larger[1]] = true; if (neighbor[0] == pos[0] && visited[neighbor[0]][neighbor[1]] == 1) gold++; //Console.WriteLine($" current neighbor: ({neighbor[0]}, {neighbor[1]})"); //Console.WriteLine($" marking edge: ({smaller[0]}, {smaller[1]}) to ({larger[0]}, {larger[1]})"); //Console.ReadLine(); DFS(neighbor); if (path.Count == len && gold == goldgoal) break; //Console.WriteLine($" blocked at ({pos[0]}, {pos[1]}), backtracking"); if (setOrient) ringOrientation[pos[0]] = 0; path.RemoveAt(path.Count - 1); visited[neighbor[0]][neighbor[1]]--; if (neighbor[0] == pos[0] && visited[neighbor[0]][neighbor[1]] == 0) gold--; used[smaller[0]][smaller[1]][larger[0]][larger[1]] = false; } //Console.WriteLine("DEBUG: Done with position " + pos[0] + ", " + pos[1]); } // Return the possible neighbors of this thing static IEnumerable<Tuple<int[], bool>> ValidNeighbors(int[] pos) { for (int i = 0; i < graph[pos[0]][pos[1]].Count; i++) { int[] neighbor = graph[pos[0]][pos[1]][i]; //Console.WriteLine($" current neighbor: ({neighbor[0]}, {neighbor[1]})"); //Console.WriteLine($"pos != null? {pos != null}, neigh != null? {neighbor != null}"); int[] smArr = smallerArr(pos, neighbor); int[] laArr = smArr[0] == pos[0] && smArr[1] == pos[1] ? neighbor : pos; //Console.WriteLine($"sm: [{smArr[0]}, {smArr[1]}], la: [{laArr[0]}, {laArr[1]}]"); if (used[smArr[0]][smArr[1]][laArr[0]][laArr[1]]) { //Console.WriteLine(" rejecting"); continue; } // We are in the current ring if (neighbor[0] == pos[0]) { int smaller = Math.Min(neighbor[1], pos[1]); int larger = Math.Max(neighbor[1], pos[1]); int dir = (smaller % 2 == 0 && larger - smaller == 1) ? 1 : -1; if (ringOrientation[pos[0]] == dir) { yield return Tuple.Create(neighbor, false); // rings go 1 to 2 and so on } else if (ringOrientation[pos[0]] != 0) { if (visited[neighbor[0]][neighbor[1]] > 0) { yield return Tuple.Create(neighbor, false); } } else /*if (ringOrientation[pos[0]] == 0)*/ { // We can choose ringOrientation[pos[0]] = dir; yield return Tuple.Create(neighbor, true); } } else { yield return Tuple.Create(neighbor, false); } } } static void modifiedDFS(int[] pos) { if (path.Count == len) return; if (path.Count == len - 1) { if (pos[0] == 1) { path.Add(new[] { 0, 0 }); return; } } //Console.WriteLine($"Inspecting current position: ({pos[0]}, {pos[1]}). Depth: {path.Count}"); foreach (int[] neighbor in modValidNeighbors(pos)) { int[] smaller = smallerArr(pos, neighbor); int[] larger = smaller[0] == pos[0] && smaller[1] == pos[1] ? neighbor : pos; //if (used[smaller[0]][smaller[1]][larger[0]][larger[1]]) { // continue; //} visited[neighbor[0]][neighbor[1]]++; path.Add(neighbor); used[smaller[0]][smaller[1]][larger[0]][larger[1]] = true; Console.WriteLine($" current neighbor: ({neighbor[0]}, {neighbor[1]})"); Console.WriteLine($" marking edge: ({smaller[0]}, {smaller[1]}) to ({larger[0]}, {larger[1]})"); //Console.ReadLine(); modifiedDFS(neighbor); if (path.Count == len) break; //Console.WriteLine($" blocked at ({pos[0]}, {pos[1]}), backtracking"); path.RemoveAt(path.Count - 1); visited[neighbor[0]][neighbor[1]]--; used[smaller[0]][smaller[1]][larger[0]][larger[1]] = false; } //Console.WriteLine("DEBUG: Done with position " + pos[0] + ", " + pos[1]); } // Return the possible neighbors of this thing static IEnumerable<int[]> modValidNeighbors(int[] pos) { for (int i = 0; i < graph[pos[0]][pos[1]].Count; i++) { int[] neighbor = graph[pos[0]][pos[1]][i]; int[] smArr = smallerArr(pos, neighbor); int[] laArr = smArr[0] == pos[0] && smArr[1] == pos[1] ? neighbor : pos; if (used[smArr[0]][smArr[1]][laArr[0]][laArr[1]]) { continue; } // We are in the current ring if (neighbor[0] == pos[0]) { int smaller = Math.Min(neighbor[1], pos[1]); int larger = Math.Max(neighbor[1], pos[1]); int dir = (smaller % 2 == 0 && larger - smaller == 1) ? 1 : -1; if (ringOrientation[pos[0]] == dir) { yield return neighbor; // rings go 1 to 2 and so on } else if (ringOrientation[pos[0]] != 0) { if (visited[neighbor[0]][neighbor[1]] > 0) { yield return neighbor; } } } else { if (!golden[smArr[0]][smArr[1]][laArr[0]][laArr[1]] || visited[neighbor[0]][neighbor[1]] > 0) { //Console.WriteLine($"Going to: {neighbor[0]}, {neighbor[1]}"); yield return neighbor; } } } } private static Queue<string> testqueue = new Queue<string>(@" 3 2 4 1 1 2 3 4 3 4 1 1 2 3 4 1 2 3 4 1 6 1 ".Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)); //1 20 1 //2 6 3 //1 3 5 //2 4 6 //1 3 5 //2 4 6 //1 3 5 //2 4 6 // *********************** HERE BE BOILERPLATE *********************** // #region input private static void Read<T>(out T t) { t = Read<T>(); } private static void Read<T, S>(out T t, out S s) { string[] vals = ReadMany<string>(); t = (T)Convert.ChangeType(vals[0], typeof(T)); s = (S)Convert.ChangeType(vals[1], typeof(S)); } private static void Read<T, S, R>(out T t, out S s, out R r) { string[] vals = ReadMany<string>(); t = (T)Convert.ChangeType(vals[0], typeof(T)); s = (S)Convert.ChangeType(vals[1], typeof(S)); r = (R)Convert.ChangeType(vals[2], typeof(R)); } private static void Read<T, S, R, A>(out T t, out S s, out R r, out A a) { string[] vals = ReadMany<string>(); t = (T)Convert.ChangeType(vals[0], typeof(T)); s = (S)Convert.ChangeType(vals[1], typeof(S)); r = (R)Convert.ChangeType(vals[2], typeof(R)); a = (A)Convert.ChangeType(vals[3], typeof(A)); } private static void Read<T, S, R, A, B>(out T t, out S s, out R r, out A a, out B b) { string[] vals = ReadMany<string>(); t = (T)Convert.ChangeType(vals[0], typeof(T)); s = (S)Convert.ChangeType(vals[1], typeof(S)); r = (R)Convert.ChangeType(vals[2], typeof(R)); a = (A)Convert.ChangeType(vals[3], typeof(A)); b = (B)Convert.ChangeType(vals[4], typeof(B)); } private static T Read<T>() { return (T)Convert.ChangeType(Read(), typeof(T)); } private static T[] ReadMany<T>(char[] sep = null) { return Read<string>().Split(sep ?? new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => (T)Convert.ChangeType(x, typeof(T))).ToArray(); } private static T[][] ReadField<T>(int len, char[] sep = null) { T[][] result = new T[len][]; for (int i = 0; i < len; i++) { result[i] = ReadMany<T>(sep); } return result; } #endregion #region dynamic programming private static Func<A, B> DP<A, B>(Func<A, Func<A, B>, B> f) { Dictionary<A, B> cache = new Dictionary<A, B>(); Func<A, B> res = null; res = a => { if (!cache.ContainsKey(a)) cache.Add(a, f(a, res)); return cache[a]; }; return res; } private static Func<A, B, C> DP<A, B, C>(Func<A, B, Func<A, B, C>, C> f) { Dictionary<Tuple<A, B>, C> cache = new Dictionary<Tuple<A, B>, C>(); Func<A, B, C> res = null; res = (a, b) => { Tuple<A, B> t = Tuple.Create(a, b); if (!cache.ContainsKey(t)) cache.Add(t, f(a, b, res)); return cache[t]; }; return res; } private static Func<A, B, C, D> DP<A, B, C, D>(Func<A, B, C, Func<A, B, C, D>, D> f) { Dictionary<Tuple<A, B, C>, D> cache = new Dictionary<Tuple<A, B, C>, D>(); Func<A, B, C, D> res = null; res = (a, b, c) => { Tuple<A, B, C> t = Tuple.Create(a, b, c); if (!cache.ContainsKey(t)) cache.Add(t, f(a, b, c, res)); return cache[t]; }; return res; } private static Func<A, B, C, D, E> DP<A, B, C, D, E>(Func<A, B, C, D, Func<A, B, C, D, E>, E> f) { Dictionary<Tuple<A, B, C, D>, E> cache = new Dictionary<Tuple<A, B, C, D>, E>(); Func<A, B, C, D, E> res = null; res = (a, b, c, d) => { Tuple<A, B, C, D> t = Tuple.Create(a, b, c, d); if (!cache.ContainsKey(t)) cache.Add(t, f(a, b, c, d, res)); return cache[t]; }; return res; } #endregion #region utils private static IEnumerable<int> Range(int start, int stop, int step) { for (int l = start; start <= stop; l+=step) yield return l; } private static IEnumerable<long> Range(long start, long stop, long step) { for (long l = start; start <= stop; l+=step) yield return l; } public static T[][] NewArray<T>(int x, int y) { T[][] res = new T[x][]; for (int i = 0; i < x; i++) res[i] = new T[y]; return res; } public static T[][][] NewArray<T>(int x, int y, int z) { T[][][] res = new T[x][][]; for (int i = 0; i < x; i++) { res[i] = new T[y][]; for (int j = 0; j < y; j++) res[i][j] = new T[z]; } return res; } #endregion #if GoogleCodeJam private static StreamReader inf; private static StreamReader outf; private delegate void o(string format, params object[] args); private static o Output; private static void Init() { const string downloads = "/home/ben/downloads/"; #if !DEBUG Console.Write($"Download folder prefix: {downloads}\nEnter file to read from: "); StreamReader inf = new StreamReader(Console.ReadLine()); Console.Write("Enter file to write to (in current directory): "); StreamWriter outf = new StreamWriter(Console.ReadLine()); #endif Output += highlightedPrinting; #if !DEBUG Output += outf.WriteLine; #endif } private static void highlightedPrinting(string format, params object[] args) { ConsoleColor c = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(format, args); Console.ForegroundColor = c; } public static void Main(string[] args) { Init(); int n = Read<int>(); for (int i = 1; i <= n; i++) Output($"Case #{i}: {solveCase()}"); #if !DEBUG inf.Close(); outf.Close(); #endif Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Done!"); } private static string Read() { #if DEBUG return testqueue.Dequeue(); #else return inf.ReadLine(); #endif } #endif #if CodeForces private static string show(object o) { IEnumerable e = o as IEnumerable; if (e != null && !(e is string)) { // Don't do this with nested arrays return string.Join(" ", e.OfType<object>().Select(show)); } else if (o is double) { return ((double)o).ToString("0.000000000", CultureInfo.InvariantCulture); } else { return o.ToString(); } } public static void Main(string[] args) { #if DEBUG Stopwatch sw = new Stopwatch(); sw.Start(); #endif object res = solve(); string s = show(res); if (!string.IsNullOrEmpty(s)) Console.WriteLine(s); #if DEBUG sw.Stop(); Console.WriteLine(sw.Elapsed); #endif } private static string Read() { #if DEBUG return testqueue.Dequeue(); #else return Console.ReadLine(); #endif } #endif } static class Extensions { public static IEnumerable<T> Times<T>(this int n, Func<T> f) { for (int i = 0; i < n; i++) yield return f(); } public static IEnumerable<T> Times<T>(this int n, Func<int, T> f) { for (int i = 0; i < n; i++) yield return f(i); } #region binary search (SearchBinary) public static int SearchBinary<T>(this IList<T> array, T elem, bool highest = false) where T : IComparable<T> { return array.SearchBinary(elem, 0, array.Count - 1, highest); } public static int SearchBinary<T>(this IList<T> array, T elem, int low, int high, bool getHighest) where T : IComparable<T> { while (low <= high) { int m = (low + high) / 2; if (elem.Equals(array[m])) { while (m >= 0 && m < array.Count && elem.Equals(array[m])) m += getHighest ? 1 : -1; return m; } if (elem.CompareTo(array[m]) < 0) high = m - 1; else low = m + 1; } return -1; } public static int SearchBinary<T>(this Func<int, T> map, T elem, int low, int high, bool highest = false) where T : IComparable<T> { while (low <= high) { int m = (low + high) / 2; T k = map(m); if (elem.Equals(k)) { // use pre-in/decrement because of oder of operations while (elem.Equals(k)) k = map(highest ? ++m : --m); return m; } if (elem.CompareTo(k) < 0) high = m - 1; else low = m + 1; } return int.MinValue; } #endregion #region cartesian product public static IEnumerable<C> Cartesian<A, B, C>(this IEnumerable<A> a, IEnumerable<B> b, Func<A, B, C> f) { return a.SelectMany(aa => b.Select(bb => f(aa, bb))); } public static IEnumerable<Tuple<A, B>> Cartesian<A, B>(this IEnumerable<A> a, IEnumerable<B> b) { return a.Cartesian(b, Tuple.Create); } public static IEnumerable<Tuple<A, B, C>> Cartesian<A, B, C>(this IEnumerable<Tuple<A, B>> ab, IEnumerable<C> c) { return ab.Cartesian(c, (t, cc) => Tuple.Create(t.Item1, t.Item2, cc)); } public static IEnumerable<Tuple<A, B, C, D>> Cartesian<A, B, C, D>(this IEnumerable<Tuple<A, B, C>> abc, IEnumerable<D> d) { return abc.Cartesian(d, (t, dd) => Tuple.Create(t.Item1, t.Item2, t.Item3, dd)); } public static IEnumerable<Tuple<A, B, C, D, E>> Cartesian<A, B, C, D, E>(this IEnumerable<Tuple<A, B, C, D>> abcd, IEnumerable<E> e) { return abcd.Cartesian(e, (t, ee) => Tuple.Create(t.Item1, t.Item2, t.Item3, t.Item4, ee)); } #endregion #region haskell list funcs // Haskell's sequence public static IEnumerable<IEnumerable<T>> Sequence<T>(this IEnumerable<IEnumerable<T>> seq) { IEnumerable<T>[] arr = seq as IEnumerable<T>[] ?? seq.ToArray(); IEnumerable<IEnumerable<T>> res = arr.First().Select(Pure); foreach (IEnumerable<T> sequence in seq.Skip(1)) { res = res.Cartesian(sequence, (cur, s) => cur.Concat(Pure(s))); } return res; } // Haskell's replicateM (generate all words from an alphabet) public static IEnumerable<IEnumerable<T>> ReplicateM<T>(this IEnumerable<T> en, int num) { return Enumerable.Repeat(en, num).Sequence(); } public static IEnumerable<T> Demask<T>(this IEnumerable<Tuple<T, bool>> en) { return en.Where(t => t.Item2).Select(t => t.Item1); } public static IEnumerable<IEnumerable<T>> Powerset<T>(IEnumerable<T> en) { T[] inp = en.ToArray(); foreach (IEnumerable<bool> config in new[] { true, false }.ReplicateM(inp.Length)) { yield return inp.Zip(config, Tuple.Create).Demask(); } } #endregion #region utils private static IEnumerable<T> Pure<T>(T item) { yield return item; } private static T Id<T>(T t) { return t; } #endregion #region reshaping public static T[][] Reshape<T>(this IEnumerable<T> seq, int x, int y) { int i = 0, j = 0; T[][] res = Program.NewArray<T>(x, y); while (true) { foreach(T item in seq) { res[i][j] = item; j++; if (j == y) { i++; j = 0; if (i == x) break; } } if (i == x) break; } return res; } public static T[][][] Reshape<T>(this IEnumerable<T> seq, int x, int y, int z) { int i = 0, j = 0, k = 0; T[][][] res = Program.NewArray<T>(x, y, z); while (true) { foreach(T item in seq) { res[i][j][k] = item; k++; if (k == z) { j++; k = 0; if (j == y) { i++; j = 0; if (i == x) break; } } } if (i == x) break; } return res; } #endregion } }
using System.Threading.Tasks; using Baseline.Dates; using IntegrationTests; using Jasper.Persistence; using Jasper.Persistence.Marten; using Jasper.Tracking; using Jasper.Util; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Shouldly; using TestingSupport; using TestingSupport.Compliance; using Weasel.Postgresql; using Xunit; namespace Jasper.AzureServiceBus.Tests { public class end_to_end { // TODO -- make this puppy be pulled from an environment variable? Something ignored? public const string ConnectionString = "Endpoint=sb://jaspertest.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=tYfuj6uX/L2kolyKi+dc7Jztu45vHVp4wf3W+YBoXHc="; // SAMPLE: can_stop_and_start_ASB [Fact] public async Task can_stop_and_start() { using (var host = JasperHost.For<ASBUsingApp>()) { await host // The TrackActivity() method starts a Fluent Interface // that gives you fine-grained control over the // message tracking .TrackActivity() .Timeout(30.Seconds()) // Include the external transports in the determination // of "completion" .IncludeExternalTransports() .SendMessageAndWait(new ColorChosen {Name = "Red"}); var colors = host.Get<ColorHistory>(); colors.Name.ShouldBe("Red"); } } // ENDSAMPLE [Fact] public async Task schedule_send_message_to_and_receive_through_asb_with_durable_transport_option() { var publisher = JasperHost.For(_ => { _.Endpoints.ConfigureAzureServiceBus(ConnectionString); _.Endpoints.PublishAllMessages().ToAzureServiceBusQueue("messages").Durably(); _.Extensions.UseMarten(opts => { opts.Connection(Servers.PostgresConnectionString); opts.AutoCreateSchemaObjects = AutoCreate.All; opts.DatabaseSchemaName = "sender"; }); _.Extensions.UseMessageTrackingTestingSupport(); }); await publisher.RebuildMessageStorage(); var receiver = JasperHost.For(_ => { _.Handlers.IncludeType<ColorHandler>(); _.Endpoints.ConfigureAzureServiceBus(ConnectionString); _.Endpoints.ListenToAzureServiceBusQueue("messages"); _.Extensions.UseMessageTrackingTestingSupport(); _.Services.AddSingleton<ColorHistory>(); _.Extensions.UseMarten(opts => { opts.Connection(Servers.PostgresConnectionString); opts.AutoCreateSchemaObjects = AutoCreate.All; opts.DatabaseSchemaName = "receiver"; }); }); await receiver.RebuildMessageStorage(); try { await publisher .TrackActivity() .AlsoTrack(receiver) .Timeout(15.Seconds()) .ExecuteAndWait(c => c.ScheduleSend(new ColorChosen {Name = "Orange"}, 5.Seconds())); receiver.Get<ColorHistory>().Name.ShouldBe("Orange"); } finally { publisher.Dispose(); receiver.Dispose(); } } [Fact] public async Task send_message_to_and_receive_through_asb() { using (var runtime = JasperHost.For<ASBUsingApp>()) { await runtime .TrackActivity() .IncludeExternalTransports() .SendMessageAndWait(new ColorChosen {Name = "Red"}); var colors = runtime.Get<ColorHistory>(); colors.Name.ShouldBe("Red"); } } [Fact] public async Task send_message_to_and_receive_through_asb_with_durable_transport_option() { var publisher = JasperHost.For(_ => { _.Endpoints.ConfigureAzureServiceBus(ConnectionString); _.Endpoints.PublishAllMessages().ToAzureServiceBusQueue("messages").Durably(); _.Extensions.UseMarten(opts => { opts.Connection(Servers.PostgresConnectionString); opts.AutoCreateSchemaObjects = AutoCreate.All; opts.DatabaseSchemaName = "sender"; }); _.Extensions.UseMessageTrackingTestingSupport(); }); await publisher.RebuildMessageStorage(); var receiver = JasperHost.For(_ => { _.Endpoints.ConfigureAzureServiceBus(ConnectionString); _.Endpoints.ListenToAzureServiceBusQueue("messages").DurablyPersistedLocally(); _.Services.AddSingleton<ColorHistory>(); _.Extensions.UseMessageTrackingTestingSupport(); _.Extensions.UseMarten(opts => { opts.Connection(Servers.PostgresConnectionString); opts.AutoCreateSchemaObjects = AutoCreate.All; opts.DatabaseSchemaName = "receiver"; }); _.Handlers.IncludeType<ColorHandler>(); }); await receiver.RebuildMessageStorage(); try { await publisher .TrackActivity() .AlsoTrack(receiver) .Timeout(30.Seconds()) .SendMessageAndWait(new ColorChosen {Name = "Orange"}); receiver.Get<ColorHistory>().Name.ShouldBe("Orange"); } finally { publisher.Dispose(); receiver.Dispose(); } } [Fact] public async Task send_message_to_and_receive_through_asb_with_named_topic() { var publisher = JasperHost.For(_ => { _.Endpoints.ConfigureAzureServiceBus(ConnectionString); _.Endpoints.PublishAllMessages().ToAzureServiceBusTopic("special").Durably(); _.Extensions.UseMarten(opts => { opts.Connection(Servers.PostgresConnectionString); opts.AutoCreateSchemaObjects = AutoCreate.All; opts.DatabaseSchemaName = "sender"; }); _.Extensions.UseMessageTrackingTestingSupport(); }); await publisher.RebuildMessageStorage(); var receiver = JasperHost.For(_ => { _.Endpoints.ConfigureAzureServiceBus(ConnectionString); _.Endpoints.ListenToAzureServiceBusTopic("special", "receiver"); _.Services.AddSingleton<ColorHistory>(); _.Extensions.UseMessageTrackingTestingSupport(); _.Extensions.UseMarten(opts => { opts.Connection(Servers.PostgresConnectionString); opts.AutoCreateSchemaObjects = AutoCreate.All; opts.DatabaseSchemaName = "receiver"; }); _.Handlers.IncludeType<ColorHandler>(); }); await receiver.RebuildMessageStorage(); try { await publisher .TrackActivity() .AlsoTrack(receiver) .SendMessageAndWait(new ColorChosen {Name = "Orange"}); receiver.Get<ColorHistory>().Name.ShouldBe("Orange"); } finally { publisher.Dispose(); receiver.Dispose(); } } public class Sender : JasperOptions { public Sender() { Endpoints.ConfigureAzureServiceBus(ConnectionString); Endpoints.ListenToAzureServiceBusQueue("replies").UseForReplies(); } public string QueueName { get; set; } } public class Receiver : JasperOptions { public Receiver(string queueName) { Endpoints.ConfigureAzureServiceBus(ConnectionString); Endpoints.ListenToAzureServiceBusQueue("messages"); } } public class AzureServiceBusSendingFixture : SendingComplianceFixture, IAsyncLifetime { public AzureServiceBusSendingFixture() : base("asb://queue/messages".ToUri()) { } public async Task InitializeAsync() { var sender = new Sender(); await SenderIs(sender); var receiver = new Receiver(sender.QueueName); await ReceiverIs(receiver); } public Task DisposeAsync() { return Task.CompletedTask; } } public class AzureServiceBusSendingComplianceTests : SendingCompliance<AzureServiceBusSendingFixture> { } } public class ASBUsingApp : JasperOptions { public ASBUsingApp() { Endpoints.ListenToAzureServiceBusQueue("messages"); Endpoints.PublishAllMessages().ToAzureServiceBusQueue("messages"); Endpoints.ConfigureAzureServiceBus(end_to_end.ConnectionString); Handlers.IncludeType<ColorHandler>(); Services.AddSingleton<ColorHistory>(); Extensions.UseMessageTrackingTestingSupport(); } public override void Configure(IHostEnvironment hosting, IConfiguration config) { //Endpoints.ConfigureAzureServiceBus(config.GetValue<string>("AzureServiceBusConnectionString")); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using JetBrains.Application.Settings; using JetBrains.Diagnostics; using JetBrains.ReSharper.Daemon.CSharp.Stages; using JetBrains.ReSharper.Daemon.VisualElements; using JetBrains.ReSharper.Feature.Services.Daemon; using JetBrains.ReSharper.Plugins.Unity.CSharp.Psi.Colors; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.Colors; using JetBrains.ReSharper.Psi.CSharp.Conversions; using JetBrains.ReSharper.Psi.CSharp.Tree; using JetBrains.ReSharper.Psi.Tree; using JetBrains.Util.Media; #nullable enable namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Daemon.Stages.Color { public class UnityColorHighlighterProcess : CSharpIncrementalDaemonStageProcessBase { public UnityColorHighlighterProcess(IDaemonProcess process, IContextBoundSettingsStore settingsStore, ICSharpFile file) : base(process, settingsStore, file) { } public override void VisitNode(ITreeNode element, IHighlightingConsumer consumer) { if (element is ITokenNode tokenNode && tokenNode.GetTokenType().IsWhitespace) return; var colorInfo = CreateColorHighlightingInfo(element); if (colorInfo != null) consumer.AddHighlighting(colorInfo.Highlighting, colorInfo.Range); } private HighlightingInfo? CreateColorHighlightingInfo(ITreeNode element) { var colorReference = GetColorReference(element); var range = colorReference?.ColorConstantRange; return range?.IsValid() == true ? new HighlightingInfo(range.Value, new ColorHighlighting(colorReference)) : null; } private static IColorReference? GetColorReference(ITreeNode element) { if (element is IObjectCreationExpression constructorExpression) return ReferenceFromConstructor(constructorExpression); var referenceExpression = element as IReferenceExpression; if (referenceExpression?.QualifierExpression is not IReferenceExpression qualifier) return null; return ReferenceFromInvocation(qualifier, referenceExpression) ?? ReferenceFromProperty(qualifier, referenceExpression); } private static IColorReference? ReferenceFromConstructor(IObjectCreationExpression constructorExpression) { // Get the type from the constructor, which allows us to support target typed new. This will fail to resolve // if the parameters don't match (e.g. calling new Color32(r, g, b) without passing a), so fall back to the // expression's type, if available. // Note that we don't do further validation of the parameters, so we'll still show a colour preview for // Color32(r, g, b) even though it's an invalid method call. var constructedType = (constructorExpression.ConstructorReference.Resolve().DeclaredElement as IConstructor)?.ContainingType ?? constructorExpression.TypeReference?.Resolve().DeclaredElement as ITypeElement; if (constructedType == null) return null; var unityColorTypes = UnityColorTypes.GetInstance(constructedType.Module); if (!unityColorTypes.IsUnityColorType(constructedType)) return null; var arguments = constructorExpression.Arguments; if (arguments.Count is < 3 or > 4) return null; JetRgbaColor? color = null; if (unityColorTypes.UnityColorType != null && unityColorTypes.UnityColorType.Equals(constructedType)) { var baseColor = GetColorFromFloatARGB(arguments); if (baseColor == null) return null; var (a, rgb) = baseColor.Value; color = a.HasValue ? rgb.WithA((byte)(255.0 * a)) : rgb; } else if (unityColorTypes.UnityColor32Type != null && unityColorTypes.UnityColor32Type.Equals(constructedType)) { var baseColor = GetColorFromIntARGB(arguments); if (baseColor == null) return null; var (a, rgb) = baseColor.Value; color = a.HasValue ? rgb.WithA((byte)a) : rgb; } if (color == null) return null; var colorElement = new ColorElement(color.Value); var argumentList = constructorExpression.ArgumentList; return new UnityColorReference(colorElement, constructorExpression, argumentList, argumentList.GetDocumentRange()); } private static IColorReference? ReferenceFromInvocation(IReferenceExpression qualifier, IReferenceExpression methodReferenceExpression) { var invocationExpression = InvocationExpressionNavigator.GetByInvokedExpression(methodReferenceExpression); if (invocationExpression == null || invocationExpression.Arguments.IsEmpty) return null; var methodReference = methodReferenceExpression.Reference; var name = methodReference.GetName(); if (!string.Equals(name, "HSVToRGB", StringComparison.Ordinal)) return null; var arguments = invocationExpression.Arguments; if (arguments.Count is < 3 or > 4) return null; var color = GetColorFromHSV(arguments); if (color == null) return null; var qualifierType = qualifier.Reference.Resolve().DeclaredElement as ITypeElement; if (qualifierType == null) return null; var unityColorTypes = UnityColorTypes.GetInstance(qualifierType.Module); if (!unityColorTypes.IsUnityColorTypeSupportingHSV(qualifierType)) return null; var colorElement = new ColorElement(color.Value); var argumentList = invocationExpression.ArgumentList; return new UnityColorReference(colorElement, invocationExpression, argumentList, argumentList.GetDocumentRange()); } private static IColorReference? ReferenceFromProperty(IReferenceExpression qualifier, IReferenceExpression colorQualifiedMemberExpression) { var name = colorQualifiedMemberExpression.Reference.GetName(); var color = UnityNamedColors.Get(name); if (color == null) return null; var qualifierType = qualifier.Reference.Resolve().DeclaredElement as ITypeElement; if (qualifierType == null) return null; var unityColorTypes = UnityColorTypes.GetInstance(qualifierType.Module); if (!unityColorTypes.IsUnityColorTypeSupportingProperties(qualifierType)) return null; var property = colorQualifiedMemberExpression.Reference.Resolve().DeclaredElement as IProperty; if (property == null) return null; var colorElement = new ColorElement(color.Value, name); return new UnityColorReference(colorElement, colorQualifiedMemberExpression, colorQualifiedMemberExpression, colorQualifiedMemberExpression.NameIdentifier.GetDocumentRange()); } private static (float? alpha, JetRgbaColor)? GetColorFromFloatARGB(ICollection<ICSharpArgument> arguments) { var a = GetArgumentAsFloatConstant(arguments, "a", 0, 1); var r = GetArgumentAsFloatConstant(arguments, "r", 0, 1); var g = GetArgumentAsFloatConstant(arguments, "g", 0, 1); var b = GetArgumentAsFloatConstant(arguments, "b", 0, 1); if (!r.HasValue || !g.HasValue || !b.HasValue) return null; return (a, JetRgbaColor.FromRgb((byte)(255.0 * r.Value), (byte)(255.0 * g.Value), (byte)(255.0 * b.Value))); } private static (int? alpha, JetRgbaColor)? GetColorFromIntARGB(ICollection<ICSharpArgument> arguments) { var a = GetArgumentAsIntConstant(arguments, "a", 0, 255); var r = GetArgumentAsIntConstant(arguments, "r", 0, 255); var g = GetArgumentAsIntConstant(arguments, "g", 0, 255); var b = GetArgumentAsIntConstant(arguments, "b", 0, 255); if (!r.HasValue || !g.HasValue || !b.HasValue) return null; return (a, JetRgbaColor.FromRgb((byte)r.Value, (byte)g.Value, (byte)b.Value)); } private static JetRgbaColor? GetColorFromHSV(ICollection<ICSharpArgument> arguments) { var h = GetArgumentAsFloatConstant(arguments, "H", 0, 1); var s = GetArgumentAsFloatConstant(arguments, "S", 0, 1); var v = GetArgumentAsFloatConstant(arguments, "V", 0, 1); if (!h.HasValue || !s.HasValue || !v.HasValue) return null; return ColorUtils.ColorFromHSV(h.Value, s.Value, v.Value); } private static float? GetArgumentAsFloatConstant(IEnumerable<ICSharpArgument> arguments, string parameterName, float min, float max) { var namedArgument = GetNamedArgument(arguments, parameterName); if (namedArgument == null) return null; var matchingParameter = namedArgument.MatchingParameter.NotNull("matchingParameter != null"); var paramType = matchingParameter.Element.Type; var expression = namedArgument.Expression; if (expression == null) return null; var constantValue = expression.ConstantValue; if (constantValue.IsBadValue()) return null; var conversionRule = namedArgument.GetTypeConversionRule(); if (!expression.GetExpressionType().IsImplicitlyConvertibleTo(paramType, conversionRule)) { return null; } double? value = null; try { value = Convert.ToDouble(constantValue.Value, CultureInfo.InvariantCulture); } catch { // ignored } // ReSharper disable once CompareOfFloatsByEqualityOperator if (value == null || value.Value.IsNanOrInf() || value.Value.Clamp(min, max) != value.Value) return null; return (float) value.Value; } private static int? GetArgumentAsIntConstant(IEnumerable<ICSharpArgument> arguments, string parameterName, int min, int max) { var namedArgument = GetNamedArgument(arguments, parameterName); if (namedArgument == null) return null; var matchingParameter = namedArgument.MatchingParameter.NotNull("matchingParameter != null"); var paramType = matchingParameter.Element.Type; var expression = namedArgument.Expression; if (expression == null) return null; var constantValue = expression.ConstantValue; if (constantValue.IsBadValue()) return null; var conversionRule = namedArgument.GetTypeConversionRule(); if (!expression.GetExpressionType().IsImplicitlyConvertibleTo(paramType, conversionRule)) { return null; } int? value = null; try { value = Convert.ToInt32(constantValue.Value, CultureInfo.InvariantCulture); } catch { // ignored } if (value == null || value.Value.Clamp(min, max) != value.Value) return null; return value.Value; } private static ICSharpArgument? GetNamedArgument(IEnumerable<ICSharpArgument> arguments, string parameterName) { return arguments.FirstOrDefault(a => parameterName.Equals(a.MatchingParameter?.Element.ShortName, StringComparison.Ordinal)); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.Media.GlyphRun.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows.Media { public partial class GlyphRun : System.Windows.Media.Composition.DUCE.IResource, System.ComponentModel.ISupportInitialize { #region Methods and constructors public Geometry BuildGeometry() { return default(Geometry); } public System.Windows.Rect ComputeAlignmentBox() { return default(System.Windows.Rect); } public System.Windows.Rect ComputeInkBoundingBox() { return default(System.Windows.Rect); } public System.Windows.Media.TextFormatting.CharacterHit GetCaretCharacterHitFromDistance(double distance, out bool isInside) { isInside = default(bool); return default(System.Windows.Media.TextFormatting.CharacterHit); } public double GetDistanceFromCaretCharacterHit(System.Windows.Media.TextFormatting.CharacterHit characterHit) { return default(double); } public System.Windows.Media.TextFormatting.CharacterHit GetNextCaretCharacterHit(System.Windows.Media.TextFormatting.CharacterHit characterHit) { return default(System.Windows.Media.TextFormatting.CharacterHit); } public System.Windows.Media.TextFormatting.CharacterHit GetPreviousCaretCharacterHit(System.Windows.Media.TextFormatting.CharacterHit characterHit) { return default(System.Windows.Media.TextFormatting.CharacterHit); } public GlyphRun(GlyphTypeface glyphTypeface, int bidiLevel, bool isSideways, double renderingEmSize, IList<ushort> glyphIndices, System.Windows.Point baselineOrigin, IList<double> advanceWidths, IList<System.Windows.Point> glyphOffsets, IList<char> characters, string deviceFontName, IList<ushort> clusterMap, IList<bool> caretStops, System.Windows.Markup.XmlLanguage language) { } public GlyphRun() { } void System.ComponentModel.ISupportInitialize.BeginInit() { } void System.ComponentModel.ISupportInitialize.EndInit() { } int System.Windows.Media.Composition.DUCE.IResource.GetChannelCount() { return default(int); } #endregion #region Properties and indexers public IList<double> AdvanceWidths { get { return default(IList<double>); } set { } } public System.Windows.Point BaselineOrigin { get { return default(System.Windows.Point); } set { } } public int BidiLevel { get { return default(int); } set { } } public IList<bool> CaretStops { get { return default(IList<bool>); } set { } } public IList<char> Characters { get { return default(IList<char>); } set { } } public IList<ushort> ClusterMap { get { return default(IList<ushort>); } set { } } public string DeviceFontName { get { return default(string); } set { } } public double FontRenderingEmSize { get { return default(double); } set { } } public IList<ushort> GlyphIndices { get { return default(IList<ushort>); } set { } } public IList<System.Windows.Point> GlyphOffsets { get { return default(IList<System.Windows.Point>); } set { } } public GlyphTypeface GlyphTypeface { get { return default(GlyphTypeface); } set { } } public bool IsHitTestable { get { return default(bool); } } public bool IsSideways { get { return default(bool); } set { } } public System.Windows.Markup.XmlLanguage Language { get { return default(System.Windows.Markup.XmlLanguage); } set { } } #endregion } }
/* ==================================================================== 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. ==================================================================== */ /* ================================================================ * About NPOI * Author: Tony Qu * Author's email: tonyqus (at) gmail.com * Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn) * HomePage: http://www.codeplex.com/npoi * Contributors: * * ==============================================================*/ namespace NPOI.HPSF { using System; using System.Text; using System.Collections; using NPOI.Util; /// <summary> /// A property in a {@link Section} of a {@link PropertySet}. /// The property's ID gives the property a meaning /// in the context of its {@link Section}. Each {@link Section} spans /// its own name space of property IDs. /// The property's type determines how its /// value is interpreted. For example, if the type Is /// {@link Variant#VT_LPSTR} (byte string), the value consists of a /// DWord telling how many bytes the string Contains. The bytes follow /// immediately, including any null bytes that terminate the /// string. The type {@link Variant#VT_I4} denotes a four-byte integer /// value, {@link Variant#VT_FILETIME} some DateTime and time (of a /// file). /// Please note that not all {@link Variant} types yet. This might Change /// over time but largely depends on your feedback so that the POI team knows /// which variant types are really needed. So please feel free To submit error /// reports or patches for the types you need. /// Microsoft documentation: /// <a href="http://msdn.microsoft.com/library/en-us/stg/stg/property_Set_display_name_dictionary.asp?frame=true"> /// Property Set Display Name Dictionary</a> /// . /// @author Rainer Klute /// <a href="mailto:klute@rainer-klute.de">&lt;klute@rainer-klute.de&gt;</a> /// @author Drew Varner (Drew.Varner InAndAround sc.edu) /// @see Section /// @see Variant /// @since 2002-02-09 /// </summary> internal class Property { /** The property's ID. */ protected long id; /** * Returns the property's ID. * * @return The ID value */ public virtual long ID { get { return id; } set { id = value ;} } /** The property's type. */ protected long type; /** * Returns the property's type. * * @return The type value */ public virtual long Type { get { return type; } set { type = value;} } /** The property's value. */ protected Object value; /// <summary> /// Gets the property's value. /// </summary> /// <value>The property's value</value> public virtual object Value { get{return this.value;} set { this.value = value; } } /// <summary> /// Initializes a new instance of the <see cref="Property"/> class. /// </summary> /// <param name="id">the property's ID.</param> /// <param name="type">the property's type, see {@link Variant}.</param> /// <param name="value">the property's value. Only certain types are allowed, see /// {@link Variant}.</param> public Property(long id, long type, Object value) { this.id = id; this.type = type; this.value = value; } /// <summary> /// Initializes a new instance of the <see cref="Property"/> class. /// </summary> /// <param name="id">The property's ID.</param> /// <param name="src">The bytes the property Set stream consists of.</param> /// <param name="offset">The property's type/value pair's offset in the /// section.</param> /// <param name="Length">The property's type/value pair's Length in bytes.</param> /// <param name="codepage">The section's and thus the property's /// codepage. It is needed only when Reading string values</param> public Property(long id, byte[] src, long offset, int Length, int codepage) { this.id = id; /* * ID 0 is a special case since it specifies a dictionary of * property IDs and property names. */ if (id == 0) { value = ReadDictionary(src, offset, Length, codepage); return; } int o = (int)offset; type = LittleEndian.GetUInt(src, o); o += LittleEndianConsts.INT_SIZE; try { value = VariantSupport.Read(src, o, Length, (int)type, codepage); } catch (UnsupportedVariantTypeException ex) { VariantSupport.WriteUnsupportedTypeMessage(ex); value = ex.Value; } } /// <summary> /// Initializes a new instance of the <see cref="Property"/> class. /// </summary> protected Property() { } /// <summary> /// Reads the dictionary. /// </summary> /// <param name="src">The byte array containing the bytes making out the dictionary.</param> /// <param name="offset">At this offset within src the dictionary starts.</param> /// <param name="Length">The dictionary Contains at most this many bytes.</param> /// <param name="codepage">The codepage of the string values.</param> /// <returns>The dictonary</returns> protected IDictionary ReadDictionary(byte[] src, long offset, int Length, int codepage) { /* Check whether "offset" points into the "src" array". */ if (offset < 0 || offset > src.Length) throw new HPSFRuntimeException ("Illegal offset " + offset + " while HPSF stream Contains " + Length + " bytes."); int o = (int)offset; /* * Read the number of dictionary entries. */ long nrEntries = LittleEndian.GetUInt(src, o); o += LittleEndianConsts.INT_SIZE; Hashtable m = new Hashtable((int)nrEntries, (float)1.0); try { for (int i = 0; i < nrEntries; i++) { /* The key. */ long id = LittleEndian.GetUInt(src, o); o += LittleEndianConsts.INT_SIZE; /* The value (a string). The Length is the either the * number of (two-byte) characters if the character Set is Unicode * or the number of bytes if the character Set is not Unicode. * The Length includes terminating 0x00 bytes which we have To strip * off To Create a Java string. */ long sLength = LittleEndian.GetUInt(src, o); o += LittleEndianConsts.INT_SIZE; /* Read the string. */ StringBuilder b = new StringBuilder(); switch (codepage) { case -1: { /* Without a codepage the Length is equal To the number of * bytes. */ b.Append(Encoding.UTF8.GetString(src, o, (int)sLength)); break; } case (int)Constants.CP_UNICODE: { /* The Length is the number of characters, i.e. the number * of bytes is twice the number of the characters. */ int nrBytes = (int)(sLength * 2); byte[] h = new byte[nrBytes]; for (int i2 = 0; i2 < nrBytes; i2 += 2) { h[i2] = src[o + i2 + 1]; h[i2 + 1] = src[o + i2]; } b.Append(Encoding.GetEncoding(codepage).GetString(h, 0, nrBytes)); break; } default: { /* For encodings other than Unicode the Length is the number * of bytes. */ b.Append(Encoding.GetEncoding(codepage).GetString(src, o, (int)sLength)); break; } } /* Strip 0x00 characters from the end of the string: */ while (b.Length > 0 && b[b.Length - 1] == 0x00) b.Length=b.Length - 1; if (codepage == (int)Constants.CP_UNICODE) { if (sLength % 2 == 1) sLength++; o += (int)(sLength + sLength); } else o += (int)sLength; m[id]= b.ToString(); } } catch (Exception ex) { POILogger l = POILogFactory.GetLogger(typeof(Property)); l.Log(POILogger.WARN, "The property Set's dictionary Contains bogus data. " + "All dictionary entries starting with the one with ID " + id + " will be ignored.", ex); } return m; } /// <summary> /// Gets the property's size in bytes. This is always a multiple of /// 4. /// </summary> /// <value>the property's size in bytes</value> public int Count { get { int Length = VariantSupport.GetVariantLength(type); if (Length >= 0) return Length; /* Fixed Length */ if (Length == -2) /* Unknown Length */ throw new WritingNotSupportedException(type, null); /* Variable Length: */ int PAddING = 4; /* Pad To multiples of 4. */ switch ((int)type) { case Variant.VT_LPSTR: { int l = ((String)value).Length + 1; int r = l % PAddING; if (r > 0) l += PAddING - r; Length += l; break; } case Variant.VT_EMPTY: break; default: throw new WritingNotSupportedException(type, value); } return Length; } } /// <summary> /// Compares two properties. /// Please beware that a property with /// ID == 0 is a special case: It does not have a type, and its value is the /// section's dictionary. Another special case are strings: Two properties /// may have the different types Variant.VT_LPSTR and Variant.VT_LPWSTR; /// </summary> /// <param name="o">The o.</param> /// <returns></returns> public override bool Equals(Object o) { if (!(o is Property)) return false; Property p = (Property)o; Object pValue = p.Value; long pId = p.ID; if (id != pId || (id != 0 && !TypesAreEqual(type, p.Type))) return false; if (value == null && pValue == null) return true; if (value == null || pValue == null) return false; /* It's clear now that both values are non-null. */ Type valueClass = value.GetType(); Type pValueClass = pValue.GetType(); if (!(valueClass.IsAssignableFrom(pValueClass)) && !(pValueClass.IsAssignableFrom(valueClass))) return false; if (value is byte[]) return Arrays.Equals((byte[])value, (byte[])pValue); return value.Equals(pValue); } /// <summary> /// Typeses the are equal. /// </summary> /// <param name="t1">The t1.</param> /// <param name="t2">The t2.</param> /// <returns></returns> private bool TypesAreEqual(long t1, long t2) { if (t1 == t2 || (t1 == Variant.VT_LPSTR && t2 == Variant.VT_LPWSTR) || (t2 == Variant.VT_LPSTR && t1 == Variant.VT_LPWSTR)) return true; else return false; } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { long GetHashCode = 0; GetHashCode += id; GetHashCode += type; if (value != null) GetHashCode += value.GetHashCode(); int returnHashCode = (int)(GetHashCode & 0x0ffffffffL); return returnHashCode; } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override String ToString() { StringBuilder b = new StringBuilder(); b.Append(this.GetType().Name); b.Append('['); b.Append("id: "); b.Append(ID); b.Append(", type: "); b.Append(GetType()); Object value = Value; b.Append(", value: "); b.Append(value.ToString()); if (value is String) { String s = (String)value; int l = s.Length; if (l > 0) { byte[] bytes = new byte[l * 2]; for (int i = 0; i < l; i++) { char c = s[i]; byte high = (byte)((c & 0x00ff00) >> 8); byte low = (byte)((c & 0x0000ff) >> 0); bytes[i * 2] = high; bytes[i * 2 + 1] = low; } String hex = HexDump.Dump(bytes, 0L, 0); b.Append(" ["); b.Append(hex); b.Append("]"); } } b.Append(']'); return b.ToString(); } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using System.Runtime.Serialization; using System.Text; using System.Xml; #if !NETFX_CORE using NUnit.Framework; #else using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #endif using Newtonsoft.Json; using System.IO; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Tests { [TestFixture] public class JsonTextWriterTest : TestFixtureBase { [Test] public void CloseOutput() { MemoryStream ms = new MemoryStream(); JsonTextWriter writer = new JsonTextWriter(new StreamWriter(ms)); Assert.IsTrue(ms.CanRead); writer.Close(); Assert.IsFalse(ms.CanRead); ms = new MemoryStream(); writer = new JsonTextWriter(new StreamWriter(ms)) { CloseOutput = false }; Assert.IsTrue(ms.CanRead); writer.Close(); Assert.IsTrue(ms.CanRead); } #if !(PORTABLE || NETFX_CORE) [Test] public void WriteIConvertable() { var sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.WriteValue(new ConvertibleInt(1)); Assert.AreEqual("1", sw.ToString()); } #endif [Test] public void ValueFormatting() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue('@'); jsonWriter.WriteValue("\r\n\t\f\b?{\\r\\n\"\'"); jsonWriter.WriteValue(true); jsonWriter.WriteValue(10); jsonWriter.WriteValue(10.99); jsonWriter.WriteValue(0.99); jsonWriter.WriteValue(0.000000000000000001d); jsonWriter.WriteValue(0.000000000000000001m); jsonWriter.WriteValue((string)null); jsonWriter.WriteValue((object)null); jsonWriter.WriteValue("This is a string."); jsonWriter.WriteNull(); jsonWriter.WriteUndefined(); jsonWriter.WriteEndArray(); } string expected = @"[""@"",""\r\n\t\f\b?{\\r\\n\""'"",true,10,10.99,0.99,1E-18,0.000000000000000001,null,null,""This is a string."",null,undefined]"; string result = sb.ToString(); Console.WriteLine("ValueFormatting"); Console.WriteLine(result); Assert.AreEqual(expected, result); } [Test] public void NullableValueFormatting() { StringWriter sw = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue((char?)null); jsonWriter.WriteValue((char?)'c'); jsonWriter.WriteValue((bool?)null); jsonWriter.WriteValue((bool?)true); jsonWriter.WriteValue((byte?)null); jsonWriter.WriteValue((byte?)1); jsonWriter.WriteValue((sbyte?)null); jsonWriter.WriteValue((sbyte?)1); jsonWriter.WriteValue((short?)null); jsonWriter.WriteValue((short?)1); jsonWriter.WriteValue((ushort?)null); jsonWriter.WriteValue((ushort?)1); jsonWriter.WriteValue((int?)null); jsonWriter.WriteValue((int?)1); jsonWriter.WriteValue((uint?)null); jsonWriter.WriteValue((uint?)1); jsonWriter.WriteValue((long?)null); jsonWriter.WriteValue((long?)1); jsonWriter.WriteValue((ulong?)null); jsonWriter.WriteValue((ulong?)1); jsonWriter.WriteValue((double?)null); jsonWriter.WriteValue((double?)1.1); jsonWriter.WriteValue((float?)null); jsonWriter.WriteValue((float?)1.1); jsonWriter.WriteValue((decimal?)null); jsonWriter.WriteValue((decimal?)1.1m); jsonWriter.WriteValue((DateTime?)null); jsonWriter.WriteValue((DateTime?)new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc)); #if !NET20 jsonWriter.WriteValue((DateTimeOffset?)null); jsonWriter.WriteValue((DateTimeOffset?)new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero)); #endif jsonWriter.WriteEndArray(); } string json = sw.ToString(); string expected; #if !NET20 expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""1970-01-01T00:00:00Z"",null,""1970-01-01T00:00:00+00:00""]"; #else expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""1970-01-01T00:00:00Z""]"; #endif Assert.AreEqual(expected, json); } [Test] public void WriteValueObjectWithNullable() { StringWriter sw = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { char? value = 'c'; jsonWriter.WriteStartArray(); jsonWriter.WriteValue((object)value); jsonWriter.WriteEndArray(); } string json = sw.ToString(); string expected = @"[""c""]"; Assert.AreEqual(expected, json); } [Test] public void WriteValueObjectWithUnsupportedValue() { ExceptionAssert.Throws<JsonWriterException>( @"Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation. Path ''.", () => { StringWriter sw = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(new Version(1, 1, 1, 1)); jsonWriter.WriteEndArray(); } }); } [Test] public void StringEscaping() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(@"""These pretzels are making me thirsty!"""); jsonWriter.WriteValue("Jeff's house was burninated."); jsonWriter.WriteValue(@"1. You don't talk about fight club. 2. You don't talk about fight club."); jsonWriter.WriteValue("35% of\t statistics\n are made\r up."); jsonWriter.WriteEndArray(); } string expected = @"[""\""These pretzels are making me thirsty!\"""",""Jeff's house was burninated."",""1. You don't talk about fight club.\r\n2. You don't talk about fight club."",""35% of\t statistics\n are made\r up.""]"; string result = sb.ToString(); Console.WriteLine("StringEscaping"); Console.WriteLine(result); Assert.AreEqual(expected, result); } [Test] public void WriteEnd() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("CPU"); jsonWriter.WriteValue("Intel"); jsonWriter.WritePropertyName("PSU"); jsonWriter.WriteValue("500W"); jsonWriter.WritePropertyName("Drives"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD read/writer"); jsonWriter.WriteComment("(broken)"); jsonWriter.WriteValue("500 gigabyte hard drive"); jsonWriter.WriteValue("200 gigabype hard drive"); jsonWriter.WriteEndObject(); Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); } string expected = @"{ ""CPU"": ""Intel"", ""PSU"": ""500W"", ""Drives"": [ ""DVD read/writer"" /*(broken)*/, ""500 gigabyte hard drive"", ""200 gigabype hard drive"" ] }"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void CloseWithRemainingContent() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("CPU"); jsonWriter.WriteValue("Intel"); jsonWriter.WritePropertyName("PSU"); jsonWriter.WriteValue("500W"); jsonWriter.WritePropertyName("Drives"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD read/writer"); jsonWriter.WriteComment("(broken)"); jsonWriter.WriteValue("500 gigabyte hard drive"); jsonWriter.WriteValue("200 gigabype hard drive"); jsonWriter.Close(); } string expected = @"{ ""CPU"": ""Intel"", ""PSU"": ""500W"", ""Drives"": [ ""DVD read/writer"" /*(broken)*/, ""500 gigabyte hard drive"", ""200 gigabype hard drive"" ] }"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void Indenting() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("CPU"); jsonWriter.WriteValue("Intel"); jsonWriter.WritePropertyName("PSU"); jsonWriter.WriteValue("500W"); jsonWriter.WritePropertyName("Drives"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD read/writer"); jsonWriter.WriteComment("(broken)"); jsonWriter.WriteValue("500 gigabyte hard drive"); jsonWriter.WriteValue("200 gigabype hard drive"); jsonWriter.WriteEnd(); jsonWriter.WriteEndObject(); Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); } // { // "CPU": "Intel", // "PSU": "500W", // "Drives": [ // "DVD read/writer" // /*(broken)*/, // "500 gigabyte hard drive", // "200 gigabype hard drive" // ] // } string expected = @"{ ""CPU"": ""Intel"", ""PSU"": ""500W"", ""Drives"": [ ""DVD read/writer"" /*(broken)*/, ""500 gigabyte hard drive"", ""200 gigabype hard drive"" ] }"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void State() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); jsonWriter.WriteStartObject(); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); Assert.AreEqual("", jsonWriter.Path); jsonWriter.WritePropertyName("CPU"); Assert.AreEqual(WriteState.Property, jsonWriter.WriteState); Assert.AreEqual("CPU", jsonWriter.Path); jsonWriter.WriteValue("Intel"); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); Assert.AreEqual("CPU", jsonWriter.Path); jsonWriter.WritePropertyName("Drives"); Assert.AreEqual(WriteState.Property, jsonWriter.WriteState); Assert.AreEqual("Drives", jsonWriter.Path); jsonWriter.WriteStartArray(); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); jsonWriter.WriteValue("DVD read/writer"); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); Assert.AreEqual("Drives[0]", jsonWriter.Path); jsonWriter.WriteEnd(); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); Assert.AreEqual("Drives", jsonWriter.Path); jsonWriter.WriteEndObject(); Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); Assert.AreEqual("", jsonWriter.Path); } } [Test] public void FloatingPointNonFiniteNumbers_Symbol() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ NaN, Infinity, -Infinity, NaN, Infinity, -Infinity ]"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void FloatingPointNonFiniteNumbers_Zero() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.DefaultValue; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteValue((double?)double.NaN); jsonWriter.WriteValue((double?)double.PositiveInfinity); jsonWriter.WriteValue((double?)double.NegativeInfinity); jsonWriter.WriteValue((float?)float.NaN); jsonWriter.WriteValue((float?)float.PositiveInfinity); jsonWriter.WriteValue((float?)float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, null, null, null, null, null, null ]"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void FloatingPointNonFiniteNumbers_String() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.String; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ ""NaN"", ""Infinity"", ""-Infinity"", ""NaN"", ""Infinity"", ""-Infinity"" ]"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void FloatingPointNonFiniteNumbers_QuoteChar() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.String; jsonWriter.QuoteChar = '\''; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ 'NaN', 'Infinity', '-Infinity', 'NaN', 'Infinity', '-Infinity' ]"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void WriteRawInStart() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteRaw("[1,2,3,4,5]"); jsonWriter.WriteWhitespace(" "); jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteEndArray(); } string expected = @"[1,2,3,4,5] [ NaN ]"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void WriteRawInArray() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteRaw(",[1,2,3,4,5]"); jsonWriter.WriteRaw(",[1,2,3,4,5]"); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteEndArray(); } string expected = @"[ NaN,[1,2,3,4,5],[1,2,3,4,5], NaN ]"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void WriteRawInObject() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WriteRaw(@"""PropertyName"":[1,2,3,4,5]"); jsonWriter.WriteEnd(); } string expected = @"{""PropertyName"":[1,2,3,4,5]}"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void WriteToken() { JsonTextReader reader = new JsonTextReader(new StringReader("[1,2,3,4,5]")); reader.Read(); reader.Read(); StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.WriteToken(reader); Assert.AreEqual("1", sw.ToString()); } [Test] public void WriteRawValue() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { int i = 0; string rawJson = "[1,2]"; jsonWriter.WriteStartObject(); while (i < 3) { jsonWriter.WritePropertyName("d" + i); jsonWriter.WriteRawValue(rawJson); i++; } jsonWriter.WriteEndObject(); } Assert.AreEqual(@"{""d0"":[1,2],""d1"":[1,2],""d2"":[1,2]}", sb.ToString()); } [Test] public void WriteObjectNestedInConstructor() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("con"); jsonWriter.WriteStartConstructor("Ext.data.JsonStore"); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("aa"); jsonWriter.WriteValue("aa"); jsonWriter.WriteEndObject(); jsonWriter.WriteEndConstructor(); jsonWriter.WriteEndObject(); } Assert.AreEqual(@"{""con"":new Ext.data.JsonStore({""aa"":""aa""})}", sb.ToString()); } [Test] public void WriteFloatingPointNumber() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(0.0); jsonWriter.WriteValue(0f); jsonWriter.WriteValue(0.1); jsonWriter.WriteValue(1.0); jsonWriter.WriteValue(1.000001); jsonWriter.WriteValue(0.000001); jsonWriter.WriteValue(double.Epsilon); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.MaxValue); jsonWriter.WriteValue(double.MinValue); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteEndArray(); } Assert.AreEqual(@"[0.0,0.0,0.1,1.0,1.000001,1E-06,4.94065645841247E-324,Infinity,-Infinity,NaN,1.7976931348623157E+308,-1.7976931348623157E+308,Infinity,-Infinity,NaN]", sb.ToString()); } [Test] public void WriteIntegerNumber() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw) { Formatting = Formatting.Indented }) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(int.MaxValue); jsonWriter.WriteValue(int.MinValue); jsonWriter.WriteValue(0); jsonWriter.WriteValue(-0); jsonWriter.WriteValue(9L); jsonWriter.WriteValue(9UL); jsonWriter.WriteValue(long.MaxValue); jsonWriter.WriteValue(long.MinValue); jsonWriter.WriteValue(ulong.MaxValue); jsonWriter.WriteValue(ulong.MinValue); jsonWriter.WriteEndArray(); } Console.WriteLine(sb.ToString()); Assert.AreEqual(@"[ 2147483647, -2147483648, 0, 0, 9, 9, 9223372036854775807, -9223372036854775808, 18446744073709551615, 0 ]", sb.ToString()); } [Test] public void BadWriteEndArray() { ExceptionAssert.Throws<JsonWriterException>( "No token to close. Path ''.", () => { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(0.0); jsonWriter.WriteEndArray(); jsonWriter.WriteEndArray(); } }); } [Test] public void InvalidQuoteChar() { ExceptionAssert.Throws<ArgumentException>( @"Invalid JavaScript string quote character. Valid quote characters are ' and "".", () => { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.QuoteChar = '*'; } }); } [Test] public void Indentation() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting); jsonWriter.Indentation = 5; Assert.AreEqual(5, jsonWriter.Indentation); jsonWriter.IndentChar = '_'; Assert.AreEqual('_', jsonWriter.IndentChar); jsonWriter.QuoteName = true; Assert.AreEqual(true, jsonWriter.QuoteName); jsonWriter.QuoteChar = '\''; Assert.AreEqual('\'', jsonWriter.QuoteChar); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("propertyName"); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteEndObject(); } string expected = @"{ _____'propertyName': NaN }"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void WriteSingleBytes() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); string text = "Hello world."; byte[] data = Encoding.UTF8.GetBytes(text); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting); jsonWriter.WriteValue(data); } string expected = @"""SGVsbG8gd29ybGQu"""; string result = sb.ToString(); Assert.AreEqual(expected, result); byte[] d2 = Convert.FromBase64String(result.Trim('"')); Assert.AreEqual(text, Encoding.UTF8.GetString(d2, 0, d2.Length)); } [Test] public void WriteBytesInArray() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); string text = "Hello world."; byte[] data = Encoding.UTF8.GetBytes(text); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting); jsonWriter.WriteStartArray(); jsonWriter.WriteValue(data); jsonWriter.WriteValue(data); jsonWriter.WriteValue((object)data); jsonWriter.WriteValue((byte[])null); jsonWriter.WriteValue((Uri)null); jsonWriter.WriteEndArray(); } string expected = @"[ ""SGVsbG8gd29ybGQu"", ""SGVsbG8gd29ybGQu"", ""SGVsbG8gd29ybGQu"", null, null ]"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void Path() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); string text = "Hello world."; byte[] data = Encoding.UTF8.GetBytes(text); using (JsonTextWriter writer = new JsonTextWriter(sw)) { writer.Formatting = Formatting.Indented; writer.WriteStartArray(); Assert.AreEqual("", writer.Path); writer.WriteStartObject(); Assert.AreEqual("[0]", writer.Path); writer.WritePropertyName("Property1"); Assert.AreEqual("[0].Property1", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1", writer.Path); writer.WriteValue(1); Assert.AreEqual("[0].Property1[0]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1[1]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1[1][0]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1[1][0][0]", writer.Path); writer.WriteEndObject(); Assert.AreEqual("[0]", writer.Path); writer.WriteStartObject(); Assert.AreEqual("[1]", writer.Path); writer.WritePropertyName("Property2"); Assert.AreEqual("[1].Property2", writer.Path); writer.WriteStartConstructor("Constructor1"); Assert.AreEqual("[1].Property2", writer.Path); writer.WriteNull(); Assert.AreEqual("[1].Property2[0]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[1].Property2[1]", writer.Path); writer.WriteValue(1); Assert.AreEqual("[1].Property2[1][0]", writer.Path); writer.WriteEnd(); Assert.AreEqual("[1].Property2[1]", writer.Path); writer.WriteEndObject(); Assert.AreEqual("[1]", writer.Path); writer.WriteEndArray(); Assert.AreEqual("", writer.Path); } Assert.AreEqual(@"[ { ""Property1"": [ 1, [ [ [] ] ] ] }, { ""Property2"": new Constructor1( null, [ 1 ] ) } ]", sb.ToString()); } [Test] public void BuildStateArray() { JsonWriter.State[][] stateArray = JsonWriter.BuildStateArray(); var valueStates = JsonWriter.StateArrayTempate[7]; foreach (JsonToken valueToken in EnumUtils.GetValues(typeof(JsonToken))) { switch (valueToken) { case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Undefined: case JsonToken.Date: case JsonToken.Bytes: Assert.AreEqual(valueStates, stateArray[(int)valueToken], "Error for " + valueToken + " states."); break; } } } [Test] public void DateTimeZoneHandling() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw) { DateTimeZoneHandling = Json.DateTimeZoneHandling.Utc }; writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified)); Assert.AreEqual(@"""2000-01-01T01:01:01Z""", sw.ToString()); } [Test] public void HtmlStringEscapeHandling() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw) { StringEscapeHandling = StringEscapeHandling.EscapeHtml }; string script = @"<script type=""text/javascript"">alert('hi');</script>"; writer.WriteValue(script); string json = sw.ToString(); Assert.AreEqual(@"""\u003cscript type=\u0022text/javascript\u0022\u003ealert(\u0027hi\u0027);\u003c/script\u003e""", json); JsonTextReader reader = new JsonTextReader(new StringReader(json)); Assert.AreEqual(script, reader.ReadAsString()); //Console.WriteLine(HttpUtility.HtmlEncode(script)); //System.Web.Script.Serialization.JavaScriptSerializer s = new System.Web.Script.Serialization.JavaScriptSerializer(); //Console.WriteLine(s.Serialize(new { html = script })); } [Test] public void NonAsciiStringEscapeHandling() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw) { StringEscapeHandling = StringEscapeHandling.EscapeNonAscii }; string unicode = "\u5f20"; writer.WriteValue(unicode); string json = sw.ToString(); Assert.AreEqual(8, json.Length); Assert.AreEqual(@"""\u5f20""", json); JsonTextReader reader = new JsonTextReader(new StringReader(json)); Assert.AreEqual(unicode, reader.ReadAsString()); sw = new StringWriter(); writer = new JsonTextWriter(sw) { StringEscapeHandling = StringEscapeHandling.Default }; writer.WriteValue(unicode); json = sw.ToString(); Assert.AreEqual(3, json.Length); Assert.AreEqual("\"\u5f20\"", json); } [Test] public void WriteEndOnProperty() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.QuoteChar = '\''; writer.WriteStartObject(); writer.WritePropertyName("Blah"); writer.WriteEnd(); Assert.AreEqual("{'Blah':null}", sw.ToString()); } #if !NET20 [Test] public void QuoteChar() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.Formatting = Formatting.Indented; writer.QuoteChar = '\''; writer.WriteStartArray(); writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat; writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.DateFormatString = "yyyy gg"; writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.WriteValue(new byte[] { 1, 2, 3 }); writer.WriteValue(TimeSpan.Zero); writer.WriteValue(new Uri("http://www.google.com/")); writer.WriteValue(Guid.Empty); writer.WriteEnd(); Assert.AreEqual(@"[ '2000-01-01T01:01:01Z', '2000-01-01T01:01:01+00:00', '\/Date(946688461000)\/', '\/Date(946688461000+0000)\/', '2000 A.D.', '2000 A.D.', 'AQID', '00:00:00', 'http://www.google.com/', '00000000-0000-0000-0000-000000000000' ]", sw.ToString()); } [Test] public void Culture() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.Formatting = Formatting.Indented; writer.DateFormatString = "yyyy tt"; writer.Culture = new CultureInfo("en-NZ"); writer.QuoteChar = '\''; writer.WriteStartArray(); writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.WriteEnd(); Assert.AreEqual(@"[ '2000 a.m.', '2000 a.m.' ]", sw.ToString()); } #endif [Test] public void CompareNewStringEscapingWithOld() { Console.WriteLine("Started"); char c = (char) 0; do { if (c % 1000 == 0) Console.WriteLine("Position: " + (int)c); StringWriter swNew = new StringWriter(); char[] buffer = null; JavaScriptUtils.WriteEscapedJavaScriptString(swNew, c.ToString(), '"', true, JavaScriptUtils.DoubleQuoteCharEscapeFlags, StringEscapeHandling.Default, ref buffer); StringWriter swOld = new StringWriter(); WriteEscapedJavaScriptStringOld(swOld, c.ToString(), '"', true); string newText = swNew.ToString(); string oldText = swOld.ToString(); if (newText != oldText) throw new Exception("Difference for char '{0}' (value {1}). Old text: {2}, New text: {3}".FormatWith(CultureInfo.InvariantCulture, c, (int) c, oldText, newText)); c++; } while (c != char.MaxValue); Console.WriteLine("Finished"); } private const string EscapedUnicodeText = "!"; private static void WriteEscapedJavaScriptStringOld(TextWriter writer, string s, char delimiter, bool appendDelimiters) { // leading delimiter if (appendDelimiters) writer.Write(delimiter); if (s != null) { char[] chars = null; char[] unicodeBuffer = null; int lastWritePosition = 0; for (int i = 0; i < s.Length; i++) { var c = s[i]; // don't escape standard text/numbers except '\' and the text delimiter if (c >= ' ' && c < 128 && c != '\\' && c != delimiter) continue; string escapedValue; switch (c) { case '\t': escapedValue = @"\t"; break; case '\n': escapedValue = @"\n"; break; case '\r': escapedValue = @"\r"; break; case '\f': escapedValue = @"\f"; break; case '\b': escapedValue = @"\b"; break; case '\\': escapedValue = @"\\"; break; case '\u0085': // Next Line escapedValue = @"\u0085"; break; case '\u2028': // Line Separator escapedValue = @"\u2028"; break; case '\u2029': // Paragraph Separator escapedValue = @"\u2029"; break; case '\'': // this charater is being used as the delimiter escapedValue = @"\'"; break; case '"': // this charater is being used as the delimiter escapedValue = "\\\""; break; default: if (c <= '\u001f') { if (unicodeBuffer == null) unicodeBuffer = new char[6]; StringUtils.ToCharAsUnicode(c, unicodeBuffer); // slightly hacky but it saves multiple conditions in if test escapedValue = EscapedUnicodeText; } else { escapedValue = null; } break; } if (escapedValue == null) continue; if (i > lastWritePosition) { if (chars == null) chars = s.ToCharArray(); // write unchanged chars before writing escaped text writer.Write(chars, lastWritePosition, i - lastWritePosition); } lastWritePosition = i + 1; if (!string.Equals(escapedValue, EscapedUnicodeText)) writer.Write(escapedValue); else writer.Write(unicodeBuffer); } if (lastWritePosition == 0) { // no escaped text, write entire string writer.Write(s); } else { if (chars == null) chars = s.ToCharArray(); // write remaining text writer.Write(chars, lastWritePosition, s.Length - lastWritePosition); } } // trailing delimiter if (appendDelimiters) writer.Write(delimiter); } [Test] public void CustomJsonTextWriterTests() { StringWriter sw = new StringWriter(); CustomJsonTextWriter writer = new CustomJsonTextWriter(sw) { Formatting = Formatting.Indented }; writer.WriteStartObject(); Assert.AreEqual(WriteState.Object, writer.WriteState); writer.WritePropertyName("Property1"); Assert.AreEqual(WriteState.Property, writer.WriteState); Assert.AreEqual("Property1", writer.Path); writer.WriteNull(); Assert.AreEqual(WriteState.Object, writer.WriteState); writer.WriteEndObject(); Assert.AreEqual(WriteState.Start, writer.WriteState); Assert.AreEqual(@"{{{ ""1ytreporP"": NULL!!! }}}", sw.ToString()); } [Test] public void QuoteDictionaryNames() { var d = new Dictionary<string, int> { { "a", 1 }, }; var jsonSerializerSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, }; var serializer = JsonSerializer.Create(jsonSerializerSettings); using (var stringWriter = new StringWriter()) { using (var writer = new JsonTextWriter(stringWriter) { QuoteName = false }) { serializer.Serialize(writer, d); writer.Close(); } Assert.AreEqual(@"{ a: 1 }", stringWriter.ToString()); } } } public class CustomJsonTextWriter : JsonTextWriter { private readonly TextWriter _writer; public CustomJsonTextWriter(TextWriter textWriter) : base(textWriter) { _writer = textWriter; } public override void WritePropertyName(string name) { WritePropertyName(name, true); } public override void WritePropertyName(string name, bool escape) { SetWriteState(JsonToken.PropertyName, name); if (QuoteName) _writer.Write(QuoteChar); _writer.Write(new string(name.ToCharArray().Reverse().ToArray())); if (QuoteName) _writer.Write(QuoteChar); _writer.Write(':'); } public override void WriteNull() { SetWriteState(JsonToken.Null, null); _writer.Write("NULL!!!"); } public override void WriteStartObject() { SetWriteState(JsonToken.StartObject, null); _writer.Write("{{{"); } public override void WriteEndObject() { SetWriteState(JsonToken.EndObject, null); } protected override void WriteEnd(JsonToken token) { if (token == JsonToken.EndObject) _writer.Write("}}}"); else base.WriteEnd(token); } } #if !(PORTABLE || NETFX_CORE) public struct ConvertibleInt : IConvertible { private readonly int _value; public ConvertibleInt(int value) { _value = value; } public TypeCode GetTypeCode() { return TypeCode.Int32; } public bool ToBoolean(IFormatProvider provider) { throw new NotImplementedException(); } public byte ToByte(IFormatProvider provider) { throw new NotImplementedException(); } public char ToChar(IFormatProvider provider) { throw new NotImplementedException(); } public DateTime ToDateTime(IFormatProvider provider) { throw new NotImplementedException(); } public decimal ToDecimal(IFormatProvider provider) { throw new NotImplementedException(); } public double ToDouble(IFormatProvider provider) { throw new NotImplementedException(); } public short ToInt16(IFormatProvider provider) { throw new NotImplementedException(); } public int ToInt32(IFormatProvider provider) { throw new NotImplementedException(); } public long ToInt64(IFormatProvider provider) { throw new NotImplementedException(); } public sbyte ToSByte(IFormatProvider provider) { throw new NotImplementedException(); } public float ToSingle(IFormatProvider provider) { throw new NotImplementedException(); } public string ToString(IFormatProvider provider) { throw new NotImplementedException(); } public object ToType(Type conversionType, IFormatProvider provider) { if (conversionType == typeof(int)) return _value; throw new Exception("Type not supported: " + conversionType.FullName); } public ushort ToUInt16(IFormatProvider provider) { throw new NotImplementedException(); } public uint ToUInt32(IFormatProvider provider) { throw new NotImplementedException(); } public ulong ToUInt64(IFormatProvider provider) { throw new NotImplementedException(); } } #endif }
using System; using System.Text; using System.Diagnostics; using Diagnostics.Tracing; using Diagnostics.Tracing.Parsers; using Address = System.UInt64; using System.Runtime.InteropServices; // This code was automatically generated by the TraceParserGen tool, which converts // an ETW event manifest into strongly typed C# classes. namespace Diagnostics.Tracing.Parsers { public sealed class JSDumpHeapTraceEventParser : TraceEventParser { public static string ProviderName = "Microsoft-IE-JSDumpHeap"; public static Guid ProviderGuid = new Guid(unchecked((int) 0x7f8e35ca), unchecked((short) 0x68e8), unchecked((short) 0x41b9), 0x86, 0xfe, 0xd6, 0xad, 0xc5, 0xb3, 0x27, 0xe7); public enum Keywords : long { jsdumpheap = 0x00000020, jsdumpheapEnvelopeOnly = 0x80000000, }; public JSDumpHeapTraceEventParser(TraceEventSource source) : base(source) {} public event Action<SettingsTraceData> JSDumpHeapEnvelopeStart { add { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName source.RegisterEventTemplate(new SettingsTraceData(value, 1, 321, "JSDumpHeapEnvelope", JSDumpHeapEnvelopeTaskGuid, 1, "Start", ProviderGuid, ProviderName)); } remove { throw new Exception("Not supported"); } } public event Action<SummaryTraceData> JSDumpHeapEnvelopeStop { add { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName source.RegisterEventTemplate(new SummaryTraceData(value, 2, 321, "JSDumpHeapEnvelope", JSDumpHeapEnvelopeTaskGuid, 2, "Stop", ProviderGuid, ProviderName)); } remove { throw new Exception("Not supported"); } } public event Action<BulkNodeTraceData> JSDumpHeapBulkNode { add { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName source.RegisterEventTemplate(new BulkNodeTraceData(value, 3, 323, "JSDumpHeapBulkNode", JSDumpHeapBulkNodeTaskGuid, 0, "Info", ProviderGuid, ProviderName)); } remove { throw new Exception("Not supported"); } } public event Action<BulkAttributeTraceData> JSDumpHeapBulkAttribute { add { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName source.RegisterEventTemplate(new BulkAttributeTraceData(value, 4, 324, "JSDumpHeapBulkAttribute", JSDumpHeapBulkAttributeTaskGuid, 0, "Info", ProviderGuid, ProviderName)); } remove { throw new Exception("Not supported"); } } public event Action<BulkEdgeTraceData> JSDumpHeapBulkEdge { add { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName source.RegisterEventTemplate(new BulkEdgeTraceData(value, 5, 325, "JSDumpHeapBulkEdge", JSDumpHeapBulkEdgeTaskGuid, 0, "Info", ProviderGuid, ProviderName)); } remove { throw new Exception("Not supported"); } } public event Action<StringTableTraceData> JSDumpHeapStringTable { add { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName source.RegisterEventTemplate(new StringTableTraceData(value, 6, 326, "JSDumpHeapStringTable", JSDumpHeapStringTableTaskGuid, 0, "Info", ProviderGuid, ProviderName)); } remove { throw new Exception("Not supported"); } } public event Action<DoubleTableTraceData> JSDumpHeapDoubleTable { add { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName source.RegisterEventTemplate(new DoubleTableTraceData(value, 7, 327, "JSDumpHeapDoubleTable", JSDumpHeapDoubleTableTaskGuid, 0, "Info", ProviderGuid, ProviderName)); } remove { throw new Exception("Not supported"); } } #region Event ID Definitions public const TraceEventID JSDumpHeapEnvelopeStartEventID = (TraceEventID) 1; public const TraceEventID JSDumpHeapEnvelopeStopEventID = (TraceEventID) 2; public const TraceEventID JSDumpHeapBulkNodeEventID = (TraceEventID) 3; public const TraceEventID JSDumpHeapBulkAttributeEventID = (TraceEventID) 4; public const TraceEventID JSDumpHeapBulkEdgeEventID = (TraceEventID) 5; public const TraceEventID JSDumpHeapStringTableEventID = (TraceEventID) 6; public const TraceEventID JSDumpHeapDoubleTableEventID = (TraceEventID) 7; #endregion #region private private static Guid JSDumpHeapEnvelopeTaskGuid = new Guid(unchecked((int) 0xfff80bb3), unchecked((short) 0x0541), unchecked((short) 0x4423), 0xb2, 0x6b, 0x8c, 0x4a, 0x5a, 0xf9, 0x06, 0xff); private static Guid JSDumpHeapBulkNodeTaskGuid = new Guid(unchecked((int) 0x89b4a9e6), unchecked((short) 0x156f), unchecked((short) 0x4ff2), 0x8c, 0x93, 0xcd, 0x86, 0xb1, 0xbc, 0xe9, 0xa4); private static Guid JSDumpHeapBulkAttributeTaskGuid = new Guid(unchecked((int) 0xb171ef0b), unchecked((short) 0xd1fb), unchecked((short) 0x4901), 0x98, 0x47, 0xe1, 0x3d, 0x58, 0x3b, 0xfa, 0x86); private static Guid JSDumpHeapBulkEdgeTaskGuid = new Guid(unchecked((int) 0xec5809c8), unchecked((short) 0xef06), unchecked((short) 0x456c), 0xbe, 0x69, 0xe8, 0xdc, 0xdf, 0x75, 0x54, 0xba); private static Guid JSDumpHeapStringTableTaskGuid = new Guid(unchecked((int) 0x8a019204), unchecked((short) 0x6cc0), unchecked((short) 0x41f3), 0x8f, 0xae, 0xe1, 0x90, 0xdd, 0xfd, 0x05, 0xa7); private static Guid JSDumpHeapDoubleTableTaskGuid = new Guid(unchecked((int) 0xeaa70a14), unchecked((short) 0xd1c3), unchecked((short) 0x4939), 0x8c, 0xa7, 0x39, 0x3c, 0x2f, 0x75, 0xfa, 0x58); #endregion } public sealed class SettingsTraceData : TraceEvent { public new int Version { get { return GetInt32At(0); } } public int MaxStringLength { get { return GetInt32At(4); } } public bool IsTypeNamePrivate { get { return GetInt32At(8) != 0; } } public bool IsEdgeStringValuePrivate { get { return GetInt32At(12) != 0; } } public bool IsEdgeNumberValuePrivate { get { return GetInt32At(16) != 0; } } public bool IsAttributeStringValuePrivate { get { return GetInt32At(20) != 0; } } public bool IsAttributeNumberValuePrivate { get { return GetInt32At(24) != 0; } } #region Private internal SettingsTraceData(Action<SettingsTraceData> action, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName) : base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName) { this.Action = action; } internal protected override void Dispatch() { Action(this); } internal protected override void Validate() { Debug.Assert(!(Version == 0 && EventDataLength != 28)); Debug.Assert(!(Version > 0 && EventDataLength < 28)); } public override StringBuilder ToXml(StringBuilder sb) { Prefix(sb); sb.XmlAttrib("Version", Version); sb.XmlAttrib("MaxStringLength", MaxStringLength); sb.XmlAttrib("IsTypeNamePrivate", IsTypeNamePrivate); sb.XmlAttrib("IsEdgeStringValuePrivate", IsEdgeStringValuePrivate); sb.XmlAttrib("IsEdgeNumberValuePrivate", IsEdgeNumberValuePrivate); sb.XmlAttrib("IsAttributeStringValuePrivate", IsAttributeStringValuePrivate); sb.XmlAttrib("IsAttributeNumberValuePrivate", IsAttributeNumberValuePrivate); sb.Append("/>"); return sb; } public override string[] PayloadNames { get { if (payloadNames == null) payloadNames = new string[] { "Version", "MaxStringLength", "IsTypeNamePrivate", "IsEdgeStringValuePrivate", "IsEdgeNumberValuePrivate", "IsAttributeStringValuePrivate", "IsAttributeNumberValuePrivate"}; return payloadNames; } } public override object PayloadValue(int index) { switch (index) { case 0: return Version; case 1: return MaxStringLength; case 2: return IsTypeNamePrivate; case 3: return IsEdgeStringValuePrivate; case 4: return IsEdgeNumberValuePrivate; case 5: return IsAttributeStringValuePrivate; case 6: return IsAttributeNumberValuePrivate; default: Debug.Assert(false, "Bad field index"); return null; } } private event Action<SettingsTraceData> Action; #endregion } public sealed class SummaryTraceData : TraceEvent { public int HrResult { get { return GetInt32At(0); } } public int NodeCount { get { return GetInt32At(4); } } public int EdgeCount { get { return GetInt32At(8); } } public int AttributeCount { get { return GetInt32At(12); } } public int NumberCount { get { return GetInt32At(16); } } public int StringCount { get { return GetInt32At(20); } } #region Private internal SummaryTraceData(Action<SummaryTraceData> action, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName) : base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName) { this.Action = action; } internal protected override void Dispatch() { Action(this); } internal protected override void Validate() { Debug.Assert(!(Version == 0 && EventDataLength != 24)); Debug.Assert(!(Version > 0 && EventDataLength < 24)); } public override StringBuilder ToXml(StringBuilder sb) { Prefix(sb); sb.XmlAttrib("HrResult", HrResult); sb.XmlAttrib("NodeCount", NodeCount); sb.XmlAttrib("EdgeCount", EdgeCount); sb.XmlAttrib("AttributeCount", AttributeCount); sb.XmlAttrib("NumberCount", NumberCount); sb.XmlAttrib("StringCount", StringCount); sb.Append("/>"); return sb; } public override string[] PayloadNames { get { if (payloadNames == null) payloadNames = new string[] { "HrResult", "NodeCount", "EdgeCount", "AttributeCount", "NumberCount", "StringCount"}; return payloadNames; } } public override object PayloadValue(int index) { switch (index) { case 0: return HrResult; case 1: return NodeCount; case 2: return EdgeCount; case 3: return AttributeCount; case 4: return NumberCount; case 5: return StringCount; default: Debug.Assert(false, "Bad field index"); return null; } } private event Action<SummaryTraceData> Action; #endregion } public sealed class BulkNodeTraceData : TraceEvent { public int Index { get { return GetInt32At(0); } } public int Count { get { return GetInt32At(4); } } public unsafe BulkNodeElement* Values(int i, BulkNodeElement* buffer) { Debug.Assert(0 <= i && i < Count); if (PointerSize != 8) { BulkNodeElement32* basePtr = (BulkNodeElement32*)(((byte*)DataStart) + 8); BulkNodeElement32* value = basePtr + i; buffer->Id = value->Id; buffer->Size = value->Size; buffer->Address = value->Address; buffer->TypeNameId = value->TypeNameId; buffer->Flags = value->Flags; buffer->AttributeCount = value->AttributeCount; buffer->EdgeCount = value->EdgeCount; return buffer; } else { BulkNodeElement* basePtr = (BulkNodeElement*)(((byte*)DataStart) + 8); return basePtr + i; } } public unsafe BulkNodeElement Val(int i) { BulkNodeElement ret = new BulkNodeElement(); return *Values(i, &ret); } #region Private internal BulkNodeTraceData(Action<BulkNodeTraceData> action, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName) : base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName) { this.Action = action; } internal protected override void Dispatch() { Action(this); } unsafe internal protected override void Validate() { Debug.Assert(!(EventDataLength < 8)); Debug.Assert(!(Version == 0 && EventDataLength != 8 + Count * (PointerSize == 8 ? sizeof(BulkNodeElement) : sizeof(BulkNodeElement32)))); } public override StringBuilder ToXml(StringBuilder sb) { Prefix(sb); sb.XmlAttrib("Index", Index); sb.XmlAttrib("Count", Count); sb.Append("/>"); return sb; } public override string[] PayloadNames { get { if (payloadNames == null) payloadNames = new string[] { "Index", "Count" }; return payloadNames; } } public override object PayloadValue(int index) { switch (index) { case 0: return Index; case 1: return Count; default: Debug.Assert(false, "Bad field index"); return null; } } private event Action<BulkNodeTraceData> Action; #endregion } /// <summary> /// This is the layout on a 32 bit system. /// </summary> [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct BulkNodeElement32 { public uint Id; public int Size; public uint Address; public int TypeNameId; public ObjectFlags Flags; public ushort AttributeCount; public int EdgeCount; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct BulkNodeElement { public ulong Id; public int Size; public ulong Address; public int TypeNameId; public ObjectFlags Flags; public ushort AttributeCount; public int EdgeCount; } // TODO change casing? This is the PROFILER_HEAP_OBJECT_FLAGS enum [Flags] public enum ObjectFlags : uint { NEW_OBJECT = 0x1, IS_ROOT = 0x2, SITE_CLOSED = 0x4, EXTERNAL = 0x8, EXTERNAL_UNKNOWN = 0x10, EXTERNAL_DISPATCH = 0x20, SIZE_APPROXIMATE = 0x40, SIZE_UNAVAILABLE = 0x80, NEW_STATE_UNAVAILABLE = 0x100, WINRT_INSTANCE = 0x200, WINRT_RUNTIMECLASS = 0x400, WINRT_DELEGATE = 0x800, WINRT_NAMESPACE = 0x1000, WINRT = (WINRT_INSTANCE|WINRT_RUNTIMECLASS|WINRT_DELEGATE|WINRT_NAMESPACE) }; public sealed class BulkAttributeTraceData : TraceEvent { public int Index { get { return GetInt32At(0); } } public int Count { get { return GetInt32At(4); } } public unsafe BulkAttributeElement* Values(int i, BulkAttributeElement* buffer) { Debug.Assert(0 <= i && i < Count); if (PointerSize != 8) { BulkAttributeElement32* basePtr = (BulkAttributeElement32*)(((byte*)DataStart) + 8); BulkAttributeElement32* value = basePtr + i; buffer->Type = value->Type; buffer->Value = value->Value; return buffer; } else { BulkAttributeElement* basePtr = (BulkAttributeElement*)(((byte*)DataStart) + 8); return basePtr + i; } } #region Private internal BulkAttributeTraceData(Action<BulkAttributeTraceData> action, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName) : base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName) { this.Action = action; } internal protected override void Dispatch() { Action(this); } internal unsafe protected override void Validate() { Debug.Assert(!(EventDataLength < 8)); Debug.Assert(!(Version == 0 && EventDataLength != 8 + Count * (PointerSize == 8 ? sizeof(BulkAttributeElement) : sizeof(BulkAttributeElement32)))); } public override StringBuilder ToXml(StringBuilder sb) { Prefix(sb); sb.XmlAttrib("Index", Index); sb.XmlAttrib("Count", Count); sb.Append("/>"); return sb; } public override string[] PayloadNames { get { if (payloadNames == null) payloadNames = new string[] { "Index", "Count" }; return payloadNames; } } public override object PayloadValue(int index) { switch (index) { case 0: return Index; case 1: return Count; default: Debug.Assert(false, "Bad field index"); return null; } } private event Action<BulkAttributeTraceData> Action; #endregion } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct BulkAttributeElement32 { public AttributeType Type; public uint Value; // Might be string index into the string table. } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct BulkAttributeElement { public AttributeType Type; public ulong Value; // Might be string index into the string table. } public enum AttributeType : ushort { DOMTagName, // Does not seem to be used yet DOMId, // Does not seem to be used yet DOMClass, // Does not seem to be used yet DOMSrc, // Does not seem to be used yet ElementAttributesSize, // Value is a number Scope, // Value is a number Prototype, // Value is a number FunctionName, // Value is a string ID TextChildrenSize, // Value is a number Max }; public sealed class BulkEdgeTraceData : TraceEvent { public int Index { get { return GetInt32At(0); } } public int Count { get { return GetInt32At(4); } } public unsafe BulkEdgeElement* Values(int i, BulkEdgeElement* buffer) { Debug.Assert(0 <= i && i < Count); if (PointerSize != 8) { BulkEdgeElement32* basePtr = (BulkEdgeElement32*)(((byte*)DataStart) + 8); BulkEdgeElement32* value = basePtr + i; buffer->RelationshipType = value->RelationshipType; buffer->TargetType = value->TargetType; buffer->NameId = value->NameId; buffer->Value = value->Value; return buffer; } else { BulkEdgeElement* basePtr = (BulkEdgeElement*)(((byte*)DataStart) + 8); return basePtr + i; } } #region Private internal BulkEdgeTraceData(Action<BulkEdgeTraceData> action, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName) : base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName) { this.Action = action; } internal unsafe protected override void Dispatch() { Action(this); } internal unsafe protected override void Validate() { Debug.Assert(!(EventDataLength < 8)); Debug.Assert(!(Version == 0 && EventDataLength != 8 + Count * (PointerSize == 8 ? sizeof(BulkEdgeElement) : sizeof(BulkEdgeElement32)))); } public override StringBuilder ToXml(StringBuilder sb) { Prefix(sb); sb.XmlAttrib("Index", Index); sb.XmlAttrib("Count", Count); sb.Append("/>"); return sb; } public override string[] PayloadNames { get { if (payloadNames == null) payloadNames = new string[] { "Index", "Count" }; return payloadNames; } } public override object PayloadValue(int index) { switch (index) { case 0: return Index; case 1: return Count; default: Debug.Assert(false, "Bad field index"); return null; } } private event Action<BulkEdgeTraceData> Action; #endregion } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct BulkEdgeElement32 { public EdgeRelationshipType RelationshipType; public EdgeTargetType TargetType; public int NameId; public uint Value; // index into string table (TargetType==string), the double table (TargetType==TargetTypeNumber) or node table (other) } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct BulkEdgeElement { public EdgeRelationshipType RelationshipType; public EdgeTargetType TargetType; public int NameId; public ulong Value; // index into string table (TargetType==string), the double table (TargetType==TargetTypeNumber) or node table (other) } public enum EdgeRelationshipType : byte { Prototype, Scope, InternalProperty, NamedProperty, IndexedProperty, // The object is an array, The Name ID is the index into that array. (Not the index in the string table) Event, RelationShip, // Some other relationship (typically a DOM tag or class) The NameId tells you the relationship. Max } public enum EdgeTargetType : byte { Number, // Value is index into double table String, // Value is ??? BSTR, // Value is index into string table Object, // Value is Node Address External, // Value is Node Address Max } public sealed class StringTableTraceData : TraceEvent { public int Index { get { return GetInt32At(0); } } public int Count { get { return GetInt32At(4); } } public string StringEntry(int i) { Debug.Assert(0 <= i && i < Count); // Perf Remember the last place we were and look from there if possible. // This handles the common case int idx = m_lastStrIdx; int offset = m_lastStrOffset; if (i < idx) { idx = 0; offset = 8; } while (idx < i) { idx++; offset = SkipUnicodeString(offset); } var ret = GetUnicodeStringAt(offset); // Point at the next offset. m_lastStrIdx = i + 1; m_lastStrOffset = offset + 2*(ret.Length + 1); return ret; } #region Private internal StringTableTraceData(Action<StringTableTraceData> action, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName) : base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName) { this.Action = action; this.m_lastStrOffset = 8; } internal protected override void Dispatch() { Action(this); } internal protected override void Validate() { Debug.Assert(!(EventDataLength < 8)); } public override StringBuilder ToXml(StringBuilder sb) { Prefix(sb); sb.XmlAttrib("Index", Index); sb.XmlAttrib("Count", Count); sb.Append("/>"); return sb; } public override string[] PayloadNames { get { if (payloadNames == null) payloadNames = new string[] { "Index", "Count" }; return payloadNames; } } public override object PayloadValue(int index) { switch (index) { case 0: return Index; case 1: return Count; default: Debug.Assert(false, "Bad field index"); return null; } } private event Action<StringTableTraceData> Action; // For efficient string lookup private int m_lastStrIdx; private int m_lastStrOffset; #endregion } public unsafe sealed class DoubleTableTraceData : TraceEvent { public int Index { get { return GetInt32At(0); } } public int Count { get { return GetInt32At(4); } } public double DoubleEntry(int i) { Debug.Assert(0 <= i && i < Count); double* basePtr = (double*)(((byte*)DataStart) + 8); return basePtr[i]; } #region Private internal DoubleTableTraceData(Action<DoubleTableTraceData> action, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName) : base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName) { this.Action = action; } internal protected override void Dispatch() { Action(this); } internal protected override void Validate() { Debug.Assert(!(EventDataLength < 8)); Debug.Assert(!(Version == 0 && EventDataLength != 8 + Count * 8)); } public override StringBuilder ToXml(StringBuilder sb) { Prefix(sb); sb.XmlAttrib("Index", Index); sb.XmlAttrib("Count", Count); sb.Append("/>"); return sb; } public override string[] PayloadNames { get { if (payloadNames == null) payloadNames = new string[] { "Index", "Count" }; return payloadNames; } } public override object PayloadValue(int index) { switch (index) { case 0: return Index; case 1: return Count; default: Debug.Assert(false, "Bad field index"); return null; } } private event Action<DoubleTableTraceData> Action; #endregion } }
using System; using System.Threading; namespace Skewworks.NETMF.Controls { /// <summary> /// Base class for creating controls with automatic scrolling /// </summary> [Serializable] public class ScrollableControl : Control //MarshalByRefObject, IControl { #region Variables /* // Name & Tag private string _name; private object _tag; // Size & Location private int _x; private int _y; private int _offsetX; private int _offsetY; private int _w; private int _h; // Owner private IContainer _parent; // States private bool _enabled = true; private bool _visible = true; private bool _suspended; // Touch private bool _mDown; // Touching when true private point _ptTapHold; // Location where touch down occurred private Thread _thHold; // Tap & Hold thread private long _lStop; // Stop waiting for hold after this tick private TapState _eTapHold; // Current tap state private long _lastTap; // Tick count of last time occurrence // Dispose private bool _disposing; */ // Scrolling private int _scrX, _scrY; private bool _needsX, _needsY; private int _sqW, _sqH; private bool _showScroll; private bool _cancelHide; private bool _bMoving; private int _horzW, _horzSize, _horzX; private int _vertH, _vertSize, _vertY; #endregion /// <summary> /// Initializes the control /// </summary> protected ScrollableControl() { } /// <summary> /// Initializes the control /// </summary> /// <param name="name">Name of the control</param> protected ScrollableControl(string name) : base(name) { } /// <summary> /// Initializes the control /// </summary> /// <param name="name">Name of the control</param> /// <param name="x">X position relative to it's parent</param> /// <param name="y">Y position relative to it's parent</param> protected ScrollableControl(string name, int x, int y) : base(name, x, y) { } /// <summary> /// Initializes the control /// </summary> /// <param name="name">Name of the control</param> /// <param name="x">X position relative to it's parent</param> /// <param name="y">Y position relative to it's parent</param> /// <param name="width">Width of the control in pixel</param> /// <param name="height">Height of the control in pixel</param> protected ScrollableControl(string name, int x, int y, int width, int height) : base(name, x, y, width, height) { } /*#region Events public event OnButtonPressed ButtonPressed; protected virtual void OnButtonPressed(object sender, int buttonId) { if (ButtonPressed != null) ButtonPressed(sender, buttonId); } public event OnButtonReleased ButtonReleased; protected virtual void OnButtonReleased(object sender, int buttonId) { if (ButtonReleased != null) ButtonReleased(sender, buttonId); } /// <summary> /// Raised on a double-tap /// </summary> public event OnDoubleTap DoubleTap; protected virtual void OnDoubleTap(object sender, point e) { if (DoubleTap != null) DoubleTap(sender, e); } public event OnGotFocus GotFocus; protected virtual void OnGotFocus(object sender) { if (GotFocus != null) GotFocus(sender); } public event OnKeyboardAltKey KeyboardAltKey; protected virtual void OnKeyboardAltKey(object sender, int key, bool pressed) { if (KeyboardAltKey != null) KeyboardAltKey(sender, key, pressed); } public event OnKeyboardKey KeyboardKey; protected virtual void OnKeyboardKey(object sender, char key, bool pressed) { if (KeyboardKey != null) KeyboardKey(sender, key, pressed); } public event OnLostFocus LostFocus; protected virtual void OnLostFocus(object sender) { if (LostFocus != null) LostFocus(sender); } /// <summary> /// Raised on tap /// </summary> public event OnTap Tap; public virtual void OnTap(object sender, point e) { if (Tap != null) Tap(sender, e); } /// <summary> /// Raised on tap and hold /// </summary> public event OnTapHold TapHold; public virtual void OnTapHold(object sender, point e) { if (TapHold != null) TapHold(sender, e); } /// <summary> /// Raised on touch down /// </summary> public event OnTouchDown TouchDown; public virtual void OnTouchDown(object sender, point e) { if (TouchDown != null) TouchDown(sender, e); } /// <summary> /// Raised on touch gesture /// </summary> public event OnTouchGesture TouchGesture; public virtual void OnTouchGesture(object sender, TouchType e, float force) { if (TouchGesture != null) TouchGesture(sender, e, force); } /// <summary> /// Raised on touch move /// </summary> public event OnTouchMove TouchMove; public virtual void OnTouchMove(object sender, point e) { if (TouchMove != null) TouchMove(sender, e); } /// <summary> /// Raised on touch up /// </summary> public event OnTouchUp TouchUp; public virtual void OnTouchUp(object sender, point e) { if (TouchUp != null) TouchUp(sender, e); } #endregion*/ #region Properties /*public virtual bool CanFocus { get { return true; } } public bool Disposing { get { return _disposing; } } public bool Enabled { get { return _enabled; } set { if (_enabled == value) return; _enabled = value; Render(true); } } public bool Focused { get { if (_parent == null) return false; return _parent.ActiveChild == this; } } public virtual int Height { get { return _h; } set { if (_h == value) return; // Create Update Region var r = new rect(Left, Top, Width, Math.Max(_h, value)); _h = value; if (_parent != null) _parent.Render(r, true); } } public point LastTouch { get { return _ptTapHold; } protected set { _ptTapHold = value; } } public int Left { get { return X + _offsetX; } }*/ /// <summary> /// Gets/Sets maximum X scroll value /// </summary> public int MaxScrollX { get; private set; } /// <summary> /// Gets/Sets maximum Y scroll value /// </summary> public int MaxScrollY { get; private set; } /*public string Name { get { return _name; } protected set { _name = value; } } public virtual IContainer Parent { get { return _parent; } set { if (_parent == value) return; if (_parent != null) _parent.RemoveChild(this); _parent = value; UpdateOffsets(); } }*/ /// <summary> /// Gets/Sets the maximum required height /// </summary> /// <remarks> /// RequiredHeight is identical with <see cref="MaxScrollY"/> /// </remarks> protected int RequiredHeight { get { return MaxScrollY; } set { if (MaxScrollY == value) { return; } MaxScrollY = value; UpdateNeeds(); } } /// <summary> /// Gets/Sets the maximum required width /// </summary> /// <remarks> /// RequiredWidth is identical with <see cref="MaxScrollX"/> /// </remarks> protected int RequiredWidth { get { return MaxScrollX; } set { if (MaxScrollX == value) { return; } MaxScrollX = value; UpdateNeeds(); } } /*public rect ScreenBounds { get { return new rect(Left, Top, Width, Height); } }*/ /// <summary> /// Gets current scroll state /// </summary> public bool Scrolling { get { return _bMoving; } } /// <summary> /// Gets/Sets current X scroll value /// </summary> public virtual int ScrollX { get { return _scrX; } set { if (value < 0) { value = 0; } else if (value > _sqW) { value = _sqW; } if (!_needsX || _scrX == value) { return; } _scrX = value; Invalidate(); } } /// <summary> /// Gets/Sets current Y scroll value /// </summary> public virtual int ScrollY { get { return _scrY; } set { if (value < 0) { value = 0; } else if (value > _sqH) { value = _sqH; } if (!_needsY || _scrY == value) { return; } _scrY = value; Invalidate(); } } /*public virtual bool Suspended { get { return _suspended; } set { if (_suspended == value) return; _suspended = value; if (!_suspended) Invalidate(); } } public object Tag { get { return _tag; } set { _tag = value; } } public int Top { get { return Y + _offsetY; } } public virtual bool Touching { get { return _mDown; } } public virtual bool Visible { get { return _visible; } set { if (_visible == value) return; _visible = value; if (_parent != null) _parent.Render(new rect(Left, Top, Width, Height), true); } } public virtual int Width { get { return _w; } set { if (_w == value) return; // Create Update Region var r = new rect(Left, Top, Math.Max(_w, value), Height); _w = value; if (_parent != null) _parent.Render(r, true); } } public virtual int X { get { return _x; } set { if (_x == value) return; // Create update region var r = new rect(Math.Min(_x, value), Top, Math.Abs(_x - value) + Width, Height); _x = value; if (_parent != null) _parent.Render(r, true); } } public virtual int Y { get { return _y; } set { if (_y == value) return; // Create update region var r = new rect(Left, Math.Min(_y, value), Width, Math.Abs(_y - value) + Height); _y = value; if (_parent != null) _parent.Render(r, true); } }*/ #endregion /*#region Buttons protected virtual void ButtonPressedMessage(int buttonId, ref bool handled) { } protected virtual void ButtonReleasedMessage(int buttonId, ref bool handled) { } public void SendButtonEvent(int buttonId, bool pressed) { bool handled = false; if (pressed) { ButtonPressedMessage(buttonId, ref handled); if (handled) return; OnButtonPressed(this, buttonId); if (buttonId == (int)ButtonIDs.Click || buttonId == (int)ButtonIDs.Select) SendTouchDown(this, Core.MousePosition); } else { ButtonReleasedMessage(buttonId, ref handled); if (handled) return; if (buttonId == (int)ButtonIDs.Click || buttonId == (int)ButtonIDs.Select) SendTouchUp(this, Core.MousePosition); OnButtonReleased(this, buttonId); } } #endregion*/ /*#region Keyboard protected virtual void KeyboardAltKeyMessage(int key, bool pressed, ref bool handled) { } protected virtual void KeyboardKeyMessage(char key, bool pressed, ref bool handled) { } public void SendKeyboardAltKeyEvent(int key, bool pressed) { bool handled = false; KeyboardAltKeyMessage(key, pressed, ref handled); if (!handled) OnKeyboardAltKey(this, key, pressed); } public void SendKeyboardKeyEvent(char key, bool pressed) { bool handled = false; KeyboardKeyMessage(key, pressed, ref handled); if (!handled) OnKeyboardKey(this, key, pressed); } #endregion*/ /*#region Touch protected virtual void TouchDownMessage(object sender, point e, ref bool handled) { } protected virtual void TouchGestureMessage(object sender, TouchType e, float force, ref bool handled) { } protected virtual void TouchMoveMessage(object sender, point e, ref bool handled) { } protected virtual void TouchUpMessage(object sender, point e, ref bool handled) { } /// <summary> /// Called when a touch down occurs and the control is active /// </summary> /// <param name="sender">Sending object</param> /// <param name="point">Location of touch</param> public void SendTouchDown(object sender, point point) { // Exit if needed if (!_enabled || !_visible || _suspended) return; bool bHandled = false; // Allow Override TouchDownMessage(sender, point, ref bHandled); // Exit if handled if (bHandled) return; // Set down state _mDown = true; // Begin Tap/Hold _ptTapHold = point; _eTapHold = TapState.TapHoldWaiting; _lStop = DateTime.Now.Ticks + (500 * TimeSpan.TicksPerMillisecond); if (_thHold == null || !_thHold.IsAlive) { _thHold = new Thread(TapHoldWaiter); _thHold.Start(); } // Raise Event OnTouchDown(sender, point); } */ /// <summary> /// Override this message to handle touch events internally. /// </summary> /// <param name="sender">Object sending the event</param> /// <param name="point">Point on screen touch event is occurring</param> /// <param name="handled">true if the event is handled. Set to true if handled.</param> /// <remarks> /// Override cleans up moving state. /// </remarks> protected override void TouchUpMessage(object sender, point point, ref bool handled) { // Handle Moving if (_bMoving) { _bMoving = false; _showScroll = false; _cancelHide = true; Invalidate(); } base.TouchUpMessage(sender, point, ref handled); } /* /// <summary> /// Called when a touch up occurs and the control is active /// </summary> /// <param name="sender">Sending object</param> /// <param name="point">Location of touch</param> public void SendTouchUp(object sender, point point) { if (!_enabled || !_visible || _suspended) { _mDown = false; return; } bool bHandled = false; // Check Tap Hold _eTapHold = TapState.Normal; // Handle Moving if (_bMoving) { _bMoving = false; _showScroll = false; _cancelHide = true; Invalidate(); } else TouchUpMessage(sender, point, ref bHandled); // Allow Override // Exit if handled if (bHandled) return; // Perform normal tap if (_mDown) { if (new rect(Left, Top, Width, Height).Contains(point)) { if (DateTime.Now.Ticks - _lastTap < (TimeSpan.TicksPerMillisecond * 500)) { OnDoubleTap(this, new point(point.X - Left, point.Y - Top)); _lastTap = 0; } else { OnTap(this, new point(point.X - Left, point.Y - Top)); _lastTap = DateTime.Now.Ticks; } } _mDown = false; OnTouchUp(this, point); } } */ /// <summary> /// Override this message to handle touch events internally. /// </summary> /// <param name="sender">Object sending the event</param> /// <param name="point">Point on screen touch event is occurring</param> /// <param name="handled">true if the event is handled. Set to true if handled.</param> protected override void TouchMoveMessage(object sender, point point, ref bool handled) { // Handle Scrolling if (_needsX || _needsY) { bool doInvalidate = false; _bMoving = true; _cancelHide = true; _showScroll = true; int dest = _scrY - (point.Y - LastTouch.Y); if (dest < 0) { dest = 0; } else if (dest > MaxScrollY - Height) { dest = MaxScrollY - Height; } if (_scrY != dest && dest > 0) { _scrY = dest; doInvalidate = true; } dest = _scrX - (point.X - LastTouch.X); if (dest < 0) { dest = 0; } else if (dest > MaxScrollX - Width) { dest = MaxScrollX - Width; } if (_scrX != dest && dest > 0) { _scrX = dest; doInvalidate = true; } LastTouch = point; if (doInvalidate) { UpdateValues(); } } base.TouchMoveMessage(sender, point, ref handled); } /* /// <summary> /// Called when a touch move occurs and the control is active /// </summary> /// <param name="sender">Sending object</param> /// <param name="point">Location of touch</param> public void SendTouchMove(object sender, point point) { if (!_enabled || !_visible || _suspended) return; bool bHandled = false; // Handle Scrolling if (_needsX || _needsY) { bool doInvalidate = false; _bMoving = true; _cancelHide = true; _showScroll = true; int dest = _scrY - (point.Y - _ptTapHold.Y); if (dest < 0) dest = 0; else if (dest > _rqHeight - Height) dest = _rqHeight - Height; if (_scrY != dest && dest > 0) { _scrY = dest; doInvalidate = true; } dest = _scrX - (point.X - LastTouch.X); if (dest < 0) dest = 0; else if (dest > _rqWidth - Width) dest = _rqWidth - Width; if (_scrX != dest && dest > 0) { _scrX = dest; doInvalidate = true; } _ptTapHold = point; if (doInvalidate) UpdateValues(); } // Allow Override TouchMoveMessage(sender, point, ref bHandled); // Exit if handled if (bHandled) return; _eTapHold = TapState.Normal; OnTouchMove(this, point); } /// <summary> /// Called when a gesture occurs and the control is active /// </summary> /// <param name="sender">Sending object</param> /// <param name="type">Type of touch gesture</param> /// <param name="force"></param> public void SendTouchGesture(object sender, TouchType type, float force) { if (!_enabled || !_visible || _suspended) return; bool bHandled = false; // Allow Override TouchGestureMessage(sender, type, force, ref bHandled); // Exit if handled if (bHandled) return; OnTouchGesture(this, type, force); } /// <summary> /// Method for detecting Tap & Hold /// </summary> private void TapHoldWaiter() { while (DateTime.Now.Ticks < _lStop) { Thread.Sleep(10); if (_eTapHold == TapState.Normal) return; } if (_eTapHold == TapState.Normal || !_enabled || !_visible || _suspended) return; //_mDown = false; _eTapHold = TapState.Normal; OnTapHold(this, _ptTapHold); } #endregion*/ /*#region Disposing public void Dispose() { if (_disposing) return; _disposing = true; // Remove Events DoubleTap = null; Tap = null; TapHold = null; TouchDown = null; TouchGesture = null; TouchMove = null; TouchUp = null; } #endregion*/ /*#region Focus public virtual void Activate() { Invalidate(); } public virtual void Blur() { Invalidate(); } public virtual bool HitTest(point point) { return ScreenBounds.Contains(point); } #endregion*/ /* #region GUI public void Invalidate() { // ReSharper disable once SuspiciousTypeConversion.Global //TODO: check this comparission if ((_parent == null && !ReferenceEquals(Core.ActiveContainer, this)) || (_parent != null && _parent.Suspended) || !_visible || _suspended) return; if (_parent == null) Render(true); else _parent.TopLevelContainer.Render(ScreenBounds, true); } public void Invalidate(rect area) { // ReSharper disable once SuspiciousTypeConversion.Global //TODO: check this comparission if ((_parent == null && !ReferenceEquals(Core.ActiveContainer, this)) || (_parent != null && _parent.Suspended) || !_visible || _suspended) return; if (_parent == null) Render(true); else _parent.TopLevelContainer.Render(area, true); } */ /// <summary> /// Renders the control contents /// </summary> /// <param name="x">X position in screen coordinates</param> /// <param name="y">Y position in screen coordinates</param> /// <param name="width">Width in pixel</param> /// <param name="height">Height in pixel</param> /// <remarks> /// Override this method to render the contents of the control /// </remarks> protected override void OnRender(int x, int y, int width, int height) { // Render scrollbar(s) if (_showScroll) { RenderScrollbar(); } base.OnRender(x, y, width, height); } /* public void Render(bool flush = false) { // Check if we actually need to render // ReSharper disable once SuspiciousTypeConversion.Global //TODO: check this comparission if ((_parent == null && !ReferenceEquals(Core.ActiveContainer, this)) || (_parent != null && _parent.Suspended) || !_visible || _suspended) return; int cw, ch; if (_parent == null) { cw = Width; ch = Height; } else { cw = Math.Min(_parent.Width - X, Width); ch = Math.Min(_parent.Height - Y, Height); } if (cw < 1 || ch < 1) return; // Update clip Core.Screen.SetClippingRectangle(Left, Top, cw, ch); // Render control lock (Core.Screen) OnRender(Left, Top, cw, ch); // Render scrollbar(s) if (_showScroll) RenderScrollbar(); // Flush as needed if (flush) Core.SafeFlush(Left, Top, cw, ch); } protected virtual void OnRender(int x, int y, int w, int h) { } public void UpdateOffsets() { if (_parent != null) { _offsetX = _parent.Left; _offsetY = _parent.Top; } else { _offsetX = 0; _offsetY = 0; } } public void UpdateOffsets(point pt) { _offsetX = pt.X; _offsetY = pt.Y; } #endregion*/ #region Scrollbar Methods private void AutoHideScrollbar() { Thread.Sleep(1000); if (_cancelHide || !_showScroll) { return; } _showScroll = false; Invalidate(); } private void RenderScrollbar() { if (_needsX) { int y = Top + Height - 4; Core.Screen.DrawRectangle(0, 0, Left, y, _horzW, 4, 0, 0, Core.SystemColors.ScrollbarBackground, 0, 0, Core.SystemColors.ScrollbarBackground, 0, 0, 128); Core.Screen.DrawRectangle(0, 0, Left + _horzX, y, _horzSize, 4, 0, 0, Core.SystemColors.ScrollbarGrip, 0, 0, Core.SystemColors.ScrollbarGrip, 0, 0, 128); } if (_needsY) { int x = Left + Width - 4; Core.Screen.DrawRectangle(0, 0, x, Top, 4, _vertH, 0, 0, Core.SystemColors.ScrollbarBackground, 0, 0, Core.SystemColors.ScrollbarBackground, 0, 0, 128); Core.Screen.DrawRectangle(0, 0, x, Top + _vertY, 4, _vertSize, 0, 0, Core.SystemColors.ScrollbarGrip, 0, 0, Core.SystemColors.ScrollbarGrip, 0, 0, 128); } } /// <summary> /// Updates the visibility state of the scrollbars /// </summary> /// <param name="invalidate">true if control should be invalidated; false if not</param> protected void UpdateScrollbar(bool invalidate = true) { UpdateNeeds(invalidate); } private void UpdateNeeds(bool invalidate = true) { bool nX = false; bool nY = false; if (MaxScrollX > Width) { nX = true; } if (MaxScrollY > Height) { nY = true; } if (nX || nY) { //_scrX = 0; //_scrY = 0; _needsX = nX; _needsY = nY; _sqW = MaxScrollX - Width; _sqH = MaxScrollY - Height; _showScroll = true; UpdateValues(invalidate); _cancelHide = false; new Thread(AutoHideScrollbar).Start(); } } private void UpdateValues(bool invalidate = true) { int w = Width; int h = Height; if (_needsX && _needsY) { w -= 4; h -= 4; } if (_needsX) { _horzW = w; _horzSize = _horzW - (_sqW/4); if (_horzSize < 8) { _horzSize = 8; } _horzX = (int) ((_horzW - _horzSize)*(_scrX/(float) _sqW)); } if (_needsY) { _vertH = h; _vertSize = _vertH - (_sqH/4); if (_vertSize < 8) { _vertSize = 8; } _vertY = (int) ((_vertH - _vertSize)*(_scrY/(float) _sqH)); } if (invalidate) { Invalidate(); } } #endregion } }
// 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. namespace Gallio.Icarus.TestExplorer { internal partial class TestExplorerView { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(TestExplorerView)); this.testTree = new Gallio.Icarus.Controls.TestTreeView(); this.testTreeMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components); this.expandAllMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.collapseAllMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator(); this.expandMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.expandPassedTestsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.expandFailedTestsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.expandSkippedTestsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.filterToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.filterPassedTestsToolStripMenuItem = new Gallio.UI.Controls.ToolStripMenuItem(); this.filterFailedTestsToolStripMenuItem = new Gallio.UI.Controls.ToolStripMenuItem(); this.filterInconclusiveTestsToolStripMenuItem = new Gallio.UI.Controls.ToolStripMenuItem(); this.selectAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.selectPassedToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.selectFailedToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.selectInconclusiveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator9 = new System.Windows.Forms.ToolStripSeparator(); this.resetTestsMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator10 = new System.Windows.Forms.ToolStripSeparator(); this.filesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.addFilesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.removeFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.removeAllFilesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.viewSourceCodeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripContainer1 = new System.Windows.Forms.ToolStripContainer(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.treeViewComboBox = new System.Windows.Forms.ToolStripComboBox(); this.filterPassedTestsToolStripButton = new Gallio.UI.Controls.ToolStripButton(); this.filterFailedTestsToolStripButton = new Gallio.UI.Controls.ToolStripButton(); this.filterInconclusiveTestsToolStripButton = new Gallio.UI.Controls.ToolStripButton(); this.sortAscToolStripButton = new Gallio.UI.Controls.ToolStripButton(); this.sortDescToolStripButton = new Gallio.UI.Controls.ToolStripButton(); this.testTreeMenuStrip.SuspendLayout(); this.toolStripContainer1.ContentPanel.SuspendLayout(); this.toolStripContainer1.TopToolStripPanel.SuspendLayout(); this.toolStripContainer1.SuspendLayout(); this.toolStrip1.SuspendLayout(); this.SuspendLayout(); // // testTree // this.testTree.AllowDrop = true; this.testTree.BackColor = System.Drawing.SystemColors.Window; this.testTree.ContextMenuStrip = this.testTreeMenuStrip; this.testTree.DefaultToolTipProvider = null; this.testTree.Dock = System.Windows.Forms.DockStyle.Fill; this.testTree.DragDropMarkColor = System.Drawing.Color.Black; this.testTree.LineColor = System.Drawing.SystemColors.ControlDark; this.testTree.Location = new System.Drawing.Point(0, 0); this.testTree.Model = null; this.testTree.Name = "testTree"; this.testTree.SelectedNode = null; this.testTree.Size = new System.Drawing.Size(281, 248); this.testTree.TabIndex = 5; this.testTree.SelectionChanged += new System.EventHandler(this.testTree_SelectionChanged); this.testTree.DoubleClick += new System.EventHandler(this.testTree_DoubleClick); // // testTreeMenuStrip // this.testTreeMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.expandAllMenuItem, this.collapseAllMenuItem, this.toolStripSeparator7, this.expandMenuItem, this.filterToolStripMenuItem, this.selectAllToolStripMenuItem, this.toolStripSeparator9, this.resetTestsMenuItem, this.toolStripSeparator10, this.filesToolStripMenuItem, this.viewSourceCodeToolStripMenuItem}); this.testTreeMenuStrip.Name = "classTreeMenuStrip"; this.testTreeMenuStrip.Size = new System.Drawing.Size(172, 198); // // expandAllMenuItem // this.expandAllMenuItem.Name = "expandAllMenuItem"; this.expandAllMenuItem.Size = new System.Drawing.Size(171, 22); this.expandAllMenuItem.Text = "&Expand All"; this.expandAllMenuItem.Click += new System.EventHandler(this.expandAllMenuItem_Click); // // collapseAllMenuItem // this.collapseAllMenuItem.Name = "collapseAllMenuItem"; this.collapseAllMenuItem.Size = new System.Drawing.Size(171, 22); this.collapseAllMenuItem.Text = "&Collapse All"; this.collapseAllMenuItem.Click += new System.EventHandler(this.collapseAllMenuItem_Click); // // toolStripSeparator7 // this.toolStripSeparator7.Name = "toolStripSeparator7"; this.toolStripSeparator7.Size = new System.Drawing.Size(168, 6); // // expandMenuItem // this.expandMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.expandPassedTestsToolStripMenuItem, this.expandFailedTestsToolStripMenuItem, this.expandSkippedTestsToolStripMenuItem}); this.expandMenuItem.Name = "expandMenuItem"; this.expandMenuItem.Size = new System.Drawing.Size(171, 22); this.expandMenuItem.Text = "Expand"; // // expandPassedTestsToolStripMenuItem // this.expandPassedTestsToolStripMenuItem.Image = global::Gallio.Icarus.Properties.Resources.tick; this.expandPassedTestsToolStripMenuItem.Name = "expandPassedTestsToolStripMenuItem"; this.expandPassedTestsToolStripMenuItem.Size = new System.Drawing.Size(144, 22); this.expandPassedTestsToolStripMenuItem.Text = "Passed"; this.expandPassedTestsToolStripMenuItem.Click += new System.EventHandler(this.expandPassedTestsToolStripMenuItem_Click); // // expandFailedTestsToolStripMenuItem // this.expandFailedTestsToolStripMenuItem.Image = global::Gallio.Icarus.Properties.Resources.cross; this.expandFailedTestsToolStripMenuItem.Name = "expandFailedTestsToolStripMenuItem"; this.expandFailedTestsToolStripMenuItem.Size = new System.Drawing.Size(144, 22); this.expandFailedTestsToolStripMenuItem.Text = "Failed"; this.expandFailedTestsToolStripMenuItem.Click += new System.EventHandler(this.expandFailedTestsToolStripMenuItem_Click); // // expandSkippedTestsToolStripMenuItem // this.expandSkippedTestsToolStripMenuItem.Image = global::Gallio.Icarus.Properties.Resources.error; this.expandSkippedTestsToolStripMenuItem.Name = "expandSkippedTestsToolStripMenuItem"; this.expandSkippedTestsToolStripMenuItem.Size = new System.Drawing.Size(144, 22); this.expandSkippedTestsToolStripMenuItem.Text = "Inconclusive"; this.expandSkippedTestsToolStripMenuItem.Click += new System.EventHandler(this.expandInconclusiveTestsToolStripMenuItem_Click); // // filterToolStripMenuItem // this.filterToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.filterPassedTestsToolStripMenuItem, this.filterFailedTestsToolStripMenuItem, this.filterInconclusiveTestsToolStripMenuItem}); this.filterToolStripMenuItem.Name = "filterToolStripMenuItem"; this.filterToolStripMenuItem.Size = new System.Drawing.Size(171, 22); this.filterToolStripMenuItem.Text = "Filter"; // // filterPassedTestsToolStripMenuItem // this.filterPassedTestsToolStripMenuItem.CheckOnClick = true; this.filterPassedTestsToolStripMenuItem.Image = global::Gallio.Icarus.Properties.Resources.FilterPassed; this.filterPassedTestsToolStripMenuItem.Name = "filterPassedTestsToolStripMenuItem"; this.filterPassedTestsToolStripMenuItem.Size = new System.Drawing.Size(144, 22); this.filterPassedTestsToolStripMenuItem.Text = "Passed"; // // filterFailedTestsToolStripMenuItem // this.filterFailedTestsToolStripMenuItem.CheckOnClick = true; this.filterFailedTestsToolStripMenuItem.Image = global::Gallio.Icarus.Properties.Resources.FilterFailed; this.filterFailedTestsToolStripMenuItem.Name = "filterFailedTestsToolStripMenuItem"; this.filterFailedTestsToolStripMenuItem.Size = new System.Drawing.Size(144, 22); this.filterFailedTestsToolStripMenuItem.Text = "Failed"; // // filterInconclusiveTestsToolStripMenuItem // this.filterInconclusiveTestsToolStripMenuItem.CheckOnClick = true; this.filterInconclusiveTestsToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("filterInconclusiveTestsToolStripMenuItem.Image"))); this.filterInconclusiveTestsToolStripMenuItem.Name = "filterInconclusiveTestsToolStripMenuItem"; this.filterInconclusiveTestsToolStripMenuItem.Size = new System.Drawing.Size(144, 22); this.filterInconclusiveTestsToolStripMenuItem.Text = "Inconclusive"; // // selectAllToolStripMenuItem // this.selectAllToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.selectPassedToolStripMenuItem, this.selectFailedToolStripMenuItem, this.selectInconclusiveToolStripMenuItem}); this.selectAllToolStripMenuItem.Name = "selectAllToolStripMenuItem"; this.selectAllToolStripMenuItem.Size = new System.Drawing.Size(171, 22); this.selectAllToolStripMenuItem.Text = "Select"; // // selectPassedToolStripMenuItem // this.selectPassedToolStripMenuItem.Image = global::Gallio.Icarus.Properties.Resources.tick; this.selectPassedToolStripMenuItem.Name = "selectPassedToolStripMenuItem"; this.selectPassedToolStripMenuItem.Size = new System.Drawing.Size(144, 22); this.selectPassedToolStripMenuItem.Text = "Passed"; this.selectPassedToolStripMenuItem.Click += new System.EventHandler(this.selectPassedToolStripMenuItem_Click); // // selectFailedToolStripMenuItem // this.selectFailedToolStripMenuItem.Image = global::Gallio.Icarus.Properties.Resources.cross; this.selectFailedToolStripMenuItem.Name = "selectFailedToolStripMenuItem"; this.selectFailedToolStripMenuItem.Size = new System.Drawing.Size(144, 22); this.selectFailedToolStripMenuItem.Text = "Failed"; this.selectFailedToolStripMenuItem.Click += new System.EventHandler(this.selectFailedToolStripMenuItem_Click); // // selectInconclusiveToolStripMenuItem // this.selectInconclusiveToolStripMenuItem.Image = global::Gallio.Icarus.Properties.Resources.error; this.selectInconclusiveToolStripMenuItem.Name = "selectInconclusiveToolStripMenuItem"; this.selectInconclusiveToolStripMenuItem.Size = new System.Drawing.Size(144, 22); this.selectInconclusiveToolStripMenuItem.Text = "Inconclusive"; this.selectInconclusiveToolStripMenuItem.Click += new System.EventHandler(this.selectInconclusiveToolStripMenuItem_Click); // // toolStripSeparator9 // this.toolStripSeparator9.Name = "toolStripSeparator9"; this.toolStripSeparator9.Size = new System.Drawing.Size(168, 6); // // resetTestsMenuItem // this.resetTestsMenuItem.Name = "resetTestsMenuItem"; this.resetTestsMenuItem.Size = new System.Drawing.Size(171, 22); this.resetTestsMenuItem.Text = "&Reset Tests"; this.resetTestsMenuItem.Click += new System.EventHandler(this.resetTestsMenuItem_Click); // // toolStripSeparator10 // this.toolStripSeparator10.Name = "toolStripSeparator10"; this.toolStripSeparator10.Size = new System.Drawing.Size(168, 6); // // filesToolStripMenuItem // this.filesToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.addFilesToolStripMenuItem, this.removeFileToolStripMenuItem, this.removeAllFilesToolStripMenuItem}); this.filesToolStripMenuItem.Name = "filesToolStripMenuItem"; this.filesToolStripMenuItem.Size = new System.Drawing.Size(171, 22); this.filesToolStripMenuItem.Text = "Files"; // // addFilesToolStripMenuItem // this.addFilesToolStripMenuItem.Name = "addFilesToolStripMenuItem"; this.addFilesToolStripMenuItem.Size = new System.Drawing.Size(162, 22); this.addFilesToolStripMenuItem.Text = "Add Files..."; this.addFilesToolStripMenuItem.Click += new System.EventHandler(this.addFilesToolStripMenuItem_Click); // // removeFileToolStripMenuItem // this.removeFileToolStripMenuItem.Enabled = false; this.removeFileToolStripMenuItem.Name = "removeFileToolStripMenuItem"; this.removeFileToolStripMenuItem.Size = new System.Drawing.Size(162, 22); this.removeFileToolStripMenuItem.Text = "Remove File"; this.removeFileToolStripMenuItem.Click += new System.EventHandler(this.removeFileToolStripMenuItem_Click); // // removeAllFilesToolStripMenuItem // this.removeAllFilesToolStripMenuItem.Name = "removeAllFilesToolStripMenuItem"; this.removeAllFilesToolStripMenuItem.Size = new System.Drawing.Size(162, 22); this.removeAllFilesToolStripMenuItem.Text = "Remove All Files"; this.removeAllFilesToolStripMenuItem.Click += new System.EventHandler(this.removeAllFilesToolStripMenuItem_Click); // // viewSourceCodeToolStripMenuItem // this.viewSourceCodeToolStripMenuItem.Enabled = false; this.viewSourceCodeToolStripMenuItem.Name = "viewSourceCodeToolStripMenuItem"; this.viewSourceCodeToolStripMenuItem.Size = new System.Drawing.Size(171, 22); this.viewSourceCodeToolStripMenuItem.Text = "View Source Code"; this.viewSourceCodeToolStripMenuItem.Click += new System.EventHandler(this.viewSourceCodeToolStripMenuItem_Click); // // toolStripContainer1 // this.toolStripContainer1.AllowDrop = true; // // toolStripContainer1.ContentPanel // this.toolStripContainer1.ContentPanel.AllowDrop = true; this.toolStripContainer1.ContentPanel.Controls.Add(this.testTree); this.toolStripContainer1.ContentPanel.Size = new System.Drawing.Size(281, 248); this.toolStripContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.toolStripContainer1.Location = new System.Drawing.Point(0, 0); this.toolStripContainer1.Name = "toolStripContainer1"; this.toolStripContainer1.Size = new System.Drawing.Size(281, 273); this.toolStripContainer1.TabIndex = 0; this.toolStripContainer1.Text = "toolStripContainer1"; // // toolStripContainer1.TopToolStripPanel // this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.toolStrip1); // // toolStrip1 // this.toolStrip1.Dock = System.Windows.Forms.DockStyle.None; this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.treeViewComboBox, this.filterPassedTestsToolStripButton, this.filterFailedTestsToolStripButton, this.filterInconclusiveTestsToolStripButton, this.sortAscToolStripButton, this.sortDescToolStripButton}); this.toolStrip1.Location = new System.Drawing.Point(3, 0); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(278, 25); this.toolStrip1.TabIndex = 5; // // treeViewComboBox // this.treeViewComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.treeViewComboBox.Name = "treeViewComboBox"; this.treeViewComboBox.Size = new System.Drawing.Size(121, 25); this.treeViewComboBox.SelectedIndexChanged += new System.EventHandler(this.treeViewComboBox_SelectedIndexChanged); // // filterPassedTestsToolStripButton // this.filterPassedTestsToolStripButton.CheckOnClick = true; this.filterPassedTestsToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.filterPassedTestsToolStripButton.Image = global::Gallio.Icarus.Properties.Resources.FilterPassed; this.filterPassedTestsToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.filterPassedTestsToolStripButton.Name = "filterPassedTestsToolStripButton"; this.filterPassedTestsToolStripButton.Size = new System.Drawing.Size(23, 22); this.filterPassedTestsToolStripButton.Text = "Filter passed tests"; // // filterFailedTestsToolStripButton // this.filterFailedTestsToolStripButton.CheckOnClick = true; this.filterFailedTestsToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.filterFailedTestsToolStripButton.Image = global::Gallio.Icarus.Properties.Resources.FilterFailed; this.filterFailedTestsToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.filterFailedTestsToolStripButton.Name = "filterFailedTestsToolStripButton"; this.filterFailedTestsToolStripButton.Size = new System.Drawing.Size(23, 22); this.filterFailedTestsToolStripButton.Text = "Filter failed tests"; // // filterInconclusiveTestsToolStripButton // this.filterInconclusiveTestsToolStripButton.CheckOnClick = true; this.filterInconclusiveTestsToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.filterInconclusiveTestsToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("filterInconclusiveTestsToolStripButton.Image"))); this.filterInconclusiveTestsToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.filterInconclusiveTestsToolStripButton.Name = "filterInconclusiveTestsToolStripButton"; this.filterInconclusiveTestsToolStripButton.Size = new System.Drawing.Size(23, 22); this.filterInconclusiveTestsToolStripButton.Text = "Filter inconclusive tests"; // // sortAscToolStripButton // this.sortAscToolStripButton.Checked = true; this.sortAscToolStripButton.CheckOnClick = true; this.sortAscToolStripButton.CheckState = System.Windows.Forms.CheckState.Checked; this.sortAscToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.sortAscToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("sortAscToolStripButton.Image"))); this.sortAscToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.sortAscToolStripButton.Name = "sortAscToolStripButton"; this.sortAscToolStripButton.Size = new System.Drawing.Size(23, 22); this.sortAscToolStripButton.Text = "Sort tree (asc)"; // // sortDescToolStripButton // this.sortDescToolStripButton.CheckOnClick = true; this.sortDescToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.sortDescToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("sortDescToolStripButton.Image"))); this.sortDescToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.sortDescToolStripButton.Name = "sortDescToolStripButton"; this.sortDescToolStripButton.Size = new System.Drawing.Size(23, 22); this.sortDescToolStripButton.Text = "Sort tree (desc)"; // // TestExplorer // this.AllowDrop = true; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(281, 273); this.Controls.Add(this.toolStripContainer1); this.Name = "TestExplorer"; this.testTreeMenuStrip.ResumeLayout(false); this.toolStripContainer1.ContentPanel.ResumeLayout(false); this.toolStripContainer1.TopToolStripPanel.ResumeLayout(false); this.toolStripContainer1.TopToolStripPanel.PerformLayout(); this.toolStripContainer1.ResumeLayout(false); this.toolStripContainer1.PerformLayout(); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ToolStripContainer toolStripContainer1; private Controls.TestTreeView testTree; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripComboBox treeViewComboBox; private UI.Controls.ToolStripButton filterPassedTestsToolStripButton; private UI.Controls.ToolStripButton filterInconclusiveTestsToolStripButton; private UI.Controls.ToolStripButton filterFailedTestsToolStripButton; private System.Windows.Forms.ContextMenuStrip testTreeMenuStrip; private System.Windows.Forms.ToolStripMenuItem expandAllMenuItem; private System.Windows.Forms.ToolStripMenuItem collapseAllMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator7; private System.Windows.Forms.ToolStripMenuItem expandMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator9; private System.Windows.Forms.ToolStripMenuItem resetTestsMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator10; private Gallio.UI.Controls.ToolStripButton sortDescToolStripButton; private System.Windows.Forms.ToolStripMenuItem expandPassedTestsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem expandFailedTestsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem expandSkippedTestsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem filterToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem viewSourceCodeToolStripMenuItem; private Gallio.UI.Controls.ToolStripMenuItem filterPassedTestsToolStripMenuItem; private Gallio.UI.Controls.ToolStripMenuItem filterFailedTestsToolStripMenuItem; private Gallio.UI.Controls.ToolStripMenuItem filterInconclusiveTestsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem filesToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem addFilesToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem removeFileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem removeAllFilesToolStripMenuItem; private Gallio.UI.Controls.ToolStripButton sortAscToolStripButton; private System.Windows.Forms.ToolStripMenuItem selectAllToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem selectPassedToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem selectFailedToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem selectInconclusiveToolStripMenuItem; } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Xml.Serialization; namespace Microsoft.PythonTools.Profiling { [Serializable] public sealed class ProfilingTarget { internal static XmlSerializer Serializer = new XmlSerializer(typeof(ProfilingTarget)); [XmlElement("ProjectTarget")] public ProjectTarget ProjectTarget { get; set; } [XmlElement("StandaloneTarget")] public StandaloneTarget StandaloneTarget { get; set; } [XmlElement("Reports")] public Reports Reports { get; set; } internal string GetProfilingName(IServiceProvider serviceProvider, out bool save) { string baseName = null; if (ProjectTarget != null) { if (!String.IsNullOrEmpty(ProjectTarget.FriendlyName)) { baseName = ProjectTarget.FriendlyName; } } else if (StandaloneTarget != null) { if (!String.IsNullOrEmpty(StandaloneTarget.Script)) { baseName = Path.GetFileNameWithoutExtension(StandaloneTarget.Script); } } if (baseName == null) { baseName = "Performance"; } baseName = baseName + ".pyperf"; var dte = (EnvDTE.DTE)serviceProvider.GetService(typeof(EnvDTE.DTE)); if (dte.Solution.IsOpen && !String.IsNullOrEmpty(dte.Solution.FullName)) { save = true; return Path.Combine(Path.GetDirectoryName(dte.Solution.FullName), baseName); } save = false; return baseName; } internal ProfilingTarget Clone() { var res = new ProfilingTarget(); if (ProjectTarget != null) { res.ProjectTarget = ProjectTarget.Clone(); } if (StandaloneTarget != null) { res.StandaloneTarget = StandaloneTarget.Clone(); } if (Reports != null) { res.Reports = Reports.Clone(); } return res; } internal static bool IsSame(ProfilingTarget self, ProfilingTarget other) { if (self == null) { return other == null; } else if (other != null) { return ProjectTarget.IsSame(self.ProjectTarget, other.ProjectTarget) && StandaloneTarget.IsSame(self.StandaloneTarget, other.StandaloneTarget); } return false; } } [Serializable] public sealed class ProjectTarget { [XmlElement("TargetProject")] public Guid TargetProject { get; set; } [XmlElement("FriendlyName")] public string FriendlyName { get; set; } internal ProjectTarget Clone() { var res = new ProjectTarget(); res.TargetProject = TargetProject; res.FriendlyName = FriendlyName; return res; } internal static bool IsSame(ProjectTarget self, ProjectTarget other) { if (self == null) { return other == null; } else if (other != null) { return self.TargetProject == other.TargetProject; } return false; } } [Serializable] public sealed class StandaloneTarget { [XmlElement(ElementName = "PythonInterpreter")] public PythonInterpreter PythonInterpreter { get; set; } [XmlElement(ElementName = "InterpreterPath")] public string InterpreterPath { get; set; } [XmlElement("WorkingDirectory")] public string WorkingDirectory { get; set; } [XmlElement("Script")] public string Script { get; set; } [XmlElement("Arguments")] public string Arguments { get; set; } internal StandaloneTarget Clone() { var res = new StandaloneTarget(); if (PythonInterpreter != null) { res.PythonInterpreter = PythonInterpreter.Clone(); } res.InterpreterPath = InterpreterPath; res.WorkingDirectory = WorkingDirectory; res.Script = Script; res.Arguments = Arguments; return res; } internal static bool IsSame(StandaloneTarget self, StandaloneTarget other) { if (self == null) { return other == null; } else if (other != null) { return PythonInterpreter.IsSame(self.PythonInterpreter, other.PythonInterpreter) && self.InterpreterPath == other.InterpreterPath && self.WorkingDirectory == other.WorkingDirectory && self.Script == other.Script && self.Arguments == other.Arguments; } return false; } } public sealed class PythonInterpreter { [XmlElement("Id")] public string Id { get; set; } internal PythonInterpreter Clone() { var res = new PythonInterpreter(); res.Id = Id; return res; } internal static bool IsSame(PythonInterpreter self, PythonInterpreter other) { if (self == null) { return other == null; } else if (other != null) { return self.Id == other.Id; } return false; } } public sealed class Reports { public Reports() { } public Reports(Profiling.Report[] reports) { Report = reports; } [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] [XmlElement("Report")] public Report[] Report { get { return AllReports.Values.ToArray(); } set { AllReports = new SortedDictionary<uint, Report>(); for (uint i = 0; i < value.Length; i++) { AllReports[i + SessionNode.StartingReportId] = value[i]; } } } internal SortedDictionary<uint, Report> AllReports { get; set; } internal Reports Clone() { var res = new Reports(); if (Report != null) { res.Report = new Report[Report.Length]; for (int i = 0; i < res.Report.Length; i++) { res.Report[i] = Report[i].Clone(); } } return res; } } public sealed class Report { public Report() { } public Report(string filename) { Filename = filename; } [XmlElement("Filename")] public string Filename { get; set; } internal Report Clone() { var res = new Report(); res.Filename = Filename; return res; } } }
// 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 Xunit; namespace System.Collections.Specialized.Tests { public static class BitVector32Tests { /// <summary> /// Data used for testing setting/unsetting multiple bits at a time. /// </summary> /// Format is: /// 1. Set data /// 2. Unset data /// 3. Bits to flip for transformation. /// <returns>Row of data</returns> public static IEnumerable<object[]> Mask_SetUnset_Multiple_Data() { yield return new object[] { 0, 0, new int[] { } }; yield return new object[] { 1, 0, new int[] { 1 } }; yield return new object[] { 2, 0, new int[] { 2 } }; yield return new object[] { int.MinValue, 0, new int[] { 32 } }; yield return new object[] { 6, 0, new int[] { 2, 3 } }; yield return new object[] { 6, 6, new int[] { 2, 3 } }; yield return new object[] { 31, 15, new int[] { 4 } }; yield return new object[] { 22, 16, new int[] { 2, 3 } }; yield return new object[] { -1, 0, new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 } }; } /// <summary> /// Data used for testing creating sections. /// </summary> /// Format is: /// 1. maximum value allowed /// 2. resulting mask /// <returns>Row of data</returns> public static IEnumerable<object[]> Section_Create_Data() { yield return new object[] { 1, 1 }; yield return new object[] { 2, 3 }; yield return new object[] { 3, 3 }; yield return new object[] { 16, 31 }; yield return new object[] { byte.MaxValue, byte.MaxValue }; yield return new object[] { short.MaxValue, short.MaxValue }; yield return new object[] { short.MaxValue - 1, short.MaxValue }; } /// <summary> /// Data used for testing setting/unsetting via sections. /// </summary> /// Format is: /// 1. value /// 2. section /// <returns>Row of data</returns> public static IEnumerable<object[]> Section_Set_Data() { yield return new object[] { 0, BitVector32.CreateSection(1) }; yield return new object[] { 1, BitVector32.CreateSection(1) }; yield return new object[] { 0, BitVector32.CreateSection(short.MaxValue) }; yield return new object[] { short.MaxValue, BitVector32.CreateSection(short.MaxValue) }; yield return new object[] { 0, BitVector32.CreateSection(1, BitVector32.CreateSection(byte.MaxValue)) }; yield return new object[] { 1, BitVector32.CreateSection(1, BitVector32.CreateSection(byte.MaxValue)) }; yield return new object[] { 0, BitVector32.CreateSection(short.MaxValue, BitVector32.CreateSection(byte.MaxValue)) }; yield return new object[] { short.MaxValue, BitVector32.CreateSection(short.MaxValue, BitVector32.CreateSection(byte.MaxValue)) }; yield return new object[] { 16, BitVector32.CreateSection(short.MaxValue) }; yield return new object[] { 16, BitVector32.CreateSection(short.MaxValue, BitVector32.CreateSection(byte.MaxValue)) }; yield return new object[] { 31, BitVector32.CreateSection(short.MaxValue) }; yield return new object[] { 31, BitVector32.CreateSection(short.MaxValue, BitVector32.CreateSection(byte.MaxValue)) }; yield return new object[] { 16, BitVector32.CreateSection(byte.MaxValue) }; yield return new object[] { 16, BitVector32.CreateSection(byte.MaxValue, BitVector32.CreateSection(byte.MaxValue, BitVector32.CreateSection(short.MaxValue))) }; yield return new object[] { 31, BitVector32.CreateSection(byte.MaxValue) }; yield return new object[] { 31, BitVector32.CreateSection(byte.MaxValue, BitVector32.CreateSection(byte.MaxValue, BitVector32.CreateSection(short.MaxValue))) }; } /// <summary> /// Data used for testing equal sections. /// </summary> /// Format is: /// 1. Section left /// 2. Section right /// <returns>Row of data</returns> public static IEnumerable<object[]> Section_Equal_Data() { BitVector32.Section original = BitVector32.CreateSection(16); BitVector32.Section nested = BitVector32.CreateSection(16, original); yield return new object[] { original, original }; yield return new object[] { original, BitVector32.CreateSection(16) }; yield return new object[] { BitVector32.CreateSection(16), original }; // Since the max value is changed to an inclusive mask, equal to mask max value yield return new object[] { original, BitVector32.CreateSection(31) }; yield return new object[] { nested, nested }; yield return new object[] { nested, BitVector32.CreateSection(16, original) }; yield return new object[] { BitVector32.CreateSection(16, original), nested }; yield return new object[] { nested, BitVector32.CreateSection(31, original) }; yield return new object[] { nested, BitVector32.CreateSection(16, BitVector32.CreateSection(16)) }; yield return new object[] { BitVector32.CreateSection(16, BitVector32.CreateSection(16)), nested }; yield return new object[] { nested, BitVector32.CreateSection(31, BitVector32.CreateSection(16)) }; // Because it only stores the offset, and not the previous section, later sections may be equal yield return new object[] { nested, BitVector32.CreateSection(16, BitVector32.CreateSection(8, BitVector32.CreateSection(1))) }; yield return new object[] { BitVector32.CreateSection(16, BitVector32.CreateSection(8, BitVector32.CreateSection(1))), nested }; } /// <summary> /// Data used for testing unequal sections. /// </summary> /// Format is: /// 1. Section left /// 2. Section right /// <returns>Row of data</returns> public static IEnumerable<object[]> Section_Unequal_Data() { BitVector32.Section original = BitVector32.CreateSection(16); BitVector32.Section nested = BitVector32.CreateSection(16, original); yield return new object[] { original, BitVector32.CreateSection(1) }; yield return new object[] { BitVector32.CreateSection(1), original }; yield return new object[] { original, nested }; yield return new object[] { nested, original }; yield return new object[] { nested, BitVector32.CreateSection(1, BitVector32.CreateSection(short.MaxValue)) }; yield return new object[] { BitVector32.CreateSection(1, BitVector32.CreateSection(short.MaxValue)), nested }; yield return new object[] { nested, BitVector32.CreateSection(16, BitVector32.CreateSection(short.MaxValue)) }; yield return new object[] { BitVector32.CreateSection(16, BitVector32.CreateSection(short.MaxValue)), nested }; yield return new object[] { nested, BitVector32.CreateSection(1, original) }; yield return new object[] { BitVector32.CreateSection(1, original), nested }; } [Fact] public static void Constructor_DefaultTest() { BitVector32 bv = new BitVector32(); Assert.Equal(0, bv.Data); // Copy constructor results in item with same data. BitVector32 copied = new BitVector32(bv); Assert.Equal(0, copied.Data); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(7)] [InlineData(99)] [InlineData(byte.MaxValue)] [InlineData(int.MaxValue / 2)] [InlineData(int.MaxValue - 1)] [InlineData(int.MaxValue)] [InlineData(-1)] [InlineData(-2)] [InlineData(-7)] [InlineData(-99)] [InlineData(byte.MinValue)] [InlineData(int.MinValue / 2)] [InlineData(int.MinValue + 1)] [InlineData(int.MinValue)] public static void Constructor_DataTest(int data) { BitVector32 bv = new BitVector32(data); Assert.Equal(data, bv.Data); // Copy constructor results in item with same data. BitVector32 copied = new BitVector32(bv); Assert.Equal(data, copied.Data); } [Fact] public static void Mask_DefaultTest() { Assert.Equal(1, BitVector32.CreateMask()); Assert.Equal(1, BitVector32.CreateMask(0)); } [Theory] [InlineData(2, 1)] [InlineData(6, 3)] [InlineData(short.MaxValue + 1, 1 << 14)] [InlineData(-2, int.MaxValue)] [InlineData(-2, -1)] // Works even if the mask has multiple bits set, which probably wasn't the intended use. public static void Mask_SeriesTest(int expected, int actual) { while (actual != int.MinValue) { actual = BitVector32.CreateMask(actual); Assert.Equal(expected, actual); expected <<= 1; } Assert.Equal(int.MinValue, actual); } [Fact] public static void Mask_LastTest() { Assert.Throws<InvalidOperationException>(() => BitVector32.CreateMask(int.MinValue)); } [Fact] public static void Get_Mask_AllSetTest() { BitVector32 all = new BitVector32(-1); int mask = 0; for (int count = 0; count < 32; count++) { mask = BitVector32.CreateMask(mask); Assert.True(all[mask]); } Assert.Equal(int.MinValue, mask); } [Fact] public static void Get_Mask_NoneSetTest() { BitVector32 none = new BitVector32(); int mask = 0; for (int count = 0; count < 32; count++) { mask = BitVector32.CreateMask(mask); Assert.False(none[mask]); } Assert.Equal(int.MinValue, mask); } [Fact] public static void Get_Mask_SomeSetTest() { // Constructs data with every even bit set. int data = Enumerable.Range(0, 16).Sum(x => 1 << (x * 2)); BitVector32 some = new BitVector32(data); int mask = 0; for (int index = 0; index < 32; index++) { mask = BitVector32.CreateMask(mask); Assert.Equal(index % 2 == 0, some[mask]); } Assert.Equal(int.MinValue, mask); } [Fact] public static void Set_Mask_EmptyTest() { BitVector32 nothing = new BitVector32(); nothing[0] = true; Assert.Equal(0, nothing.Data); BitVector32 all = new BitVector32(-1); all[0] = false; Assert.Equal(-1, all.Data); } [Fact] public static void Set_Mask_AllTest() { BitVector32 flip = new BitVector32(); int mask = 0; for (int bit = 1; bit < 32 + 1; bit++) { mask = BitVector32.CreateMask(mask); BitVector32 single = new BitVector32(); Assert.False(single[mask]); single[mask] = true; Assert.True(single[mask]); Assert.Equal(1 << (bit - 1), single.Data); flip[mask] = true; } Assert.Equal(-1, flip.Data); Assert.Equal(int.MinValue, mask); } [Fact] public static void Set_Mask_UnsetAllTest() { BitVector32 flip = new BitVector32(-1); int mask = 0; for (int bit = 1; bit < 32 + 1; bit++) { mask = BitVector32.CreateMask(mask); BitVector32 single = new BitVector32(1 << (bit - 1)); Assert.True(single[mask]); single[mask] = false; Assert.False(single[mask]); Assert.Equal(0, single.Data); flip[mask] = false; } Assert.Equal(0, flip.Data); Assert.Equal(int.MinValue, mask); } [Theory] [MemberData(nameof(Mask_SetUnset_Multiple_Data))] public static void Set_Mask_MultipleTest(int expected, int start, int[] maskPositions) { _ = expected; _ = start; int mask = maskPositions.Sum(x => 1 << (x - 1)); BitVector32 blank = new BitVector32(); BitVector32 set = new BitVector32(); set[mask] = true; for (int bit = 0; bit < 32; bit++) { Assert.False(blank[1 << bit]); bool willSet = maskPositions.Contains(bit + 1); blank[1 << bit] = willSet; Assert.Equal(willSet, blank[1 << bit]); Assert.Equal(willSet, set[1 << bit]); } Assert.Equal(set, blank); } [Theory] [MemberData(nameof(Mask_SetUnset_Multiple_Data))] public static void Set_Mask_Multiple_UnsetTest(int start, int expected, int[] maskPositions) { _ = start; _ = expected; int mask = maskPositions.Sum(x => 1 << (x - 1)); BitVector32 set = new BitVector32(); set[mask] = true; for (int bit = 0; bit < 32; bit++) { bool willUnset = maskPositions.Contains(bit + 1); Assert.Equal(willUnset, set[1 << bit]); set[1 << bit] = false; Assert.False(set[1 << bit]); } Assert.Equal(set, new BitVector32()); } [Theory] [MemberData(nameof(Section_Set_Data))] public static void Set_SectionTest(int value, BitVector32.Section section) { BitVector32 empty = new BitVector32(); empty[section] = value; Assert.Equal(value, empty[section]); Assert.Equal(value << section.Offset, empty.Data); BitVector32 full = new BitVector32(-1); full[section] = value; Assert.Equal(value, full[section]); int offsetMask = section.Mask << section.Offset; Assert.Equal((-1 & ~offsetMask) | (value << section.Offset), full.Data); } [Theory] [InlineData(short.MaxValue, int.MaxValue)] [InlineData(1, 2)] [InlineData(1, short.MaxValue)] [InlineData(1, -1)] [InlineData(short.MaxValue, short.MinValue)] public static void Set_Section_OutOfRangeTest(short maximum, int value) { { BitVector32 data = new BitVector32(); BitVector32.Section section = BitVector32.CreateSection(maximum); data[section] = value; Assert.Equal(maximum & value, data.Data); Assert.NotEqual(value, data.Data); Assert.Equal(maximum & value, data[section]); Assert.NotEqual(value, data[section]); } { BitVector32 data = new BitVector32(); BitVector32.Section nested = BitVector32.CreateSection(maximum, BitVector32.CreateSection(short.MaxValue)); data[nested] = value; Assert.Equal((maximum & value) << 15, data.Data); Assert.NotEqual(value << 15, data.Data); Assert.Equal(maximum & value, data[nested]); Assert.NotEqual(value, data[nested]); } } [Theory] [InlineData(4)] [InlineData(5)] [InlineData(short.MaxValue)] [InlineData(byte.MaxValue)] // Regardless of mask size, values will be truncated if they hang off the end public static void Set_Section_OverflowTest(int value) { BitVector32 data = new BitVector32(); BitVector32.Section offset = BitVector32.CreateSection(short.MaxValue, BitVector32.CreateSection(short.MaxValue)); BitVector32.Section final = BitVector32.CreateSection(short.MaxValue, offset); data[final] = value; Assert.Equal((3 & value) << 30, data.Data); Assert.NotEqual(value, data.Data); Assert.Equal(3 & value, data[final]); Assert.NotEqual(value, data[final]); } [Theory] [MemberData(nameof(Section_Create_Data))] public static void CreateSectionTest(short maximum, short mask) { BitVector32.Section section = BitVector32.CreateSection(maximum); Assert.Equal(0, section.Offset); Assert.Equal(mask, section.Mask); } [Theory] [MemberData(nameof(Section_Create_Data))] public static void CreateSection_NextTest(short maximum, short mask) { BitVector32.Section initial = BitVector32.CreateSection(short.MaxValue); BitVector32.Section section = BitVector32.CreateSection(maximum, initial); Assert.Equal(15, section.Offset); Assert.Equal(mask, section.Mask); } [Theory] [InlineData(short.MinValue)] [InlineData(-1)] [InlineData(0)] public static void CreateSection_InvalidMaximumTest(short maxvalue) { AssertExtensions.Throws<ArgumentException>("maxValue", () => BitVector32.CreateSection(maxvalue)); BitVector32.Section valid = BitVector32.CreateSection(1); AssertExtensions.Throws<ArgumentException>("maxValue", () => BitVector32.CreateSection(maxvalue, valid)); } [Theory] [InlineData(7, short.MaxValue)] [InlineData(short.MaxValue, 7)] [InlineData(short.MaxValue, short.MaxValue)] [InlineData(byte.MaxValue, byte.MaxValue)] public static void CreateSection_FullTest(short prior, short invalid) { // BV32 can hold just over 2 shorts, so fill most of the way first.... BitVector32.Section initial = BitVector32.CreateSection(short.MaxValue, BitVector32.CreateSection(short.MaxValue)); BitVector32.Section overflow = BitVector32.CreateSection(prior, initial); // Final masked value can hang off the end Assert.Equal(prior, overflow.Mask); Assert.Equal(30, overflow.Offset); // The next section would be created "off the end" // - the current offset is 30, and the current mask requires more than the remaining 1 bit. Assert.InRange(CountBitsRequired(overflow.Mask), 2, 15); Assert.Throws<InvalidOperationException>(() => BitVector32.CreateSection(invalid, overflow)); } [Theory] [MemberData(nameof(Section_Equal_Data))] public static void Section_EqualsTest(BitVector32.Section left, BitVector32.Section right) { Assert.True(left.Equals(left)); Assert.True(left.Equals(right)); Assert.True(right.Equals(left)); Assert.True(left.Equals((object)left)); Assert.True(left.Equals((object)right)); Assert.True(right.Equals((object)left)); Assert.True(left == right); Assert.True(right == left); Assert.False(left != right); Assert.False(right != left); } [Theory] [MemberData(nameof(Section_Unequal_Data))] public static void Section_Unequal_EqualsTest(BitVector32.Section left, BitVector32.Section right) { Assert.False(left.Equals(right)); Assert.False(right.Equals(left)); Assert.False(left.Equals((object)right)); Assert.False(right.Equals((object)left)); Assert.False(left.Equals(new object())); Assert.False(left == right); Assert.False(right == left); Assert.True(left != right); Assert.True(right != left); } [Theory] [MemberData(nameof(Section_Equal_Data))] public static void Section_GetHashCodeTest(BitVector32.Section left, BitVector32.Section right) { Assert.Equal(left.GetHashCode(), left.GetHashCode()); Assert.Equal(left.GetHashCode(), right.GetHashCode()); } [Fact] public static void Section_ToStringTest() { Random random = new Random(-55); short maxValue = (short)random.Next(1, short.MaxValue); BitVector32.Section section1 = BitVector32.CreateSection(maxValue); BitVector32.Section section2 = BitVector32.CreateSection(maxValue); Assert.Equal(section1.ToString(), section2.ToString()); Assert.Equal(section1.ToString(), BitVector32.Section.ToString(section2)); } [Fact] public static void EqualsTest() { BitVector32 original = new BitVector32(); Assert.True(original.Equals(original)); Assert.True(new BitVector32().Equals(original)); Assert.True(original.Equals(new BitVector32())); Assert.True(new BitVector32(0).Equals(original)); Assert.True(original.Equals(new BitVector32(0))); BitVector32 other = new BitVector32(int.MaxValue / 2 - 1); Assert.True(other.Equals(other)); Assert.True(new BitVector32(int.MaxValue / 2 - 1).Equals(other)); Assert.True(other.Equals(new BitVector32(int.MaxValue / 2 - 1))); Assert.False(other.Equals(original)); Assert.False(original.Equals(other)); Assert.False(other.Equals(null)); Assert.False(original.Equals(null)); Assert.False(other.Equals(int.MaxValue / 2 - 1)); Assert.False(original.Equals(0)); } [Fact] public static void GetHashCodeTest() { BitVector32 original = new BitVector32(); Assert.Equal(original.GetHashCode(), original.GetHashCode()); Assert.Equal(new BitVector32().GetHashCode(), original.GetHashCode()); Assert.Equal(new BitVector32(0).GetHashCode(), original.GetHashCode()); BitVector32 other = new BitVector32(int.MaxValue / 2 - 1); Assert.Equal(other.GetHashCode(), other.GetHashCode()); Assert.Equal(new BitVector32(int.MaxValue / 2 - 1).GetHashCode(), other.GetHashCode()); } [Theory] [InlineData(0, "BitVector32{00000000000000000000000000000000}")] [InlineData(1, "BitVector32{00000000000000000000000000000001}")] [InlineData(-1, "BitVector32{11111111111111111111111111111111}")] [InlineData(16 - 2, "BitVector32{00000000000000000000000000001110}")] [InlineData(-(16 - 2), "BitVector32{11111111111111111111111111110010}")] [InlineData(int.MaxValue, "BitVector32{01111111111111111111111111111111}")] [InlineData(int.MinValue, "BitVector32{10000000000000000000000000000000}")] [InlineData(short.MaxValue, "BitVector32{00000000000000000111111111111111}")] [InlineData(short.MinValue, "BitVector32{11111111111111111000000000000000}")] public static void ToStringTest(int data, string expected) { Assert.Equal(expected, new BitVector32(data).ToString()); Assert.Equal(expected, BitVector32.ToString(new BitVector32(data))); } private static short CountBitsRequired(short value) { short required = 16; while ((value & 0x8000) == 0) { required--; value <<= 1; } return required; } } }
using System; using System.IO; using System.Linq; using AsmResolver.DotNet.Builder; using AsmResolver.DotNet.Code.Cil; using AsmResolver.DotNet.Signatures; using AsmResolver.DotNet.Signatures.Types; using AsmResolver.DotNet.TestCases.CustomAttributes; using AsmResolver.DotNet.TestCases.Properties; using AsmResolver.IO; using AsmResolver.PE; using AsmResolver.PE.DotNet.Cil; using AsmResolver.PE.DotNet.Metadata.Tables; using AsmResolver.PE.DotNet.Metadata.Tables.Rows; using Xunit; namespace AsmResolver.DotNet.Tests { public class CustomAttributeTest { private readonly SignatureComparer _comparer = new SignatureComparer(); [Fact] public void ReadConstructor() { var module = ModuleDefinition.FromFile(typeof(CustomAttributesTestClass).Assembly.Location); var type = module.TopLevelTypes.First(t => t.Name == nameof(CustomAttributesTestClass)); Assert.All(type.CustomAttributes, a => Assert.Equal(nameof(TestCaseAttribute), a.Constructor.DeclaringType.Name)); } [Fact] public void PersistentConstructor() { var module = ModuleDefinition.FromFile(typeof(CustomAttributesTestClass).Assembly.Location); using var stream = new MemoryStream(); module.Write(stream); module = ModuleDefinition.FromReader(ByteArrayDataSource.CreateReader(stream.ToArray())); var type = module.TopLevelTypes.First(t => t.Name == nameof(CustomAttributesTestClass)); Assert.All(type.CustomAttributes, a => Assert.Equal(nameof(TestCaseAttribute), a.Constructor.DeclaringType.Name)); } [Fact] public void ReadParent() { int parentToken = typeof(CustomAttributesTestClass).MetadataToken; string filePath = typeof(CustomAttributesTestClass).Assembly.Location; var image = PEImage.FromFile(filePath); var tablesStream = image.DotNetDirectory.Metadata.GetStream<TablesStream>(); var encoder = tablesStream.GetIndexEncoder(CodedIndex.HasCustomAttribute); var attributeTable = tablesStream.GetTable<CustomAttributeRow>(TableIndex.CustomAttribute); // Find token of custom attribute var attributeToken = MetadataToken.Zero; for (int i = 0; i < attributeTable.Count && attributeToken == 0; i++) { var row = attributeTable[i]; var token = encoder.DecodeIndex(row.Parent); if (token == parentToken) attributeToken = new MetadataToken(TableIndex.CustomAttribute, (uint) (i + 1)); } // Resolve by token and verify parent (forcing parent to execute the lazy initialization ). var module = ModuleDefinition.FromFile(filePath); var attribute = (CustomAttribute) module.LookupMember(attributeToken); Assert.NotNull(attribute.Parent); Assert.IsAssignableFrom<TypeDefinition>(attribute.Parent); Assert.Equal(parentToken, attribute.Parent.MetadataToken); } private static CustomAttribute GetCustomAttributeTestCase(string methodName, bool rebuild = false) { var module = ModuleDefinition.FromFile(typeof(CustomAttributesTestClass).Assembly.Location); var type = module.TopLevelTypes.First(t => t.Name == nameof(CustomAttributesTestClass)); var method = type.Methods.First(m => m.Name == methodName); var attribute = method.CustomAttributes .First(c => c.Constructor.DeclaringType.Name == nameof(TestCaseAttribute)); if (rebuild) attribute = RebuildAndLookup(attribute); return attribute; } private static CustomAttribute RebuildAndLookup(CustomAttribute attribute) { var stream = new MemoryStream(); var method = (MethodDefinition) attribute.Parent; method.Module.Write(stream); var newModule = ModuleDefinition.FromBytes(stream.ToArray()); return newModule .TopLevelTypes.First(t => t.FullName == method.DeclaringType.FullName) .Methods.First(f => f.Name == method.Name) .CustomAttributes[0]; } [Theory] [InlineData(false)] [InlineData(true)] public void FixedInt32Argument(bool rebuild) { var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedInt32Argument), rebuild); Assert.Single(attribute.Signature.FixedArguments); Assert.Empty(attribute.Signature.NamedArguments); var argument = attribute.Signature.FixedArguments[0]; Assert.Equal(1, argument.Element); } [Theory] [InlineData(false)] [InlineData(true)] public void FixedStringArgument(bool rebuild) { var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedStringArgument), rebuild); Assert.Single(attribute.Signature.FixedArguments); Assert.Empty(attribute.Signature.NamedArguments); var argument = attribute.Signature.FixedArguments[0]; Assert.Equal("String fixed arg", argument.Element); } [Theory] [InlineData(false)] [InlineData(true)] public void FixedEnumArgument(bool rebuild) { var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedEnumArgument), rebuild); Assert.Single(attribute.Signature.FixedArguments); Assert.Empty(attribute.Signature.NamedArguments); var argument = attribute.Signature.FixedArguments[0]; Assert.Equal((int) TestEnum.Value3, argument.Element); } [Theory] [InlineData(false)] [InlineData(true)] public void FixedNullTypeArgument(bool rebuild) { var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedNullTypeArgument), rebuild); var fixedArg = Assert.Single(attribute.Signature.FixedArguments); Assert.Null(fixedArg.Element); } [Theory] [InlineData(false)] [InlineData(true)] public void FixedTypeArgument(bool rebuild) { var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedTypeArgument), rebuild); Assert.Single(attribute.Signature.FixedArguments); Assert.Empty(attribute.Signature.NamedArguments); var argument = attribute.Signature.FixedArguments[0]; Assert.Equal( attribute.Constructor.Module.CorLibTypeFactory.String, argument.Element as TypeSignature, _comparer); } [Theory] [InlineData(false)] [InlineData(true)] public void FixedComplexTypeArgument(bool rebuild) { var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedComplexTypeArgument), rebuild); Assert.Single(attribute.Signature.FixedArguments); Assert.Empty(attribute.Signature.NamedArguments); var argument = attribute.Signature.FixedArguments[0]; var factory = attribute.Constructor.Module.CorLibTypeFactory; var listRef = new TypeReference(factory.CorLibScope, "System.Collections.Generic", "KeyValuePair`2"); var instance = new GenericInstanceTypeSignature(listRef, false, new SzArrayTypeSignature(factory.String), new SzArrayTypeSignature(factory.Int32)); Assert.Equal(instance, argument.Element as TypeSignature, _comparer); } [Theory] [InlineData(false)] [InlineData(true)] public void NamedInt32Argument(bool rebuild) { var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.NamedInt32Argument), rebuild); Assert.Empty(attribute.Signature.FixedArguments); Assert.Single(attribute.Signature.NamedArguments); var argument = attribute.Signature.NamedArguments[0]; Assert.Equal(nameof(TestCaseAttribute.IntValue), argument.MemberName); Assert.Equal(2, argument.Argument.Element); } [Theory] [InlineData(false)] [InlineData(true)] public void NamedStringArgument(bool rebuild) { var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.NamedStringArgument), rebuild); Assert.Empty(attribute.Signature.FixedArguments); Assert.Single(attribute.Signature.NamedArguments); var argument = attribute.Signature.NamedArguments[0]; Assert.Equal(nameof(TestCaseAttribute.StringValue), argument.MemberName); Assert.Equal("String named arg", argument.Argument.Element); } [Theory] [InlineData(false)] [InlineData(true)] public void NamedEnumArgument(bool rebuild) { var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.NamedEnumArgument), rebuild); Assert.Empty(attribute.Signature.FixedArguments); Assert.Single(attribute.Signature.NamedArguments); var argument = attribute.Signature.NamedArguments[0]; Assert.Equal(nameof(TestCaseAttribute.EnumValue), argument.MemberName); Assert.Equal((int) TestEnum.Value2, argument.Argument.Element); } [Theory] [InlineData(false)] [InlineData(true)] public void NamedTypeArgument(bool rebuild) { var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.NamedTypeArgument), rebuild); Assert.Empty(attribute.Signature.FixedArguments); Assert.Single(attribute.Signature.NamedArguments); var expected = new TypeReference( attribute.Constructor.Module.CorLibTypeFactory.CorLibScope, "System", "Int32"); var argument = attribute.Signature.NamedArguments[0]; Assert.Equal(nameof(TestCaseAttribute.TypeValue), argument.MemberName); Assert.Equal(expected, (ITypeDescriptor) argument.Argument.Element, _comparer); } [Fact] public void IsCompilerGeneratedMember() { var module = ModuleDefinition.FromFile(typeof(SingleProperty).Assembly.Location); var type = module.TopLevelTypes.First(t => t.Name == nameof(SingleProperty)); var property = type.Properties.First(); var setMethod = property.SetMethod; Assert.True(setMethod.IsCompilerGenerated()); } [Theory] [InlineData(false)] [InlineData(true)] public void GenericTypeArgument(bool rebuild) { // https://github.com/Washi1337/AsmResolver/issues/92 var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.GenericType), rebuild); var argument = attribute.Signature.FixedArguments[0]; var module = attribute.Constructor.Module; var nestedClass = (TypeDefinition) module.LookupMember(typeof(TestGenericType<>).MetadataToken); var expected = new GenericInstanceTypeSignature(nestedClass, false, module.CorLibTypeFactory.Object); Assert.IsAssignableFrom<TypeSignature>(argument.Element); Assert.Equal(expected, (TypeSignature) argument.Element, _comparer); } [Theory] [InlineData(false)] [InlineData(true)] public void ArrayGenericTypeArgument(bool rebuild) { // https://github.com/Washi1337/AsmResolver/issues/92 var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.GenericTypeArray), rebuild); var argument = attribute.Signature.FixedArguments[0]; var module = attribute.Constructor.Module; var nestedClass = (TypeDefinition) module.LookupMember(typeof(TestGenericType<>).MetadataToken); var expected = new SzArrayTypeSignature( new GenericInstanceTypeSignature(nestedClass, false, module.CorLibTypeFactory.Object) ); Assert.IsAssignableFrom<TypeSignature>(argument.Element); Assert.Equal(expected, (TypeSignature) argument.Element, _comparer); } [Theory] [InlineData(false)] [InlineData(true)] public void IntPassedOnAsObject(bool rebuild) { // https://github.com/Washi1337/AsmResolver/issues/92 var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.Int32PassedAsObject), rebuild); var argument = attribute.Signature.FixedArguments[0]; Assert.IsAssignableFrom<BoxedArgument>(argument.Element); Assert.Equal(123, ((BoxedArgument) argument.Element).Value); } [Theory] [InlineData(false)] [InlineData(true)] public void TypePassedOnAsObject(bool rebuild) { // https://github.com/Washi1337/AsmResolver/issues/92 var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.TypePassedAsObject), rebuild); var argument = attribute.Signature.FixedArguments[0]; var module = attribute.Constructor.Module; Assert.IsAssignableFrom<BoxedArgument>(argument.Element); Assert.Equal(module.CorLibTypeFactory.Int32, (ITypeDescriptor) ((BoxedArgument) argument.Element).Value, _comparer); } [Theory] [InlineData(false)] [InlineData(true)] public void FixedInt32NullArray(bool rebuild) { var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedInt32ArrayNullArgument), rebuild); var argument = attribute.Signature.FixedArguments[0]; Assert.True(argument.IsNullArray); } [Theory] [InlineData(false)] [InlineData(true)] public void FixedInt32EmptyArray(bool rebuild) { var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedInt32ArrayEmptyArgument), rebuild); var argument = attribute.Signature.FixedArguments[0]; Assert.False(argument.IsNullArray); Assert.Empty(argument.Elements); } [Theory] [InlineData(false)] [InlineData(true)] public void FixedInt32Array(bool rebuild) { var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedInt32ArrayArgument), rebuild); var argument = attribute.Signature.FixedArguments[0]; Assert.Equal(new[] { 1, 2, 3, 4 }, argument.Elements.Cast<int>()); } [Theory] [InlineData(false)] [InlineData(true)] public void FixedInt32ArrayNullAsObject(bool rebuild) { var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedInt32ArrayAsObjectNullArgument), rebuild); var argument = attribute.Signature.FixedArguments[0]; Assert.IsAssignableFrom<BoxedArgument>(argument.Element); var boxedArgument = (BoxedArgument) argument.Element; Assert.Null(boxedArgument.Value); } [Theory] [InlineData(false)] [InlineData(true)] public void FixedInt32EmptyArrayAsObject(bool rebuild) { var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedInt32ArrayAsObjectEmptyArgument), rebuild); var argument = attribute.Signature.FixedArguments[0]; Assert.IsAssignableFrom<BoxedArgument>(argument.Element); var boxedArgument = (BoxedArgument) argument.Element; Assert.Equal(new object[0], boxedArgument.Value); } [Theory] [InlineData(false)] [InlineData(true)] public void FixedInt32ArrayAsObject(bool rebuild) { var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedInt32ArrayAsObjectArgument), rebuild); var argument = attribute.Signature.FixedArguments[0]; Assert.IsAssignableFrom<BoxedArgument>(argument.Element); var boxedArgument = (BoxedArgument) argument.Element; Assert.Equal(new[] { 1, 2, 3, 4 }, boxedArgument.Value); } } }
using UnityEngine; using System.Collections; public class Block { const float tileSize = 0.25f; // 1 divided by rows public struct Tile { public int x; public int y; } public enum Direction { North, East, South, West, Up, Down }; public virtual Tile TexturePosition(Direction direction) { Tile tile = new Tile(); tile.x = 0; tile.y = 0; return tile; } public virtual Vector2[] FaceUVs(Direction direction) { Vector2[] UVs = new Vector2[4]; Tile tilePos = TexturePosition(direction); UVs[0] = new Vector2(tileSize * tilePos.x + tileSize, tileSize * tilePos.y); UVs[1] = new Vector2(tileSize * tilePos.x + tileSize, tileSize * tilePos.y + tileSize); UVs[2] = new Vector2(tileSize * tilePos.x, tileSize * tilePos.y + tileSize); UVs[3] = new Vector2(tileSize * tilePos.x, tileSize * tilePos.y); return UVs; } public Block() { } public virtual MeshData Blockdata(Chunk chunk, int x, int y, int z, MeshData meshData) { meshData.useRenderDataForCol = true; if (!chunk.GetBlock(x, y + 1, z).IsSolid(Direction.Down)) { meshData = FaceDataUp(chunk, x, y, z, meshData); } if (!chunk.GetBlock(x, y - 1, z).IsSolid(Direction.Up)) { meshData = FaceDataDown(chunk, x, y, z, meshData); } if (!chunk.GetBlock(x, y, z + 1).IsSolid(Direction.South)) { meshData = FaceDataNorth(chunk, x, y, z, meshData); } if (!chunk.GetBlock(x, y, z - 1).IsSolid(Direction.North)) { meshData = FaceDataSouth(chunk, x, y, z, meshData); } if (!chunk.GetBlock(x + 1, y, z).IsSolid(Direction.West)) { meshData = FaceDataEast(chunk, x, y, z, meshData); } if (!chunk.GetBlock(x - 1, y, z).IsSolid(Direction.East)) { meshData = FaceDataWest(chunk, x, y, z, meshData); } return meshData; } protected virtual MeshData FaceDataUp (Chunk chunk, int x, int y, int z, MeshData meshData) { meshData.AddVertex(new Vector3(x - 0.5f, y + 0.5f, z + 0.5f)); meshData.AddVertex(new Vector3(x + 0.5f, y + 0.5f, z + 0.5f)); meshData.AddVertex(new Vector3(x + 0.5f, y + 0.5f, z - 0.5f)); meshData.AddVertex(new Vector3(x - 0.5f, y + 0.5f, z - 0.5f)); meshData.AddQuadTriangles(); meshData.uv.AddRange(FaceUVs(Direction.Up)); return meshData; } protected virtual MeshData FaceDataDown (Chunk chunk, int x, int y, int z, MeshData meshData) { meshData.AddVertex(new Vector3(x - 0.5f, y - 0.5f, z - 0.5f)); meshData.AddVertex(new Vector3(x + 0.5f, y - 0.5f, z - 0.5f)); meshData.AddVertex(new Vector3(x + 0.5f, y - 0.5f, z + 0.5f)); meshData.AddVertex(new Vector3(x - 0.5f, y - 0.5f, z + 0.5f)); meshData.AddQuadTriangles(); meshData.uv.AddRange(FaceUVs(Direction.Down)); return meshData; } protected virtual MeshData FaceDataNorth (Chunk chunk, int x, int y, int z, MeshData meshData) { meshData.AddVertex(new Vector3(x + 0.5f, y - 0.5f, z + 0.5f)); meshData.AddVertex(new Vector3(x + 0.5f, y + 0.5f, z + 0.5f)); meshData.AddVertex(new Vector3(x - 0.5f, y + 0.5f, z + 0.5f)); meshData.AddVertex(new Vector3(x - 0.5f, y - 0.5f, z + 0.5f)); meshData.AddQuadTriangles(); meshData.uv.AddRange(FaceUVs(Direction.North)); return meshData; } protected virtual MeshData FaceDataEast (Chunk chunk, int x, int y, int z, MeshData meshData) { meshData.AddVertex(new Vector3(x + 0.5f, y - 0.5f, z - 0.5f)); meshData.AddVertex(new Vector3(x + 0.5f, y + 0.5f, z - 0.5f)); meshData.AddVertex(new Vector3(x + 0.5f, y + 0.5f, z + 0.5f)); meshData.AddVertex(new Vector3(x + 0.5f, y - 0.5f, z + 0.5f)); meshData.AddQuadTriangles(); meshData.uv.AddRange(FaceUVs(Direction.East)); return meshData; } protected virtual MeshData FaceDataSouth (Chunk chunk, int x, int y, int z, MeshData meshData) { meshData.AddVertex(new Vector3(x - 0.5f, y - 0.5f, z - 0.5f)); meshData.AddVertex(new Vector3(x - 0.5f, y + 0.5f, z - 0.5f)); meshData.AddVertex(new Vector3(x + 0.5f, y + 0.5f, z - 0.5f)); meshData.AddVertex(new Vector3(x + 0.5f, y - 0.5f, z - 0.5f)); meshData.AddQuadTriangles(); meshData.uv.AddRange(FaceUVs(Direction.South)); return meshData; } protected virtual MeshData FaceDataWest (Chunk chunk, int x, int y, int z, MeshData meshData) { meshData.AddVertex(new Vector3(x - 0.5f, y - 0.5f, z + 0.5f)); meshData.AddVertex(new Vector3(x - 0.5f, y + 0.5f, z + 0.5f)); meshData.AddVertex(new Vector3(x - 0.5f, y + 0.5f, z - 0.5f)); meshData.AddVertex(new Vector3(x - 0.5f, y - 0.5f, z - 0.5f)); meshData.AddQuadTriangles(); meshData.uv.AddRange(FaceUVs(Direction.West)); return meshData; } public virtual bool IsSolid(Direction direction) { switch (direction) { case Direction.North: return true; case Direction.East: return true; case Direction.South: return true; case Direction.West: return true; case Direction.Up: return true; case Direction.Down: return true; } return false; } }
// 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 gagvr = Google.Ads.GoogleAds.V10.Resources; using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V10.Resources { /// <summary>Resource name for the <c>Experiment</c> resource.</summary> public sealed partial class ExperimentName : gax::IResourceName, sys::IEquatable<ExperimentName> { /// <summary>The possible contents of <see cref="ExperimentName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>customers/{customer_id}/experiments/{trial_id}</c>.</summary> CustomerTrial = 1, } private static gax::PathTemplate s_customerTrial = new gax::PathTemplate("customers/{customer_id}/experiments/{trial_id}"); /// <summary>Creates a <see cref="ExperimentName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="ExperimentName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static ExperimentName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new ExperimentName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="ExperimentName"/> with the pattern <c>customers/{customer_id}/experiments/{trial_id}</c> /// . /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="trialId">The <c>Trial</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ExperimentName"/> constructed from the provided ids.</returns> public static ExperimentName FromCustomerTrial(string customerId, string trialId) => new ExperimentName(ResourceNameType.CustomerTrial, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), trialId: gax::GaxPreconditions.CheckNotNullOrEmpty(trialId, nameof(trialId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ExperimentName"/> with pattern /// <c>customers/{customer_id}/experiments/{trial_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="trialId">The <c>Trial</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ExperimentName"/> with pattern /// <c>customers/{customer_id}/experiments/{trial_id}</c>. /// </returns> public static string Format(string customerId, string trialId) => FormatCustomerTrial(customerId, trialId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ExperimentName"/> with pattern /// <c>customers/{customer_id}/experiments/{trial_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="trialId">The <c>Trial</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ExperimentName"/> with pattern /// <c>customers/{customer_id}/experiments/{trial_id}</c>. /// </returns> public static string FormatCustomerTrial(string customerId, string trialId) => s_customerTrial.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(trialId, nameof(trialId))); /// <summary>Parses the given resource name string into a new <see cref="ExperimentName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/experiments/{trial_id}</c></description></item> /// </list> /// </remarks> /// <param name="experimentName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="ExperimentName"/> if successful.</returns> public static ExperimentName Parse(string experimentName) => Parse(experimentName, false); /// <summary> /// Parses the given resource name string into a new <see cref="ExperimentName"/> instance; optionally allowing /// an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/experiments/{trial_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="experimentName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="ExperimentName"/> if successful.</returns> public static ExperimentName Parse(string experimentName, bool allowUnparsed) => TryParse(experimentName, allowUnparsed, out ExperimentName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ExperimentName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/experiments/{trial_id}</c></description></item> /// </list> /// </remarks> /// <param name="experimentName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="ExperimentName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string experimentName, out ExperimentName result) => TryParse(experimentName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ExperimentName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/experiments/{trial_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="experimentName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="ExperimentName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string experimentName, bool allowUnparsed, out ExperimentName result) { gax::GaxPreconditions.CheckNotNull(experimentName, nameof(experimentName)); gax::TemplatedResourceName resourceName; if (s_customerTrial.TryParseName(experimentName, out resourceName)) { result = FromCustomerTrial(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(experimentName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private ExperimentName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string trialId = null) { Type = type; UnparsedResource = unparsedResourceName; CustomerId = customerId; TrialId = trialId; } /// <summary> /// Constructs a new instance of a <see cref="ExperimentName"/> class from the component parts of pattern /// <c>customers/{customer_id}/experiments/{trial_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="trialId">The <c>Trial</c> ID. Must not be <c>null</c> or empty.</param> public ExperimentName(string customerId, string trialId) : this(ResourceNameType.CustomerTrial, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), trialId: gax::GaxPreconditions.CheckNotNullOrEmpty(trialId, nameof(trialId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>Trial</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string TrialId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerTrial: return s_customerTrial.Expand(CustomerId, TrialId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as ExperimentName); /// <inheritdoc/> public bool Equals(ExperimentName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(ExperimentName a, ExperimentName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(ExperimentName a, ExperimentName b) => !(a == b); } public partial class Experiment { /// <summary> /// <see cref="gagvr::ExperimentName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal ExperimentName ResourceNameAsExperimentName { get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::ExperimentName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagvr::ExperimentName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> internal ExperimentName ExperimentName { get => string.IsNullOrEmpty(Name) ? null : gagvr::ExperimentName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
#region Copyright notice and license // Copyright 2015 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Concurrent; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; using Grpc.Core.Logging; using Grpc.Core.Utils; namespace Grpc.Core.Internal { internal delegate void NativeCallbackTestDelegate(bool success); /// <summary> /// Provides access to all native methods provided by <c>NativeExtension</c>. /// An extra level of indirection is added to P/Invoke calls to allow intelligent loading /// of the right configuration of the native extension based on current platform, architecture etc. /// </summary> internal class NativeMethods { #region Native methods public readonly Delegates.grpcsharp_init_delegate grpcsharp_init; public readonly Delegates.grpcsharp_shutdown_delegate grpcsharp_shutdown; public readonly Delegates.grpcsharp_version_string_delegate grpcsharp_version_string; public readonly Delegates.grpcsharp_batch_context_create_delegate grpcsharp_batch_context_create; public readonly Delegates.grpcsharp_batch_context_recv_initial_metadata_delegate grpcsharp_batch_context_recv_initial_metadata; public readonly Delegates.grpcsharp_batch_context_recv_message_length_delegate grpcsharp_batch_context_recv_message_length; public readonly Delegates.grpcsharp_batch_context_recv_message_to_buffer_delegate grpcsharp_batch_context_recv_message_to_buffer; public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_status_delegate grpcsharp_batch_context_recv_status_on_client_status; public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_details_delegate grpcsharp_batch_context_recv_status_on_client_details; public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate grpcsharp_batch_context_recv_status_on_client_trailing_metadata; public readonly Delegates.grpcsharp_batch_context_recv_close_on_server_cancelled_delegate grpcsharp_batch_context_recv_close_on_server_cancelled; public readonly Delegates.grpcsharp_batch_context_destroy_delegate grpcsharp_batch_context_destroy; public readonly Delegates.grpcsharp_request_call_context_create_delegate grpcsharp_request_call_context_create; public readonly Delegates.grpcsharp_request_call_context_call_delegate grpcsharp_request_call_context_call; public readonly Delegates.grpcsharp_request_call_context_method_delegate grpcsharp_request_call_context_method; public readonly Delegates.grpcsharp_request_call_context_host_delegate grpcsharp_request_call_context_host; public readonly Delegates.grpcsharp_request_call_context_deadline_delegate grpcsharp_request_call_context_deadline; public readonly Delegates.grpcsharp_request_call_context_request_metadata_delegate grpcsharp_request_call_context_request_metadata; public readonly Delegates.grpcsharp_request_call_context_destroy_delegate grpcsharp_request_call_context_destroy; public readonly Delegates.grpcsharp_composite_call_credentials_create_delegate grpcsharp_composite_call_credentials_create; public readonly Delegates.grpcsharp_call_credentials_release_delegate grpcsharp_call_credentials_release; public readonly Delegates.grpcsharp_call_cancel_delegate grpcsharp_call_cancel; public readonly Delegates.grpcsharp_call_cancel_with_status_delegate grpcsharp_call_cancel_with_status; public readonly Delegates.grpcsharp_call_start_unary_delegate grpcsharp_call_start_unary; public readonly Delegates.grpcsharp_call_start_client_streaming_delegate grpcsharp_call_start_client_streaming; public readonly Delegates.grpcsharp_call_start_server_streaming_delegate grpcsharp_call_start_server_streaming; public readonly Delegates.grpcsharp_call_start_duplex_streaming_delegate grpcsharp_call_start_duplex_streaming; public readonly Delegates.grpcsharp_call_send_message_delegate grpcsharp_call_send_message; public readonly Delegates.grpcsharp_call_send_close_from_client_delegate grpcsharp_call_send_close_from_client; public readonly Delegates.grpcsharp_call_send_status_from_server_delegate grpcsharp_call_send_status_from_server; public readonly Delegates.grpcsharp_call_recv_message_delegate grpcsharp_call_recv_message; public readonly Delegates.grpcsharp_call_recv_initial_metadata_delegate grpcsharp_call_recv_initial_metadata; public readonly Delegates.grpcsharp_call_start_serverside_delegate grpcsharp_call_start_serverside; public readonly Delegates.grpcsharp_call_send_initial_metadata_delegate grpcsharp_call_send_initial_metadata; public readonly Delegates.grpcsharp_call_set_credentials_delegate grpcsharp_call_set_credentials; public readonly Delegates.grpcsharp_call_get_peer_delegate grpcsharp_call_get_peer; public readonly Delegates.grpcsharp_call_destroy_delegate grpcsharp_call_destroy; public readonly Delegates.grpcsharp_channel_args_create_delegate grpcsharp_channel_args_create; public readonly Delegates.grpcsharp_channel_args_set_string_delegate grpcsharp_channel_args_set_string; public readonly Delegates.grpcsharp_channel_args_set_integer_delegate grpcsharp_channel_args_set_integer; public readonly Delegates.grpcsharp_channel_args_destroy_delegate grpcsharp_channel_args_destroy; public readonly Delegates.grpcsharp_override_default_ssl_roots grpcsharp_override_default_ssl_roots; public readonly Delegates.grpcsharp_ssl_credentials_create_delegate grpcsharp_ssl_credentials_create; public readonly Delegates.grpcsharp_composite_channel_credentials_create_delegate grpcsharp_composite_channel_credentials_create; public readonly Delegates.grpcsharp_channel_credentials_release_delegate grpcsharp_channel_credentials_release; public readonly Delegates.grpcsharp_insecure_channel_create_delegate grpcsharp_insecure_channel_create; public readonly Delegates.grpcsharp_secure_channel_create_delegate grpcsharp_secure_channel_create; public readonly Delegates.grpcsharp_channel_create_call_delegate grpcsharp_channel_create_call; public readonly Delegates.grpcsharp_channel_check_connectivity_state_delegate grpcsharp_channel_check_connectivity_state; public readonly Delegates.grpcsharp_channel_watch_connectivity_state_delegate grpcsharp_channel_watch_connectivity_state; public readonly Delegates.grpcsharp_channel_get_target_delegate grpcsharp_channel_get_target; public readonly Delegates.grpcsharp_channel_destroy_delegate grpcsharp_channel_destroy; public readonly Delegates.grpcsharp_sizeof_grpc_event_delegate grpcsharp_sizeof_grpc_event; public readonly Delegates.grpcsharp_completion_queue_create_async_delegate grpcsharp_completion_queue_create_async; public readonly Delegates.grpcsharp_completion_queue_create_sync_delegate grpcsharp_completion_queue_create_sync; public readonly Delegates.grpcsharp_completion_queue_shutdown_delegate grpcsharp_completion_queue_shutdown; public readonly Delegates.grpcsharp_completion_queue_next_delegate grpcsharp_completion_queue_next; public readonly Delegates.grpcsharp_completion_queue_pluck_delegate grpcsharp_completion_queue_pluck; public readonly Delegates.grpcsharp_completion_queue_destroy_delegate grpcsharp_completion_queue_destroy; public readonly Delegates.gprsharp_free_delegate gprsharp_free; public readonly Delegates.grpcsharp_metadata_array_create_delegate grpcsharp_metadata_array_create; public readonly Delegates.grpcsharp_metadata_array_add_delegate grpcsharp_metadata_array_add; public readonly Delegates.grpcsharp_metadata_array_count_delegate grpcsharp_metadata_array_count; public readonly Delegates.grpcsharp_metadata_array_get_key_delegate grpcsharp_metadata_array_get_key; public readonly Delegates.grpcsharp_metadata_array_get_value_delegate grpcsharp_metadata_array_get_value; public readonly Delegates.grpcsharp_metadata_array_destroy_full_delegate grpcsharp_metadata_array_destroy_full; public readonly Delegates.grpcsharp_redirect_log_delegate grpcsharp_redirect_log; public readonly Delegates.grpcsharp_metadata_credentials_create_from_plugin_delegate grpcsharp_metadata_credentials_create_from_plugin; public readonly Delegates.grpcsharp_metadata_credentials_notify_from_plugin_delegate grpcsharp_metadata_credentials_notify_from_plugin; public readonly Delegates.grpcsharp_ssl_server_credentials_create_delegate grpcsharp_ssl_server_credentials_create; public readonly Delegates.grpcsharp_server_credentials_release_delegate grpcsharp_server_credentials_release; public readonly Delegates.grpcsharp_server_create_delegate grpcsharp_server_create; public readonly Delegates.grpcsharp_server_register_completion_queue_delegate grpcsharp_server_register_completion_queue; public readonly Delegates.grpcsharp_server_add_insecure_http2_port_delegate grpcsharp_server_add_insecure_http2_port; public readonly Delegates.grpcsharp_server_add_secure_http2_port_delegate grpcsharp_server_add_secure_http2_port; public readonly Delegates.grpcsharp_server_start_delegate grpcsharp_server_start; public readonly Delegates.grpcsharp_server_request_call_delegate grpcsharp_server_request_call; public readonly Delegates.grpcsharp_server_cancel_all_calls_delegate grpcsharp_server_cancel_all_calls; public readonly Delegates.grpcsharp_server_shutdown_and_notify_callback_delegate grpcsharp_server_shutdown_and_notify_callback; public readonly Delegates.grpcsharp_server_destroy_delegate grpcsharp_server_destroy; public readonly Delegates.grpcsharp_call_auth_context_delegate grpcsharp_call_auth_context; public readonly Delegates.grpcsharp_auth_context_peer_identity_property_name_delegate grpcsharp_auth_context_peer_identity_property_name; public readonly Delegates.grpcsharp_auth_context_property_iterator_delegate grpcsharp_auth_context_property_iterator; public readonly Delegates.grpcsharp_auth_property_iterator_next_delegate grpcsharp_auth_property_iterator_next; public readonly Delegates.grpcsharp_auth_context_release_delegate grpcsharp_auth_context_release; public readonly Delegates.gprsharp_now_delegate gprsharp_now; public readonly Delegates.gprsharp_inf_future_delegate gprsharp_inf_future; public readonly Delegates.gprsharp_inf_past_delegate gprsharp_inf_past; public readonly Delegates.gprsharp_convert_clock_type_delegate gprsharp_convert_clock_type; public readonly Delegates.gprsharp_sizeof_timespec_delegate gprsharp_sizeof_timespec; public readonly Delegates.grpcsharp_test_callback_delegate grpcsharp_test_callback; public readonly Delegates.grpcsharp_test_nop_delegate grpcsharp_test_nop; public readonly Delegates.grpcsharp_test_override_method_delegate grpcsharp_test_override_method; #endregion public NativeMethods(UnmanagedLibrary library) { this.grpcsharp_init = GetMethodDelegate<Delegates.grpcsharp_init_delegate>(library); this.grpcsharp_shutdown = GetMethodDelegate<Delegates.grpcsharp_shutdown_delegate>(library); this.grpcsharp_version_string = GetMethodDelegate<Delegates.grpcsharp_version_string_delegate>(library); this.grpcsharp_batch_context_create = GetMethodDelegate<Delegates.grpcsharp_batch_context_create_delegate>(library); this.grpcsharp_batch_context_recv_initial_metadata = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_initial_metadata_delegate>(library); this.grpcsharp_batch_context_recv_message_length = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_message_length_delegate>(library); this.grpcsharp_batch_context_recv_message_to_buffer = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_message_to_buffer_delegate>(library); this.grpcsharp_batch_context_recv_status_on_client_status = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_status_on_client_status_delegate>(library); this.grpcsharp_batch_context_recv_status_on_client_details = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_status_on_client_details_delegate>(library); this.grpcsharp_batch_context_recv_status_on_client_trailing_metadata = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate>(library); this.grpcsharp_batch_context_recv_close_on_server_cancelled = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_close_on_server_cancelled_delegate>(library); this.grpcsharp_batch_context_destroy = GetMethodDelegate<Delegates.grpcsharp_batch_context_destroy_delegate>(library); this.grpcsharp_request_call_context_create = GetMethodDelegate<Delegates.grpcsharp_request_call_context_create_delegate>(library); this.grpcsharp_request_call_context_call = GetMethodDelegate<Delegates.grpcsharp_request_call_context_call_delegate>(library); this.grpcsharp_request_call_context_method = GetMethodDelegate<Delegates.grpcsharp_request_call_context_method_delegate>(library); this.grpcsharp_request_call_context_host = GetMethodDelegate<Delegates.grpcsharp_request_call_context_host_delegate>(library); this.grpcsharp_request_call_context_deadline = GetMethodDelegate<Delegates.grpcsharp_request_call_context_deadline_delegate>(library); this.grpcsharp_request_call_context_request_metadata = GetMethodDelegate<Delegates.grpcsharp_request_call_context_request_metadata_delegate>(library); this.grpcsharp_request_call_context_destroy = GetMethodDelegate<Delegates.grpcsharp_request_call_context_destroy_delegate>(library); this.grpcsharp_composite_call_credentials_create = GetMethodDelegate<Delegates.grpcsharp_composite_call_credentials_create_delegate>(library); this.grpcsharp_call_credentials_release = GetMethodDelegate<Delegates.grpcsharp_call_credentials_release_delegate>(library); this.grpcsharp_call_cancel = GetMethodDelegate<Delegates.grpcsharp_call_cancel_delegate>(library); this.grpcsharp_call_cancel_with_status = GetMethodDelegate<Delegates.grpcsharp_call_cancel_with_status_delegate>(library); this.grpcsharp_call_start_unary = GetMethodDelegate<Delegates.grpcsharp_call_start_unary_delegate>(library); this.grpcsharp_call_start_client_streaming = GetMethodDelegate<Delegates.grpcsharp_call_start_client_streaming_delegate>(library); this.grpcsharp_call_start_server_streaming = GetMethodDelegate<Delegates.grpcsharp_call_start_server_streaming_delegate>(library); this.grpcsharp_call_start_duplex_streaming = GetMethodDelegate<Delegates.grpcsharp_call_start_duplex_streaming_delegate>(library); this.grpcsharp_call_send_message = GetMethodDelegate<Delegates.grpcsharp_call_send_message_delegate>(library); this.grpcsharp_call_send_close_from_client = GetMethodDelegate<Delegates.grpcsharp_call_send_close_from_client_delegate>(library); this.grpcsharp_call_send_status_from_server = GetMethodDelegate<Delegates.grpcsharp_call_send_status_from_server_delegate>(library); this.grpcsharp_call_recv_message = GetMethodDelegate<Delegates.grpcsharp_call_recv_message_delegate>(library); this.grpcsharp_call_recv_initial_metadata = GetMethodDelegate<Delegates.grpcsharp_call_recv_initial_metadata_delegate>(library); this.grpcsharp_call_start_serverside = GetMethodDelegate<Delegates.grpcsharp_call_start_serverside_delegate>(library); this.grpcsharp_call_send_initial_metadata = GetMethodDelegate<Delegates.grpcsharp_call_send_initial_metadata_delegate>(library); this.grpcsharp_call_set_credentials = GetMethodDelegate<Delegates.grpcsharp_call_set_credentials_delegate>(library); this.grpcsharp_call_get_peer = GetMethodDelegate<Delegates.grpcsharp_call_get_peer_delegate>(library); this.grpcsharp_call_destroy = GetMethodDelegate<Delegates.grpcsharp_call_destroy_delegate>(library); this.grpcsharp_channel_args_create = GetMethodDelegate<Delegates.grpcsharp_channel_args_create_delegate>(library); this.grpcsharp_channel_args_set_string = GetMethodDelegate<Delegates.grpcsharp_channel_args_set_string_delegate>(library); this.grpcsharp_channel_args_set_integer = GetMethodDelegate<Delegates.grpcsharp_channel_args_set_integer_delegate>(library); this.grpcsharp_channel_args_destroy = GetMethodDelegate<Delegates.grpcsharp_channel_args_destroy_delegate>(library); this.grpcsharp_override_default_ssl_roots = GetMethodDelegate<Delegates.grpcsharp_override_default_ssl_roots>(library); this.grpcsharp_ssl_credentials_create = GetMethodDelegate<Delegates.grpcsharp_ssl_credentials_create_delegate>(library); this.grpcsharp_composite_channel_credentials_create = GetMethodDelegate<Delegates.grpcsharp_composite_channel_credentials_create_delegate>(library); this.grpcsharp_channel_credentials_release = GetMethodDelegate<Delegates.grpcsharp_channel_credentials_release_delegate>(library); this.grpcsharp_insecure_channel_create = GetMethodDelegate<Delegates.grpcsharp_insecure_channel_create_delegate>(library); this.grpcsharp_secure_channel_create = GetMethodDelegate<Delegates.grpcsharp_secure_channel_create_delegate>(library); this.grpcsharp_channel_create_call = GetMethodDelegate<Delegates.grpcsharp_channel_create_call_delegate>(library); this.grpcsharp_channel_check_connectivity_state = GetMethodDelegate<Delegates.grpcsharp_channel_check_connectivity_state_delegate>(library); this.grpcsharp_channel_watch_connectivity_state = GetMethodDelegate<Delegates.grpcsharp_channel_watch_connectivity_state_delegate>(library); this.grpcsharp_channel_get_target = GetMethodDelegate<Delegates.grpcsharp_channel_get_target_delegate>(library); this.grpcsharp_channel_destroy = GetMethodDelegate<Delegates.grpcsharp_channel_destroy_delegate>(library); this.grpcsharp_sizeof_grpc_event = GetMethodDelegate<Delegates.grpcsharp_sizeof_grpc_event_delegate>(library); this.grpcsharp_completion_queue_create_async = GetMethodDelegate<Delegates.grpcsharp_completion_queue_create_async_delegate>(library); this.grpcsharp_completion_queue_create_sync = GetMethodDelegate<Delegates.grpcsharp_completion_queue_create_sync_delegate>(library); this.grpcsharp_completion_queue_shutdown = GetMethodDelegate<Delegates.grpcsharp_completion_queue_shutdown_delegate>(library); this.grpcsharp_completion_queue_next = GetMethodDelegate<Delegates.grpcsharp_completion_queue_next_delegate>(library); this.grpcsharp_completion_queue_pluck = GetMethodDelegate<Delegates.grpcsharp_completion_queue_pluck_delegate>(library); this.grpcsharp_completion_queue_destroy = GetMethodDelegate<Delegates.grpcsharp_completion_queue_destroy_delegate>(library); this.gprsharp_free = GetMethodDelegate<Delegates.gprsharp_free_delegate>(library); this.grpcsharp_metadata_array_create = GetMethodDelegate<Delegates.grpcsharp_metadata_array_create_delegate>(library); this.grpcsharp_metadata_array_add = GetMethodDelegate<Delegates.grpcsharp_metadata_array_add_delegate>(library); this.grpcsharp_metadata_array_count = GetMethodDelegate<Delegates.grpcsharp_metadata_array_count_delegate>(library); this.grpcsharp_metadata_array_get_key = GetMethodDelegate<Delegates.grpcsharp_metadata_array_get_key_delegate>(library); this.grpcsharp_metadata_array_get_value = GetMethodDelegate<Delegates.grpcsharp_metadata_array_get_value_delegate>(library); this.grpcsharp_metadata_array_destroy_full = GetMethodDelegate<Delegates.grpcsharp_metadata_array_destroy_full_delegate>(library); this.grpcsharp_redirect_log = GetMethodDelegate<Delegates.grpcsharp_redirect_log_delegate>(library); this.grpcsharp_metadata_credentials_create_from_plugin = GetMethodDelegate<Delegates.grpcsharp_metadata_credentials_create_from_plugin_delegate>(library); this.grpcsharp_metadata_credentials_notify_from_plugin = GetMethodDelegate<Delegates.grpcsharp_metadata_credentials_notify_from_plugin_delegate>(library); this.grpcsharp_ssl_server_credentials_create = GetMethodDelegate<Delegates.grpcsharp_ssl_server_credentials_create_delegate>(library); this.grpcsharp_server_credentials_release = GetMethodDelegate<Delegates.grpcsharp_server_credentials_release_delegate>(library); this.grpcsharp_server_create = GetMethodDelegate<Delegates.grpcsharp_server_create_delegate>(library); this.grpcsharp_server_register_completion_queue = GetMethodDelegate<Delegates.grpcsharp_server_register_completion_queue_delegate>(library); this.grpcsharp_server_add_insecure_http2_port = GetMethodDelegate<Delegates.grpcsharp_server_add_insecure_http2_port_delegate>(library); this.grpcsharp_server_add_secure_http2_port = GetMethodDelegate<Delegates.grpcsharp_server_add_secure_http2_port_delegate>(library); this.grpcsharp_server_start = GetMethodDelegate<Delegates.grpcsharp_server_start_delegate>(library); this.grpcsharp_server_request_call = GetMethodDelegate<Delegates.grpcsharp_server_request_call_delegate>(library); this.grpcsharp_server_cancel_all_calls = GetMethodDelegate<Delegates.grpcsharp_server_cancel_all_calls_delegate>(library); this.grpcsharp_server_shutdown_and_notify_callback = GetMethodDelegate<Delegates.grpcsharp_server_shutdown_and_notify_callback_delegate>(library); this.grpcsharp_server_destroy = GetMethodDelegate<Delegates.grpcsharp_server_destroy_delegate>(library); this.grpcsharp_call_auth_context = GetMethodDelegate<Delegates.grpcsharp_call_auth_context_delegate>(library); this.grpcsharp_auth_context_peer_identity_property_name = GetMethodDelegate<Delegates.grpcsharp_auth_context_peer_identity_property_name_delegate>(library); this.grpcsharp_auth_context_property_iterator = GetMethodDelegate<Delegates.grpcsharp_auth_context_property_iterator_delegate>(library); this.grpcsharp_auth_property_iterator_next = GetMethodDelegate<Delegates.grpcsharp_auth_property_iterator_next_delegate>(library); this.grpcsharp_auth_context_release = GetMethodDelegate<Delegates.grpcsharp_auth_context_release_delegate>(library); this.gprsharp_now = GetMethodDelegate<Delegates.gprsharp_now_delegate>(library); this.gprsharp_inf_future = GetMethodDelegate<Delegates.gprsharp_inf_future_delegate>(library); this.gprsharp_inf_past = GetMethodDelegate<Delegates.gprsharp_inf_past_delegate>(library); this.gprsharp_convert_clock_type = GetMethodDelegate<Delegates.gprsharp_convert_clock_type_delegate>(library); this.gprsharp_sizeof_timespec = GetMethodDelegate<Delegates.gprsharp_sizeof_timespec_delegate>(library); this.grpcsharp_test_callback = GetMethodDelegate<Delegates.grpcsharp_test_callback_delegate>(library); this.grpcsharp_test_nop = GetMethodDelegate<Delegates.grpcsharp_test_nop_delegate>(library); this.grpcsharp_test_override_method = GetMethodDelegate<Delegates.grpcsharp_test_override_method_delegate>(library); } /// <summary> /// Gets singleton instance of this class. /// </summary> public static NativeMethods Get() { return NativeExtension.Get().NativeMethods; } static T GetMethodDelegate<T>(UnmanagedLibrary library) where T : class { var methodName = RemoveStringSuffix(typeof(T).Name, "_delegate"); return library.GetNativeMethodDelegate<T>(methodName); } static string RemoveStringSuffix(string str, string toRemove) { if (!str.EndsWith(toRemove)) { return str; } return str.Substring(0, str.Length - toRemove.Length); } /// <summary> /// Delegate types for all published native methods. Declared under inner class to prevent scope pollution. /// </summary> public class Delegates { public delegate void grpcsharp_init_delegate(); public delegate void grpcsharp_shutdown_delegate(); public delegate IntPtr grpcsharp_version_string_delegate(); // returns not-owned const char* public delegate BatchContextSafeHandle grpcsharp_batch_context_create_delegate(); public delegate IntPtr grpcsharp_batch_context_recv_initial_metadata_delegate(BatchContextSafeHandle ctx); public delegate IntPtr grpcsharp_batch_context_recv_message_length_delegate(BatchContextSafeHandle ctx); public delegate void grpcsharp_batch_context_recv_message_to_buffer_delegate(BatchContextSafeHandle ctx, byte[] buffer, UIntPtr bufferLen); public delegate StatusCode grpcsharp_batch_context_recv_status_on_client_status_delegate(BatchContextSafeHandle ctx); public delegate IntPtr grpcsharp_batch_context_recv_status_on_client_details_delegate(BatchContextSafeHandle ctx, out UIntPtr detailsLength); public delegate IntPtr grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate(BatchContextSafeHandle ctx); public delegate int grpcsharp_batch_context_recv_close_on_server_cancelled_delegate(BatchContextSafeHandle ctx); public delegate void grpcsharp_batch_context_destroy_delegate(IntPtr ctx); public delegate RequestCallContextSafeHandle grpcsharp_request_call_context_create_delegate(); public delegate CallSafeHandle grpcsharp_request_call_context_call_delegate(RequestCallContextSafeHandle ctx); public delegate IntPtr grpcsharp_request_call_context_method_delegate(RequestCallContextSafeHandle ctx, out UIntPtr methodLength); public delegate IntPtr grpcsharp_request_call_context_host_delegate(RequestCallContextSafeHandle ctx, out UIntPtr hostLength); public delegate Timespec grpcsharp_request_call_context_deadline_delegate(RequestCallContextSafeHandle ctx); public delegate IntPtr grpcsharp_request_call_context_request_metadata_delegate(RequestCallContextSafeHandle ctx); public delegate void grpcsharp_request_call_context_destroy_delegate(IntPtr ctx); public delegate CallCredentialsSafeHandle grpcsharp_composite_call_credentials_create_delegate(CallCredentialsSafeHandle creds1, CallCredentialsSafeHandle creds2); public delegate void grpcsharp_call_credentials_release_delegate(IntPtr credentials); public delegate CallError grpcsharp_call_cancel_delegate(CallSafeHandle call); public delegate CallError grpcsharp_call_cancel_with_status_delegate(CallSafeHandle call, StatusCode status, string description); public delegate CallError grpcsharp_call_start_unary_delegate(CallSafeHandle call, BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags); public delegate CallError grpcsharp_call_start_client_streaming_delegate(CallSafeHandle call, BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags); public delegate CallError grpcsharp_call_start_server_streaming_delegate(CallSafeHandle call, BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags); public delegate CallError grpcsharp_call_start_duplex_streaming_delegate(CallSafeHandle call, BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags); public delegate CallError grpcsharp_call_send_message_delegate(CallSafeHandle call, BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags, int sendEmptyInitialMetadata); public delegate CallError grpcsharp_call_send_close_from_client_delegate(CallSafeHandle call, BatchContextSafeHandle ctx); public delegate CallError grpcsharp_call_send_status_from_server_delegate(CallSafeHandle call, BatchContextSafeHandle ctx, StatusCode statusCode, byte[] statusMessage, UIntPtr statusMessageLen, MetadataArraySafeHandle metadataArray, int sendEmptyInitialMetadata, byte[] optionalSendBuffer, UIntPtr optionalSendBufferLen, WriteFlags writeFlags); public delegate CallError grpcsharp_call_recv_message_delegate(CallSafeHandle call, BatchContextSafeHandle ctx); public delegate CallError grpcsharp_call_recv_initial_metadata_delegate(CallSafeHandle call, BatchContextSafeHandle ctx); public delegate CallError grpcsharp_call_start_serverside_delegate(CallSafeHandle call, BatchContextSafeHandle ctx); public delegate CallError grpcsharp_call_send_initial_metadata_delegate(CallSafeHandle call, BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray); public delegate CallError grpcsharp_call_set_credentials_delegate(CallSafeHandle call, CallCredentialsSafeHandle credentials); public delegate CStringSafeHandle grpcsharp_call_get_peer_delegate(CallSafeHandle call); public delegate void grpcsharp_call_destroy_delegate(IntPtr call); public delegate ChannelArgsSafeHandle grpcsharp_channel_args_create_delegate(UIntPtr numArgs); public delegate void grpcsharp_channel_args_set_string_delegate(ChannelArgsSafeHandle args, UIntPtr index, string key, string value); public delegate void grpcsharp_channel_args_set_integer_delegate(ChannelArgsSafeHandle args, UIntPtr index, string key, int value); public delegate void grpcsharp_channel_args_destroy_delegate(IntPtr args); public delegate void grpcsharp_override_default_ssl_roots(string pemRootCerts); public delegate ChannelCredentialsSafeHandle grpcsharp_ssl_credentials_create_delegate(string pemRootCerts, string keyCertPairCertChain, string keyCertPairPrivateKey); public delegate ChannelCredentialsSafeHandle grpcsharp_composite_channel_credentials_create_delegate(ChannelCredentialsSafeHandle channelCreds, CallCredentialsSafeHandle callCreds); public delegate void grpcsharp_channel_credentials_release_delegate(IntPtr credentials); public delegate ChannelSafeHandle grpcsharp_insecure_channel_create_delegate(string target, ChannelArgsSafeHandle channelArgs); public delegate ChannelSafeHandle grpcsharp_secure_channel_create_delegate(ChannelCredentialsSafeHandle credentials, string target, ChannelArgsSafeHandle channelArgs); public delegate CallSafeHandle grpcsharp_channel_create_call_delegate(ChannelSafeHandle channel, CallSafeHandle parentCall, ContextPropagationFlags propagationMask, CompletionQueueSafeHandle cq, string method, string host, Timespec deadline); public delegate ChannelState grpcsharp_channel_check_connectivity_state_delegate(ChannelSafeHandle channel, int tryToConnect); public delegate void grpcsharp_channel_watch_connectivity_state_delegate(ChannelSafeHandle channel, ChannelState lastObservedState, Timespec deadline, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx); public delegate CStringSafeHandle grpcsharp_channel_get_target_delegate(ChannelSafeHandle call); public delegate void grpcsharp_channel_destroy_delegate(IntPtr channel); public delegate int grpcsharp_sizeof_grpc_event_delegate(); public delegate CompletionQueueSafeHandle grpcsharp_completion_queue_create_async_delegate(); public delegate CompletionQueueSafeHandle grpcsharp_completion_queue_create_sync_delegate(); public delegate void grpcsharp_completion_queue_shutdown_delegate(CompletionQueueSafeHandle cq); public delegate CompletionQueueEvent grpcsharp_completion_queue_next_delegate(CompletionQueueSafeHandle cq); public delegate CompletionQueueEvent grpcsharp_completion_queue_pluck_delegate(CompletionQueueSafeHandle cq, IntPtr tag); public delegate void grpcsharp_completion_queue_destroy_delegate(IntPtr cq); public delegate void gprsharp_free_delegate(IntPtr ptr); public delegate MetadataArraySafeHandle grpcsharp_metadata_array_create_delegate(UIntPtr capacity); public delegate void grpcsharp_metadata_array_add_delegate(MetadataArraySafeHandle array, string key, byte[] value, UIntPtr valueLength); public delegate UIntPtr grpcsharp_metadata_array_count_delegate(IntPtr metadataArray); public delegate IntPtr grpcsharp_metadata_array_get_key_delegate(IntPtr metadataArray, UIntPtr index, out UIntPtr keyLength); public delegate IntPtr grpcsharp_metadata_array_get_value_delegate(IntPtr metadataArray, UIntPtr index, out UIntPtr valueLength); public delegate void grpcsharp_metadata_array_destroy_full_delegate(IntPtr array); public delegate void grpcsharp_redirect_log_delegate(GprLogDelegate callback); public delegate CallCredentialsSafeHandle grpcsharp_metadata_credentials_create_from_plugin_delegate(NativeMetadataInterceptor interceptor); public delegate void grpcsharp_metadata_credentials_notify_from_plugin_delegate(IntPtr callbackPtr, IntPtr userData, MetadataArraySafeHandle metadataArray, StatusCode statusCode, string errorDetails); public delegate ServerCredentialsSafeHandle grpcsharp_ssl_server_credentials_create_delegate(string pemRootCerts, string[] keyCertPairCertChainArray, string[] keyCertPairPrivateKeyArray, UIntPtr numKeyCertPairs, int forceClientAuth); public delegate void grpcsharp_server_credentials_release_delegate(IntPtr credentials); public delegate ServerSafeHandle grpcsharp_server_create_delegate(ChannelArgsSafeHandle args); public delegate void grpcsharp_server_register_completion_queue_delegate(ServerSafeHandle server, CompletionQueueSafeHandle cq); public delegate int grpcsharp_server_add_insecure_http2_port_delegate(ServerSafeHandle server, string addr); public delegate int grpcsharp_server_add_secure_http2_port_delegate(ServerSafeHandle server, string addr, ServerCredentialsSafeHandle creds); public delegate void grpcsharp_server_start_delegate(ServerSafeHandle server); public delegate CallError grpcsharp_server_request_call_delegate(ServerSafeHandle server, CompletionQueueSafeHandle cq, RequestCallContextSafeHandle ctx); public delegate void grpcsharp_server_cancel_all_calls_delegate(ServerSafeHandle server); public delegate void grpcsharp_server_shutdown_and_notify_callback_delegate(ServerSafeHandle server, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx); public delegate void grpcsharp_server_destroy_delegate(IntPtr server); public delegate AuthContextSafeHandle grpcsharp_call_auth_context_delegate(CallSafeHandle call); public delegate IntPtr grpcsharp_auth_context_peer_identity_property_name_delegate(AuthContextSafeHandle authContext); // returns const char* public delegate AuthContextSafeHandle.NativeAuthPropertyIterator grpcsharp_auth_context_property_iterator_delegate(AuthContextSafeHandle authContext); public delegate IntPtr grpcsharp_auth_property_iterator_next_delegate(ref AuthContextSafeHandle.NativeAuthPropertyIterator iterator); // returns const auth_property* public delegate void grpcsharp_auth_context_release_delegate(IntPtr authContext); public delegate Timespec gprsharp_now_delegate(ClockType clockType); public delegate Timespec gprsharp_inf_future_delegate(ClockType clockType); public delegate Timespec gprsharp_inf_past_delegate(ClockType clockType); public delegate Timespec gprsharp_convert_clock_type_delegate(Timespec t, ClockType targetClock); public delegate int gprsharp_sizeof_timespec_delegate(); public delegate CallError grpcsharp_test_callback_delegate([MarshalAs(UnmanagedType.FunctionPtr)] NativeCallbackTestDelegate callback); public delegate IntPtr grpcsharp_test_nop_delegate(IntPtr ptr); public delegate void grpcsharp_test_override_method_delegate(string methodName, string variant); } } }
// 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.CodeRefactorings; using Microsoft.CodeAnalysis.CodeRefactorings.ExtractMethod; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.ExtractMethod { public class ExtractMethodTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace) { return new ExtractMethodCodeRefactoringProvider(); } [WorkItem(540799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540799")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestPartialSelection() { await TestAsync( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); } private static bool NewMethod(bool b) { return b != true; } }", index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestCodeStyle1() { await TestAsync( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); } private static bool NewMethod(bool b) => b != true; }", options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CodeStyleOptions.TrueWithNoneEnforcement)); } [WorkItem(540796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540796")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestReadOfDataThatDoesNotFlowIn() { await TestAsync( @"class Program { static void Main(string[] args) { int x = 1; object y = 0; [|int s = true ? fun(x) : fun(y);|] } private static T fun<T>(T t) { return t; } }", @"class Program { static void Main(string[] args) { int x = 1; object y = 0; {|Rename:NewMethod|}(x, y); } private static void NewMethod(int x, object y) { int s = true ? fun(x) : fun(y); } private static T fun<T>(T t) { return t; } }", index: 0); } [WorkItem(540819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540819")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestMissingOnGoto() { await TestMissingAsync( @"delegate int del(int i); class C { static void Main(string[] args) { del q = x => { [|goto label2; return x * x;|] }; label2: return; } }"); } [WorkItem(540819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540819")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestOnStatementAfterUnconditionalGoto() { await TestAsync( @"delegate int del(int i); class C { static void Main(string[] args) { del q = x => { goto label2; [|return x * x;|] }; label2: return; } }", @"delegate int del(int i); class C { static void Main(string[] args) { del q = x => { goto label2; return {|Rename:NewMethod|}(x); }; label2: return; } private static int NewMethod(int x) { return x * x; } }", index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestMissingOnNamespace() { await TestAsync( @"class Program { void Main() { [|System|].Console.WriteLine(4); } }", @"class Program { void Main() { {|Rename:NewMethod|}(); } private static void NewMethod() { System.Console.WriteLine(4); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestMissingOnType() { await TestAsync( @"class Program { void Main() { [|System.Console|].WriteLine(4); } }", @"class Program { void Main() { {|Rename:NewMethod|}(); } private static void NewMethod() { System.Console.WriteLine(4); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestMissingOnBase() { await TestAsync( @"class Program { void Main() { [|base|].ToString(); } }", @"class Program { void Main() { {|Rename:NewMethod|}(); } private void NewMethod() { base.ToString(); } }"); } [WorkItem(545623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545623")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestOnActionInvocation() { await TestAsync( @"using System; class C { public static Action X { get; set; } } class Program { void Main() { [|C.X|](); } }", @"using System; class C { public static Action X { get; set; } } class Program { void Main() { {|Rename:GetX|}()(); } private static Action GetX() { return C.X; } }"); } [WorkItem(529841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529841"), WorkItem(714632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/714632")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task DisambiguateCallSiteIfNecessary1() { await TestAsync( @"using System; class Program { static void Main() { byte z = 0; Foo([|x => 0|], y => 0, z, z); } static void Foo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); } static void Foo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); } }", @"using System; class Program { static void Main() { byte z = 0; Foo<byte, byte>({|Rename:NewMethod|}(), y => 0, z, z); } private static Func<byte, byte> NewMethod() { return x => 0; } static void Foo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); } static void Foo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); } }", compareTokens: false); } [WorkItem(529841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529841"), WorkItem(714632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/714632")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task DisambiguateCallSiteIfNecessary2() { await TestAsync( @"using System; class Program { static void Main() { byte z = 0; Foo([|x => 0|], y => { return 0; }, z, z); } static void Foo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); } static void Foo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); } }", @"using System; class Program { static void Main() { byte z = 0; Foo<byte, byte>({|Rename:NewMethod|}(), y => { return 0; }, z, z); } private static Func<byte, byte> NewMethod() { return x => 0; } static void Foo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); } static void Foo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); } }", compareTokens: false); } [WorkItem(530709, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530709")] [WorkItem(632182, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632182")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task DontOverparenthesize() { await TestAsync( @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => [|x|].Ex(), y), - -1); } } static class E { public static void Ex(this int x) { } }", @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => {|Rename:GetX|}(x).Ex(), y), (object)- -1); } private static string GetX(string x) { return x; } } static class E { public static void Ex(this int x) { } }", parseOptions: Options.Regular); } [WorkItem(632182, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632182")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task DontOverparenthesizeGenerics() { await TestAsync( @"using System; static class C { static void Ex<T>(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => [|x|].Ex<int>(), y), - -1); } } static class E { public static void Ex<T>(this int x) { } }", @"using System; static class C { static void Ex<T>(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => {|Rename:GetX|}(x).Ex<int>(), y), (object)- -1); } private static string GetX(string x) { return x; } } static class E { public static void Ex<T>(this int x) { } }", parseOptions: Options.Regular); } [WorkItem(984831, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984831")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task PreserveCommentsBeforeDeclaration_1() { await TestAsync( @"class Construct { public void Do() { } static void Main(string[] args) { [|Construct obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ Construct obj2 = new Construct(); obj2.Do();|] obj1.Do(); obj2.Do(); } }", @"class Construct { public void Do() { } static void Main(string[] args) { Construct obj1, obj2; {|Rename:NewMethod|}(out obj1, out obj2); obj1.Do(); obj2.Do(); } private static void NewMethod(out Construct obj1, out Construct obj2) { obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ obj2 = new Construct(); obj2.Do(); } }", compareTokens: false); } [WorkItem(984831, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984831")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task PreserveCommentsBeforeDeclaration_2() { await TestAsync( @"class Construct { public void Do() { } static void Main(string[] args) { [|Construct obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ Construct obj2 = new Construct(); obj2.Do(); /* Second Interesting comment. */ Construct obj3 = new Construct(); obj3.Do();|] obj1.Do(); obj2.Do(); obj3.Do(); } }", @"class Construct { public void Do() { } static void Main(string[] args) { Construct obj1, obj2, obj3; {|Rename:NewMethod|}(out obj1, out obj2, out obj3); obj1.Do(); obj2.Do(); obj3.Do(); } private static void NewMethod(out Construct obj1, out Construct obj2, out Construct obj3) { obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ obj2 = new Construct(); obj2.Do(); /* Second Interesting comment. */ obj3 = new Construct(); obj3.Do(); } }", compareTokens: false); } [WorkItem(984831, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984831")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task PreserveCommentsBeforeDeclaration_3() { await TestAsync( @"class Construct { public void Do() { } static void Main(string[] args) { [|Construct obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ Construct obj2 = new Construct(), obj3 = new Construct(); obj2.Do(); obj3.Do();|] obj1.Do(); obj2.Do(); obj3.Do(); } }", @"class Construct { public void Do() { } static void Main(string[] args) { Construct obj1, obj2, obj3; {|Rename:NewMethod|}(out obj1, out obj2, out obj3); obj1.Do(); obj2.Do(); obj3.Do(); } private static void NewMethod(out Construct obj1, out Construct obj2, out Construct obj3) { obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ obj2 = new Construct(); obj3 = new Construct(); obj2.Do(); obj3.Do(); } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task TestTuple() { await TestAsync( @"class Program { static void Main(string[] args) { [|(int, int) x = (1, 2);|] System.Console.WriteLine(x.Item1); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int, int) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.Item1); } private static (int, int) NewMethod() { return (1, 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task TestTupleDeclarationWithNames() { await TestAsync( @"class Program { static void Main(string[] args) { [|(int a, int b) x = (1, 2);|] System.Console.WriteLine(x.a); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int a, int b) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.a); } private static (int a, int b) NewMethod() { return (1, 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task TestTupleDeclarationWithSomeNames() { await TestAsync( @"class Program { static void Main(string[] args) { [|(int a, int) x = (1, 2);|] System.Console.WriteLine(x.a); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int a, int) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.a); } private static (int a, int) NewMethod() { return (1, 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task TestTupleLiteralWithNames() { await TestAsync( @"class Program { static void Main(string[] args) { [|(int, int) x = (a: 1, b: 2);|] System.Console.WriteLine(x.Item1); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int, int) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.Item1); } private static (int, int) NewMethod() { return (a: 1, b: 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task TestTupleDeclarationAndLiteralWithNames() { await TestAsync( @"class Program { static void Main(string[] args) { [|(int a, int b) x = (c: 1, d: 2);|] System.Console.WriteLine(x.a); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int a, int b) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.a); } private static (int a, int b) NewMethod() { return (c: 1, d: 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task TestTupleIntoVar() { await TestAsync( @"class Program { static void Main(string[] args) { [|var x = (c: 1, d: 2);|] System.Console.WriteLine(x.c); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int c, int d) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.c); } private static (int c, int d) NewMethod() { return (c: 1, d: 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task RefactorWithoutSystemValueTuple() { await TestAsync( @"class Program { static void Main(string[] args) { [|var x = (c: 1, d: 2);|] System.Console.WriteLine(x.c); } }", @"class Program { static void Main(string[] args) { object x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.c); } private static object NewMethod() { return (c: 1, d: 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task TestTupleWithNestedNamedTuple() { // This is not the best refactoring, but this is an edge case await TestAsync( @"class Program { static void Main(string[] args) { [|var x = new System.ValueTuple<int, int, int, int, int, int, int, (string a, string b)>(1, 2, 3, 4, 5, 6, 7, (a: ""hello"", b: ""world""));|] System.Console.WriteLine(x.c); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int, int, int, int, int, int, int, string, string) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.c); } private static (int, int, int, int, int, int, int, string, string) NewMethod() { return new System.ValueTuple<int, int, int, int, int, int, int, (string a, string b)>(1, 2, 3, 4, 5, 6, 7, (a: ""hello"", b: ""world"")); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)] public async Task TestDeconstruction() { await TestAsync( @"class Program { static void Main(string[] args) { var (x, y) = [|(1, 2)|]; System.Console.WriteLine(x); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { var (x, y) = {|Rename:NewMethod|}(); System.Console.WriteLine(x); } private static (int, int) NewMethod() { return (1, 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)] public async Task TestDeconstruction2() { await TestAsync( @"class Program { static void Main(string[] args) { var (x, y) = (1, 2); var z = [|3;|] System.Console.WriteLine(z); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { var (x, y) = (1, 2); int z = {|Rename:NewMethod|}(); System.Console.WriteLine(z); } private static int NewMethod() { return 3; } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] [Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.OutVar)] public async Task TestOutVar() { await TestAsync( @"class C { static void M(int i) { int r; [|r = M1(out int y, i);|] System.Console.WriteLine(r + y); } }", @"class C { static void M(int i) { int r; int y; {|Rename:NewMethod|}(i, out r, out y); System.Console.WriteLine(r + y); } private static void NewMethod(int i, out int r, out int y) { r = M1(out y, i); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] [Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Patterns)] public async Task TestIsPattern() { await TestAsync( @"class C { static void M(int i) { int r; [|r = M1(3 is int y, i);|] System.Console.WriteLine(r + y); } }", @"class C { static void M(int i) { int r; int y; {|Rename:NewMethod|}(i, out r, out y); System.Console.WriteLine(r + y); } private static void NewMethod(int i, out int r, out int y) { r = M1(3 is int {|Conflict:y|}, i); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] [Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Patterns)] public async Task TestOutVarAndIsPattern() { await TestAsync( @"class C { static void M() { int r; [|r = M1(out /*out*/ int /*int*/ y /*y*/) + M2(3 is int z);|] System.Console.WriteLine(r + y + z); } } ", @"class C { static void M() { int r; int y, z; {|Rename:NewMethod|}(out r, out y, out z); System.Console.WriteLine(r + y + z); } private static void NewMethod(out int r, out int y, out int z) { r = M1(out /*out*/ /*int*/ y /*y*/) + M2(3 is int {|Conflict:z|}); } } ", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] [Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Patterns)] public async Task ConflictingOutVarLocals() { await TestAsync( @"class C { static void M() { int r; [|r = M1(out int y); { M2(out int y); System.Console.Write(y); }|] System.Console.WriteLine(r + y); } }", @"class C { static void M() { int r; int y; {|Rename:NewMethod|}(out r, out y); System.Console.WriteLine(r + y); } private static void NewMethod(out int r, out int y) { r = M1(out y); { M2(out int y); System.Console.Write(y); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] [Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Patterns)] public async Task ConflictingPatternLocals() { await TestAsync( @"class C { static void M() { int r; [|r = M1(1 is int y); { M2(2 is int y); System.Console.Write(y); }|] System.Console.WriteLine(r + y); } }", @"class C { static void M() { int r; int y; {|Rename:NewMethod|}(out r, out y); System.Console.WriteLine(r + y); } private static void NewMethod(out int r, out int y) { r = M1(1 is int {|Conflict:y|}); { M2(2 is int y); System.Console.Write(y); } } }"); } [WorkItem(15218, "https://github.com/dotnet/roslyn/issues/15218")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestCancellationTokenGoesLast() { await TestAsync( @"using System; using System.Threading; class C { void M(CancellationToken ct) { var v = 0; [|if (true) { ct.ThrowIfCancellationRequested(); Console.WriteLine(v); }|] } }", @"using System; using System.Threading; class C { void M(CancellationToken ct) { var v = 0; {|Rename:NewMethod|}(v, ct); } private static void NewMethod(int v, CancellationToken ct) { if (true) { ct.ThrowIfCancellationRequested(); Console.WriteLine(v); } } }"); } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Reflection; using System.Text; using NLog.Common; using NLog.Conditions; using NLog.Config; using NLog.Internal; using NLog.Layouts; using NLog.Targets; /// <summary> /// Reflection helpers for accessing properties. /// </summary> internal static class PropertyHelper { private static Dictionary<Type, Dictionary<string, PropertyInfo>> parameterInfoCache = new Dictionary<Type, Dictionary<string, PropertyInfo>>(); private static Dictionary<Type, Func<string, ConfigurationItemFactory, object>> DefaultPropertyConversionMapper = BuildPropertyConversionMapper(); #pragma warning disable S1144 // Unused private types or members should be removed. BUT they help CoreRT to provide config through reflection private static readonly RequiredParameterAttribute _requiredParameterAttribute = new RequiredParameterAttribute(); private static readonly ArrayParameterAttribute _arrayParameterAttribute = new ArrayParameterAttribute(null, string.Empty); private static readonly DefaultParameterAttribute _defaultParameterAttribute = new DefaultParameterAttribute(); private static readonly NLogConfigurationIgnorePropertyAttribute _ignorePropertyAttribute = new NLogConfigurationIgnorePropertyAttribute(); private static readonly NLogConfigurationItemAttribute _configPropertyAttribute = new NLogConfigurationItemAttribute(); private static readonly FlagsAttribute _flagsAttribute = new FlagsAttribute(); #pragma warning restore S1144 // Unused private types or members should be removed private static Dictionary<Type, Func<string, ConfigurationItemFactory, object>> BuildPropertyConversionMapper() { return new Dictionary<Type, Func<string, ConfigurationItemFactory, object>>() { { typeof(Layout), TryParseLayoutValue }, { typeof(SimpleLayout), TryParseLayoutValue }, { typeof(ConditionExpression), TryParseConditionValue }, { typeof(Encoding), TryParseEncodingValue }, { typeof(string), (stringvalue, factory) => stringvalue }, { typeof(int), (stringvalue, factory) => Convert.ChangeType(stringvalue.Trim(), TypeCode.Int32, CultureInfo.InvariantCulture) }, { typeof(bool), (stringvalue, factory) => Convert.ChangeType(stringvalue.Trim(), TypeCode.Boolean, CultureInfo.InvariantCulture) }, { typeof(CultureInfo), (stringvalue, factory) => TryParseCultureInfo(stringvalue) }, { typeof(Type), (stringvalue, factory) => Type.GetType(stringvalue.Trim(), true) }, { typeof(LineEndingMode), (stringvalue, factory) => LineEndingMode.FromString(stringvalue.Trim()) }, { typeof(Uri), (stringvalue, factory) => new Uri(stringvalue.Trim()) } }; } /// <summary> /// Set value parsed from string. /// </summary> /// <param name="targetObject">object instance to set with property <paramref name="propertyName"/></param> /// <param name="propertyName">name of the property on <paramref name="targetObject"/></param> /// <param name="stringValue">The value to be parsed.</param> /// <param name="configurationItemFactory"></param> internal static void SetPropertyFromString(object targetObject, string propertyName, string stringValue, ConfigurationItemFactory configurationItemFactory) { var objType = targetObject.GetType(); InternalLogger.Debug("Setting '{0}.{1}' to '{2}'", objType, propertyName, stringValue); if (!TryGetPropertyInfo(objType, propertyName, out var propInfo)) { throw new NLogConfigurationException($"'{objType?.Name}' cannot assign unknown property '{propertyName}'='{stringValue}'"); } SetPropertyFromString(targetObject, propInfo, stringValue, configurationItemFactory); } internal static void SetPropertyFromString(object targetObject, PropertyInfo propInfo, string stringValue, ConfigurationItemFactory configurationItemFactory) { object propertyValue = null; try { var propertyType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType; if (!TryNLogSpecificConversion(propertyType, stringValue, configurationItemFactory, out propertyValue)) { if (propInfo.IsDefined(_arrayParameterAttribute.GetType(), false)) { throw new NotSupportedException($"'{targetObject?.GetType()?.Name}' cannot assign property '{propInfo.Name}', because property of type array and not scalar value: '{stringValue}'."); } if (!(TryGetEnumValue(propertyType, stringValue, out propertyValue, true) || TryImplicitConversion(propertyType, stringValue, out propertyValue) || TryFlatListConversion(targetObject, propInfo, stringValue, configurationItemFactory, out propertyValue) || TryTypeConverterConversion(propertyType, stringValue, out propertyValue))) propertyValue = Convert.ChangeType(stringValue, propertyType, CultureInfo.InvariantCulture); } } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } throw new NLogConfigurationException($"'{targetObject?.GetType()?.Name}' cannot assign property '{propInfo.Name}'='{stringValue}'. Error: {ex.Message}", ex); } SetPropertyValueForObject(targetObject, propertyValue, propInfo); } internal static void SetPropertyValueForObject(object targetObject, object value, PropertyInfo propInfo) { try { propInfo.SetValue(targetObject, value, null); } catch (TargetInvocationException ex) { throw new NLogConfigurationException($"'{targetObject?.GetType()?.Name}' cannot assign property '{propInfo.Name}'", ex.InnerException ?? ex); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } throw new NLogConfigurationException($"'{targetObject?.GetType()?.Name}' cannot assign property '{propInfo.Name}'. Error={ex.Message}", ex); } } /// <summary> /// Get property info /// </summary> /// <param name="obj">object which could have property <paramref name="propertyName"/></param> /// <param name="propertyName">property name on <paramref name="obj"/></param> /// <param name="result">result when success.</param> /// <returns>success.</returns> internal static bool TryGetPropertyInfo(object obj, string propertyName, out PropertyInfo result) { return TryGetPropertyInfo(obj.GetType(), propertyName, out result); } internal static Type GetArrayItemType(PropertyInfo propInfo) { var arrayParameterAttribute = propInfo.GetFirstCustomAttribute<ArrayParameterAttribute>(); return arrayParameterAttribute?.ItemType; } internal static bool IsConfigurationItemType(Type type) { if (type is null || IsSimplePropertyType(type)) return false; if (typeof(LayoutRenderers.LayoutRenderer).IsAssignableFrom(type)) return true; if (typeof(Layout).IsAssignableFrom(type)) return true; // NLog will register no properties for types that are not marked with NLogConfigurationItemAttribute return TryLookupConfigItemProperties(type) != null; } internal static Dictionary<string, PropertyInfo> GetAllConfigItemProperties(Type type) { // NLog will ignore all properties marked with NLogConfigurationIgnorePropertyAttribute return TryLookupConfigItemProperties(type) ?? new Dictionary<string, PropertyInfo>(); } private static Dictionary<string, PropertyInfo> TryLookupConfigItemProperties(Type type) { lock (parameterInfoCache) { // NLog will ignore all properties marked with NLogConfigurationIgnorePropertyAttribute if (!parameterInfoCache.TryGetValue(type, out var cache)) { if (TryCreatePropertyInfoDictionary(type, out cache)) { parameterInfoCache[type] = cache; } else { parameterInfoCache[type] = null; // Not config item type } } return cache; } } internal static void CheckRequiredParameters(object o) { foreach (var configProp in GetAllConfigItemProperties(o.GetType())) { var propInfo = configProp.Value; if (propInfo.IsDefined(_requiredParameterAttribute.GetType(), false)) { object value = propInfo.GetValue(o, null); if (value is null) { throw new NLogConfigurationException( $"Required parameter '{propInfo.Name}' on '{o}' was not specified."); } } } } internal static bool IsSimplePropertyType(Type type) { #if !NETSTANDARD1_3 if (Type.GetTypeCode(type) != TypeCode.Object) #else if (type.IsPrimitive() || type == typeof(string)) #endif return true; if (type == typeof(CultureInfo)) return true; if (type == typeof(Type)) return true; if (type == typeof(Encoding)) return true; return false; } private static bool TryImplicitConversion(Type resultType, string value, out object result) { try { if (IsSimplePropertyType(resultType)) { result = null; return false; } MethodInfo operatorImplicitMethod = resultType.GetMethod("op_Implicit", BindingFlags.Public | BindingFlags.Static, null, new Type[] { value.GetType() }, null); if (operatorImplicitMethod is null || !resultType.IsAssignableFrom(operatorImplicitMethod.ReturnType)) { result = null; return false; } result = operatorImplicitMethod.Invoke(null, new object[] { value }); return true; } catch (Exception ex) { InternalLogger.Warn(ex, "Implicit Conversion Failed of {0} to {1}", value, resultType); } result = null; return false; } private static bool TryNLogSpecificConversion(Type propertyType, string value, ConfigurationItemFactory configurationItemFactory, out object newValue) { if (DefaultPropertyConversionMapper.TryGetValue(propertyType, out var objectConverter)) { newValue = objectConverter.Invoke(value, configurationItemFactory); return true; } if (propertyType.IsGenericType() && propertyType.GetGenericTypeDefinition() == typeof(Layout<>)) { var simpleLayout = new SimpleLayout(value, configurationItemFactory); var concreteType = typeof(Layout<>).MakeGenericType(propertyType.GetGenericArguments()); newValue = Activator.CreateInstance(concreteType, BindingFlags.Instance | BindingFlags.Public, null, new object[] { simpleLayout }, null); return true; } newValue = null; return false; } private static bool TryGetEnumValue(Type resultType, string value, out object result, bool flagsEnumAllowed) { if (!resultType.IsEnum()) { result = null; return false; } if (flagsEnumAllowed && resultType.IsDefined(_flagsAttribute.GetType(), false)) { ulong union = 0; foreach (string v in value.SplitAndTrimTokens(',')) { FieldInfo enumField = resultType.GetField(v, BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.Public); if (enumField is null) { throw new NLogConfigurationException($"Invalid enumeration value '{value}'."); } union |= Convert.ToUInt64(enumField.GetValue(null), CultureInfo.InvariantCulture); } result = Convert.ChangeType(union, Enum.GetUnderlyingType(resultType), CultureInfo.InvariantCulture); result = Enum.ToObject(resultType, result); return true; } else { FieldInfo enumField = resultType.GetField(value, BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.Public); if (enumField is null) { throw new NLogConfigurationException($"Invalid enumeration value '{value}'."); } result = enumField.GetValue(null); return true; } } private static object TryParseCultureInfo(string stringValue) { stringValue = stringValue?.Trim(); if (string.IsNullOrEmpty(stringValue)) return CultureInfo.InvariantCulture; else return new CultureInfo(stringValue); } private static object TryParseEncodingValue(string stringValue, ConfigurationItemFactory configurationItemFactory) { _ = configurationItemFactory; // Discard unreferenced parameter stringValue = stringValue.Trim(); if (string.Equals(stringValue, nameof(Encoding.UTF8), StringComparison.OrdinalIgnoreCase)) stringValue = Encoding.UTF8.WebName; // Support utf8 without hyphen (And not just Utf-8) return Encoding.GetEncoding(stringValue); } private static object TryParseLayoutValue(string stringValue, ConfigurationItemFactory configurationItemFactory) { return new SimpleLayout(stringValue, configurationItemFactory); } private static object TryParseConditionValue(string stringValue, ConfigurationItemFactory configurationItemFactory) { try { return ConditionParser.ParseExpression(stringValue, configurationItemFactory); } catch (ConditionParseException ex) { throw new NLogConfigurationException($"Cannot parse ConditionExpression '{stringValue}'. Error: {ex.Message}", ex); } } /// <summary> /// Try parse of string to (Generic) list, comma separated. /// </summary> /// <remarks> /// If there is a comma in the value, then (single) quote the value. For single quotes, use the backslash as escape /// </remarks> private static bool TryFlatListConversion(object obj, PropertyInfo propInfo, string valueRaw, ConfigurationItemFactory configurationItemFactory, out object newValue) { if (propInfo.PropertyType.IsGenericType() && TryCreateCollectionObject(obj, propInfo, valueRaw, out var newList, out var collectionAddMethod, out var propertyType)) { var values = valueRaw.SplitQuoted(',', '\'', '\\'); foreach (var value in values) { if (!(TryGetEnumValue(propertyType, value, out newValue, false) || TryNLogSpecificConversion(propertyType, value, configurationItemFactory, out newValue) || TryImplicitConversion(propertyType, value, out newValue) || TryTypeConverterConversion(propertyType, value, out newValue))) { newValue = Convert.ChangeType(value, propertyType, CultureInfo.InvariantCulture); } collectionAddMethod.Invoke(newList, new object[] { newValue }); } newValue = newList; return true; } newValue = null; return false; } private static bool TryCreateCollectionObject(object obj, PropertyInfo propInfo, string valueRaw, out object collectionObject, out MethodInfo collectionAddMethod, out Type collectionItemType) { var collectionType = propInfo.PropertyType; var typeDefinition = collectionType.GetGenericTypeDefinition(); #if !NET35 var isSet = typeDefinition == typeof(ISet<>) || typeDefinition == typeof(HashSet<>); #else var isSet = typeDefinition == typeof(HashSet<>); #endif //not checking "implements" interface as we are creating HashSet<T> or List<T> and also those checks are expensive if (isSet || typeDefinition == typeof(List<>) || typeDefinition == typeof(IList<>) || typeDefinition == typeof(IEnumerable<>)) //set or list/array etc { object hashsetComparer = isSet ? ExtractHashSetComparer(obj, propInfo) : null; //note: type.GenericTypeArguments is .NET 4.5+ collectionItemType = collectionType.GetGenericArguments()[0]; collectionObject = CreateCollectionObjectInstance(isSet ? typeof(HashSet<>) : typeof(List<>), collectionItemType, hashsetComparer); //no support for array if (collectionObject is null) { throw new NLogConfigurationException($"Cannot create instance of {collectionType.ToString()} for value {valueRaw}"); } collectionAddMethod = collectionObject.GetType().GetMethod("Add", BindingFlags.Instance | BindingFlags.Public); if (collectionAddMethod is null) { throw new NLogConfigurationException($"Add method on type {collectionType.ToString()} for value {valueRaw} not found"); } return true; } collectionObject = null; collectionAddMethod = null; collectionItemType = null; return false; } private static object CreateCollectionObjectInstance(Type collectionType, Type collectionItemType, object hashSetComparer) { var concreteType = collectionType.MakeGenericType(collectionItemType); if (hashSetComparer != null) { var constructor = concreteType.GetConstructor(new[] { hashSetComparer.GetType() }); if (constructor != null) return constructor.Invoke(new[] { hashSetComparer }); } return Activator.CreateInstance(concreteType); } /// <summary> /// Attempt to reuse the HashSet.Comparer from the original HashSet-object (Ex. StringComparer.OrdinalIgnoreCase) /// </summary> private static object ExtractHashSetComparer(object obj, PropertyInfo propInfo) { var exitingValue = propInfo.IsValidPublicProperty() ? propInfo.GetPropertyValue(obj) : null; if (exitingValue != null) { // Found original HashSet-object. See if we can extract the Comparer var comparerPropInfo = exitingValue.GetType().GetProperty("Comparer", BindingFlags.Instance | BindingFlags.Public); if (comparerPropInfo.IsValidPublicProperty()) { return comparerPropInfo.GetPropertyValue(exitingValue); } } return null; } internal static bool TryTypeConverterConversion(Type type, string value, out object newValue) { try { var converter = TypeDescriptor.GetConverter(type); if (converter.CanConvertFrom(typeof(string))) { newValue = converter.ConvertFromInvariantString(value); return true; } newValue = null; return false; } catch (MissingMethodException ex) { InternalLogger.Error(ex, "Error in lookup of TypeDescriptor for type={0} to convert value '{1}'", type, value); newValue = null; return false; } } private static bool TryGetPropertyInfo(Type targetType, string propertyName, out PropertyInfo result) { if (!string.IsNullOrEmpty(propertyName)) { PropertyInfo propInfo = targetType.GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); if (propInfo != null) { result = propInfo; return true; } } // NLog has special property-lookup handling for default-parameters (and array-properties) var configProperties = GetAllConfigItemProperties(targetType); return configProperties.TryGetValue(propertyName, out result); } private static bool TryCreatePropertyInfoDictionary(Type t, out Dictionary<string, PropertyInfo> result) { result = null; try { if (!t.IsDefined(_configPropertyAttribute.GetType(), true)) { return false; } result = new Dictionary<string, PropertyInfo>(StringComparer.OrdinalIgnoreCase); foreach (PropertyInfo propInfo in t.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { try { var parameterName = LookupPropertySymbolName(propInfo); if (string.IsNullOrEmpty(parameterName)) { continue; } result[parameterName] = propInfo; if (propInfo.IsDefined(_defaultParameterAttribute.GetType(), false)) { // define a property with empty name (Default property name) result[string.Empty] = propInfo; } } catch (Exception ex) { InternalLogger.Debug(ex, "Type reflection not possible for property {0} on type {1}. Maybe because of .NET Native.", propInfo.Name, t); } } } catch (Exception ex) { InternalLogger.Debug(ex, "Type reflection not possible for type {0}. Maybe because of .NET Native.", t); } return result != null; } private static string LookupPropertySymbolName(PropertyInfo propInfo) { if (propInfo.PropertyType is null) return null; if (IsSimplePropertyType(propInfo.PropertyType)) return propInfo.Name; if (typeof(LayoutRenderers.LayoutRenderer).IsAssignableFrom(propInfo.PropertyType)) return propInfo.Name; if (typeof(Layout).IsAssignableFrom(propInfo.PropertyType)) return propInfo.Name; if (propInfo.IsDefined(_ignorePropertyAttribute.GetType(), false)) return null; var arrayParameterAttribute = propInfo.GetFirstCustomAttribute<ArrayParameterAttribute>(); if (arrayParameterAttribute != null) { return arrayParameterAttribute.ElementName; } return propInfo.Name; } } }
using UnityEngine; using UnityEditor; using System.IO; using System.Collections.Generic; using System.Xml; using System.Xml.Serialization; namespace PixelCrushers.DialogueSystem { /// <summary> /// This wizard sets up the Dialogue Manager object. /// </summary> public class DialogueManagerWizard : EditorWindow { [MenuItem("Window/Dialogue System/Wizards/Dialogue Manager", false, 1)] public static void Init() { (EditorWindow.GetWindow(typeof(DialogueManagerWizard), false, "Dialogue Mgr") as DialogueManagerWizard).minSize = new Vector2(720, 500); } // Private fields for the window: private enum Stage { Database, UI, Localization, Subtitles, Cutscenes, Inputs, Alerts, Review }; private Stage stage = Stage.Database; private string[] stageLabels = new string[] { "Database", "UI", "Localization", "Subtitles", "Cutscenes", "Input", "Alerts", "Review" }; private bool createNewDatabase = false; /// <summary> /// Draws the window. /// </summary> void OnGUI() { try { DrawProgressIndicator(); DrawCurrentStage(); CheckCreateNewDatabase(); } catch (System.Exception e) { Debug.LogError("Error updating Dialogue Manager Setup Wizard window: " + e.Message); } } private void CheckCreateNewDatabase() { if (createNewDatabase) { createNewDatabase = false; DialogueManager.Instance.initialDatabase = DialogueSystemMenuItems.CreateDialogueDatabaseInstance(); DialogueSystemMenuItems.CreateAsset(DialogueManager.Instance.initialDatabase, "Dialogue Database"); } } private void DrawProgressIndicator() { EditorGUI.BeginDisabledGroup(true); EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); GUILayout.Toolbar((int) stage, stageLabels, GUILayout.Width(720)); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); EditorGUI.EndDisabledGroup(); EditorWindowTools.DrawHorizontalLine(); } private void DrawNavigationButtons(bool backEnabled, bool nextEnabled, bool nextCloses) { GUILayout.FlexibleSpace(); EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Cancel", GUILayout.Width(100))) { this.Close(); } else if (backEnabled && GUILayout.Button("Back", GUILayout.Width(100))) { stage--; } else { EditorGUI.BeginDisabledGroup(!nextEnabled); if (GUILayout.Button(nextCloses ? "Finish" : "Next", GUILayout.Width(100))) { if (nextCloses) { Close(); } else { stage++; } } EditorGUI.EndDisabledGroup(); } EditorGUILayout.EndHorizontal(); EditorGUILayout.LabelField(string.Empty, GUILayout.Height(2)); } private void DrawCurrentStage() { switch (stage) { case Stage.Database: DrawDatabaseStage(); break; case Stage.UI: DrawUIStage(); break; case Stage.Localization: DrawLocalizationStage(); break; case Stage.Subtitles: DrawSubtitlesStage(); break; case Stage.Cutscenes: DrawCutscenesStage(); break; case Stage.Inputs: DrawInputsStage(); break; case Stage.Alerts: DrawAlertsStage(); break; case Stage.Review: DrawReviewStage(); break; } } private void DrawDatabaseStage() { EditorGUILayout.LabelField("Dialogue Database", EditorStyles.boldLabel); EditorWindowTools.StartIndentedSection(); EditorGUILayout.HelpBox("This wizard will help you configure the Dialogue Manager object. The first step is to assign an initial dialogue database asset. This asset contains your conversations and related data.", MessageType.Info); EditorGUILayout.BeginHorizontal(); if (DialogueManager.Instance == null) { EditorGUILayout.LabelField("Dialogue Manager object is null. Creating a new instance..."); if (DialogueManager.Instance == null) { new GameObject("Dialogue Manager").AddComponent<DialogueSystemController>(); } } else { DialogueManager.Instance.initialDatabase = EditorGUILayout.ObjectField("Database", DialogueManager.Instance.initialDatabase, typeof(DialogueDatabase), false) as DialogueDatabase; bool disabled = (DialogueManager.Instance.initialDatabase != null); EditorGUI.BeginDisabledGroup(disabled); if (GUILayout.Button("Create New", GUILayout.Width (100))) createNewDatabase = true; EditorGUI.EndDisabledGroup(); } EditorGUILayout.EndHorizontal(); EditorWindowTools.EndIndentedSection(); if (DialogueManager.Instance != null) { DrawNavigationButtons(false, (DialogueManager.Instance.initialDatabase != null), false); } } private void DrawUIStage() { EditorGUILayout.LabelField("User Interface", EditorStyles.boldLabel); EditorWindowTools.StartIndentedSection(); EditorGUILayout.HelpBox("Assign a dialogue UI. You can find pre-built Unity GUI dialogue UI prefabs in Prefabs/Unity Dialogue UIs. To assign a prefab for a different GUI system, import its support package found in Third Party Support. You can also assign a UI scene object.", MessageType.Info); if (DialogueManager.Instance.displaySettings == null) DialogueManager.Instance.displaySettings = new DisplaySettings(); DialogueManager.Instance.displaySettings.dialogueUI = EditorGUILayout.ObjectField("Dialogue UI", DialogueManager.Instance.displaySettings.dialogueUI, typeof(GameObject), true) as GameObject; if (DialogueManager.Instance.displaySettings.dialogueUI == null) { EditorGUILayout.HelpBox("If you continue without assigning a UI, the Dialogue System will use a very plain default UI.", MessageType.Warning); } else { IDialogueUI ui = DialogueManager.Instance.displaySettings.dialogueUI.GetComponent(typeof(IDialogueUI)) as IDialogueUI; if (ui == null) DialogueManager.Instance.displaySettings.dialogueUI = null; } EditorWindowTools.EndIndentedSection(); DrawNavigationButtons(true, true, false); } private void DrawLocalizationStage() { if (DialogueManager.Instance.displaySettings.localizationSettings == null) DialogueManager.Instance.displaySettings.localizationSettings = new DisplaySettings.LocalizationSettings(); EditorGUILayout.LabelField("Localization", EditorStyles.boldLabel); EditorWindowTools.StartIndentedSection(); EditorGUILayout.HelpBox("The Dialogue System supports language localization. If you don't want to set up localization right now, you can just click Next.", MessageType.Info); EditorGUILayout.BeginHorizontal(); DialogueManager.Instance.displaySettings.localizationSettings.language = EditorGUILayout.TextField("Override Language", DialogueManager.Instance.displaySettings.localizationSettings.language); EditorGUILayout.HelpBox("Use the language defined by a language code (e.g., 'ES-es') instead of the default language.", MessageType.None); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); DialogueManager.Instance.displaySettings.localizationSettings.useSystemLanguage = EditorGUILayout.Toggle("Use System Language", DialogueManager.Instance.displaySettings.localizationSettings.useSystemLanguage); EditorGUILayout.HelpBox("Tick to use the current system language instead of the default language.", MessageType.None); EditorGUILayout.EndHorizontal(); EditorWindowTools.EndIndentedSection(); DrawNavigationButtons(true, true, false); } private void DrawSubtitlesStage() { if (DialogueManager.Instance.displaySettings.subtitleSettings == null) DialogueManager.Instance.displaySettings.subtitleSettings = new DisplaySettings.SubtitleSettings(); EditorGUILayout.LabelField("Subtitles", EditorStyles.boldLabel); EditorWindowTools.StartIndentedSection(); EditorGUILayout.HelpBox("In this section, you'll specify how subtitles are displayed.", MessageType.Info); EditorGUILayout.BeginHorizontal(); DialogueManager.Instance.displaySettings.subtitleSettings.showNPCSubtitlesDuringLine = EditorGUILayout.Toggle("NPC Subtitles During Line", DialogueManager.Instance.displaySettings.subtitleSettings.showNPCSubtitlesDuringLine); EditorGUILayout.HelpBox("Tick to display NPC subtitles while NPCs are speaking. Subtitles are the lines of dialogue defined in your dialogue database asset. You might untick this if, for example, you use lip-synced voiceovers without onscreen text.", MessageType.None); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); DialogueManager.Instance.displaySettings.subtitleSettings.showNPCSubtitlesWithResponses = EditorGUILayout.Toggle(" With Response Menu", DialogueManager.Instance.displaySettings.subtitleSettings.showNPCSubtitlesWithResponses); EditorGUILayout.HelpBox("Tick to display the last NPC subtitle during the player response menu. This helps remind the players what they're responding to.", MessageType.None); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); DialogueManager.Instance.displaySettings.subtitleSettings.showPCSubtitlesDuringLine = EditorGUILayout.Toggle("PC Subtitles", DialogueManager.Instance.displaySettings.subtitleSettings.showPCSubtitlesDuringLine); EditorGUILayout.HelpBox("Tick to display PC subtitles while the PC is speaking. If you use different Menu Text and Dialogue Text, this should probably be ticked. Otherwise you may choose to leave it unticked.", MessageType.None); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); DialogueManager.Instance.displaySettings.subtitleSettings.subtitleCharsPerSecond = EditorGUILayout.FloatField("Chars/Second", DialogueManager.Instance.displaySettings.subtitleSettings.subtitleCharsPerSecond); EditorGUILayout.HelpBox("Determines how long the subtitle is displayed before moving to the next stage of the conversation. If the subtitle is 90 characters and Chars/Second is 30, then it will be displayed for 3 seconds.", MessageType.None); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); DialogueManager.Instance.displaySettings.subtitleSettings.minSubtitleSeconds = EditorGUILayout.FloatField("Min Seconds", DialogueManager.Instance.displaySettings.subtitleSettings.minSubtitleSeconds); EditorGUILayout.HelpBox("Min Seconds below is the guaranteed minimum amount of time that a subtitle will be displayed (if its corresponding checkbox is ticked).", MessageType.None); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); DialogueManager.Instance.displaySettings.subtitleSettings.continueButton = (DisplaySettings.SubtitleSettings.ContinueButtonMode) EditorGUILayout.EnumPopup("Continue Button", DialogueManager.Instance.displaySettings.subtitleSettings.continueButton); //.waitForContinueButton = EditorGUILayout.Toggle("Use Continue Button", DialogueManager.Instance.displaySettings.subtitleSettings.waitForContinueButton); EditorGUILayout.HelpBox("- Never: Conversation automatically moves to next stage when subtitle is done." + "\n- Always: Requires player to click a continue button to progress past each subtitle." + "\n- Optional Before Response Menu: If player response menu is next, shows but doesn't require clicking." + "\n- Never Before Response Menu: If player response menu is next, doesn't show." + "\nFor any setting other than Never, your UI must contain continue button(s).", MessageType.None); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); DialogueManager.Instance.displaySettings.subtitleSettings.richTextEmphases = EditorGUILayout.Toggle("Rich Text", DialogueManager.Instance.displaySettings.subtitleSettings.richTextEmphases); EditorGUILayout.HelpBox("By default, emphasis tags embedded in dialogue text are applied to the entire subtitle. To convert them to rich text tags instead, tick this checkbox. This allows emphases to affect only parts of the text, but your GUI system must support rich text.", MessageType.None); EditorGUILayout.EndHorizontal(); EditorWindowTools.EndIndentedSection(); DrawNavigationButtons(true, true, false); } private enum DefaultSequenceStyle { DefaultCameraAngles, Closeups, WaitForSubtitle, Custom }; private const string DefaultCameraAngleSequence = "Camera(default); required Camera(default,listener)@{{end}}"; private const string DefaultCloseupSequence = "Camera(Closeup); required Camera(Closeup,listener)@{{end}}"; private const string DefaultWaitForSubtitleSequence = "Delay({{end}})"; private void DrawCutscenesStage() { if (DialogueManager.Instance.displaySettings.cameraSettings == null) DialogueManager.Instance.displaySettings.cameraSettings = new DisplaySettings.CameraSettings(); EditorGUILayout.LabelField("Cutscene Sequences", EditorStyles.boldLabel); EditorWindowTools.StartIndentedSection(); EditorGUILayout.HelpBox("The Dialogue System uses an integrated cutscene sequencer. Every line of dialogue can have a cutscene sequence -- for example to move the camera, play animations on the speaker, or play a lip-synced voiceover.", MessageType.Info); EditorWindowTools.DrawHorizontalLine(); EditorGUILayout.HelpBox("You can set up a camera object or prefab specifically for sequences. This can be useful to apply depth of field effects or other filters that you wouldn't normally apply to your gameplay camera. If you've set up a sequencer camera, assign it below. Otherwise the sequencer will just use the current main camera.", MessageType.None); DialogueManager.Instance.displaySettings.cameraSettings.sequencerCamera = EditorGUILayout.ObjectField("Sequencer Camera", DialogueManager.Instance.displaySettings.cameraSettings.sequencerCamera, typeof(Camera), true) as Camera; EditorWindowTools.DrawHorizontalLine(); EditorGUILayout.HelpBox("Cutscene sequence commands can reference camera angles defined on a camera angle prefab. If you've set up a camera angle prefab, assign it below. Otherwise the sequencer will use a default camera angle prefab with basic angles such as Closeup, Medium, and Wide.", MessageType.None); DialogueManager.Instance.displaySettings.cameraSettings.cameraAngles = EditorGUILayout.ObjectField("Camera Angles", DialogueManager.Instance.displaySettings.cameraSettings.cameraAngles, typeof(GameObject), true) as GameObject; EditorWindowTools.DrawHorizontalLine(); EditorGUILayout.HelpBox("If a dialogue entry doesn't define its own cutscene sequence, it will use the default sequence below.", MessageType.None); EditorGUILayout.BeginHorizontal(); DefaultSequenceStyle style = string.Equals(DefaultCameraAngleSequence, DialogueManager.Instance.displaySettings.cameraSettings.defaultSequence) ? DefaultSequenceStyle.DefaultCameraAngles : string.Equals(DefaultCloseupSequence, DialogueManager.Instance.displaySettings.cameraSettings.defaultSequence) ? DefaultSequenceStyle.Closeups : (string.Equals(DefaultWaitForSubtitleSequence, DialogueManager.Instance.displaySettings.cameraSettings.defaultSequence) ? DefaultSequenceStyle.WaitForSubtitle : DefaultSequenceStyle.Custom); DefaultSequenceStyle newStyle = (DefaultSequenceStyle) EditorGUILayout.EnumPopup("Default Sequence", style); if (newStyle != style) { style = newStyle; switch (style) { case DefaultSequenceStyle.DefaultCameraAngles: DialogueManager.Instance.displaySettings.cameraSettings.defaultSequence = DefaultCameraAngleSequence; break; case DefaultSequenceStyle.Closeups: DialogueManager.Instance.displaySettings.cameraSettings.defaultSequence = DefaultCloseupSequence; break; case DefaultSequenceStyle.WaitForSubtitle: DialogueManager.Instance.displaySettings.cameraSettings.defaultSequence = DefaultWaitForSubtitleSequence; break; default: break; } } switch (style) { case DefaultSequenceStyle.DefaultCameraAngles: EditorGUILayout.HelpBox("Changes to the speaker's default camera angle. At the end of the subtitle, changes to the listener's default angle. If angles aren't specified on the speaker or listener, the default is Closeup. Don't use this if your player is a body-less first person controller, since focusing the camera on the player probably doesn't make sense in this case.", MessageType.None); break; case DefaultSequenceStyle.Closeups: EditorGUILayout.HelpBox("Does a camera closeup of the speaker. At the end of the subtitle, changes to a closeup of the listener. Don't use this if your player is a body-less first person controller, since a closeup doesn't make sense in this case.", MessageType.None); break; case DefaultSequenceStyle.WaitForSubtitle: EditorGUILayout.HelpBox("Just waits for the subtitle to finish. Doesn't touch the camera.", MessageType.None); break; default: EditorGUILayout.HelpBox("Custom default sequence defined below.", MessageType.None); break; } EditorGUILayout.EndHorizontal(); EditorGUILayout.HelpBox("In the default sequence, you can use '{{end}}' to refer to the duration of the subtitle as determined by Chars/Second and Min Seconds.", MessageType.None); DialogueManager.Instance.displaySettings.cameraSettings.defaultSequence = EditorGUILayout.TextField("Default Sequence", DialogueManager.Instance.displaySettings.cameraSettings.defaultSequence); EditorWindowTools.EndIndentedSection(); DrawNavigationButtons(true, true, false); } private const float DefaultResponseTimeoutDuration = 10f; private void DrawInputsStage() { if (DialogueManager.Instance.displaySettings.inputSettings == null) DialogueManager.Instance.displaySettings.inputSettings = new DisplaySettings.InputSettings(); EditorGUILayout.LabelField("Input Settings", EditorStyles.boldLabel); EditorWindowTools.StartIndentedSection(); EditorGUILayout.HelpBox("In this section, you'll specify input settings for the dialogue UI.", MessageType.Info); EditorWindowTools.StartIndentedSection(); EditorWindowTools.DrawHorizontalLine(); EditorGUILayout.LabelField("Player Response Menu", EditorStyles.boldLabel); EditorGUILayout.BeginHorizontal(); DialogueManager.Instance.displaySettings.inputSettings.alwaysForceResponseMenu = EditorGUILayout.Toggle("Always Force Menu", DialogueManager.Instance.displaySettings.inputSettings.alwaysForceResponseMenu); EditorGUILayout.HelpBox("Tick to always force the response menu. If unticked, then when the player only has one valid response, the UI will automatically select it without showing the response menu.", MessageType.None); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); bool useTimeout = EditorGUILayout.Toggle("Timer", (DialogueManager.Instance.displaySettings.inputSettings.responseTimeout > 0)); EditorGUILayout.HelpBox("Tick to make the response menu timed. If unticked, players can take as long as they want to make their selection.", MessageType.None); EditorGUILayout.EndHorizontal(); if (useTimeout) { if (Tools.ApproximatelyZero(DialogueManager.Instance.displaySettings.inputSettings.responseTimeout)) DialogueManager.Instance.displaySettings.inputSettings.responseTimeout = DefaultResponseTimeoutDuration; DialogueManager.Instance.displaySettings.inputSettings.responseTimeout = EditorGUILayout.FloatField("Timeout Seconds", DialogueManager.Instance.displaySettings.inputSettings.responseTimeout); DialogueManager.Instance.displaySettings.inputSettings.responseTimeoutAction = (ResponseTimeoutAction) EditorGUILayout.EnumPopup("If Time Runs Out", DialogueManager.Instance.displaySettings.inputSettings.responseTimeoutAction); } else { DialogueManager.Instance.displaySettings.inputSettings.responseTimeout = 0; } EditorWindowTools.DrawHorizontalLine(); EditorGUILayout.LabelField("Quick Time Event (QTE) Trigger Buttons", EditorStyles.boldLabel); EditorGUILayout.HelpBox("QTE trigger buttons may be defined on the Dialogue Manager object's inspector under Display Settings > Input Settings > Qte Buttons.", MessageType.None); if (GUILayout.Button("Inspect Dialogue Manager object", GUILayout.Width(240))) Selection.activeObject = DialogueManager.Instance; EditorWindowTools.DrawHorizontalLine(); EditorGUILayout.LabelField("Cancel", EditorStyles.boldLabel); EditorGUILayout.BeginHorizontal(); DialogueManager.Instance.displaySettings.inputSettings.cancel.key = (KeyCode) EditorGUILayout.EnumPopup("Key", DialogueManager.Instance.displaySettings.inputSettings.cancel.key); EditorGUILayout.HelpBox("Pressing this key cancels the response menu or conversation.", MessageType.None); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); DialogueManager.Instance.displaySettings.inputSettings.cancel.buttonName = EditorGUILayout.TextField("Button Name", DialogueManager.Instance.displaySettings.inputSettings.cancel.buttonName); EditorGUILayout.HelpBox("Pressing this button cancels the response menu or conversation.", MessageType.None); EditorGUILayout.EndHorizontal(); EditorWindowTools.EndIndentedSection(); EditorWindowTools.EndIndentedSection(); DrawNavigationButtons(true, true, false); } private const float DefaultAlertCheckFrequency = 2f; private void DrawAlertsStage() { if (DialogueManager.Instance.displaySettings.alertSettings == null) DialogueManager.Instance.displaySettings.alertSettings = new DisplaySettings.AlertSettings(); EditorGUILayout.LabelField("Alerts", EditorStyles.boldLabel); EditorWindowTools.StartIndentedSection(); EditorGUILayout.HelpBox("Alerts are gameplay messages. They can be delivered from conversations or other sources.", MessageType.Info); EditorGUILayout.BeginHorizontal(); DialogueManager.Instance.displaySettings.alertSettings.allowAlertsDuringConversations = EditorGUILayout.Toggle("Allow In Conversations", DialogueManager.Instance.displaySettings.alertSettings.allowAlertsDuringConversations); EditorGUILayout.HelpBox("Tick to allow alerts to be displayed while in conversations. If unticked, alerts won't be displayed until the conversation has ended.", MessageType.None); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); bool monitorAlerts = EditorGUILayout.Toggle("Monitor Alerts", (DialogueManager.Instance.displaySettings.alertSettings.alertCheckFrequency > 0)); EditorGUILayout.HelpBox("Tick to constantly monitor the Lua value \"Variable['Alert']\" and display its contents as an alert. This runs as a background process. The value is automatically checked at the end of conversations, and you can check it manually. Unless you have a need to constantly monitor the value, it's more efficient to leave this unticked.", MessageType.None); EditorGUILayout.EndHorizontal(); if (monitorAlerts) { if (Tools.ApproximatelyZero(DialogueManager.Instance.displaySettings.alertSettings.alertCheckFrequency)) DialogueManager.Instance.displaySettings.alertSettings.alertCheckFrequency = DefaultAlertCheckFrequency; DialogueManager.Instance.displaySettings.alertSettings.alertCheckFrequency = EditorGUILayout.FloatField("Frequency (Seconds)", DialogueManager.Instance.displaySettings.alertSettings.alertCheckFrequency); } else { DialogueManager.Instance.displaySettings.alertSettings.alertCheckFrequency = 0; } EditorWindowTools.EndIndentedSection(); DrawNavigationButtons(true, true, false); } private void DrawReviewStage() { EditorGUILayout.LabelField("Review", EditorStyles.boldLabel); EditorWindowTools.StartIndentedSection(); EditorGUILayout.HelpBox("Your Dialogue Manager is ready! Below is a brief summary of the configuration.", MessageType.Info); EditorGUILayout.LabelField(string.Format("Dialogue database: {0}", DialogueManager.Instance.initialDatabase.name)); EditorGUILayout.LabelField(string.Format("Dialogue UI: {0}", (DialogueManager.Instance.displaySettings.dialogueUI == null) ? "(use default)" : DialogueManager.Instance.displaySettings.dialogueUI.name)); EditorGUILayout.LabelField(string.Format("Show subtitles: {0}", GetSubtitlesInfo())); EditorGUILayout.LabelField(string.Format("Always force response menu: {0}", DialogueManager.Instance.displaySettings.inputSettings.alwaysForceResponseMenu)); EditorGUILayout.LabelField(string.Format("Response menu timeout: {0}", Tools.ApproximatelyZero(DialogueManager.Instance.displaySettings.inputSettings.responseTimeout) ? "Unlimited Time" : DialogueManager.Instance.displaySettings.inputSettings.responseTimeout.ToString())); EditorGUILayout.LabelField(string.Format("Allow alerts during conversations: {0}", DialogueManager.Instance.displaySettings.alertSettings.allowAlertsDuringConversations)); EditorWindowTools.EndIndentedSection(); DrawNavigationButtons(true, true, true); } private string GetSubtitlesInfo() { if ((DialogueManager.Instance.displaySettings.subtitleSettings.showNPCSubtitlesDuringLine == true) && (DialogueManager.Instance.displaySettings.subtitleSettings.showNPCSubtitlesWithResponses == true) && (DialogueManager.Instance.displaySettings.subtitleSettings.showPCSubtitlesDuringLine == true)) { return "All"; } else if ((DialogueManager.Instance.displaySettings.subtitleSettings.showNPCSubtitlesDuringLine == true) && (DialogueManager.Instance.displaySettings.subtitleSettings.showNPCSubtitlesWithResponses == true) && (DialogueManager.Instance.displaySettings.subtitleSettings.showPCSubtitlesDuringLine == false)) { return "NPC only"; } else if ((DialogueManager.Instance.displaySettings.subtitleSettings.showNPCSubtitlesDuringLine == true) && (DialogueManager.Instance.displaySettings.subtitleSettings.showNPCSubtitlesWithResponses == false) && (DialogueManager.Instance.displaySettings.subtitleSettings.showPCSubtitlesDuringLine == true)) { return "While speaking lines"; } else if ((DialogueManager.Instance.displaySettings.subtitleSettings.showNPCSubtitlesDuringLine == true) && (DialogueManager.Instance.displaySettings.subtitleSettings.showNPCSubtitlesWithResponses == false) && (DialogueManager.Instance.displaySettings.subtitleSettings.showPCSubtitlesDuringLine == false)) { return "Only while NPC is speaking"; } else if ((DialogueManager.Instance.displaySettings.subtitleSettings.showNPCSubtitlesDuringLine == false) && (DialogueManager.Instance.displaySettings.subtitleSettings.showNPCSubtitlesWithResponses == true) && (DialogueManager.Instance.displaySettings.subtitleSettings.showPCSubtitlesDuringLine == true)) { return "Only PC and response menu reminder"; } else if ((DialogueManager.Instance.displaySettings.subtitleSettings.showNPCSubtitlesDuringLine == false) && (DialogueManager.Instance.displaySettings.subtitleSettings.showNPCSubtitlesWithResponses == true) && (DialogueManager.Instance.displaySettings.subtitleSettings.showPCSubtitlesDuringLine == false)) { return "Only response menu reminder"; } else if ((DialogueManager.Instance.displaySettings.subtitleSettings.showNPCSubtitlesDuringLine == false) && (DialogueManager.Instance.displaySettings.subtitleSettings.showNPCSubtitlesWithResponses == false) && (DialogueManager.Instance.displaySettings.subtitleSettings.showPCSubtitlesDuringLine == true)) { return "PC Only"; } else if ((DialogueManager.Instance.displaySettings.subtitleSettings.showNPCSubtitlesDuringLine == false) && (DialogueManager.Instance.displaySettings.subtitleSettings.showNPCSubtitlesWithResponses == false) && (DialogueManager.Instance.displaySettings.subtitleSettings.showPCSubtitlesDuringLine == false)) { return "None"; } else { return "See inspector"; } } } }
/*************************************************************************** * DateButton.cs * * Copyright (C) 2005 Novell * Written by Aaron Bockover (aaron@aaronbock.net) ****************************************************************************/ /* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ using System; using GLib; using Gtk; using Tasque; namespace Gtk.Extras { public class DateButton : ToggleButton { private Window popup; private DateTime date; private Calendar cal; private bool show_time; private const uint CURRENT_TIME = 0; // FIXME: If this is ever moved to its own library // this reference to Tomboy will obviously have to // be removed. public DateButton(DateTime date_time, bool show_time) : base(Utilities.GetPrettyPrintDate (date_time, show_time)) { Toggled += OnToggled; popup = null; date = date_time; this.show_time = show_time; } private void ShowCalendar() { popup = new Window(WindowType.Popup); popup.Screen = this.Screen; Frame frame = new Frame(); frame.Shadow = ShadowType.Out; frame.Show(); popup.Add(frame); VBox box = new VBox(false, 0); box.Show(); frame.Add(box); cal = new Calendar(); cal.DisplayOptions = CalendarDisplayOptions.ShowHeading | CalendarDisplayOptions.ShowDayNames | CalendarDisplayOptions.ShowWeekNumbers; cal.KeyPressEvent += OnCalendarKeyPressed; popup.ButtonPressEvent += OnButtonPressed; cal.Show(); Alignment calAlignment = new Alignment(0.0f, 0.0f, 1.0f, 1.0f); calAlignment.Show(); calAlignment.SetPadding(4, 4, 4, 4); calAlignment.Add(cal); box.PackStart(calAlignment, false, false, 0); Requisition req = SizeRequest(); int x = 0, y = 0; GdkWindow.GetOrigin(out x, out y); popup.Move(x + Allocation.X, y + Allocation.Y + req.Height + 3); popup.Show(); popup.GrabFocus(); Grab.Add(popup); Gdk.GrabStatus grabbed = Gdk.Pointer.Grab(popup.GdkWindow, true, Gdk.EventMask.ButtonPressMask | Gdk.EventMask.ButtonReleaseMask | Gdk.EventMask.PointerMotionMask, null, null, CURRENT_TIME); if (grabbed == Gdk.GrabStatus.Success) { grabbed = Gdk.Keyboard.Grab(popup.GdkWindow, true, CURRENT_TIME); if (grabbed != Gdk.GrabStatus.Success) { Grab.Remove(popup); popup.Destroy(); popup = null; } } else { Grab.Remove(popup); popup.Destroy(); popup = null; } cal.DaySelectedDoubleClick += OnCalendarDaySelected; cal.ButtonPressEvent += OnCalendarButtonPressed; cal.Date = date; } public void HideCalendar(bool update) { if (popup != null) { Grab.Remove(popup); Gdk.Pointer.Ungrab(CURRENT_TIME); Gdk.Keyboard.Ungrab(CURRENT_TIME); popup.Destroy(); popup = null; } if (update) { date = cal.GetDate(); // FIXME: If this is ever moved to its own library // this reference to Tomboy will obviously have to // be removed. Label = Utilities.GetPrettyPrintDate (date, show_time); } Active = false; } private void OnToggled(object o, EventArgs args) { if (Active) { ShowCalendar(); } else { HideCalendar(false); } } private void OnButtonPressed(object o, ButtonPressEventArgs args) { if (popup != null) HideCalendar(false); } private void OnCalendarDaySelected(object o, EventArgs args) { HideCalendar(true); } private void OnCalendarButtonPressed(object o, ButtonPressEventArgs args) { args.RetVal = true; } private void OnCalendarKeyPressed(object o, KeyPressEventArgs args) { switch (args.Event.Key) { case Gdk.Key.Escape: HideCalendar(false); break; case Gdk.Key.KP_Enter: case Gdk.Key.ISO_Enter: case Gdk.Key.Key_3270_Enter: case Gdk.Key.Return: case Gdk.Key.space: case Gdk.Key.KP_Space: HideCalendar(true); break; default: break; } } public DateTime Date { get { return date; } set { date = value; Label = Utilities.GetPrettyPrintDate (date, show_time); } } /// <summary> /// If true, both the date and time will be shown. If false, the time /// will be omitted. /// </summary> public bool ShowTime { get { return show_time; } set { show_time = value; } } } }
using System.Collections.Generic; using System.Linq; using System.Xml; using DbShell.Driver.Common.AbstractDb; using DbShell.Driver.Common.CommonTypeSystem; using DbShell.Driver.Common.Utility; using System.Text; using System.Runtime.Serialization; namespace DbShell.Driver.Common.Structure { /// <summary> /// Information about column structure /// </summary> [DataContract] public class ColumnInfo : TableObjectInfo, IExplicitXmlPersistent { public ColumnInfo(TableInfo table) : base(table) { CommonType = new DbTypeString(); } /// <summary> /// Column name /// </summary> [XmlAttrib("name")] [DataMember] public string Name { get; set; } /// <summary> /// Data type /// </summary> [XmlAttrib("datatype")] [DataMember] public string DataType { get; set; } /// <summary> /// Default value /// </summary> [XmlAttrib("default")] [DataMember] public string DefaultValue { get; set; } /// <summary> /// Column cannot be null /// </summary> [XmlAttrib("notnull")] [DataMember] public bool NotNull { get; set; } /// <summary> /// Is Identity? /// </summary> [XmlAttrib("auto_increment")] [DataMember] public bool AutoIncrement { get; set; } /// <summary> /// Is part of primary key? /// </summary> [XmlAttrib("primary_key")] [DataMember] public bool PrimaryKey { get; set; } /// <summary> /// Comment /// </summary> [XmlAttrib("comment")] [DataMember] public string Comment { get; set; } /// <summary> /// name of default constraint /// </summary> [XmlAttrib("default_constraint")] [DataMember] public string DefaultConstraint { get; set; } /// <summary> /// expression for computed column /// </summary> [XmlAttrib("computed_expression")] [DataMember] public string ComputedExpression { get; set; } /// <summary> /// whether computed column is persisted /// </summary> [XmlAttrib("is_persisted")] [DataMember] public bool IsPersisted { get; set; } /// <summary> /// whether computed column is sparse /// </summary> [XmlAttrib("is_sparse")] [DataMember] public bool IsSparse { get; set; } /// <summary> /// Portable data type /// </summary> [DataMember] public DbTypeBase CommonType { get; set; } [DataMember] public FilterParserType FilterType => FilterParserTool.GetExpressionType(CommonType); [DataMember] public DbTypeCode? CommonTypeCode => CommonType?.Code; public int ColumnOrder { get { if (OwnerTable == null) return -1; return OwnerTable.Columns.IndexOf(this); } } public ColumnInfo CloneColumn(TableInfo ownTable = null) { var res = new ColumnInfo(ownTable ?? OwnerTable); res.Assign(this); return res; } public override DatabaseObjectInfo CloneObject(DatabaseObjectInfo owner) { return CloneColumn(owner as TableInfo); } public override void Assign(DatabaseObjectInfo source) { base.Assign(source); var src = (ColumnInfo)source; Name = src.Name; DataType = src.DataType; DefaultValue = src.DefaultValue; DefaultConstraint = src.DefaultConstraint; NotNull = src.NotNull; AutoIncrement = src.AutoIncrement; PrimaryKey = src.PrimaryKey; Comment = src.Comment; IsPersisted = src.IsPersisted; ComputedExpression = src.ComputedExpression; IsSparse = src.IsSparse; if (src.CommonType != null) CommonType = src.CommonType.Clone(); else CommonType = null; } public void SaveToXml(XmlElement xml) { this.SavePropertiesCore(xml); if (CommonType != null) { CommonType.SaveToXml(xml.AddChild("Type")); } } public void LoadFromXml(XmlElement xml) { this.LoadPropertiesCore(xml); var type = xml.FindElement("Type"); if (type != null) CommonType = DbTypeBase.Load(type); } public List<ForeignKeyInfo> GetForeignKeys() { var res = new List<ForeignKeyInfo>(); if (OwnerTable != null) { foreach (var fk in OwnerTable.ForeignKeys) { if (fk.Columns.Any(c => c.RefColumn == this)) { res.Add(fk); } } } return res; } public bool IsSingleColumnPk() { if (OwnerTable?.PrimaryKey?.Columns?.Count != 1) return false; return OwnerTable.PrimaryKey.Columns[0].RefColumn == this; } public string DefaultValueDisplay { get { string res = DefaultValue; while (res != null && res.StartsWith("(") && res.EndsWith(")")) { res = res.Substring(1, res.Length - 2); } return res; } } public override DatabaseObjectType ObjectType { get { return DatabaseObjectType.Column; } } public override void SetDummyTable(NameWithSchema name) { var table = new TableInfo(null); table.FullName = name; table.Columns.Add(this); } public bool IsStringColumn() { if (DataType != null) return DataType.ToLower().Contains("char"); if (CommonType != null) return CommonType is DbTypeString; return true; } public void EnsureDataType(ISqlTypeProvider typeProvider) { if (DataType == null) { typeProvider.GetNativeDataType(CommonType, this); } } public override FullDatabaseRelatedName GetName() { return new FullDatabaseRelatedName { ObjectName = OwnerTable != null ? OwnerTable.FullName : null, ObjectType = DatabaseObjectType.Column, SubName = Name, }; } public override string ToString() { string res = Name; if (OwnerTable != null && OwnerTable.FullName != null) res = OwnerTable.FullName.ToString() + "." + res; return res; } //public string GetSqlType() //{ // var sb = new StringBuilder(); // sb.Append(DataType); // if (Length != 0 && (CommonType == null || CommonType is DbTypeString)) // { // if (Length == -1 || Length > 8000) sb.Append("(max)"); // else sb.Append($"({Length})"); // } // if (Precision > 0 && CommonType is DbTypeNumeric && (DataType.ToLower() != "money")) // { // sb.Append($"({Precision},{Scale})"); // } // return sb.ToString(); //} } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel; using System.Data; using System.Data.Common; using System.Data.ProviderBase; using System.Data.SqlTypes; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Text; using System.Threading; namespace System.Data.Odbc { [ TypeConverterAttribute(typeof(System.Data.Odbc.OdbcParameter.OdbcParameterConverter)) ] public sealed partial class OdbcParameter : DbParameter, ICloneable, IDbDataParameter { private bool _hasChanged; private bool _userSpecifiedType; // _typemap User explicit set type or default parameter type // _infertpe _typemap if the user explicitly sets type // otherwise it is infered from the value // _bindtype The actual type used for binding. E.g. string substitutes numeric // // set_DbType: _bindtype = _infertype = _typemap = TypeMap.FromDbType(value) // set_OdbcType: _bindtype = _infertype = _typemap = TypeMap.FromOdbcType(value) // // GetParameterType: If _typemap != _infertype AND value != 0 // _bindtype = _infertype = TypeMap.FromSystemType(value.GetType()); // otherwise // _bindtype = _infertype // // Bind: Bind may change _bindtype if the type is not supported through the driver // private TypeMap _typemap; private TypeMap _bindtype; private string _parameterName; private byte _precision; private byte _scale; private bool _hasScale; private ODBC32.SQL_C _boundSqlCType; private ODBC32.SQL_TYPE _boundParameterType; // if we bound already that is the type we used private int _boundSize; private int _boundScale; private IntPtr _boundBuffer; private IntPtr _boundIntbuffer; private TypeMap _originalbindtype; // the original type in case we had to change the bindtype // (e.g. decimal to string) private byte _internalPrecision; private bool _internalShouldSerializeSize; private int _internalSize; private ParameterDirection _internalDirection; private byte _internalScale; private int _internalOffset; internal bool _internalUserSpecifiedType; private object _internalValue; private int _preparedOffset; private int _preparedSize; private int _preparedBufferSize; private object _preparedValue; private int _preparedIntOffset; private int _preparedValueOffset; private ODBC32.SQL_C _prepared_Sql_C_Type; public OdbcParameter() : base() { // uses System.Threading! } public OdbcParameter(string name, object value) : this() { ParameterName = name; Value = value; } public OdbcParameter(string name, OdbcType type) : this() { ParameterName = name; OdbcType = type; } public OdbcParameter(string name, OdbcType type, int size) : this() { ParameterName = name; OdbcType = type; Size = size; } public OdbcParameter(string name, OdbcType type, int size, string sourcecolumn) : this() { ParameterName = name; OdbcType = type; Size = size; SourceColumn = sourcecolumn; } [EditorBrowsableAttribute(EditorBrowsableState.Advanced)] // MDAC 69508 public OdbcParameter(string parameterName, OdbcType odbcType, int size, ParameterDirection parameterDirection, Boolean isNullable, Byte precision, Byte scale, string srcColumn, DataRowVersion srcVersion, object value ) : this() { // V1.0 everything this.ParameterName = parameterName; this.OdbcType = odbcType; this.Size = size; this.Direction = parameterDirection; this.IsNullable = isNullable; PrecisionInternal = precision; ScaleInternal = scale; this.SourceColumn = srcColumn; this.SourceVersion = srcVersion; this.Value = value; } [EditorBrowsableAttribute(EditorBrowsableState.Advanced)] // MDAC 69508 public OdbcParameter(string parameterName, OdbcType odbcType, int size, ParameterDirection parameterDirection, Byte precision, Byte scale, string sourceColumn, DataRowVersion sourceVersion, bool sourceColumnNullMapping, object value) : this() { // V2.0 everything - round trip all browsable properties + precision/scale this.ParameterName = parameterName; this.OdbcType = odbcType; this.Size = size; this.Direction = parameterDirection; this.PrecisionInternal = precision; this.ScaleInternal = scale; this.SourceColumn = sourceColumn; this.SourceVersion = sourceVersion; this.SourceColumnNullMapping = sourceColumnNullMapping; this.Value = value; } override public System.Data.DbType DbType { get { if (_userSpecifiedType) { return _typemap._dbType; } return TypeMap._NVarChar._dbType; // default type } set { if ((null == _typemap) || (_typemap._dbType != value)) { PropertyTypeChanging(); _typemap = TypeMap.FromDbType(value); _userSpecifiedType = true; } } } public override void ResetDbType() { ResetOdbcType(); } [ DefaultValue(OdbcType.NChar), RefreshProperties(RefreshProperties.All), ResCategoryAttribute(Res.DataCategory_Data), ResDescriptionAttribute(Res.OdbcParameter_OdbcType), System.Data.Common.DbProviderSpecificTypePropertyAttribute(true), ] public OdbcType OdbcType { get { if (_userSpecifiedType) { return _typemap._odbcType; } return TypeMap._NVarChar._odbcType; // default type } set { if ((null == _typemap) || (_typemap._odbcType != value)) { PropertyTypeChanging(); _typemap = TypeMap.FromOdbcType(value); _userSpecifiedType = true; } } } public void ResetOdbcType() { PropertyTypeChanging(); _typemap = null; _userSpecifiedType = false; } internal bool HasChanged { set { _hasChanged = value; } } internal bool UserSpecifiedType { get { return _userSpecifiedType; } } [ ResCategoryAttribute(Res.DataCategory_Data), ResDescriptionAttribute(Res.DbParameter_ParameterName), ] override public string ParameterName { // V1.2.3300, XXXParameter V1.0.3300 get { string parameterName = _parameterName; return ((null != parameterName) ? parameterName : ADP.StrEmpty); } set { if (_parameterName != value) { PropertyChanging(); _parameterName = value; } } } [DefaultValue((Byte)0)] // MDAC 65862 [ResCategoryAttribute(Res.DataCategory_Data)] [ResDescriptionAttribute(Res.DbDataParameter_Precision)] public new Byte Precision { get { return PrecisionInternal; } set { PrecisionInternal = value; } } internal byte PrecisionInternal { get { byte precision = _precision; if (0 == precision) { precision = ValuePrecision(Value); } return precision; } set { if (_precision != value) { PropertyChanging(); _precision = value; } } } private bool ShouldSerializePrecision() { return (0 != _precision); } [DefaultValue((Byte)0)] // MDAC 65862 [ResCategoryAttribute(Res.DataCategory_Data)] [ResDescriptionAttribute(Res.DbDataParameter_Scale)] public new Byte Scale { get { return ScaleInternal; } set { ScaleInternal = value; } } internal byte ScaleInternal { get { byte scale = _scale; if (!ShouldSerializeScale(scale)) { // WebData 94688 scale = ValueScale(Value); } return scale; } set { if (_scale != value || !_hasScale) { PropertyChanging(); _scale = value; _hasScale = true; } } } private bool ShouldSerializeScale() { return ShouldSerializeScale(_scale); } private bool ShouldSerializeScale(byte scale) { return _hasScale && ((0 != scale) || ShouldSerializePrecision()); } // returns the count of bytes for the data (ColumnSize argument to SqlBindParameter) private int GetColumnSize(object value, int offset, int ordinal) { if ((ODBC32.SQL_C.NUMERIC == _bindtype._sql_c) && (0 != _internalPrecision)) { return Math.Min((int)_internalPrecision, ADP.DecimalMaxPrecision); } int cch = _bindtype._columnSize; if (0 >= cch) { if (ODBC32.SQL_C.NUMERIC == _typemap._sql_c) { cch = 62; // (DecimalMaxPrecision+sign+terminator)*BytesPerUnicodeCharacter } else { cch = _internalSize; if (!_internalShouldSerializeSize || 0x3fffffff <= cch || cch < 0) { Debug.Assert((ODBC32.SQL_C.WCHAR == _bindtype._sql_c) || (ODBC32.SQL_C.BINARY == _bindtype._sql_c), "not wchar or binary"); if (!_internalShouldSerializeSize && (0 != (ParameterDirection.Output & _internalDirection))) { throw ADP.UninitializedParameterSize(ordinal, _bindtype._type); } if ((null == value) || Convert.IsDBNull(value)) { cch = 0; } else if (value is String) { cch = ((String)value).Length - offset; if ((0 != (ParameterDirection.Output & _internalDirection)) && (0x3fffffff <= _internalSize)) { // restrict output parameters when user set Size to Int32.MaxValue // to the greater of intput size or 8K cch = Math.Max(cch, 4 * 1024); // MDAC 69224 } // the following code causes failure against SQL 6.5 // ERROR [HY104] [Microsoft][ODBC SQL Server Driver]Invalid precision value // // the code causes failure if it is NOT there (remark added by [....]) // it causes failure with jet if it is there // // MDAC 76227: Code is required for japanese client/server tests. // If this causes regressions with Jet please doc here including bug#. ([....]) // if ((ODBC32.SQL_TYPE.CHAR == _bindtype._sql_type) || (ODBC32.SQL_TYPE.VARCHAR == _bindtype._sql_type) || (ODBC32.SQL_TYPE.LONGVARCHAR == _bindtype._sql_type)) { cch = System.Text.Encoding.Default.GetMaxByteCount(cch); } } else if (value is char[]) { cch = ((char[])value).Length - offset; if ((0 != (ParameterDirection.Output & _internalDirection)) && (0x3fffffff <= _internalSize)) { cch = Math.Max(cch, 4 * 1024); // MDAC 69224 } if ((ODBC32.SQL_TYPE.CHAR == _bindtype._sql_type) || (ODBC32.SQL_TYPE.VARCHAR == _bindtype._sql_type) || (ODBC32.SQL_TYPE.LONGVARCHAR == _bindtype._sql_type)) { cch = System.Text.Encoding.Default.GetMaxByteCount(cch); } } else if (value is byte[]) { cch = ((byte[])value).Length - offset; if ((0 != (ParameterDirection.Output & _internalDirection)) && (0x3fffffff <= _internalSize)) { // restrict output parameters when user set Size to Int32.MaxValue // to the greater of intput size or 8K cch = Math.Max(cch, 8 * 1024); // MDAC 69224 } } #if DEBUG else { Debug.Assert(false, "not expecting this"); } #endif // Note: ColumnSize should never be 0, // this represents the size of the column on the backend. // // without the following code causes failure //ERROR [HY104] [Microsoft][ODBC Microsoft Access Driver]Invalid precision value cch = Math.Max(2, cch); } } } Debug.Assert((0 <= cch) && (cch < 0x3fffffff), String.Format((IFormatProvider)null, "GetColumnSize: cch = {0} out of range, _internalShouldSerializeSize = {1}, _internalSize = {2}", cch, _internalShouldSerializeSize, _internalSize)); return cch; } // Return the count of bytes for the data (size in bytes for the native buffer) // private int GetValueSize(object value, int offset) { if ((ODBC32.SQL_C.NUMERIC == _bindtype._sql_c) && (0 != _internalPrecision)) { return Math.Min((int)_internalPrecision, ADP.DecimalMaxPrecision); } int cch = _bindtype._columnSize; if (0 >= cch) { bool twobytesperunit = false; if (value is String) { cch = ((string)value).Length - offset; twobytesperunit = true; } else if (value is char[]) { cch = ((char[])value).Length - offset; twobytesperunit = true; } else if (value is byte[]) { cch = ((byte[])value).Length - offset; } else { cch = 0; } if (_internalShouldSerializeSize && (_internalSize >= 0) && (_internalSize < cch) && (_bindtype == _originalbindtype)) { cch = _internalSize; } if (twobytesperunit) { cch *= 2; } } Debug.Assert((0 <= cch) && (cch < 0x3fffffff), String.Format((IFormatProvider)null, "GetValueSize: cch = {0} out of range, _internalShouldSerializeSize = {1}, _internalSize = {2}", cch, _internalShouldSerializeSize, _internalSize)); return cch; } // return the count of bytes for the data, used for SQLBindParameter // private int GetParameterSize(object value, int offset, int ordinal) { int ccb = _bindtype._bufferSize; if (0 >= ccb) { if (ODBC32.SQL_C.NUMERIC == _typemap._sql_c) { ccb = 518; // _bindtype would be VarChar ([0-9]?{255} + '-' + '.') * 2 } else { ccb = _internalSize; if (!_internalShouldSerializeSize || (0x3fffffff <= ccb) || (ccb < 0)) { Debug.Assert((ODBC32.SQL_C.WCHAR == _bindtype._sql_c) || (ODBC32.SQL_C.BINARY == _bindtype._sql_c), "not wchar or binary"); if ((ccb <= 0) && (0 != (ParameterDirection.Output & _internalDirection))) { throw ADP.UninitializedParameterSize(ordinal, _bindtype._type); } if ((null == value) || Convert.IsDBNull(value)) { if (_bindtype._sql_c == ODBC32.SQL_C.WCHAR) { ccb = 2; // allow for null termination } else { ccb = 0; } } else if (value is String) { ccb = (((String)value).Length - offset) * 2 + 2; } else if (value is char[]) { ccb = (((char[])value).Length - offset) * 2 + 2; } else if (value is byte[]) { ccb = ((byte[])value).Length - offset; } #if DEBUG else { Debug.Assert(false, "not expecting this"); } #endif if ((0 != (ParameterDirection.Output & _internalDirection)) && (0x3fffffff <= _internalSize)) { // restrict output parameters when user set Size to Int32.MaxValue // to the greater of intput size or 8K ccb = Math.Max(ccb, 8 * 1024); // MDAC 69224 } } else if (ODBC32.SQL_C.WCHAR == _bindtype._sql_c) { if ((value is String) && (ccb < ((String)value).Length) && (_bindtype == _originalbindtype)) { // silently truncate ... MDAC 84408 ... do not truncate upgraded values ... MDAC 84706 ccb = ((String)value).Length; } ccb = (ccb * 2) + 2; // allow for null termination } else if ((value is byte[]) && (ccb < ((byte[])value).Length) && (_bindtype == _originalbindtype)) { // silently truncate ... MDAC 84408 ... do not truncate upgraded values ... MDAC 84706 ccb = ((byte[])value).Length; } } } Debug.Assert((0 <= ccb) && (ccb < 0x3fffffff), "GetParameterSize: out of range " + ccb); return ccb; } private byte GetParameterPrecision(object value) { if (0 != _internalPrecision && value is decimal) { // from qfe 762 if (_internalPrecision < 29) { // from SqlClient ... if (_internalPrecision != 0) { // devnote: If the userspecified precision (_internalPrecision) is less than the actual values precision // we silently adjust the userspecified precision to the values precision. byte precision = ((SqlDecimal)(decimal)value).Precision; _internalPrecision = Math.Max(_internalPrecision, precision); // silently adjust the precision } return _internalPrecision; } return ADP.DecimalMaxPrecision; } if ((null == value) || (value is Decimal) || Convert.IsDBNull(value)) { // MDAC 60882 return ADP.DecimalMaxPrecision28; } return 0; } private byte GetParameterScale(object value) { // For any value that is not decimal simply return the Scale // if (!(value is decimal)) { return _internalScale; } // Determin the values scale // If the user specified a lower scale we return the user specified scale, // otherwise the values scale // byte s = (byte)((Decimal.GetBits((Decimal)value)[3] & 0x00ff0000) >> 0x10); if ((_internalScale > 0) && (_internalScale < s)) { return _internalScale; } return s; } //This is required for OdbcCommand.Clone to deep copy the parameters collection object ICloneable.Clone() { return new OdbcParameter(this); } private void CopyParameterInternal() { _internalValue = Value; // we should coerce the parameter value at this time. _internalPrecision = ShouldSerializePrecision() ? PrecisionInternal : ValuePrecision(_internalValue); _internalShouldSerializeSize = ShouldSerializeSize(); _internalSize = _internalShouldSerializeSize ? Size : ValueSize(_internalValue); _internalDirection = Direction; _internalScale = ShouldSerializeScale() ? ScaleInternal : ValueScale(_internalValue); _internalOffset = Offset; _internalUserSpecifiedType = UserSpecifiedType; } private void CloneHelper(OdbcParameter destination) { CloneHelperCore(destination); destination._userSpecifiedType = _userSpecifiedType; destination._typemap = _typemap; destination._parameterName = _parameterName; destination._precision = _precision; destination._scale = _scale; destination._hasScale = _hasScale; } internal void ClearBinding() { if (!_userSpecifiedType) { _typemap = null; } _bindtype = null; } internal void PrepareForBind(OdbcCommand command, short ordinal, ref int parameterBufferSize) { // make a snapshot of the current properties. Properties may change while we work on them // CopyParameterInternal(); object value = ProcessAndGetParameterValue(); int offset = _internalOffset; int size = _internalSize; ODBC32.SQL_C sql_c_type; // offset validation based on the values type // if (offset > 0) { if (value is string) { if (offset > ((string)value).Length) { throw ADP.OffsetOutOfRangeException(); } } else if (value is char[]) { if (offset > ((char[])value).Length) { throw ADP.OffsetOutOfRangeException(); } } else if (value is byte[]) { if (offset > ((byte[])value).Length) { throw ADP.OffsetOutOfRangeException(); } } else { // for all other types offset has no meaning // this is important since we might upgrade some types to strings offset = 0; } } // type support verification for certain data types // switch (_bindtype._sql_type) { case ODBC32.SQL_TYPE.DECIMAL: case ODBC32.SQL_TYPE.NUMERIC: if ( !command.Connection.IsV3Driver // for non V3 driver we always do the conversion || !command.Connection.TestTypeSupport(ODBC32.SQL_TYPE.NUMERIC) // otherwise we convert if the driver does not support numeric || command.Connection.TestRestrictedSqlBindType(_bindtype._sql_type)// or the type is not supported ) { // No support for NUMERIC // Change the type _bindtype = TypeMap._VarChar; if ((null != value) && !Convert.IsDBNull(value)) { value = ((Decimal)value).ToString(CultureInfo.CurrentCulture); size = ((string)value).Length; offset = 0; } } break; case ODBC32.SQL_TYPE.BIGINT: if (!command.Connection.IsV3Driver) { // No support for BIGINT // Change the type _bindtype = TypeMap._VarChar; if ((null != value) && !Convert.IsDBNull(value)) { value = ((Int64)value).ToString(CultureInfo.CurrentCulture); size = ((string)value).Length; offset = 0; } } break; case ODBC32.SQL_TYPE.WCHAR: // MDAC 68993 case ODBC32.SQL_TYPE.WVARCHAR: case ODBC32.SQL_TYPE.WLONGVARCHAR: if (value is Char) { value = value.ToString(); size = ((string)value).Length; offset = 0; } if (!command.Connection.TestTypeSupport(_bindtype._sql_type)) { // No support for WCHAR, WVARCHAR or WLONGVARCHAR // Change the type if (ODBC32.SQL_TYPE.WCHAR == _bindtype._sql_type) { _bindtype = TypeMap._Char; } else if (ODBC32.SQL_TYPE.WVARCHAR == _bindtype._sql_type) { _bindtype = TypeMap._VarChar; } else if (ODBC32.SQL_TYPE.WLONGVARCHAR == _bindtype._sql_type) { _bindtype = TypeMap._Text; } } break; } // end switch // Conversation from WCHAR to CHAR, VARCHAR or LONVARCHAR (AnsiString) is different for some providers // we need to chonvert WCHAR to CHAR and bind as sql_c_type = CHAR // sql_c_type = _bindtype._sql_c; if (!command.Connection.IsV3Driver) { if (sql_c_type == ODBC32.SQL_C.WCHAR) { sql_c_type = ODBC32.SQL_C.CHAR; if (null != value) { if (!Convert.IsDBNull(value) && value is string) { int lcid = System.Globalization.CultureInfo.CurrentCulture.LCID; CultureInfo culInfo = new CultureInfo(lcid); Encoding cpe = System.Text.Encoding.GetEncoding(culInfo.TextInfo.ANSICodePage); value = cpe.GetBytes(value.ToString()); size = ((byte[])value).Length; } } } }; int cbParameterSize = GetParameterSize(value, offset, ordinal); // count of bytes for the data, for SQLBindParameter // here we upgrade the datatypes if the given values size is bigger than the types columnsize // switch (_bindtype._sql_type) { case ODBC32.SQL_TYPE.VARBINARY: // MDAC 74372 // Note: per definition DbType.Binary does not support more than 8000 bytes so we change the type for binding if ((cbParameterSize > 8000)) { _bindtype = TypeMap._Image; } // will change to LONGVARBINARY break; case ODBC32.SQL_TYPE.VARCHAR: // MDAC 74372 // Note: per definition DbType.Binary does not support more than 8000 bytes so we change the type for binding if ((cbParameterSize > 8000)) { _bindtype = TypeMap._Text; } // will change to LONGVARCHAR break; case ODBC32.SQL_TYPE.WVARCHAR: // MDAC 75099 // Note: per definition DbType.Binary does not support more than 8000 bytes so we change the type for binding if ((cbParameterSize > 4000)) { _bindtype = TypeMap._NText; } // will change to WLONGVARCHAR break; } _prepared_Sql_C_Type = sql_c_type; _preparedOffset = offset; _preparedSize = size; _preparedValue = value; _preparedBufferSize = cbParameterSize; _preparedIntOffset = parameterBufferSize; _preparedValueOffset = _preparedIntOffset + IntPtr.Size; parameterBufferSize += (cbParameterSize + IntPtr.Size); } internal void Bind(OdbcStatementHandle hstmt, OdbcCommand command, short ordinal, CNativeBuffer parameterBuffer, bool allowReentrance) { ODBC32.RetCode retcode; ODBC32.SQL_C sql_c_type = _prepared_Sql_C_Type; ODBC32.SQL_PARAM sqldirection = SqlDirectionFromParameterDirection(); int offset = _preparedOffset; int size = _preparedSize; object value = _preparedValue; int cbValueSize = GetValueSize(value, offset); // count of bytes for the data int cchSize = GetColumnSize(value, offset, ordinal); // count of bytes for the data, used to allocate the buffer length byte precision = GetParameterPrecision(value); byte scale = GetParameterScale(value); int cbActual; HandleRef valueBuffer = parameterBuffer.PtrOffset(_preparedValueOffset, _preparedBufferSize); HandleRef intBuffer = parameterBuffer.PtrOffset(_preparedIntOffset, IntPtr.Size); // for the numeric datatype we need to do some special case handling ... // if (ODBC32.SQL_C.NUMERIC == sql_c_type) { // for input/output parameters we need to adjust the scale of the input value since the convert function in // sqlsrv32 takes this scale for the output parameter (possible bug in sqlsrv32?) // if ((ODBC32.SQL_PARAM.INPUT_OUTPUT == sqldirection) && (value is Decimal)) { if (scale < _internalScale) { while (scale < _internalScale) { value = ((decimal)value) * 10; scale++; } } } SetInputValue(value, sql_c_type, cbValueSize, precision, 0, parameterBuffer); // for output parameters we need to write precision and scale to the buffer since the convert function in // sqlsrv32 expects these values there (possible bug in sqlsrv32?) // if (ODBC32.SQL_PARAM.INPUT != sqldirection) { parameterBuffer.WriteInt16(_preparedValueOffset, (short)(((ushort)scale << 8) | (ushort)precision)); } } else { SetInputValue(value, sql_c_type, cbValueSize, size, offset, parameterBuffer); } // Try to reuse existing bindings if // the binding is valid (means we already went through binding all parameters) // the parametercollection is bound already // the bindtype ParameterType did not change (forced upgrade) if (!_hasChanged && (_boundSqlCType == sql_c_type) && (_boundParameterType == _bindtype._sql_type) && (_boundSize == cchSize) && (_boundScale == scale) && (_boundBuffer == valueBuffer.Handle) && (_boundIntbuffer == intBuffer.Handle) ) { return; } //SQLBindParameter retcode = hstmt.BindParameter( ordinal, // Parameter Number (short)sqldirection, // InputOutputType sql_c_type, // ValueType _bindtype._sql_type, // ParameterType (IntPtr)cchSize, // ColumnSize (IntPtr)scale, // DecimalDigits valueBuffer, // ParameterValuePtr (IntPtr)_preparedBufferSize, intBuffer); // StrLen_or_IndPtr if (ODBC32.RetCode.SUCCESS != retcode) { if ("07006" == command.GetDiagSqlState()) { Bid.Trace("<odbc.OdbcParameter.Bind|ERR> Call to BindParameter returned errorcode [07006]\n"); command.Connection.FlagRestrictedSqlBindType(_bindtype._sql_type); if (allowReentrance) { this.Bind(hstmt, command, ordinal, parameterBuffer, false); return; } } command.Connection.HandleError(hstmt, retcode); } _hasChanged = false; _boundSqlCType = sql_c_type; _boundParameterType = _bindtype._sql_type; _boundSize = cchSize; _boundScale = scale; _boundBuffer = valueBuffer.Handle; _boundIntbuffer = intBuffer.Handle; if (ODBC32.SQL_C.NUMERIC == sql_c_type) { OdbcDescriptorHandle hdesc = command.GetDescriptorHandle(ODBC32.SQL_ATTR.APP_PARAM_DESC); // descriptor handle is cached on command wrapper, don't release it // Set descriptor Type // //SQLSetDescField(hdesc, i+1, SQL_DESC_TYPE, (void *)SQL_C_NUMERIC, 0); retcode = hdesc.SetDescriptionField1(ordinal, ODBC32.SQL_DESC.TYPE, (IntPtr)ODBC32.SQL_C.NUMERIC); if (ODBC32.RetCode.SUCCESS != retcode) { command.Connection.HandleError(hstmt, retcode); } // Set precision // cbActual = (int)precision; //SQLSetDescField(hdesc, i+1, SQL_DESC_PRECISION, (void *)precision, 0); retcode = hdesc.SetDescriptionField1(ordinal, ODBC32.SQL_DESC.PRECISION, (IntPtr)cbActual); if (ODBC32.RetCode.SUCCESS != retcode) { command.Connection.HandleError(hstmt, retcode); } // Set scale // // SQLSetDescField(hdesc, i+1, SQL_DESC_SCALE, (void *)llen, 0); cbActual = (int)scale; retcode = hdesc.SetDescriptionField1(ordinal, ODBC32.SQL_DESC.SCALE, (IntPtr)cbActual); if (ODBC32.RetCode.SUCCESS != retcode) { command.Connection.HandleError(hstmt, retcode); } // Set data pointer // // SQLSetDescField(hdesc, i+1, SQL_DESC_DATA_PTR, (void *)&numeric, 0); retcode = hdesc.SetDescriptionField2(ordinal, ODBC32.SQL_DESC.DATA_PTR, valueBuffer); if (ODBC32.RetCode.SUCCESS != retcode) { command.Connection.HandleError(hstmt, retcode); } } } internal void GetOutputValue(CNativeBuffer parameterBuffer) { //Handle any output params // No value is available if the user fiddles with the parameters properties // if (_hasChanged) return; if ((null != _bindtype) && (_internalDirection != ParameterDirection.Input)) { TypeMap typemap = _bindtype; _bindtype = null; int cbActual = (int)parameterBuffer.ReadIntPtr(_preparedIntOffset); if (ODBC32.SQL_NULL_DATA == cbActual) { Value = DBNull.Value; } else if ((0 <= cbActual) || (cbActual == ODBC32.SQL_NTS)) { // safeguard Value = parameterBuffer.MarshalToManaged(_preparedValueOffset, _boundSqlCType, cbActual); if (_boundSqlCType == ODBC32.SQL_C.CHAR) { if ((null != Value) && !Convert.IsDBNull(Value)) { int lcid = System.Globalization.CultureInfo.CurrentCulture.LCID; CultureInfo culInfo = new CultureInfo(lcid); Encoding cpe = System.Text.Encoding.GetEncoding(culInfo.TextInfo.ANSICodePage); Value = cpe.GetString((Byte[])Value); } } if ((typemap != _typemap) && (null != Value) && !Convert.IsDBNull(Value) && (Value.GetType() != _typemap._type)) { Debug.Assert(ODBC32.SQL_C.NUMERIC == _typemap._sql_c, "unexpected"); Value = Decimal.Parse((string)Value, System.Globalization.CultureInfo.CurrentCulture); } } } } private object ProcessAndGetParameterValue() { object value = _internalValue; if (_internalUserSpecifiedType) { if ((null != value) && !Convert.IsDBNull(value)) { Type valueType = value.GetType(); if (!valueType.IsArray) { if (valueType != _typemap._type) { try { value = Convert.ChangeType(value, _typemap._type, (System.IFormatProvider)null); } catch (Exception e) { // Don't know which exception to expect from ChangeType so we filter out the serious ones // if (!ADP.IsCatchableExceptionType(e)) { throw; } throw ADP.ParameterConversionFailed(value, _typemap._type, e); // WebData 75433 } } } else if (valueType == typeof(char[])) { value = new String((char[])value); } } } else if (null == _typemap) { if ((null == value) || Convert.IsDBNull(value)) { _typemap = TypeMap._NVarChar; // default type } else { Type type = value.GetType(); _typemap = TypeMap.FromSystemType(type); } } Debug.Assert(null != _typemap, "GetParameterValue: null _typemap"); _originalbindtype = _bindtype = _typemap; return value; } private void PropertyChanging() { _hasChanged = true; } private void PropertyTypeChanging() { PropertyChanging(); //CoercedValue = null; } internal void SetInputValue(object value, ODBC32.SQL_C sql_c_type, int cbsize, int sizeorprecision, int offset, CNativeBuffer parameterBuffer) { //Handle any input params if ((ParameterDirection.Input == _internalDirection) || (ParameterDirection.InputOutput == _internalDirection)) { //Note: (lang) "null" means to use the servers default (not DBNull). //We probably should just not have bound this parameter, period, but that //would mess up the users question marks, etc... if ((null == value)) { parameterBuffer.WriteIntPtr(_preparedIntOffset, (IntPtr)ODBC32.SQL_DEFAULT_PARAM); } else if (Convert.IsDBNull(value)) { parameterBuffer.WriteIntPtr(_preparedIntOffset, (IntPtr)ODBC32.SQL_NULL_DATA); } else { switch (sql_c_type) { case ODBC32.SQL_C.CHAR: case ODBC32.SQL_C.WCHAR: case ODBC32.SQL_C.BINARY: //StrLen_or_IndPtr is ignored except for Character or Binary or data. parameterBuffer.WriteIntPtr(_preparedIntOffset, (IntPtr)cbsize); break; default: parameterBuffer.WriteIntPtr(_preparedIntOffset, IntPtr.Zero); break; } //Place the input param value into the native buffer parameterBuffer.MarshalToNative(_preparedValueOffset, value, sql_c_type, sizeorprecision, offset); } } else { // always set ouput only and return value parameter values to null when executing _internalValue = null; //Always initialize the intbuffer (for output params). Since we need to know //if/when the parameters are available for output. (ie: when is the buffer valid...) //if (_sqldirection != ODBC32.SQL_PARAM.INPUT) parameterBuffer.WriteIntPtr(_preparedIntOffset, (IntPtr)ODBC32.SQL_NULL_DATA); } } private ODBC32.SQL_PARAM SqlDirectionFromParameterDirection() { switch (_internalDirection) { case ParameterDirection.Input: return ODBC32.SQL_PARAM.INPUT; case ParameterDirection.Output: case ParameterDirection.ReturnValue: //ODBC doesn't seem to distinguish between output and return value //as SQL_PARAM_RETURN_VALUE fails with "Invalid parameter type" return ODBC32.SQL_PARAM.OUTPUT; case ParameterDirection.InputOutput: return ODBC32.SQL_PARAM.INPUT_OUTPUT; default: Debug.Assert(false, "Unexpected Direction Property on Parameter"); return ODBC32.SQL_PARAM.INPUT; } } [ RefreshProperties(RefreshProperties.All), ResCategoryAttribute(Res.DataCategory_Data), ResDescriptionAttribute(Res.DbParameter_Value), TypeConverterAttribute(typeof(StringConverter)), ] override public object Value { // V1.2.3300, XXXParameter V1.0.3300 get { return _value; } set { _coercedValue = null; _value = value; } } private byte ValuePrecision(object value) { return ValuePrecisionCore(value); } private byte ValueScale(object value) { return ValueScaleCore(value); } private int ValueSize(object value) { return ValueSizeCore(value); } // implemented as nested class to take advantage of the private/protected ShouldSerializeXXX methods internal sealed class OdbcParameterConverter : ExpandableObjectConverter { // converter classes should have public ctor public OdbcParameterConverter() { } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(System.ComponentModel.Design.Serialization.InstanceDescriptor)) { return true; } return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == null) { throw ADP.ArgumentNull("destinationType"); } if (destinationType == typeof(System.ComponentModel.Design.Serialization.InstanceDescriptor) && value is OdbcParameter) { OdbcParameter p = (OdbcParameter)value; // MDAC 67321 - reducing parameter generated code int flags = 0; // if part of the collection - the parametername can't be empty if (OdbcType.NChar != p.OdbcType) { flags |= 1; } if (p.ShouldSerializeSize()) { flags |= 2; } if (!ADP.IsEmpty(p.SourceColumn)) { flags |= 4; } if (null != p.Value) { flags |= 8; } if ((ParameterDirection.Input != p.Direction) || p.IsNullable || p.ShouldSerializePrecision() || p.ShouldSerializeScale() || (DataRowVersion.Current != p.SourceVersion)) { flags |= 16; // V1.0 everything } if (p.SourceColumnNullMapping) { flags |= 32; // v2.0 everything } Type[] ctorParams; object[] ctorValues; switch (flags) { case 0: // ParameterName case 1: // SqlDbType ctorParams = new Type[] { typeof(string), typeof(OdbcType) }; ctorValues = new object[] { p.ParameterName, p.OdbcType }; break; case 2: // Size case 3: // Size, SqlDbType ctorParams = new Type[] { typeof(string), typeof(OdbcType), typeof(int) }; ctorValues = new object[] { p.ParameterName, p.OdbcType, p.Size }; break; case 4: // SourceColumn case 5: // SourceColumn, SqlDbType case 6: // SourceColumn, Size case 7: // SourceColumn, Size, SqlDbType ctorParams = new Type[] { typeof(string), typeof(OdbcType), typeof(int), typeof(string) }; ctorValues = new object[] { p.ParameterName, p.OdbcType, p.Size, p.SourceColumn }; break; case 8: // Value ctorParams = new Type[] { typeof(string), typeof(object) }; ctorValues = new object[] { p.ParameterName, p.Value }; break; default: if (0 == (32 & flags)) { // V1.0 everything ctorParams = new Type[] { typeof(string), typeof(OdbcType), typeof(int), typeof(ParameterDirection), typeof(bool), typeof(byte), typeof(byte), typeof(string), typeof(DataRowVersion), typeof(object) }; ctorValues = new object[] { p.ParameterName, p.OdbcType, p.Size, p.Direction, p.IsNullable, p.PrecisionInternal, p.ScaleInternal, p.SourceColumn, p.SourceVersion, p.Value }; } else { // v2.0 everything - round trip all browsable properties + precision/scale ctorParams = new Type[] { typeof(string), typeof(OdbcType), typeof(int), typeof(ParameterDirection), typeof(byte), typeof(byte), typeof(string), typeof(DataRowVersion), typeof(bool), typeof(object) }; ctorValues = new object[] { p.ParameterName, p.OdbcType, p.Size, p.Direction, p.PrecisionInternal, p.ScaleInternal, p.SourceColumn, p.SourceVersion, p.SourceColumnNullMapping, p.Value }; } break; } System.Reflection.ConstructorInfo ctor = typeof(OdbcParameter).GetConstructor(ctorParams); if (null != ctor) { return new System.ComponentModel.Design.Serialization.InstanceDescriptor(ctor, ctorValues); } } return base.ConvertTo(context, culture, value, destinationType); } } } }
/* * SystemPens.cs - Implementation of the * "System.Drawing.SystemPens" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Drawing { public sealed class SystemPens { // Internal state. private static Pen[] systemPens; // Cannot instantiate this class. private SystemPens() {} // Get a pen for a system color. public static Pen FromSystemColor(Color c) { if(c.IsSystemColor) { return GetOrCreatePen(c.ToKnownColor()); } else { throw new ArgumentException(S._("Arg_NotSystemColor")); } } // Get or create a system pen. private static Pen GetOrCreatePen(KnownColor color) { lock(typeof(SystemPens)) { if(systemPens == null) { systemPens = new Pen [((int)(KnownColor.WindowText)) - ((int)(KnownColor.ActiveBorder)) + 1]; } int index = ((int)color) - ((int)(KnownColor.ActiveBorder)); if(systemPens[index] == null) { systemPens[index] = new Pen(new Color(color)); } return systemPens[index]; } } // Standard system brush objects. public static Pen ActiveBorder { get { return GetOrCreatePen(KnownColor.ActiveBorder); } } public static Pen ActiveCaption { get { return GetOrCreatePen(KnownColor.ActiveCaption); } } public static Pen ActiveCaptionText { get { return GetOrCreatePen(KnownColor.ActiveCaptionText); } } public static Pen AppWorkspace { get { return GetOrCreatePen(KnownColor.AppWorkspace); } } public static Pen Control { get { return GetOrCreatePen(KnownColor.Control); } } public static Pen ControlDark { get { return GetOrCreatePen(KnownColor.ControlDark); } } public static Pen ControlDarkDark { get { return GetOrCreatePen(KnownColor.ControlDarkDark); } } public static Pen ControlLight { get { return GetOrCreatePen(KnownColor.ControlLight); } } public static Pen ControlLightLight { get { return GetOrCreatePen(KnownColor.ControlLightLight); } } public static Pen ControlText { get { return GetOrCreatePen(KnownColor.ControlText); } } public static Pen Desktop { get { return GetOrCreatePen(KnownColor.Desktop); } } public static Pen GrayText { get { return GetOrCreatePen(KnownColor.GrayText); } } public static Pen Highlight { get { return GetOrCreatePen(KnownColor.Highlight); } } public static Pen HighlightText { get { return GetOrCreatePen(KnownColor.HighlightText); } } public static Pen HotTrack { get { return GetOrCreatePen(KnownColor.HotTrack); } } public static Pen InactiveBorder { get { return GetOrCreatePen(KnownColor.InactiveBorder); } } public static Pen InactiveCaption { get { return GetOrCreatePen(KnownColor.InactiveCaption); } } public static Pen InactiveCaptionText { get { return GetOrCreatePen(KnownColor.InactiveCaptionText); } } public static Pen Info { get { return GetOrCreatePen(KnownColor.Info); } } public static Pen InfoText { get { return GetOrCreatePen(KnownColor.InfoText); } } public static Pen Menu { get { return GetOrCreatePen(KnownColor.Menu); } } public static Pen MenuText { get { return GetOrCreatePen(KnownColor.MenuText); } } public static Pen ScrollBar { get { return GetOrCreatePen(KnownColor.ScrollBar); } } public static Pen Window { get { return GetOrCreatePen(KnownColor.Window); } } public static Pen WindowFrame { get { return GetOrCreatePen(KnownColor.WindowFrame); } } public static Pen WindowText { get { return GetOrCreatePen(KnownColor.WindowText); } } }; // class SystemPens }; // namespace System.Drawing
// 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 Xunit; namespace System.Tests { public partial class VersionTests { [Theory] [MemberData(nameof(Parse_Valid_TestData))] public static void Ctor_String(string input, Version expected) { Assert.Equal(expected, new Version(input)); } [Theory] [MemberData(nameof(Parse_Invalid_TestData))] public static void Ctor_String_Invalid(string input, Type exceptionType) { Assert.Throws(exceptionType, () => new Version(input)); // Input is invalid } [Theory] [InlineData(0, 0)] [InlineData(2, 3)] [InlineData(int.MaxValue, int.MaxValue)] public static void Ctor_Int_Int(int major, int minor) { VerifyVersion(new Version(major, minor), major, minor, -1, -1); } [Fact] public static void Ctor_Int_Int_Invalid() { Assert.Throws<ArgumentOutOfRangeException>("major", () => new Version(-1, 0)); // Major < 0 Assert.Throws<ArgumentOutOfRangeException>("minor", () => new Version(0, -1)); // Minor < 0 } [Theory] [InlineData(0, 0, 0)] [InlineData(2, 3, 4)] [InlineData(int.MaxValue, int.MaxValue, int.MaxValue)] public static void Ctor_Int_Int_Int(int major, int minor, int build) { VerifyVersion(new Version(major, minor, build), major, minor, build, -1); } [Fact] public static void Ctor_Int_Int_Int_Invalid() { Assert.Throws<ArgumentOutOfRangeException>("major", () => new Version(-1, 0, 0)); // Major < 0 Assert.Throws<ArgumentOutOfRangeException>("minor", () => new Version(0, -1, 0)); // Minor < 0 Assert.Throws<ArgumentOutOfRangeException>("build", () => new Version(0, 0, -1)); // Build < 0 } [Theory] [InlineData(0, 0, 0, 0)] [InlineData(2, 3, 4, 7)] [InlineData(2, 3, 4, 32767)] [InlineData(2, 3, 4, 32768)] [InlineData(2, 3, 4, 65535)] [InlineData(2, 3, 4, 65536)] [InlineData(2, 3, 4, 2147483647)] [InlineData(2, 3, 4, 2147450879)] [InlineData(2, 3, 4, 2147418112)] [InlineData(int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue)] public static void Ctor_Int_Int_Int_Int(int major, int minor, int build, int revision) { VerifyVersion(new Version(major, minor, build, revision), major, minor, build, revision); } [Fact] public static void Ctor_Int_Int_Int_Int_Invalid() { Assert.Throws<ArgumentOutOfRangeException>("major", () => new Version(-1, 0, 0, 0)); // Major < 0 Assert.Throws<ArgumentOutOfRangeException>("minor", () => new Version(0, -1, 0, 0)); // Minor < 0 Assert.Throws<ArgumentOutOfRangeException>("build", () => new Version(0, 0, -1, 0)); // Build < 0 Assert.Throws<ArgumentOutOfRangeException>("revision", () => new Version(0, 0, 0, -1)); // Revision < 0 } public static IEnumerable<object[]> CompareTo_TestData() { yield return new object[] { new Version(1, 2), null, 1 }; yield return new object[] { new Version(1, 2), new Version(1, 2), 0 }; yield return new object[] { new Version(1, 2), new Version(1, 3), -1 }; yield return new object[] { new Version(1, 2), new Version(1, 1), 1 }; yield return new object[] { new Version(1, 2), new Version(2, 0), -1 }; yield return new object[] { new Version(1, 2), new Version(1, 2, 1), -1 }; yield return new object[] { new Version(1, 2), new Version(1, 2, 0, 1), -1 }; yield return new object[] { new Version(1, 2), new Version(1, 0), 1 }; yield return new object[] { new Version(1, 2), new Version(1, 0, 1), 1 }; yield return new object[] { new Version(1, 2), new Version(1, 0, 0, 1), 1 }; yield return new object[] { new Version(3, 2, 1), new Version(2, 2, 1), 1 }; yield return new object[] { new Version(3, 2, 1), new Version(3, 1, 1), 1 }; yield return new object[] { new Version(3, 2, 1), new Version(3, 2, 0), 1 }; yield return new object[] { new Version(1, 2, 3, 4), new Version(1, 2, 3, 4), 0 }; yield return new object[] { new Version(1, 2, 3, 4), new Version(1, 2, 3, 5), -1 }; yield return new object[] { new Version(1, 2, 3, 4), new Version(1, 2, 3, 3), 1 }; } [Theory] [MemberData(nameof(CompareTo_TestData))] public static void CompareTo(Version version1, Version version2, int expectedSign) { Assert.Equal(expectedSign, Math.Sign(version1.CompareTo(version2))); if (version1 != null && version2 != null) { if (expectedSign >= 0) { Assert.True(version1 >= version2); Assert.False(version1 < version2); } if (expectedSign > 0) { Assert.True(version1 > version2); Assert.False(version1 <= version2); } if (expectedSign <= 0) { Assert.True(version1 <= version2); Assert.False(version1 > version2); } if (expectedSign < 0) { Assert.True(version1 < version2); Assert.False(version1 >= version2); } } IComparable comparable = version1; Assert.Equal(expectedSign, Math.Sign(comparable.CompareTo(version2))); } [Fact] public static void CompareTo_Invalid() { IComparable comparable = new Version(1, 1); Assert.Throws<ArgumentException>(null, () => comparable.CompareTo(1)); // Obj is not a version Assert.Throws<ArgumentException>(null, () => comparable.CompareTo("1.1")); // Obj is not a version Version nullVersion = null; Version testVersion = new Version(1, 2); Assert.Throws<ArgumentNullException>("v1", () => testVersion >= nullVersion); // V2 is null Assert.Throws<ArgumentNullException>("v1", () => testVersion > nullVersion); // V2 is null Assert.Throws<ArgumentNullException>("v1", () => nullVersion < testVersion); // V1 is null Assert.Throws<ArgumentNullException>("v1", () => nullVersion <= testVersion); // V1 is null } private static IEnumerable<object[]> Equals_TestData() { yield return new object[] { new Version(2, 3), new Version(2, 3), true }; yield return new object[] { new Version(2, 3), new Version(2, 4), false }; yield return new object[] { new Version(2, 3), new Version(3, 3), false }; yield return new object[] { new Version(2, 3, 4), new Version(2, 3, 4), true }; yield return new object[] { new Version(2, 3, 4), new Version(2, 3, 5), false }; yield return new object[] { new Version(2, 3, 4), new Version(2, 3), false }; yield return new object[] { new Version(2, 3, 4, 5), new Version(2, 3, 4, 5), true }; yield return new object[] { new Version(2, 3, 4, 5), new Version(2, 3, 4, 6), false }; yield return new object[] { new Version(2, 3, 4, 5), new Version(2, 3), false }; yield return new object[] { new Version(2, 3, 4, 5), new Version(2, 3, 4), false }; yield return new object[] { new Version(2, 3, 0), new Version(2, 3), false }; yield return new object[] { new Version(2, 3, 4, 0), new Version(2, 3, 4), false }; yield return new object[] { new Version(2, 3, 4, 5), new TimeSpan(), false }; yield return new object[] { new Version(2, 3, 4, 5), null, false }; } [Theory] [MemberData(nameof(Equals_TestData))] public static void Equals(Version version1, object obj, bool expected) { Version version2 = obj as Version; Assert.Equal(expected, version1.Equals(version2)); Assert.Equal(expected, version1.Equals(obj)); Assert.Equal(expected, version1 == version2); Assert.Equal(!expected, version1 != version2); if (version2 != null) { Assert.Equal(expected, version1.GetHashCode().Equals(version2.GetHashCode())); } } private static IEnumerable<object[]> Parse_Valid_TestData() { yield return new object[] { "1.2", new Version(1, 2) }; yield return new object[] { "1.2.3", new Version(1, 2, 3) }; yield return new object[] { "1.2.3.4", new Version(1, 2, 3, 4) }; yield return new object[] { "2 .3. 4. \t\r\n15 ", new Version(2, 3, 4, 15) }; yield return new object[] { " 2 .3. 4. \t\r\n15 ", new Version(2, 3, 4, 15) }; yield return new object[] { "+1.+2.+3.+4", new Version(1, 2, 3, 4) }; } [Theory] [MemberData(nameof(Parse_Valid_TestData))] public static void Parse(string input, Version expected) { Assert.Equal(expected, Version.Parse(input)); Version version; Assert.True(Version.TryParse(input, out version)); Assert.Equal(expected, version); } private static IEnumerable<object[]> Parse_Invalid_TestData() { yield return new object[] { null, typeof(ArgumentNullException) }; // Input is null yield return new object[] { "", typeof(ArgumentException) }; // Input is empty yield return new object[] { "1,2,3,4", typeof(ArgumentException) }; // Input has fewer than 4 version components yield return new object[] { "1", typeof(ArgumentException) }; // Input has fewer than 2 version components yield return new object[] { "1.2.3.4.5", typeof(ArgumentException) }; // Input has more than 4 version components yield return new object[] { "-1.2.3.4", typeof(ArgumentOutOfRangeException) }; // Input contains negative value yield return new object[] { "1.-2.3.4", typeof(ArgumentOutOfRangeException) }; // Input contains negative value yield return new object[] { "1.2.-3.4", typeof(ArgumentOutOfRangeException) }; // Input contains negative value yield return new object[] { "1.2.3.-4", typeof(ArgumentOutOfRangeException) }; // Input contains negative value yield return new object[] { "b.2.3.4", typeof(FormatException) }; // Input contains non-numeric value yield return new object[] { "1.b.3.4", typeof(FormatException) }; // Input contains non-numeric value yield return new object[] { "1.2.b.4", typeof(FormatException) }; // Input contains non-numeric value yield return new object[] { "1.2.3.b", typeof(FormatException) }; // Input contains non-numeric value yield return new object[] { "2147483648.2.3.4", typeof(OverflowException) }; // Input contains a value > int.MaxValue yield return new object[] { "1.2147483648.3.4", typeof(OverflowException) }; // Input contains a value > int.MaxValue yield return new object[] { "1.2.2147483648.4", typeof(OverflowException) }; // Input contains a value > int.MaxValue yield return new object[] { "1.2.3.2147483648", typeof(OverflowException) }; // Input contains a value > int.MaxValue // Input contains a value < 0 yield return new object[] { "-1.2.3.4", typeof(ArgumentOutOfRangeException) }; yield return new object[] { "1.-2.3.4", typeof(ArgumentOutOfRangeException) }; yield return new object[] { "1.2.-3.4", typeof(ArgumentOutOfRangeException) }; yield return new object[] { "1.2.3.-4", typeof(ArgumentOutOfRangeException) }; } [Theory] [MemberData(nameof(Parse_Invalid_TestData))] public static void Parse_Invalid(string input, Type exceptionType) { Assert.Throws(exceptionType, () => Version.Parse(input)); Version version; Assert.False(Version.TryParse(input, out version)); Assert.Null(version); } public static IEnumerable<object[]> ToString_TestData() { yield return new object[] { new Version(1, 2), new string[] { "", "1", "1.2" } }; yield return new object[] { new Version(1, 2, 3), new string[] { "", "1", "1.2", "1.2.3" } }; yield return new object[] { new Version(1, 2, 3, 4), new string[] { "", "1", "1.2", "1.2.3", "1.2.3.4" } }; } [Theory] [MemberData(nameof(ToString_TestData))] public static void ToString(Version version, string[] expected) { for (int i = 0; i < expected.Length; i++) { Assert.Equal(expected[i], version.ToString(i)); } int maxFieldCount = expected.Length - 1; Assert.Equal(expected[maxFieldCount], version.ToString()); Assert.Throws<ArgumentException>("fieldCount", () => version.ToString(-1)); // Index < 0 Assert.Throws<ArgumentException>("fieldCount", () => version.ToString(maxFieldCount + 1)); // Index > version.fieldCount } private static void VerifyVersion(Version version, int major, int minor, int build, int revision) { Assert.Equal(major, version.Major); Assert.Equal(minor, version.Minor); Assert.Equal(build, version.Build); Assert.Equal(revision, version.Revision); Assert.Equal((short)(revision >> 16), version.MajorRevision); Assert.Equal(unchecked((short)(revision & 0xFFFF)), version.MinorRevision); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //----------------------------------------------------------------------------- // // Description: // This is a sub class of the abstract class for Package. // This implementation is specific to Zip file format. // //----------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Xml; //Required for Content Type File manipulation using System.Diagnostics; using System.IO.Compression; namespace System.IO.Packaging { /// <summary> /// ZipPackage is a specific implementation for the abstract Package /// class, corresponding to the Zip file format. /// This is a part of the Packaging Layer APIs. /// </summary> public sealed class ZipPackage : Package { //------------------------------------------------------ // // Public Constructors // //------------------------------------------------------ // None //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ // None //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods #region PackagePart Methods /// <summary> /// This method is for custom implementation for the underlying file format /// Adds a new item to the zip archive corresponding to the PackagePart in the package. /// </summary> /// <param name="partUri">PartName</param> /// <param name="contentType">Content type of the part</param> /// <param name="compressionOption">Compression option for this part</param> /// <returns></returns> /// <exception cref="ArgumentNullException">If partUri parameter is null</exception> /// <exception cref="ArgumentNullException">If contentType parameter is null</exception> /// <exception cref="ArgumentException">If partUri parameter does not conform to the valid partUri syntax</exception> /// <exception cref="ArgumentOutOfRangeException">If CompressionOption enumeration [compressionOption] does not have one of the valid values</exception> protected override PackagePart CreatePartCore(Uri partUri, string contentType, CompressionOption compressionOption) { //Validating the PartUri - this method will do the argument checking required for uri. partUri = PackUriHelper.ValidatePartUri(partUri); if (contentType == null) throw new ArgumentNullException("contentType"); Package.ThrowIfCompressionOptionInvalid(compressionOption); // Convert Metro CompressionOption to Zip CompressionMethodEnum. CompressionLevel level; GetZipCompressionMethodFromOpcCompressionOption(compressionOption, out level); // Create new Zip item. // We need to remove the leading "/" character at the beginning of the part name. // The partUri object must be a ValidatedPartUri string zipItemName = ((PackUriHelper.ValidatedPartUri)partUri).PartUriString.Substring(1); ZipArchiveEntry zipArchiveEntry = _zipArchive.CreateEntry(zipItemName, level); //Store the content type of this part in the content types stream. _contentTypeHelper.AddContentType((PackUriHelper.ValidatedPartUri)partUri, new ContentType(contentType), level); return new ZipPackagePart(this, zipArchiveEntry.Archive, zipArchiveEntry, _zipStreamManager, (PackUriHelper.ValidatedPartUri)partUri, contentType, compressionOption); } /// <summary> /// This method is for custom implementation specific to the file format. /// Returns the part after reading the actual physical bits. The method /// returns a null to indicate that the part corresponding to the specified /// Uri was not found in the container. /// This method does not throw an exception if a part does not exist. /// </summary> /// <param name="partUri"></param> /// <returns></returns> protected override PackagePart GetPartCore(Uri partUri) { //Currently the design has two aspects which makes it possible to return //a null from this method - // 1. All the parts are loaded at Package.Open time and as such, this // method would not be invoked, unless the user is asking for - // i. a part that does not exist - we can safely return null // ii.a part(interleaved/non-interleaved) that was added to the // underlying package by some other means, and the user wants to // access the updated part. This is currently not possible as the // underlying zip i/o layer does not allow for FileShare.ReadWrite. // 2. Also, its not a straighforward task to determine if a new part was // added as we need to look for atomic as well as interleaved parts and // this has to be done in a case sensitive manner. So, effectively // we will have to go through the entire list of zip items to determine // if there are any updates. // If ever the design changes, then this method must be updated accordingly return null; } /// <summary> /// This method is for custom implementation specific to the file format. /// Deletes the part corresponding to the uri specified. Deleting a part that does not /// exists is not an error and so we do not throw an exception in that case. /// </summary> /// <param name="partUri"></param> /// <exception cref="ArgumentNullException">If partUri parameter is null</exception> /// <exception cref="ArgumentException">If partUri parameter does not conform to the valid partUri syntax</exception> protected override void DeletePartCore(Uri partUri) { //Validating the PartUri - this method will do the argument checking required for uri. partUri = PackUriHelper.ValidatePartUri(partUri); string partZipName = GetZipItemNameFromOpcName(PackUriHelper.GetStringForPartUri(partUri)); ZipArchiveEntry zipArchiveEntry = _zipArchive.GetEntry(partZipName); if (zipArchiveEntry != null) { // Case of an atomic part. zipArchiveEntry.Delete(); } //Delete the content type for this part if it was specified as an override _contentTypeHelper.DeleteContentType((PackUriHelper.ValidatedPartUri)partUri); } /// <summary> /// This method is for custom implementation specific to the file format. /// This is the method that knows how to get the actual parts from the underlying /// zip archive. /// </summary> /// <remarks> /// <para> /// Some or all of the parts may be interleaved. The Part object for an interleaved part encapsulates /// the Uri of the proper part name and the ZipFileInfo of the initial piece. /// This function does not go through the extra work of checking piece naming validity /// throughout the package. /// </para> /// <para> /// This means that interleaved parts without an initial piece will be silently ignored. /// Other naming anomalies get caught at the Stream level when an I/O operation involves /// an anomalous or missing piece. /// </para> /// <para> /// This function reads directly from the underlying IO layer and is supposed to be called /// just once in the lifetime of a package (at init time). /// </para> /// </remarks> /// <returns>An array of ZipPackagePart.</returns> protected override PackagePart[] GetPartsCore() { List<PackagePart> parts = new List<PackagePart>(InitialPartListSize); // The list of files has to be searched linearly (1) to identify the content type // stream, and (2) to identify parts. System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> zipArchiveEntries = _zipArchive.Entries; // We have already identified the [ContentTypes].xml pieces if any are present during // the initialization of ZipPackage object // Record parts and ignored items. foreach (ZipArchiveEntry zipArchiveEntry in zipArchiveEntries) { //Returns false if - // a. its a content type item // b. items that have either a leading or trailing slash. if (IsZipItemValidOpcPartOrPiece(zipArchiveEntry.FullName)) { Uri partUri = new Uri(GetOpcNameFromZipItemName(zipArchiveEntry.FullName), UriKind.Relative); PackUriHelper.ValidatedPartUri validatedPartUri; if (PackUriHelper.TryValidatePartUri(partUri, out validatedPartUri)) { ContentType contentType = _contentTypeHelper.GetContentType(validatedPartUri); if (contentType != null) { // In case there was some redundancy between pieces and/or the atomic // part, it will be detected at this point because the part's Uri (which // is independent of interleaving) will already be in the dictionary. parts.Add(new ZipPackagePart(this, zipArchiveEntry.Archive, zipArchiveEntry, _zipStreamManager, validatedPartUri, contentType.ToString(), GetCompressionOptionFromZipFileInfo(zipArchiveEntry))); } } //If not valid part uri we can completely ignore this zip file item. Even if later someone adds //a new part, the corresponding zip item can never map to one of these items } // If IsZipItemValidOpcPartOrPiece returns false, it implies that either the zip file Item // starts or ends with a "/" and as such we can completely ignore this zip file item. Even if later // a new part gets added, its corresponding zip item cannot map to one of these items. } return parts.ToArray(); } #endregion PackagePart Methods #region Other Methods /// <summary> /// This method is for custom implementation corresponding to the underlying zip file format. /// </summary> protected override void FlushCore() { //Save the content type file to the archive. _contentTypeHelper.SaveToFile(); } /// <summary> /// Closes the underlying ZipArchive object for this container /// </summary> /// <param name="disposing">True if called during Dispose, false if called during Finalize</param> protected override void Dispose(bool disposing) { try { if (disposing) { if (_contentTypeHelper != null) { _contentTypeHelper.SaveToFile(); } if (_zipStreamManager != null) { _zipStreamManager.Dispose(); } if (_zipArchive != null) { _zipArchive.Dispose(); } // _containerStream may be opened given a file name, in which case it should be closed here. // _containerStream may be passed into the constructor, in which case, it should not be closed here. if (_shouldCloseContainerStream) { _containerStream.Dispose(); } else { } _containerStream = null; } } finally { base.Dispose(disposing); } } #endregion Other Methods #endregion Public Methods //------------------------------------------------------ // // Public Events // //------------------------------------------------------ // None //------------------------------------------------------ // // Internal Constructors // //------------------------------------------------------ #region Internal Constructors /// <summary> /// Internal constructor that is called by the OpenOnFile static method. /// </summary> /// <param name="path">File path to the container.</param> /// <param name="packageFileMode">Container is opened in the specified mode if possible</param> /// <param name="packageFileAccess">Container is opened with the speficied access if possible</param> /// <param name="share">Container is opened with the specified share if possible</param> internal ZipPackage(string path, FileMode packageFileMode, FileAccess packageFileAccess, FileShare share) : base(packageFileAccess) { ZipArchive zipArchive = null; ContentTypeHelper contentTypeHelper = null; _packageFileMode = packageFileMode; _packageFileAccess = packageFileAccess; try { _containerStream = new FileStream(path, _packageFileMode, _packageFileAccess, share); _shouldCloseContainerStream = true; ZipArchiveMode zipArchiveMode = ZipArchiveMode.Update; if (packageFileAccess == FileAccess.Read) zipArchiveMode = ZipArchiveMode.Read; else if (packageFileAccess == FileAccess.Write) zipArchiveMode = ZipArchiveMode.Create; else if (packageFileAccess == FileAccess.ReadWrite) zipArchiveMode = ZipArchiveMode.Update; zipArchive = new ZipArchive(_containerStream, zipArchiveMode, true, Text.Encoding.UTF8); _zipStreamManager = new ZipStreamManager(zipArchive, _packageFileMode, _packageFileAccess); contentTypeHelper = new ContentTypeHelper(zipArchive, _packageFileMode, _packageFileAccess, _zipStreamManager); } catch { if (zipArchive != null) { zipArchive.Dispose(); } throw; } _zipArchive = zipArchive; _contentTypeHelper = contentTypeHelper; } /// <summary> /// Internal constructor that is called by the Open(Stream) static methods. /// </summary> /// <param name="s"></param> /// <param name="packageFileMode"></param> /// <param name="packageFileAccess"></param> internal ZipPackage(Stream s, FileMode packageFileMode, FileAccess packageFileAccess) : base(packageFileAccess) { ZipArchive zipArchive = null; ContentTypeHelper contentTypeHelper = null; _packageFileMode = packageFileMode; _packageFileAccess = packageFileAccess; try { ZipArchiveMode zipArchiveMode = ZipArchiveMode.Update; if (packageFileAccess == FileAccess.Read) zipArchiveMode = ZipArchiveMode.Read; else if (packageFileAccess == FileAccess.Write) zipArchiveMode = ZipArchiveMode.Create; else if (packageFileAccess == FileAccess.ReadWrite) zipArchiveMode = ZipArchiveMode.Update; zipArchive = new ZipArchive(s, zipArchiveMode, true, Text.Encoding.UTF8); _zipStreamManager = new ZipStreamManager(zipArchive, packageFileMode, packageFileAccess); contentTypeHelper = new ContentTypeHelper(zipArchive, packageFileMode, packageFileAccess, _zipStreamManager); } catch (InvalidDataException) { throw new FileFormatException("File contains corrupted data."); } catch { if (zipArchive != null) { zipArchive.Dispose(); } throw; } _containerStream = s; _shouldCloseContainerStream = false; _zipArchive = zipArchive; _contentTypeHelper = contentTypeHelper; } #endregion Internal Constructors //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods // More generic function than GetZipItemNameFromPartName. In particular, it will handle piece names. internal static string GetZipItemNameFromOpcName(string opcName) { Debug.Assert(opcName != null && opcName.Length > 0); return opcName.Substring(1); } // More generic function than GetPartNameFromZipItemName. In particular, it will handle piece names. internal static string GetOpcNameFromZipItemName(string zipItemName) { return String.Concat(s_forwardSlash, zipItemName); } // Convert from Metro CompressionOption to ZipFileInfo compression properties. internal static void GetZipCompressionMethodFromOpcCompressionOption( CompressionOption compressionOption, out CompressionLevel compressionLevel) { switch (compressionOption) { case CompressionOption.NotCompressed: { compressionLevel = CompressionLevel.NoCompression; } break; case CompressionOption.Normal: { compressionLevel = CompressionLevel.Optimal; } break; case CompressionOption.Maximum: { compressionLevel = CompressionLevel.Optimal; } break; case CompressionOption.Fast: { compressionLevel = CompressionLevel.Fastest; } break; case CompressionOption.SuperFast: { compressionLevel = CompressionLevel.Fastest; } break; // fall-through is not allowed default: { Debug.Assert(false, "Encountered an invalid CompressionOption enum value"); goto case CompressionOption.NotCompressed; } } } #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ internal FileMode PackageFileMode { get { return _packageFileMode; } } //------------------------------------------------------ // // Internal Events // //------------------------------------------------------ // None //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods //returns a boolean indicating if the underlying zip item is a valid metro part or piece // This mainly excludes the content type item, as well as entries with leading or trailing // slashes. private bool IsZipItemValidOpcPartOrPiece(string zipItemName) { Debug.Assert(zipItemName != null, "The parameter zipItemName should not be null"); //check if the zip item is the Content type item -case sensitive comparison // The following test will filter out an atomic content type file, with name // "[Content_Types].xml", as well as an interleaved one, with piece names such as // "[Content_Types].xml/[0].piece" or "[Content_Types].xml/[5].last.piece". if (zipItemName.StartsWith(ContentTypeHelper.ContentTypeFileName, StringComparison.OrdinalIgnoreCase)) return false; else { //Could be an empty zip folder //We decided to ignore zip items that contain a "/" as this could be a folder in a zip archive //Some of the tools support this and some dont. There is no way ensure that the zip item never have //a leading "/", although this is a requirement we impose on items created through our API //Therefore we ignore them at the packaging api level. if (zipItemName.StartsWith(s_forwardSlash, StringComparison.Ordinal)) return false; //This will ignore the folder entries found in the zip package created by some zip tool //PartNames ending with a "/" slash is also invalid so we are skipping these entries, //this will also prevent the PackUriHelper.CreatePartUri from throwing when it encounters a // partname ending with a "/" if (zipItemName.EndsWith(s_forwardSlash, StringComparison.Ordinal)) return false; else return true; } } // convert from Zip CompressionMethodEnum and DeflateOptionEnum to Metro CompressionOption static private CompressionOption GetCompressionOptionFromZipFileInfo(ZipArchiveEntry zipFileInfo) { // Note: we can't determine compression method / level from the ZipArchiveEntry. CompressionOption result = CompressionOption.Normal; return result; } #endregion Private Methods //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Members private const int InitialPartListSize = 50; private const int InitialPieceNameListSize = 50; private ZipArchive _zipArchive; private Stream _containerStream; // stream we are opened in if Open(Stream) was called private bool _shouldCloseContainerStream; private ContentTypeHelper _contentTypeHelper; // manages the content types for all the parts in the container private ZipStreamManager _zipStreamManager; // manages streams for all parts, avoiding opening streams multiple times private FileAccess _packageFileAccess; private FileMode _packageFileMode; private static readonly string s_forwardSlash = "/"; //Required for creating a part name from a zip item name //IEqualityComparer for extensions private static readonly ExtensionEqualityComparer s_extensionEqualityComparer = new ExtensionEqualityComparer(); #endregion Private Members //------------------------------------------------------ // // Private Types // //------------------------------------------------------ #region Private Class /// <summary> /// ExtensionComparer /// The Extensions are stored in the Default Dicitonary in their original form, /// however they are compared in a normalized manner. /// Equivalence for extensions in the content type stream, should follow /// the same rules as extensions of partnames. Also, by the time this code is invoked, /// we have already validated, that the extension is in the correct format as per the /// part name rules.So we are simplifying the logic here to just convert the extensions /// to Upper invariant form and then compare them. /// </summary> private sealed class ExtensionEqualityComparer : IEqualityComparer<string> { bool IEqualityComparer<string>.Equals(string extensionA, string extensionB) { Debug.Assert(extensionA != null, "extenstion should not be null"); Debug.Assert(extensionB != null, "extenstion should not be null"); //Important Note: any change to this should be made in accordance //with the rules for comparing/normalizing partnames. //Refer to PackUriHelper.ValidatedPartUri.GetNormalizedPartUri method. //Currently normalization just involves upper-casing ASCII and hence the simplification. return (String.CompareOrdinal(extensionA.ToUpperInvariant(), extensionB.ToUpperInvariant()) == 0); } int IEqualityComparer<string>.GetHashCode(string extension) { Debug.Assert(extension != null, "extenstion should not be null"); //Important Note: any change to this should be made in accordance //with the rules for comparing/normalizing partnames. //Refer to PackUriHelper.ValidatedPartUri.GetNormalizedPartUri method. //Currently normalization just involves upper-casing ASCII and hence the simplification. return extension.ToUpperInvariant().GetHashCode(); } } #region ContentTypeHelper Class /// <summary> /// This is a helper class that maintains the Content Types File related to /// this ZipPackage. /// </summary> private class ContentTypeHelper { #region Constructor /// <summary> /// Initialize the object without uploading any information from the package. /// Complete initialization in read mode also involves calling ParseContentTypesFile /// to deserialize content type information. /// </summary> internal ContentTypeHelper(ZipArchive zipArchive, FileMode packageFileMode, FileAccess packageFileAccess, ZipStreamManager zipStreamManager) { _zipArchive = zipArchive; //initialized in the ZipPackage constructor _packageFileMode = packageFileMode; _packageFileAccess = packageFileAccess; _zipStreamManager = zipStreamManager; //initialized in the ZipPackage constructor // The extensions are stored in the default Dictionary in their original form , but they are compared // in a normalized manner using the ExtensionComparer. _defaultDictionary = new Dictionary<string, ContentType>(s_defaultDictionaryInitialSize, s_extensionEqualityComparer); // Identify the content type file or files before identifying parts and piece sequences. // This is necessary because the name of the content type stream is not a part name and // the information it contains is needed to recognize valid parts. if (_zipArchive.Mode == ZipArchiveMode.Read || _zipArchive.Mode == ZipArchiveMode.Update) ParseContentTypesFile(_zipArchive.Entries); //No contents to persist to the disk - _dirty = false; //by default //Lazy initialize these members as required //_overrideDictionary - Overrides should be rare //_contentTypeFileInfo - We will either find an atomin part, or //_contentTypeStreamPieces - an interleaved part //_contentTypeStreamExists - defaults to false - not yet found } #endregion Constructor #region Internal Properties internal static string ContentTypeFileName { get { return s_contentTypesFile; } } #endregion Internal Properties #region Internal Methods //Adds the Default entry if it is the first time we come across //the extension for the partUri, does nothing if the content type //corresponding to the default entry for the extension matches or //adds a override corresponding to this part and content type. //This call is made when a new part is being added to the package. // This method assumes the partUri is valid. internal void AddContentType(PackUriHelper.ValidatedPartUri partUri, ContentType contentType, CompressionLevel compressionLevel) { //save the compressionOption and deflateOption that should be used //to create the content type item later if (!_contentTypeStreamExists) { _cachedCompressionLevel = compressionLevel; } // Figure out whether the mapping matches a default entry, can be made into a new // default entry, or has to be entered as an override entry. bool foundMatchingDefault = false; string extension = partUri.PartUriExtension; // Need to create an override entry? if (extension.Length == 0 || (_defaultDictionary.ContainsKey(extension) && !(foundMatchingDefault = _defaultDictionary[extension].AreTypeAndSubTypeEqual(contentType)))) { AddOverrideElement(partUri, contentType); } // Else, either there is already a mapping from extension to contentType, // or one needs to be created. else if (!foundMatchingDefault) { AddDefaultElement(extension, contentType); } } //Returns the content type for the part, if present, else returns null. internal ContentType GetContentType(PackUriHelper.ValidatedPartUri partUri) { //Step 1: Check if there is an override entry present corresponding to the //partUri provided. Override takes precedence over the default entries if (_overrideDictionary != null) { if (_overrideDictionary.ContainsKey(partUri)) return _overrideDictionary[partUri]; } //Step 2: Check if there is a default entry corresponding to the //extension of the partUri provided. string extension = partUri.PartUriExtension; if (_defaultDictionary.ContainsKey(extension)) return _defaultDictionary[extension]; //Step 3: If we did not find an entry in the override and the default //dictionaries, this is an error condition return null; } //Deletes the override entry corresponding to the partUri, if it exists internal void DeleteContentType(PackUriHelper.ValidatedPartUri partUri) { if (_overrideDictionary != null) { if (_overrideDictionary.Remove(partUri)) _dirty = true; } } internal void SaveToFile() { if (_dirty) { //Lazy init: Initialize when the first part is added. if (!_contentTypeStreamExists) { _contentTypeZipArchiveEntry = _zipArchive.CreateEntry(s_contentTypesFile, _cachedCompressionLevel); _contentTypeStreamExists = true; } // delete and re-create entry for content part. When writing this, the stream will not truncate the content // if the XML is shorter than the existing content part. var contentTypefullName = _contentTypeZipArchiveEntry.FullName; var thisArchive = _contentTypeZipArchiveEntry.Archive; _zipStreamManager.Close(_contentTypeZipArchiveEntry); _contentTypeZipArchiveEntry.Delete(); _contentTypeZipArchiveEntry = thisArchive.CreateEntry(contentTypefullName); using (Stream s = _zipStreamManager.Open(_contentTypeZipArchiveEntry, _packageFileMode, FileAccess.ReadWrite)) { // use UTF-8 encoding by default using (XmlWriter writer = XmlWriter.Create(s, new XmlWriterSettings { Encoding = System.Text.Encoding.UTF8 })) { writer.WriteStartDocument(); // write root element tag - Types writer.WriteStartElement(s_typesTagName, s_typesNamespaceUri); // for each default entry foreach (string key in _defaultDictionary.Keys) { WriteDefaultElement(writer, key, _defaultDictionary[key]); } if (_overrideDictionary != null) { // for each override entry foreach (PackUriHelper.ValidatedPartUri key in _overrideDictionary.Keys) { WriteOverrideElement(writer, key, _overrideDictionary[key]); } } // end of Types tag writer.WriteEndElement(); // close the document writer.WriteEndDocument(); _dirty = false; } } } } #endregion Internal Methods #region Private Methods private void EnsureOverrideDictionary() { // The part Uris are stored in the Override Dictionary in their original form , but they are compared // in a normalized manner using the PartUriComparer if (_overrideDictionary == null) _overrideDictionary = new Dictionary<PackUriHelper.ValidatedPartUri, ContentType>(s_overrideDictionaryInitialSize); } private void ParseContentTypesFile(System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> zipFiles) { // Find the content type stream, allowing for interleaving. Naming collisions // (as between an atomic and an interleaved part) will result in an exception being thrown. Stream s = OpenContentTypeStream(zipFiles); // Allow non-existent content type stream. if (s == null) return; XmlReaderSettings xrs = new XmlReaderSettings(); xrs.IgnoreWhitespace = true; using (s) using (XmlReader reader = XmlReader.Create(s, xrs)) { //This method expects the reader to be in ReadState.Initial. //It will make the first read call. PackagingUtilities.PerformInitailReadAndVerifyEncoding(reader); //Note: After the previous method call the reader should be at the first tag in the markup. //MoveToContent - Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace //If the reader is currently at a content node then this function call is a no-op reader.MoveToContent(); // look for our root tag and namespace pair - ignore others in case of version changes // Make sure that the current node read is an Element if ((reader.NodeType == XmlNodeType.Element) && (reader.Depth == 0) && (String.CompareOrdinal(reader.NamespaceURI, s_typesNamespaceUri) == 0) && (String.CompareOrdinal(reader.Name, s_typesTagName) == 0)) { //There should be a namespace Attribute present at this level. //Also any other attribute on the <Types> tag is an error including xml: and xsi: attributes if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) > 0) { throw new XmlException(SR.TypesTagHasExtraAttributes, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } // start tag encountered // now parse individual Default and Override tags while (reader.Read()) { //Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace //If the reader is currently at a content node then this function call is a no-op reader.MoveToContent(); //If MoveToContent() takes us to the end of the content if (reader.NodeType == XmlNodeType.None) continue; // Make sure that the current node read is an element // Currently we expect the Default and Override Tag at Depth 1 if (reader.NodeType == XmlNodeType.Element && reader.Depth == 1 && (String.CompareOrdinal(reader.NamespaceURI, s_typesNamespaceUri) == 0) && (String.CompareOrdinal(reader.Name, s_defaultTagName) == 0)) { ProcessDefaultTagAttributes(reader); } else if (reader.NodeType == XmlNodeType.Element && reader.Depth == 1 && (String.CompareOrdinal(reader.NamespaceURI, s_typesNamespaceUri) == 0) && (String.CompareOrdinal(reader.Name, s_overrideTagName) == 0)) { ProcessOverrideTagAttributes(reader); } else if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == 0 && String.CompareOrdinal(reader.Name, s_typesTagName) == 0) continue; else { throw new XmlException(SR.TypesXmlDoesNotMatchSchema, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } } } else { throw new XmlException(SR.TypesElementExpected, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } } } /// <summary> /// Find the content type stream, allowing for interleaving. Naming collisions /// (as between an atomic and an interleaved part) will result in an exception being thrown. /// Return null if no content type stream has been found. /// </summary> /// <remarks> /// The input array is lexicographically sorted /// </remarks> private Stream OpenContentTypeStream(System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> zipFiles) { foreach (ZipArchiveEntry zipFileInfo in zipFiles) { if (zipFileInfo.Name.ToUpperInvariant().StartsWith(s_contentTypesFileUpperInvariant, StringComparison.Ordinal)) { // Atomic name. if (zipFileInfo.Name.Length == ContentTypeFileName.Length) { // Record the file info. _contentTypeZipArchiveEntry = zipFileInfo; } } } // If an atomic file was found, open a stream on it. if (_contentTypeZipArchiveEntry != null) { _contentTypeStreamExists = true; return _zipStreamManager.Open(_contentTypeZipArchiveEntry, _packageFileMode, FileAccess.ReadWrite); } // No content type stream was found. return null; } // Process the attributes for the Default tag private void ProcessDefaultTagAttributes(XmlReader reader) { #region Default Tag //There could be a namespace Attribute present at this level. //Also any other attribute on the <Default> tag is an error including xml: and xsi: attributes if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) != 2) throw new XmlException(SR.DefaultTagDoesNotMatchSchema, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); // get the required Extension and ContentType attributes string extensionAttributeValue = reader.GetAttribute(s_extensionAttributeName); ValidateXmlAttribute(s_extensionAttributeName, extensionAttributeValue, s_defaultTagName, reader); string contentTypeAttributeValue = reader.GetAttribute(s_contentTypeAttributeName); ThrowIfXmlAttributeMissing(s_contentTypeAttributeName, contentTypeAttributeValue, s_defaultTagName, reader); // The extensions are stored in the Default Dictionary in their original form , but they are compared // in a normalized manner using the ExtensionComparer. PackUriHelper.ValidatedPartUri temporaryUri = PackUriHelper.ValidatePartUri( new Uri(s_temporaryPartNameWithoutExtension + extensionAttributeValue, UriKind.Relative)); _defaultDictionary.Add(temporaryUri.PartUriExtension, new ContentType(contentTypeAttributeValue)); //Skip the EndElement for Default Tag if (!reader.IsEmptyElement) ProcessEndElement(reader, s_defaultTagName); #endregion Default Tag } // Process the attributes for the Default tag private void ProcessOverrideTagAttributes(XmlReader reader) { #region Override Tag //There could be a namespace Attribute present at this level. //Also any other attribute on the <Override> tag is an error including xml: and xsi: attributes if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) != 2) throw new XmlException(SR.OverrideTagDoesNotMatchSchema, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); // get the required Extension and ContentType attributes string partNameAttributeValue = reader.GetAttribute(s_partNameAttributeName); ValidateXmlAttribute(s_partNameAttributeName, partNameAttributeValue, s_overrideTagName, reader); string contentTypeAttributeValue = reader.GetAttribute(s_contentTypeAttributeName); ThrowIfXmlAttributeMissing(s_contentTypeAttributeName, contentTypeAttributeValue, s_overrideTagName, reader); PackUriHelper.ValidatedPartUri partUri = PackUriHelper.ValidatePartUri(new Uri(partNameAttributeValue, UriKind.Relative)); //Lazy initializing - ensure that the override dictionary has been initialized EnsureOverrideDictionary(); // The part Uris are stored in the Override Dictionary in their original form , but they are compared // in a normalized manner using PartUriComparer. _overrideDictionary.Add(partUri, new ContentType(contentTypeAttributeValue)); //Skip the EndElement for Override Tag if (!reader.IsEmptyElement) ProcessEndElement(reader, s_overrideTagName); #endregion Override Tag } //If End element is present for Relationship then we process it private void ProcessEndElement(XmlReader reader, string elementName) { Debug.Assert(!reader.IsEmptyElement, "This method should only be called it the Relationship Element is not empty"); reader.Read(); //Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace reader.MoveToContent(); if (reader.NodeType == XmlNodeType.EndElement && String.CompareOrdinal(elementName, reader.LocalName) == 0) return; else throw new XmlException(SR.Format(SR.ElementIsNotEmptyElement, elementName), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } private void AddOverrideElement(PackUriHelper.ValidatedPartUri partUri, ContentType contentType) { //Delete any entry corresponding in the Override dictionary //corresponding to the PartUri for which the contentType is being added. //This is to compensate for dead override entries in the content types file. DeleteContentType(partUri); //Lazy initializing - ensure that the override dictionary has been initialized EnsureOverrideDictionary(); // The part Uris are stored in the Override Dictionary in their original form , but they are compared // in a normalized manner using PartUriComparer. _overrideDictionary.Add(partUri, contentType); _dirty = true; } private void AddDefaultElement(string extension, ContentType contentType) { // The extensions are stored in the Default Dictionary in their original form , but they are compared // in a normalized manner using the ExtensionComparer. _defaultDictionary.Add(extension, contentType); _dirty = true; } private void WriteOverrideElement(XmlWriter xmlWriter, PackUriHelper.ValidatedPartUri partUri, ContentType contentType) { xmlWriter.WriteStartElement(s_overrideTagName); xmlWriter.WriteAttributeString(s_partNameAttributeName, partUri.PartUriString); xmlWriter.WriteAttributeString(s_contentTypeAttributeName, contentType.ToString()); xmlWriter.WriteEndElement(); } private void WriteDefaultElement(XmlWriter xmlWriter, string extension, ContentType contentType) { xmlWriter.WriteStartElement(s_defaultTagName); xmlWriter.WriteAttributeString(s_extensionAttributeName, extension); xmlWriter.WriteAttributeString(s_contentTypeAttributeName, contentType.ToString()); xmlWriter.WriteEndElement(); } //Validate if the required XML attribute is present and not an empty string private void ValidateXmlAttribute(string attributeName, string attributeValue, string tagName, XmlReader reader) { ThrowIfXmlAttributeMissing(attributeName, attributeValue, tagName, reader); //Checking for empty attribute if (attributeValue == String.Empty) throw new XmlException(SR.Format(SR.RequiredAttributeEmpty, tagName, attributeName), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } //Validate if the required Content type XML attribute is present //Content type of a part can be empty private void ThrowIfXmlAttributeMissing(string attributeName, string attributeValue, string tagName, XmlReader reader) { if (attributeValue == null) throw new XmlException(SR.Format(SR.RequiredAttributeMissing, tagName, attributeName), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } #endregion Private Methods #region Member Variables private Dictionary<PackUriHelper.ValidatedPartUri, ContentType> _overrideDictionary; private Dictionary<string, ContentType> _defaultDictionary; private ZipArchive _zipArchive; private FileMode _packageFileMode; private FileAccess _packageFileAccess; private ZipStreamManager _zipStreamManager; private ZipArchiveEntry _contentTypeZipArchiveEntry; private bool _contentTypeStreamExists; private bool _dirty; private CompressionLevel _cachedCompressionLevel; private static readonly string s_contentTypesFile = "[Content_Types].xml"; private static readonly string s_contentTypesFileUpperInvariant = "[CONTENT_TYPES].XML"; private static readonly int s_defaultDictionaryInitialSize = 16; private static readonly int s_overrideDictionaryInitialSize = 8; //Xml tag specific strings for the Content Type file private static readonly string s_typesNamespaceUri = "http://schemas.openxmlformats.org/package/2006/content-types"; private static readonly string s_typesTagName = "Types"; private static readonly string s_defaultTagName = "Default"; private static readonly string s_extensionAttributeName = "Extension"; private static readonly string s_contentTypeAttributeName = "ContentType"; private static readonly string s_overrideTagName = "Override"; private static readonly string s_partNameAttributeName = "PartName"; private static readonly string s_temporaryPartNameWithoutExtension = "/tempfiles/sample."; #endregion Member Variables } #endregion ContentTypeHelper Class #endregion Private Class } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using FluentAssertions; using Microsoft.DotNet.TestFramework; using Microsoft.DotNet.Tools.Test.Utilities; using Xunit; using LocalizableStrings = Microsoft.DotNet.Tools.Run.LocalizableStrings; namespace Microsoft.DotNet.Cli.Run.Tests { public class GivenDotnetRunBuildsCsproj : TestBase { [Fact] public void ItCanRunAMSBuildProject() { var testAppName = "MSBuildTestApp"; var testInstance = TestAssets.Get(testAppName) .CreateInstance() .WithSourceFiles(); var testProjectDirectory = testInstance.Root.FullName; new RestoreCommand() .WithWorkingDirectory(testProjectDirectory) .Execute("/p:SkipInvalidConfigurations=true") .Should().Pass(); new BuildCommand() .WithWorkingDirectory(testProjectDirectory) .Execute() .Should().Pass(); new RunCommand() .WithWorkingDirectory(testProjectDirectory) .ExecuteWithCapturedOutput() .Should().Pass() .And.HaveStdOutContaining("Hello World!"); } [Fact] public void ItImplicitlyRestoresAProjectWhenRunning() { var testAppName = "MSBuildTestApp"; var testInstance = TestAssets.Get(testAppName) .CreateInstance() .WithSourceFiles(); var testProjectDirectory = testInstance.Root.FullName; new RunCommand() .WithWorkingDirectory(testProjectDirectory) .ExecuteWithCapturedOutput() .Should().Pass() .And.HaveStdOutContaining("Hello World!"); } [Fact] public void ItCanRunAMultiTFMProjectWithImplicitRestore() { var testInstance = TestAssets.Get( TestAssetKinds.DesktopTestProjects, "NETFrameworkReferenceNETStandard20") .CreateInstance() .WithSourceFiles(); string projectDirectory = Path.Combine(testInstance.Root.FullName, "MultiTFMTestApp"); new RunCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput("--framework netcoreapp2.1") .Should().Pass() .And.HaveStdOutContaining("This string came from the test library!"); } [Fact] public void ItDoesNotImplicitlyRestoreAProjectWhenRunningWithTheNoRestoreOption() { var testAppName = "MSBuildTestApp"; var testInstance = TestAssets.Get(testAppName) .CreateInstance() .WithSourceFiles(); var testProjectDirectory = testInstance.Root.FullName; new RunCommand() .WithWorkingDirectory(testProjectDirectory) .ExecuteWithCapturedOutput("--no-restore") .Should().Fail() .And.HaveStdOutContaining("project.assets.json"); } [Fact] public void ItBuildsTheProjectBeforeRunning() { var testAppName = "MSBuildTestApp"; var testInstance = TestAssets.Get(testAppName) .CreateInstance() .WithSourceFiles(); var testProjectDirectory = testInstance.Root.FullName; new RestoreCommand() .WithWorkingDirectory(testProjectDirectory) .Execute("/p:SkipInvalidConfigurations=true") .Should().Pass(); new RunCommand() .WithWorkingDirectory(testProjectDirectory) .ExecuteWithCapturedOutput() .Should().Pass() .And.HaveStdOutContaining("Hello World!"); } [Fact] public void ItCanRunAMSBuildProjectWhenSpecifyingAFramework() { var testAppName = "MSBuildTestApp"; var testInstance = TestAssets.Get(testAppName) .CreateInstance() .WithSourceFiles(); var testProjectDirectory = testInstance.Root.FullName; new RestoreCommand() .WithWorkingDirectory(testProjectDirectory) .Execute("/p:SkipInvalidConfigurations=true") .Should().Pass(); new RunCommand() .WithWorkingDirectory(testProjectDirectory) .ExecuteWithCapturedOutput("--framework netcoreapp2.1") .Should().Pass() .And.HaveStdOutContaining("Hello World!"); } [Fact] public void ItRunsPortableAppsFromADifferentPathAfterBuilding() { var testInstance = TestAssets.Get("MSBuildTestApp") .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); new BuildCommand() .WithWorkingDirectory(testInstance.Root) .Execute() .Should().Pass(); new RunCommand() .WithWorkingDirectory(testInstance.Root) .ExecuteWithCapturedOutput($"--no-build") .Should().Pass() .And.HaveStdOutContaining("Hello World!"); } [Fact] public void ItRunsPortableAppsFromADifferentPathWithoutBuilding() { var testAppName = "MSBuildTestApp"; var testInstance = TestAssets.Get(testAppName) .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var projectFile = testInstance.Root.GetFile(testAppName + ".csproj"); new RunCommand() .WithWorkingDirectory(testInstance.Root.Parent) .ExecuteWithCapturedOutput($"--project {projectFile.FullName}") .Should().Pass() .And.HaveStdOutContaining("Hello World!"); } [Fact] public void ItRunsPortableAppsFromADifferentPathSpecifyingOnlyTheDirectoryWithoutBuilding() { var testAppName = "MSBuildTestApp"; var testInstance = TestAssets.Get(testAppName) .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var testProjectDirectory = testInstance.Root.FullName; new RunCommand() .WithWorkingDirectory(testInstance.Root.Parent) .ExecuteWithCapturedOutput($"--project {testProjectDirectory}") .Should().Pass() .And.HaveStdOutContaining("Hello World!"); } [Fact] public void ItRunsAppWhenRestoringToSpecificPackageDirectory() { var rootPath = TestAssets.CreateTestDirectory().FullName; string dir = "pkgs"; string args = $"--packages {dir}"; string newArgs = $"console -o \"{rootPath}\" --no-restore"; new NewCommandShim() .WithWorkingDirectory(rootPath) .Execute(newArgs) .Should() .Pass(); new RestoreCommand() .WithWorkingDirectory(rootPath) .Execute(args) .Should() .Pass(); new RunCommand() .WithWorkingDirectory(rootPath) .ExecuteWithCapturedOutput("--no-restore") .Should().Pass() .And.HaveStdOutContaining("Hello World"); } [Fact] public void ItReportsAGoodErrorWhenProjectHasMultipleFrameworks() { var testAppName = "MSBuildAppWithMultipleFrameworks"; var testInstance = TestAssets.Get(testAppName) .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); // use --no-build so this test can run on all platforms. // the test app targets net451, which can't be built on non-Windows new RunCommand() .WithWorkingDirectory(testInstance.Root) .ExecuteWithCapturedOutput("--no-build") .Should().Fail() .And.HaveStdErrContaining("--framework"); } [Fact] public void ItCanPassArgumentsToSubjectAppByDoubleDash() { const string testAppName = "MSBuildTestApp"; var testInstance = TestAssets.Get(testAppName) .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var testProjectDirectory = testInstance.Root.FullName; new RunCommand() .WithWorkingDirectory(testProjectDirectory) .ExecuteWithCapturedOutput("-- foo bar baz") .Should() .Pass() .And.HaveStdOutContaining("echo args:foo;bar;baz"); } [Fact] public void ItGivesAnErrorWhenAttemptingToUseALaunchProfileThatDoesNotExistWhenThereIsNoLaunchSettingsFile() { var testAppName = "MSBuildTestApp"; var testInstance = TestAssets.Get(testAppName) .CreateInstance() .WithSourceFiles(); var testProjectDirectory = testInstance.Root.FullName; new RestoreCommand() .WithWorkingDirectory(testProjectDirectory) .Execute("/p:SkipInvalidConfigurations=true") .Should().Pass(); new BuildCommand() .WithWorkingDirectory(testProjectDirectory) .Execute() .Should().Pass(); new RunCommand() .WithWorkingDirectory(testProjectDirectory) .ExecuteWithCapturedOutput("--launch-profile test") .Should().Pass() .And.HaveStdOutContaining("Hello World!") .And.HaveStdErrContaining(LocalizableStrings.RunCommandExceptionCouldNotLocateALaunchSettingsFile); } [Fact] public void ItUsesLaunchProfileOfTheSpecifiedName() { var testAppName = "AppWithLaunchSettings"; var testInstance = TestAssets.Get(testAppName) .CreateInstance() .WithSourceFiles(); var testProjectDirectory = testInstance.Root.FullName; new RestoreCommand() .WithWorkingDirectory(testProjectDirectory) .Execute("/p:SkipInvalidConfigurations=true") .Should().Pass(); new BuildCommand() .WithWorkingDirectory(testProjectDirectory) .Execute() .Should().Pass(); var cmd = new RunCommand() .WithWorkingDirectory(testProjectDirectory) .ExecuteWithCapturedOutput("--launch-profile Second"); cmd.Should().Pass() .And.HaveStdOutContaining("Second"); cmd.StdErr.Should().BeEmpty(); } [Fact] public void ItDefaultsToTheFirstUsableLaunchProfile() { var testAppName = "AppWithLaunchSettings"; var testInstance = TestAssets.Get(testAppName) .CreateInstance() .WithSourceFiles(); var testProjectDirectory = testInstance.Root.FullName; new RestoreCommand() .WithWorkingDirectory(testProjectDirectory) .Execute("/p:SkipInvalidConfigurations=true") .Should().Pass(); new BuildCommand() .WithWorkingDirectory(testProjectDirectory) .Execute() .Should().Pass(); var cmd = new RunCommand() .WithWorkingDirectory(testProjectDirectory) .ExecuteWithCapturedOutput(); cmd.Should().Pass() .And.HaveStdOutContaining("First"); cmd.StdErr.Should().BeEmpty(); } [Fact] public void ItGivesAnErrorWhenTheLaunchProfileNotFound() { var testAppName = "AppWithLaunchSettings"; var testInstance = TestAssets.Get(testAppName) .CreateInstance() .WithSourceFiles(); var testProjectDirectory = testInstance.Root.FullName; new RestoreCommand() .WithWorkingDirectory(testProjectDirectory) .Execute("/p:SkipInvalidConfigurations=true") .Should().Pass(); new BuildCommand() .WithWorkingDirectory(testProjectDirectory) .Execute() .Should().Pass(); new RunCommand() .WithWorkingDirectory(testProjectDirectory) .ExecuteWithCapturedOutput("--launch-profile Third") .Should().Pass() .And.HaveStdOutContaining("(NO MESSAGE)") .And.HaveStdErrContaining(string.Format(LocalizableStrings.RunCommandExceptionCouldNotApplyLaunchSettings, "Third", "").Trim()); } [Fact] public void ItGivesAnErrorWhenTheLaunchProfileCanNotBeHandled() { var testAppName = "AppWithLaunchSettings"; var testInstance = TestAssets.Get(testAppName) .CreateInstance() .WithSourceFiles(); var testProjectDirectory = testInstance.Root.FullName; new RestoreCommand() .WithWorkingDirectory(testProjectDirectory) .Execute("/p:SkipInvalidConfigurations=true") .Should().Pass(); new BuildCommand() .WithWorkingDirectory(testProjectDirectory) .Execute() .Should().Pass(); new RunCommand() .WithWorkingDirectory(testProjectDirectory) .ExecuteWithCapturedOutput("--launch-profile \"IIS Express\"") .Should().Pass() .And.HaveStdOutContaining("(NO MESSAGE)") .And.HaveStdErrContaining(string.Format(LocalizableStrings.RunCommandExceptionCouldNotApplyLaunchSettings, "IIS Express", "").Trim()); } [Fact] public void ItSkipsLaunchProfilesWhenTheSwitchIsSupplied() { var testAppName = "AppWithLaunchSettings"; var testInstance = TestAssets.Get(testAppName) .CreateInstance() .WithSourceFiles(); var testProjectDirectory = testInstance.Root.FullName; new RestoreCommand() .WithWorkingDirectory(testProjectDirectory) .Execute("/p:SkipInvalidConfigurations=true") .Should().Pass(); new BuildCommand() .WithWorkingDirectory(testProjectDirectory) .Execute() .Should().Pass(); var cmd = new RunCommand() .WithWorkingDirectory(testProjectDirectory) .ExecuteWithCapturedOutput("--no-launch-profile"); cmd.Should().Pass() .And.HaveStdOutContaining("(NO MESSAGE)"); cmd.StdErr.Should().BeEmpty(); } [Fact] public void ItSkipsLaunchProfilesWhenTheSwitchIsSuppliedWithoutErrorWhenThereAreNoLaunchSettings() { var testAppName = "MSBuildTestApp"; var testInstance = TestAssets.Get(testAppName) .CreateInstance() .WithSourceFiles(); var testProjectDirectory = testInstance.Root.FullName; new RestoreCommand() .WithWorkingDirectory(testProjectDirectory) .Execute("/p:SkipInvalidConfigurations=true") .Should().Pass(); new BuildCommand() .WithWorkingDirectory(testProjectDirectory) .Execute() .Should().Pass(); var cmd = new RunCommand() .WithWorkingDirectory(testProjectDirectory) .ExecuteWithCapturedOutput("--no-launch-profile"); cmd.Should().Pass() .And.HaveStdOutContaining("Hello World!"); cmd.StdErr.Should().BeEmpty(); } [Fact] public void ItSkipsLaunchProfilesWhenThereIsNoUsableDefault() { var testAppName = "AppWithLaunchSettingsNoDefault"; var testInstance = TestAssets.Get(testAppName) .CreateInstance() .WithSourceFiles(); var testProjectDirectory = testInstance.Root.FullName; new RestoreCommand() .WithWorkingDirectory(testProjectDirectory) .Execute("/p:SkipInvalidConfigurations=true") .Should().Pass(); new BuildCommand() .WithWorkingDirectory(testProjectDirectory) .Execute() .Should().Pass(); var cmd = new RunCommand() .WithWorkingDirectory(testProjectDirectory) .ExecuteWithCapturedOutput(); cmd.Should().Pass() .And.HaveStdOutContaining("(NO MESSAGE)") .And.HaveStdErrContaining(string.Format(LocalizableStrings.RunCommandExceptionCouldNotApplyLaunchSettings, LocalizableStrings.DefaultLaunchProfileDisplayName, "").Trim()); } [Fact] public void ItPrintsAnErrorWhenLaunchSettingsAreCorrupted() { var testAppName = "AppWithCorruptedLaunchSettings"; var testInstance = TestAssets.Get(testAppName) .CreateInstance() .WithSourceFiles(); var testProjectDirectory = testInstance.Root.FullName; new RestoreCommand() .WithWorkingDirectory(testProjectDirectory) .Execute("/p:SkipInvalidConfigurations=true") .Should().Pass(); new BuildCommand() .WithWorkingDirectory(testProjectDirectory) .Execute() .Should().Pass(); var cmd = new RunCommand() .WithWorkingDirectory(testProjectDirectory) .ExecuteWithCapturedOutput(); cmd.Should().Pass() .And.HaveStdOutContaining("(NO MESSAGE)") .And.HaveStdErrContaining(string.Format(LocalizableStrings.RunCommandExceptionCouldNotApplyLaunchSettings, LocalizableStrings.DefaultLaunchProfileDisplayName, "").Trim()); } } }
using System; using System.Linq; using JetBrains.DataFlow; using JetBrains.Metadata.Reader.API; using JetBrains.Metadata.Reader.Impl; using JetBrains.Metadata.Utils; using JetBrains.Util; using NUnit.Framework; using Xunit.Abstractions; using XunitContrib.Runner.ReSharper.UnitTestProvider; namespace XunitContrib.Runner.ReSharper.Tests.Abstractions { public class MetadataMethodInfoAdapterTest : IDisposable { private readonly MetadataLoader loader; private readonly LifetimeDefinition lifetimeDefinition; public MetadataMethodInfoAdapterTest() { lifetimeDefinition = Lifetimes.Define(EternalLifetime.Instance); var lifetime = lifetimeDefinition.Lifetime; var gacResolver = GacAssemblyResolver.CreateOnCurrentRuntimeGac(GacAssemblyResolver.GacResolvePreferences.MatchSameOrNewer); var resolver = new CombiningAssemblyResolver(gacResolver, new LoadedAssembliesResolver(lifetime, true)); loader = new MetadataLoader(resolver); lifetime.AddDispose(loader); } public void Dispose() { lifetimeDefinition.Terminate(); } [Test] public void Should_indicate_if_method_is_abstract() { var methodInfo = GetMethodInfo(typeof (ClassWithMethods), "NormalMethod"); var abstractMethodInfo = GetMethodInfo(typeof (AbstractClassWithMethods), "AbstractMethod"); Assert.False(methodInfo.IsAbstract); Assert.True(abstractMethodInfo.IsAbstract); } [Test] public void Should_indicate_if_method_is_a_generic_method() { var methodInfo = GetMethodInfo(typeof(ClassWithMethods), "NormalMethod"); var genericMethodInfo = GetMethodInfo(typeof(ClassWithMethods), "GenericMethod"); Assert.False(methodInfo.IsGenericMethodDefinition); Assert.True(genericMethodInfo.IsGenericMethodDefinition); } [Test] public void Should_indicate_if_method_is_generic_in_an_open_generic_class() { var methodInfo = GetMethodInfo(typeof(GenericType<>), "NormalMethod"); var genericMethodInfo = GetMethodInfo(typeof(GenericType<>), "GenericMethod"); Assert.False(methodInfo.IsGenericMethodDefinition); Assert.False(genericMethodInfo.IsGenericMethodDefinition); } [Test] public void Should_indicate_if_method_is_generic_in_an_closed_generic_class() { var methodInfo = GetMethodInfo(typeof(GenericType<string>), "NormalMethod"); var genericMethodInfo = GetMethodInfo(typeof(GenericType<string>), "GenericMethod"); Assert.False(methodInfo.IsGenericMethodDefinition); Assert.False(genericMethodInfo.IsGenericMethodDefinition); } [Test] public void Should_indicate_if_method_is_public() { var methodInfo = GetMethodInfo(typeof(ClassWithMethods), "NormalMethod"); var privateMethodInfo = GetMethodInfo(typeof(ClassWithMethods), "PrivateMethod", true); Assert.True(methodInfo.IsPublic); Assert.False(privateMethodInfo.IsPublic); } [Test] public void Should_indicate_if_method_is_static() { var methodInfo = GetMethodInfo(typeof(ClassWithMethods), "NormalMethod"); var privateMethodInfo = GetMethodInfo(typeof(ClassWithMethods), "StaticMethod"); Assert.False(methodInfo.IsStatic); Assert.True(privateMethodInfo.IsStatic); } [Test] public void Should_return_methods_name() { var methodInfo = GetMethodInfo(typeof(ClassWithMethods), "NormalMethod"); Assert.AreEqual("NormalMethod", methodInfo.Name); } [Test] public void Should_give_methods_return_type() { var methodInfo = GetMethodInfo(typeof (ClassWithMethods), "ReturnsString"); Assert.AreEqual("System.String", methodInfo.ReturnType.Name); } [Test] public void Should_handle_void_return_type() { var methodInfo = GetMethodInfo(typeof (ClassWithMethods), "NormalMethod"); Assert.AreEqual("System.Void", methodInfo.ReturnType.Name); } [Test] public void Should_give_return_type_for_open_generic() { var methodInfo = GetMethodInfo(typeof (ClassWithMethods), "GenericMethod"); Assert.AreEqual("T", methodInfo.ReturnType.Name); Assert.True(methodInfo.ReturnType.IsGenericParameter); } [Test] public void Should_give_return_type_for_closed_generic() { var methodInfo = GetMethodInfo(typeof(GenericType<string>), "GenericMethod"); Assert.AreEqual("System.String", methodInfo.ReturnType.Name); Assert.False(methodInfo.ReturnType.IsGenericParameter); Assert.False(methodInfo.ReturnType.IsGenericType); } [Test] public void Should_return_attributes() { var method = GetMethodInfo(typeof(ClassWithMethods), "MethodWithAttributes"); var attributeType = typeof(CustomAttribute); var attributeArgs = method.GetCustomAttributes(attributeType.AssemblyQualifiedName) .Select(a => a.GetConstructorArguments().First()).ToList(); var expectedArgs = new[] { "Foo", "Bar" }; CollectionAssert.AreEquivalent(expectedArgs, attributeArgs); } [Test] public void Should_return_generic_arguments_for_generic_method() { var method = GetMethodInfo(typeof (ClassWithMethods), "GenericMethod2"); var args = method.GetGenericArguments().ToList(); Assert.AreEqual(2, args.Count); Assert.AreEqual("T1", args[0].Name); Assert.True(args[0].IsGenericParameter); Assert.AreEqual("T2", args[1].Name); Assert.True(args[1].IsGenericParameter); } [Test] public void Should_return_parameter_information() { var method = GetMethodInfo(typeof(ClassWithMethods), "WithParameters"); var parameters = method.GetParameters().ToList(); Assert.AreEqual(2, parameters.Count); Assert.AreEqual("i", parameters[0].Name); Assert.AreEqual("System.Int32", parameters[0].ParameterType.Name); Assert.AreEqual("s", parameters[1].Name); Assert.AreEqual("System.String", parameters[1].ParameterType.Name); } [Test] public void Should_return_empty_list_for_method_with_no_parameters() { var method = GetMethodInfo(typeof (ClassWithMethods), "NormalMethod"); var parameters = method.GetParameters().ToList(); Assert.IsEmpty(parameters); } [Test] public void Should_return_parameter_information_for_open_class_generic() { var method = GetMethodInfo(typeof (GenericType<>), "NormalMethod"); var parameters = method.GetParameters().ToList(); Assert.AreEqual(1, parameters.Count); Assert.AreEqual("t", parameters[0].Name); Assert.AreEqual("T", parameters[0].ParameterType.Name); Assert.True(parameters[0].ParameterType.IsGenericParameter); Assert.False(parameters[0].ParameterType.IsGenericType); } [Test] public void Should_return_parameter_information_for_closed_class_generic() { var method = GetMethodInfo(typeof(GenericType<string>), "NormalMethod"); var parameters = method.GetParameters().ToList(); Assert.AreEqual(1, parameters.Count); Assert.AreEqual("t", parameters[0].Name); Assert.AreEqual("System.String", parameters[0].ParameterType.Name); Assert.False(parameters[0].ParameterType.IsGenericParameter); Assert.False(parameters[0].ParameterType.IsGenericType); } [Test] public void Should_return_parameter_information_for_generic_method() { var method = GetMethodInfo(typeof (ClassWithMethods), "GenericMethod"); var parameters = method.GetParameters().ToList(); Assert.AreEqual(1, parameters.Count); Assert.AreEqual("t", parameters[0].Name); Assert.AreEqual("T", parameters[0].ParameterType.Name); Assert.True(parameters[0].ParameterType.IsGenericParameter); Assert.False(parameters[0].ParameterType.IsGenericType); } [Test] public void Should_convert_open_generic_method_to_closed_definition() { var method = GetMethodInfo(typeof (ClassWithMethods), "GenericMethod3"); var closedMethod = method.MakeGenericMethod(GetTypeInfo(typeof (string)), GetTypeInfo(typeof (int)), GetTypeInfo(typeof (double))); Assert.AreEqual("System.Double", closedMethod.ReturnType.Name); Assert.False(closedMethod.ReturnType.IsGenericParameter); Assert.False(closedMethod.ReturnType.IsGenericType); var parameters = closedMethod.GetParameters().ToList(); Assert.AreEqual(2, parameters.Count); Assert.AreEqual("t1", parameters[0].Name); Assert.AreEqual("System.String", parameters[0].ParameterType.Name); Assert.False(parameters[0].ParameterType.IsGenericParameter); Assert.AreEqual("t2", parameters[1].Name); Assert.AreEqual("System.Int32", parameters[1].ParameterType.Name); Assert.False(parameters[1].ParameterType.IsGenericParameter); } [Test] public void Should_return_owning_type_info() { var method = GetMethodInfo(typeof (ClassWithMethods), "NormalMethod"); var typeInfo = method.Type; Assert.AreEqual(typeof(ClassWithMethods).FullName, typeInfo.Name); } private ITypeInfo GetTypeInfo(Type type) { var assembly = loader.LoadFrom(FileSystemPath.Parse(type.Assembly.Location), JetFunc<AssemblyNameInfo>.True); var typeInfo = new MetadataAssemblyInfoAdapter(assembly).GetType(type.FullName); Assert.NotNull(typeInfo, "Cannot load type {0}", type.FullName); return typeInfo; // Ugh. This requires xunit.execution, which is .net 4.5, but if we change // this project to be .net 4.5, the ReSharper tests fail... //var assembly = Xunit.Sdk.Reflector.Wrap(type.Assembly); //var typeInfo = assembly.GetType(type.FullName); //Assert.NotNull(typeInfo, "Cannot load type {0}", type.FullName); //return typeInfo; } private IMethodInfo GetMethodInfo(Type type, string methodName, bool includePrivateMethod = false) { var typeInfo = GetTypeInfo(type); var methodInfo = typeInfo.GetMethod(methodName, includePrivateMethod); Assert.NotNull(methodInfo, "Cannot find method {0}.{1}", type.FullName, methodName); return methodInfo; } } public class ClassWithMethods { public void NormalMethod() { } private void PrivateMethod() { } public static void StaticMethod() { } [Custom("Foo"), Custom("Bar")] public void MethodWithAttributes() { } public T GenericMethod<T>(T t) { return default(T); } public void GenericMethod2<T1, T2>(T1 t1, T2 t2) { } public TResult GenericMethod3<T1, T2, TResult>(T1 t1, T2 t2) { throw new NotImplementedException(); } public void WithParameters(int i, string s) { } public string ReturnsString() { return "foo"; } } public abstract class AbstractClassWithMethods { public abstract void AbstractMethod(); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Runtime.Tests.Common; using Xunit; public static class EnumTests { [Theory] [InlineData("Red", false, true, SimpleEnum.Red)] [InlineData(" Red", false, true, SimpleEnum.Red)] [InlineData(" red ", true, true, SimpleEnum.Red)] [InlineData(" Red , Blue ", false, true, (SimpleEnum)3)] [InlineData("1", false, true, SimpleEnum.Red)] [InlineData(" 1 ", false, true, SimpleEnum.Red)] [InlineData("2", false, true, SimpleEnum.Blue)] [InlineData("99", false, true, (SimpleEnum)99)] [InlineData(" red ", false, false, default(SimpleEnum))] // No actual expected result [InlineData("Purple", false, false, default(SimpleEnum))] public static void TestParse(string value, bool ignoreCase, bool expectedCanParse, Enum expectedParseResult) { bool b; SimpleEnum e; if (!ignoreCase) { b = Enum.TryParse(value, out e); Assert.Equal(expectedCanParse, b); Assert.Equal(expectedParseResult, e); } b = Enum.TryParse(value, ignoreCase, out e); Assert.Equal(expectedCanParse, b); Assert.Equal(expectedParseResult, e); } [Theory] [InlineData(99, null)] [InlineData(1, "Red")] [InlineData(SimpleEnum.Red, "Red")] public static void TestGetName(object value, string expected) { string s = Enum.GetName(typeof(SimpleEnum), value); Assert.Equal(expected, s); } [Fact] public static void TestGetNameMultipleMatches() { // In the case of multiple matches, GetName returns one of them (which one is an implementation detail.) string s = Enum.GetName(typeof(SimpleEnum), 3); Assert.True(s == "Green" || s == "Green_a" || s == "Green_b"); } [Fact] public static void TestGetNameInvalid() { Type t = typeof(SimpleEnum); Assert.Throws<ArgumentNullException>("enumType", () => Enum.GetName(null, 1)); // Enum type is null Assert.Throws<ArgumentNullException>("value", () => Enum.GetName(t, null)); // Value is null Assert.Throws<ArgumentException>(null, () => Enum.GetName(typeof(object), 1)); // Enum type is not an enum Assert.Throws<ArgumentException>("value", () => Enum.GetName(t, "Red")); // Value is not the type of the enum's raw data Assert.Throws<ArgumentException>("value", () => Enum.GetName(t, (IntPtr)0)); // Value is out of range } [Theory] [InlineData(0xffffffffffffff80LU, "Min")] [InlineData(0xffffff80u, null)] [InlineData(unchecked((int)(0xffffff80u)), "Min")] [InlineData(true, "One")] [InlineData((char)1, "One")] [InlineData(SimpleEnum.Red, "One")] // API doesnt't care if you pass in a completely different enum public static void TestGetNameNonIntegralTypes(object value, string expected) { /* * Despite what MSDN says, GetName() does not require passing in the exact integral type. * * For the purposes of comparison: * * - The enum member value are normalized as follows: * - unsigned ints zero-extended to 64-bits * - signed ints sign-extended to 64-bits * * - The value passed in as an argument to GetNames() is normalized as follows: * - unsigned ints zero-extended to 64-bits * - signed ints sign-extended to 64-bits * * Then comparison is done on all 64 bits. */ string s = Enum.GetName(typeof(SByteEnum), value); Assert.Equal(expected, s); } [Theory] [InlineData(typeof(SimpleEnum), "Red", true)] //string [InlineData(typeof(SimpleEnum), "Green", true)] [InlineData(typeof(SimpleEnum), "Blue", true)] [InlineData(typeof(SimpleEnum), " Blue", false)] [InlineData(typeof(SimpleEnum), "blue", false)] [InlineData(typeof(SimpleEnum), "", false)] [InlineData(typeof(SimpleEnum), SimpleEnum.Red, true)] //Enum [InlineData(typeof(SimpleEnum), (SimpleEnum)99, false)] [InlineData(typeof(SimpleEnum), 1, true)] // Integer [InlineData(typeof(SimpleEnum), 99, false)] [InlineData(typeof(Int32Enum), 0x1 | 0x02, false)] // "Combos" do not pass public static void TestIsDefined(Type t, object value, bool expected) { bool b = Enum.IsDefined(t, value); Assert.Equal(expected, b); } [Fact] public static void TestIsDefinedInvalid() { Type t = typeof(SimpleEnum); Assert.Throws<ArgumentNullException>("enumType", () => Enum.IsDefined(null, 1)); // Enum type is null Assert.Throws<ArgumentNullException>("value", () => Enum.IsDefined(t, null)); // Value is null Assert.Throws<ArgumentException>(null, () => Enum.IsDefined(t, Int32Enum.One)); // Value is different enum type // Value is not a valid type (MSDN claims this should throw InvalidOperationException) Assert.Throws<ArgumentException>(null, () => Enum.IsDefined(t, true)); Assert.Throws<ArgumentException>(null, () => Enum.IsDefined(t, 'a')); // Non-integers throw InvalidOperationException prior to Win8P. Assert.Throws<InvalidOperationException>(() => Enum.IsDefined(t, (IntPtr)0)); Assert.Throws<InvalidOperationException>(() => Enum.IsDefined(t, 5.5)); Assert.Throws<InvalidOperationException>(() => Enum.IsDefined(t, 5.5f)); } [Fact] public static void TestHasFlagInvalid() { Int32Enum e = (Int32Enum)0x3f06; Assert.Throws<ArgumentNullException>("flag", () => e.HasFlag(null)); // Flag is null Assert.Throws<ArgumentException>(null, () => e.HasFlag((SimpleEnum)0x2)); // Different enum type } [Theory] [InlineData((Int32Enum)0x3000, true)] [InlineData((Int32Enum)0x1000, true)] [InlineData((Int32Enum)0x0000, true)] [InlineData((Int32Enum)0x3f06, true)] [InlineData((Int32Enum)0x0010, false)] [InlineData((Int32Enum)0x3f16, false)] public static void TestHasFlag(Enum flag, bool expected) { Int32Enum e = (Int32Enum)0x3f06; bool b = e.HasFlag(flag); Assert.Equal(expected, b); } [Fact] public static void TestToObject() { TestToObjectVerifySuccess<SByteEnum, sbyte>(42); TestToObjectVerifySuccess<SByteEnum, SByteEnum>((SByteEnum)0x42); TestToObjectVerifySuccess<UInt64Enum, ulong>(0x0123456789abcdefL); ulong l = 0x0ccccccccccccc2aL; ByteEnum e = (ByteEnum)(Enum.ToObject(typeof(ByteEnum), l)); Assert.True((sbyte)e == 0x2a); } private static void TestToObjectVerifySuccess<E, T>(T value) { object oValue = value; object e = Enum.ToObject(typeof(E), oValue); Assert.Equal(e.GetType(), typeof(E)); E expected = (E)(object)(value); object oExpected = (object)expected; // Workaround for Bartok codegen bug: Calling Object methods on enum through type variable fails (due to missing box) Assert.True(oExpected.Equals(e)); } [Fact] public static void TestToObjectInvalid() { Assert.Throws<ArgumentNullException>("enumType", () => Enum.ToObject(null, 3)); // Enum type is null Assert.Throws<ArgumentNullException>("value", () => Enum.ToObject(typeof(SimpleEnum), null)); // Value is null Assert.Throws<ArgumentException>("enumType", () => Enum.ToObject(typeof(Enum), 1)); // Enum type is simply an enum Assert.Throws<ArgumentException>("value", () => Enum.ToObject(typeof(SimpleEnum), "Hello")); //Value is not a supported enum type } [Fact] public static void TestHashCode() { SimpleEnum e = (SimpleEnum)42; int h = e.GetHashCode(); int h2 = e.GetHashCode(); Assert.Equal(h, h2); } [Theory] [InlineData(null, false)] [InlineData((long)42, false)] [InlineData((Int32Enum)42, false)] [InlineData((Int64Enum)43, false)] [InlineData((Int64Enum)0x700000000000002aL, false)] [InlineData((Int64Enum)42, true)] public static void TestEquals(object obj, bool expected) { Int64Enum e = (Int64Enum)42; bool b = e.Equals(obj); Assert.Equal(expected, b); } [Theory] [InlineData(null, 1)] // Special case: All values are "greater than" null [InlineData(SimpleEnum.Red, 0)] [InlineData((SimpleEnum)0, 1)] [InlineData((SimpleEnum)2, -1)] public static void TestCompareTo(object target, int expected) { SimpleEnum e = SimpleEnum.Red; int i = CompareHelper.NormalizeCompare(e.CompareTo(target)); Assert.Equal(expected, i); } [Fact] public static void TestCompareToInvalid() { Assert.Throws<ArgumentException>(null, () => SimpleEnum.Red.CompareTo((sbyte)1)); //Target is an enum type Assert.Throws<ArgumentException>(null, () => SimpleEnum.Red.CompareTo(Int32Enum.One)); //Target is a different enum type } [Theory] [InlineData(typeof(SByteEnum), typeof(sbyte))] [InlineData(typeof(ByteEnum), typeof(byte))] [InlineData(typeof(Int16Enum), typeof(short))] [InlineData(typeof(UInt16Enum), typeof(ushort))] [InlineData(typeof(Int32Enum), typeof(int))] [InlineData(typeof(UInt32Enum), typeof(uint))] [InlineData(typeof(Int64Enum), typeof(long))] [InlineData(typeof(UInt64Enum), typeof(ulong))] public static void TestGetUnderlyingType(Type enumType, Type expected) { Assert.Equal(expected, Enum.GetUnderlyingType(enumType)); } [Fact] public static void TestGetUnderlyingTypeInvalid() { Assert.Throws<ArgumentNullException>("enumType", () => Enum.GetUnderlyingType(null)); // Enum type is null Assert.Throws<ArgumentException>("enumType", () => Enum.GetUnderlyingType(typeof(Enum))); // Enum type is simply an enum } [Theory] [InlineData(typeof(SimpleEnum), new[] { "Red", "Blue", "Green", "Green_a", "Green_b" }, new object[] { SimpleEnum.Red, SimpleEnum.Blue, SimpleEnum.Green, SimpleEnum.Green_a, SimpleEnum.Green_b })] [InlineData(typeof(ByteEnum), new[] { "Min", "One", "Two", "Max" }, new object[] { ByteEnum.Min, ByteEnum.One, ByteEnum.Two, ByteEnum.Max })] [InlineData(typeof(SByteEnum), new[] { "One", "Two", "Max", "Min" }, new object[] { SByteEnum.One, SByteEnum.Two, SByteEnum.Max, SByteEnum.Min })] [InlineData(typeof(UInt16Enum), new[] { "Min", "One", "Two", "Max" }, new object[] { UInt16Enum.Min, UInt16Enum.One, UInt16Enum.Two, UInt16Enum.Max })] [InlineData(typeof(Int16Enum), new[] { "One", "Two", "Max", "Min" }, new object[] { Int16Enum.One, Int16Enum.Two, Int16Enum.Max, Int16Enum.Min })] [InlineData(typeof(UInt32Enum), new[] { "Min", "One", "Two", "Max" }, new object[] { UInt32Enum.Min, UInt32Enum.One, UInt32Enum.Two, UInt32Enum.Max })] [InlineData(typeof(Int32Enum), new[] { "One", "Two", "Max", "Min" }, new object[] { Int32Enum.One, Int32Enum.Two, Int32Enum.Max, Int32Enum.Min })] [InlineData(typeof(UInt64Enum), new[] { "Min", "One", "Two", "Max" }, new object[] { UInt64Enum.Min, UInt64Enum.One, UInt64Enum.Two, UInt64Enum.Max })] [InlineData(typeof(Int64Enum), new[] { "One", "Two", "Max", "Min" }, new object[] { Int64Enum.One, Int64Enum.Two, Int64Enum.Max, Int64Enum.Min })] public static void TestGetNamesAndValues(Type t, string[] expectedNames, object[] expectedValues) { string[] names = Enum.GetNames(t); Array values = Enum.GetValues(t); Assert.Equal(names.Length, values.Length); for (int i = 0; i < names.Length; i++) { Assert.Equal(expectedNames[i], names[i]); Assert.Equal(expectedValues[i], values.GetValue(i)); } } [Theory] // Format: "D" [InlineData(ByteEnum.Min, "D", "0")] [InlineData(ByteEnum.One, "D", "1")] [InlineData(ByteEnum.Two, "D", "2")] [InlineData((ByteEnum)99, "D", "99")] [InlineData(ByteEnum.Max, "D", "255")] [InlineData(SByteEnum.Min, "D", "-128")] [InlineData(SByteEnum.One, "D", "1")] [InlineData(SByteEnum.Two, "D", "2")] [InlineData((SByteEnum)99, "D", "99")] [InlineData(SByteEnum.Max, "D", "127")] [InlineData(UInt16Enum.Min, "D", "0")] [InlineData(UInt16Enum.One, "D", "1")] [InlineData(UInt16Enum.Two, "D", "2")] [InlineData((UInt16Enum)99, "D", "99")] [InlineData(UInt16Enum.Max, "D", "65535")] [InlineData(Int16Enum.Min, "D", "-32768")] [InlineData(Int16Enum.One, "D", "1")] [InlineData(Int16Enum.Two, "D", "2")] [InlineData((Int16Enum)99, "D", "99")] [InlineData(Int16Enum.Max, "D", "32767")] [InlineData(UInt32Enum.Min, "D", "0")] [InlineData(UInt32Enum.One, "D", "1")] [InlineData(UInt32Enum.Two, "D", "2")] [InlineData((UInt32Enum)99, "D", "99")] [InlineData(UInt32Enum.Max, "D", "4294967295")] [InlineData(Int32Enum.Min, "D", "-2147483648")] [InlineData(Int32Enum.One, "D", "1")] [InlineData(Int32Enum.Two, "D", "2")] [InlineData((Int32Enum)99, "D", "99")] [InlineData(Int32Enum.Max, "D", "2147483647")] [InlineData(UInt64Enum.Min, "D", "0")] [InlineData(UInt64Enum.One, "D", "1")] [InlineData(UInt64Enum.Two, "D", "2")] [InlineData((UInt64Enum)99, "D", "99")] [InlineData(UInt64Enum.Max, "D", "18446744073709551615")] [InlineData(Int64Enum.Min, "D", "-9223372036854775808")] [InlineData(Int64Enum.One, "D", "1")] [InlineData(Int64Enum.Two, "D", "2")] [InlineData((Int64Enum)99, "D", "99")] [InlineData(Int64Enum.Max, "D", "9223372036854775807")] //Format "X": value in hex form without a leading "0x" [InlineData(ByteEnum.Min, "X", "00")] [InlineData(ByteEnum.One, "X", "01")] [InlineData(ByteEnum.Two, "X", "02")] [InlineData((ByteEnum)99, "X", "63")] [InlineData(ByteEnum.Max, "X", "FF")] [InlineData(SByteEnum.Min, "X", "80")] [InlineData(SByteEnum.One, "X", "01")] [InlineData(SByteEnum.Two, "X", "02")] [InlineData((SByteEnum)99, "X", "63")] [InlineData(SByteEnum.Max, "X", "7F")] [InlineData(UInt16Enum.Min, "X", "0000")] [InlineData(UInt16Enum.One, "X", "0001")] [InlineData(UInt16Enum.Two, "X", "0002")] [InlineData((UInt16Enum)99, "X", "0063")] [InlineData(UInt16Enum.Max, "X", "FFFF")] [InlineData(Int16Enum.Min, "X", "8000")] [InlineData(Int16Enum.One, "X", "0001")] [InlineData(Int16Enum.Two, "X", "0002")] [InlineData((Int16Enum)99, "X", "0063")] [InlineData(Int16Enum.Max, "X", "7FFF")] [InlineData(UInt32Enum.Min, "X", "00000000")] [InlineData(UInt32Enum.One, "X", "00000001")] [InlineData(UInt32Enum.Two, "X", "00000002")] [InlineData((UInt32Enum)99, "X", "00000063")] [InlineData(UInt32Enum.Max, "X", "FFFFFFFF")] [InlineData(Int32Enum.Min, "X", "80000000")] [InlineData(Int32Enum.One, "X", "00000001")] [InlineData(Int32Enum.Two, "X", "00000002")] [InlineData((Int32Enum)99, "X", "00000063")] [InlineData(Int32Enum.Max, "X", "7FFFFFFF")] [InlineData(UInt64Enum.Min, "X", "0000000000000000")] [InlineData(UInt64Enum.One, "X", "0000000000000001")] [InlineData(UInt64Enum.Two, "X", "0000000000000002")] [InlineData((UInt64Enum)99, "X", "0000000000000063")] [InlineData(UInt64Enum.Max, "X", "FFFFFFFFFFFFFFFF")] [InlineData(Int64Enum.Min, "X", "8000000000000000")] [InlineData(Int64Enum.One, "X", "0000000000000001")] [InlineData(Int64Enum.Two, "X", "0000000000000002")] [InlineData((Int64Enum)99, "X", "0000000000000063")] [InlineData(Int64Enum.Max, "X", "7FFFFFFFFFFFFFFF")] // Format "F". value is treated as a bit field that contains one or more flags that consist of one or more bits. // If value is equal to a combination of named enumerated constants, a delimiter-separated list of the names // of those constants is returned. value is searched for flags, going from the flag with the largest value // to the smallest value. For each flag that corresponds to a bit field in value, the name of the constant // is concatenated to the delimiter-separated list. The value of that flag is then excluded from further // consideration, and the search continues for the next flag. // // If value is not equal to a combination of named enumerated constants, the decimal equivalent of value is returned. [InlineData(SimpleEnum.Red, "F", "Red")] [InlineData(SimpleEnum.Blue, "F", "Blue")] [InlineData((SimpleEnum)99, "F", "99")] [InlineData((SimpleEnum)0, "F", "0")] // Not found [InlineData((ByteEnum)0, "F", "Min")] [InlineData((ByteEnum)3, "F", "One, Two")] [InlineData((ByteEnum)0xff, "F", "Max")] // Larger values take precedence (and remove the bits from consideration.) // Format "G": If value is equal to a named enumerated constant, the name of that constant is returned. // Otherwise, if "[Flags]" present, do as Format "F" - else return the decimal value of "value". [InlineData(SimpleEnum.Red, "G", "Red")] [InlineData(SimpleEnum.Blue, "G", "Blue")] [InlineData((SimpleEnum)99, "G", "99")] [InlineData((SimpleEnum)0, "G", "0")] // Not found [InlineData((ByteEnum)0, "G", "Min")] [InlineData((ByteEnum)3, "G", "3")] // No [Flags] attribute [InlineData((ByteEnum)0xff, "F", "Max")] // Larger values take precedence (and remove the bits from consideration.) [InlineData(AttributeTargets.Class | AttributeTargets.Delegate, "F", "Class, Delegate")] // [Flags] attribute public static void TestFormat(Enum e, string format, string expected) { string s = e.ToString(format); Assert.Equal(expected, s); } [Fact] public static void TestFormatMultipleMatches() { string s = ((SimpleEnum)3).ToString("F"); Assert.True(s == "Green" || s == "Green_a" || s == "Green_b"); s = ((SimpleEnum)3).ToString("G"); Assert.True(s == "Green" || s == "Green_a" || s == "Green_b"); } [Theory] [InlineData(SimpleEnum.Red, "Red")] [InlineData(1, "Red")] // Underlying integral public static void TestFormat(object value, string expected) { string s = Enum.Format(typeof(SimpleEnum), value, "F"); Assert.Equal(expected, s); } [Fact] public static void TestFormatInvalid() { Assert.Throws<ArgumentNullException>("enumType", () => Enum.Format(null, (Int32Enum)1, "F")); // Enum type is null Assert.Throws<ArgumentNullException>("value", () => Enum.Format(typeof(SimpleEnum), null, "F")); // Value is null Assert.Throws<ArgumentException>("enumType", () => Enum.Format(typeof(object), 1, "F")); // Enum type is not an enum type Assert.Throws<ArgumentException>(null, () => Enum.Format(typeof(SimpleEnum), (Int32Enum)1, "F")); // Value is of the wrong enum type Assert.Throws<ArgumentException>(null, () => Enum.Format(typeof(SimpleEnum), (short)1, "F")); // Value is of the wrong integral Assert.Throws<ArgumentException>(null, () => Enum.Format(typeof(SimpleEnum), "Red", "F")); // Value is of the wrong integral } private enum SimpleEnum { Red = 1, Blue = 2, Green = 3, Green_a = 3, Green_b = 3 } private enum ByteEnum : byte { Min = byte.MinValue, One = 1, Two = 2, Max = byte.MaxValue, } private enum SByteEnum : sbyte { Min = sbyte.MinValue, One = 1, Two = 2, Max = sbyte.MaxValue, } private enum UInt16Enum : ushort { Min = ushort.MinValue, One = 1, Two = 2, Max = ushort.MaxValue, } private enum Int16Enum : short { Min = short.MinValue, One = 1, Two = 2, Max = short.MaxValue, } private enum UInt32Enum : uint { Min = uint.MinValue, One = 1, Two = 2, Max = uint.MaxValue, } private enum Int32Enum : int { Min = int.MinValue, One = 1, Two = 2, Max = int.MaxValue, } private enum UInt64Enum : ulong { Min = ulong.MinValue, One = 1, Two = 2, Max = ulong.MaxValue, } private enum Int64Enum : long { Min = long.MinValue, One = 1, Two = 2, Max = long.MaxValue, } }
/* part of Pyrolite, by Irmen de Jong (irmen@razorvine.net) */ using System; using System.Collections; namespace Razorvine.Pickle.Objects { /// <summary> /// Creates arrays of objects. Returns a primitive type array such as int[] if /// the objects are ints, etc. /// </summary> public class ArrayConstructor : IObjectConstructor { public object construct(object[] args) { // args for array constructor: [ string typecode, ArrayList values ] // or: [ constructor_class, typecode, machinecode_type, byte[] ] (this form is not supported yet) if (args.Length==4) { ArrayConstructor constructor = (ArrayConstructor) args[0]; char arraytype = ((string) args[1])[0]; int machinecodeType = (int) args[2]; byte[] data = (byte[]) args[3]; return constructor.construct(arraytype, machinecodeType, data); } if (args.Length != 2) { throw new PickleException("invalid pickle data for array; expected 2 args, got "+args.Length); } string typecode = (string) args[0]; ArrayList values = (ArrayList)args[1]; switch (typecode[0]) { case 'c':// character 1 -> char[] case 'u':// Unicode character 2 -> char[] { char[] result = new char[values.Count]; int i = 0; foreach(var c in values) { result[i++] = ((string) c)[0]; } return result; } case 'b':// signed char -> sbyte[] { sbyte[] result = new sbyte[values.Count]; int i = 0; foreach(var c in values) { result[i++] = Convert.ToSByte(c); } return result; } case 'B':// unsigned char -> byte[] { byte[] result = new byte[values.Count]; int i = 0; foreach(var c in values) { result[i++] = Convert.ToByte(c); } return result; } case 'h':// signed short -> short[] { short[] result = new short[values.Count]; int i = 0; foreach(var c in values) { result[i++] = Convert.ToInt16(c); } return result; } case 'H':// unsigned short -> ushort[] { ushort[] result = new ushort[values.Count]; int i = 0; foreach(var c in values) { result[i++] = Convert.ToUInt16(c); } return result; } case 'i':// signed integer -> int[] { int[] result = new int[values.Count]; int i = 0; foreach(var c in values) { result[i++] = Convert.ToInt32(c); } return result; } case 'I':// unsigned integer 4 -> uint[] { uint[] result = new uint[values.Count]; int i = 0; foreach(var c in values) { result[i++] = Convert.ToUInt32(c); } return result; } case 'l':// signed long -> long[] { long[] result = new long[values.Count]; int i = 0; foreach(var c in values) { result[i++] = Convert.ToInt64(c); } return result; } case 'L':// unsigned long -> ulong[] { ulong[] result = new ulong[values.Count]; int i = 0; foreach(var c in values) { result[i++] = Convert.ToUInt64(c); } return result; } case 'f':// floating point 4 -> float[] { float[] result = new float[values.Count]; int i = 0; foreach(var c in values) { result[i++] = Convert.ToSingle(c); } return result; } case 'd':// floating point 8 -> double[] { double[] result = new double[values.Count]; int i = 0; foreach(var c in values) { result[i++] = Convert.ToDouble(c); } return result; } default: throw new PickleException("invalid array typecode: " + typecode); } } /** * Create an object based on machine code type */ public Object construct(char typecode, int machinecode, byte[] data) { // Machine format codes. // Search for "enum machine_format_code" in Modules/arraymodule.c to get // the authoritative values. // UNKNOWN_FORMAT = -1 // UNSIGNED_INT8 = 0 // SIGNED_INT8 = 1 // UNSIGNED_INT16_LE = 2 // UNSIGNED_INT16_BE = 3 // SIGNED_INT16_LE = 4 // SIGNED_INT16_BE = 5 // UNSIGNED_INT32_LE = 6 // UNSIGNED_INT32_BE = 7 // SIGNED_INT32_LE = 8 // SIGNED_INT32_BE = 9 // UNSIGNED_INT64_LE = 10 // UNSIGNED_INT64_BE = 11 // SIGNED_INT64_LE = 12 // SIGNED_INT64_BE = 13 // IEEE_754_FLOAT_LE = 14 // IEEE_754_FLOAT_BE = 15 // IEEE_754_DOUBLE_LE = 16 // IEEE_754_DOUBLE_BE = 17 // UTF16_LE = 18 // UTF16_BE = 19 // UTF32_LE = 20 // UTF32_BE = 21 if (machinecode < 0) throw new PickleException("unknown machine type format"); switch (typecode) { case 'c':// character 1 -> char[] case 'u':// Unicode character 2 -> char[] { if (machinecode != 18 && machinecode != 19 && machinecode != 20 && machinecode != 21) throw new PickleException("for c/u type must be 18/19/20/21"); if (machinecode == 18 || machinecode == 19) { // utf-16 , 2 bytes if (data.Length % 2 != 0) throw new PickleException("data size alignment error"); return constructCharArrayUTF16(machinecode, data); } else { // utf-32, 4 bytes if (data.Length % 4 != 0) throw new PickleException("data size alignment error"); return constructCharArrayUTF32(machinecode, data); } } case 'b':// signed integer 1 -> sbyte[] { if (machinecode != 1) throw new PickleException("for b type must be 1"); sbyte[] result=new sbyte[data.Length]; Buffer.BlockCopy(data,0,result,0,data.Length); return result; } case 'B':// unsigned integer 1 -> byte[] { if (machinecode != 0) throw new PickleException("for B type must be 0"); return data; } case 'h':// signed integer 2 -> short[] { if (machinecode != 4 && machinecode != 5) throw new PickleException("for h type must be 4/5"); if (data.Length % 2 != 0) throw new PickleException("data size alignment error"); return constructShortArraySigned(machinecode, data); } case 'H':// unsigned integer 2 -> ushort[] { if (machinecode != 2 && machinecode != 3) throw new PickleException("for H type must be 2/3"); if (data.Length % 2 != 0) throw new PickleException("data size alignment error"); return constructUShortArrayFromUShort(machinecode, data); } case 'i':// signed integer 4 -> int[] { if (machinecode != 8 && machinecode != 9) throw new PickleException("for i type must be 8/9"); if (data.Length % 4 != 0) throw new PickleException("data size alignment error"); return constructIntArrayFromInt32(machinecode, data); } case 'l':// signed integer 4/8 -> int[]/long[] { if (machinecode != 8 && machinecode != 9 && machinecode != 12 && machinecode != 13) throw new PickleException("for l type must be 8/9/12/13"); if ((machinecode==8 || machinecode==9) && (data.Length % 4 != 0)) throw new PickleException("data size alignment error"); if ((machinecode==12 || machinecode==13) && (data.Length % 8 != 0)) throw new PickleException("data size alignment error"); if(machinecode==8 || machinecode==9) { //32 bits return constructIntArrayFromInt32(machinecode, data); } else { //64 bits return constructLongArrayFromInt64(machinecode, data); } } case 'I':// unsigned integer 4 -> uint[] { if (machinecode != 6 && machinecode != 7) throw new PickleException("for I type must be 6/7"); if (data.Length % 4 != 0) throw new PickleException("data size alignment error"); return constructUIntArrayFromUInt32(machinecode, data); } case 'L':// unsigned integer 4/8 -> uint[]/ulong[] { if (machinecode != 6 && machinecode != 7 && machinecode != 10 && machinecode != 11) throw new PickleException("for L type must be 6/7/10/11"); if ((machinecode==6 || machinecode==7) && (data.Length % 4 != 0)) throw new PickleException("data size alignment error"); if ((machinecode==10 || machinecode==11) && (data.Length % 8 != 0)) throw new PickleException("data size alignment error"); if(machinecode==6 || machinecode==7) { // 32 bits return constructUIntArrayFromUInt32(machinecode, data); } else { // 64 bits return constructULongArrayFromUInt64(machinecode, data); } } case 'f':// floating point 4 -> float[] { if (machinecode != 14 && machinecode != 15) throw new PickleException("for f type must be 14/15"); if (data.Length % 4 != 0) throw new PickleException("data size alignment error"); return constructFloatArray(machinecode, data); } case 'd':// floating point 8 -> double[] { if (machinecode != 16 && machinecode != 17) throw new PickleException("for d type must be 16/17"); if (data.Length % 8 != 0) throw new PickleException("data size alignment error"); return constructDoubleArray(machinecode, data); } default: throw new PickleException("invalid array typecode: " + typecode); } } protected int[] constructIntArrayFromInt32(int machinecode, byte[] data) { int[] result=new int[data.Length/4]; byte[] bigendian=new byte[4]; for(int i=0; i<data.Length/4; i++) { if(machinecode==8) { result[i]=PickleUtils.bytes_to_integer(data, i*4, 4); } else { // big endian, swap bigendian[0]=data[3+i*4]; bigendian[1]=data[2+i*4]; bigendian[2]=data[1+i*4]; bigendian[3]=data[0+i*4]; result[i]=PickleUtils.bytes_to_integer(bigendian); } } return result; } protected uint[] constructUIntArrayFromUInt32(int machinecode, byte[] data) { uint[] result=new uint[data.Length/4]; byte[] bigendian=new byte[4]; for(int i=0; i<data.Length/4; i++) { if(machinecode==6) { result[i]=PickleUtils.bytes_to_uint(data, i*4); } else { // big endian, swap bigendian[0]=data[3+i*4]; bigendian[1]=data[2+i*4]; bigendian[2]=data[1+i*4]; bigendian[3]=data[0+i*4]; result[i]=PickleUtils.bytes_to_uint(bigendian, 0); } } return result; } protected ulong[] constructULongArrayFromUInt64(int machinecode, byte[] data) { ulong[] result=new ulong[data.Length/8]; byte[] swapped=new byte[8]; if(BitConverter.IsLittleEndian) { for(int i=0; i<data.Length/8; i++) { if(machinecode==10) { result[i]=BitConverter.ToUInt64(data, i*8); } else { swapped[0]=data[7+i*8]; swapped[1]=data[6+i*8]; swapped[2]=data[5+i*8]; swapped[3]=data[4+i*8]; swapped[4]=data[3+i*8]; swapped[5]=data[2+i*8]; swapped[6]=data[1+i*8]; swapped[7]=data[0+i*8]; result[i]=BitConverter.ToUInt64(swapped, 0); } } } else { for(int i=0; i<data.Length/8; i++) { if(machinecode==11) { result[i]=BitConverter.ToUInt64(data, i*8); } else { swapped[0]=data[7+i*8]; swapped[1]=data[6+i*8]; swapped[2]=data[5+i*8]; swapped[3]=data[4+i*8]; swapped[4]=data[3+i*8]; swapped[5]=data[2+i*8]; swapped[6]=data[1+i*8]; swapped[7]=data[0+i*8]; result[i]=BitConverter.ToUInt64(swapped, 0); } } } return result; } protected long[] constructLongArrayFromInt64(int machinecode, byte[] data) { long[] result=new long[data.Length/8]; byte[] bigendian=new byte[8]; for(int i=0; i<data.Length/8; i++) { if(machinecode==12) { // little endian can go result[i]=PickleUtils.bytes_to_long(data, i*8); } else { // 13=big endian, swap bigendian[0]=data[7+i*8]; bigendian[1]=data[6+i*8]; bigendian[2]=data[5+i*8]; bigendian[3]=data[4+i*8]; bigendian[4]=data[3+i*8]; bigendian[5]=data[2+i*8]; bigendian[6]=data[1+i*8]; bigendian[7]=data[0+i*8]; result[i]=PickleUtils.bytes_to_long(bigendian, 0); } } return result; } protected double[] constructDoubleArray(int machinecode, byte[] data) { double[] result = new double[data.Length / 8]; byte[] bigendian=new byte[8]; for (int i = 0; i < data.Length / 8; ++i) { if(machinecode==16) { result[i] = PickleUtils.bytes_to_double(data, i * 8); } else { // 17=big endian, flip the bytes bigendian[0]=data[7+i*8]; bigendian[1]=data[6+i*8]; bigendian[2]=data[5+i*8]; bigendian[3]=data[4+i*8]; bigendian[4]=data[3+i*8]; bigendian[5]=data[2+i*8]; bigendian[6]=data[1+i*8]; bigendian[7]=data[0+i*8]; result[i] = PickleUtils.bytes_to_double(bigendian, 0); } } return result; } protected float[] constructFloatArray(int machinecode, byte[] data) { float[] result = new float[data.Length / 4]; byte[] bigendian=new byte[4]; for (int i = 0; i < data.Length / 4; ++i) { if (machinecode == 14) { result[i] = PickleUtils.bytes_to_float(data, i * 4); } else { // 15=big endian, flip the bytes bigendian[0]=data[3+i*4]; bigendian[1]=data[2+i*4]; bigendian[2]=data[1+i*4]; bigendian[3]=data[0+i*4]; result[i] = PickleUtils.bytes_to_float(bigendian, 0); } } return result; } protected ushort[] constructUShortArrayFromUShort(int machinecode, byte[] data) { ushort[] result = new ushort[data.Length / 2]; for(int i=0; i<data.Length/2; ++i) { ushort b1=data[0+i*2]; ushort b2=data[1+i*2]; if(machinecode==2) { result[i] = (ushort)((b2<<8) | b1); } else { // big endian result[i] = (ushort)((b1<<8) | b2); } } return result; } protected short[] constructShortArraySigned(int machinecode, byte[] data) { short[] result = new short[data.Length / 2]; byte[] swapped=new byte[2]; if(BitConverter.IsLittleEndian) { for(int i=0; i<data.Length/2; ++i) { if(machinecode==4) { result[i]=BitConverter.ToInt16(data, i*2); } else { swapped[0]=data[1+i*2]; swapped[1]=data[0+i*2]; result[i]=BitConverter.ToInt16(swapped,0); } } } else { // big endian for(int i=0; i<data.Length/2; ++i) { if(machinecode==5) { result[i]=BitConverter.ToInt16(data, i*2); } else { swapped[0]=data[1+i*2]; swapped[1]=data[0+i*2]; result[i]=BitConverter.ToInt16(swapped,0); } } } return result; } protected char[] constructCharArrayUTF32(int machinecode, byte[] data) { char[] result = new char[data.Length / 4]; byte[] bigendian=new byte[4]; for (int index = 0; index < data.Length / 4; ++index) { if (machinecode == 20) { int codepoint=PickleUtils.bytes_to_integer(data, index*4, 4); string cc=char.ConvertFromUtf32(codepoint); if(cc.Length>1) throw new PickleException("cannot process UTF-32 character codepoint "+codepoint); result[index] = cc[0]; } else { // big endian, swap bigendian[0]=data[3+index*4]; bigendian[1]=data[2+index*4]; bigendian[2]=data[1+index*4]; bigendian[3]=data[index*4]; int codepoint=PickleUtils.bytes_to_integer(bigendian); string cc=char.ConvertFromUtf32(codepoint); if(cc.Length>1) throw new PickleException("cannot process UTF-32 character codepoint "+codepoint); result[index] = cc[0]; } } return result; } protected char[] constructCharArrayUTF16(int machinecode, byte[] data) { char[] result = new char[data.Length / 2]; byte[] bigendian=new byte[2]; for (int index = 0; index < data.Length / 2; ++index) { if (machinecode == 18) { result[index] = (char) PickleUtils.bytes_to_integer(data, index*2, 2); } else { // big endian, swap bigendian[0]=data[1+index*2]; bigendian[1]=data[0+index*2]; result[index] = (char) PickleUtils.bytes_to_integer(bigendian); } } return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.InteropServices.WindowsRuntime; using System.Security; using System.Threading; using Windows.Foundation; using Windows.UI.Core; using System.Diagnostics.Tracing; namespace System.Threading { #if FEATURE_APPX [WindowsRuntimeImport] [Guid("DFA2DC9C-1A2D-4917-98F2-939AF1D6E0C8")] public delegate void DispatcherQueueHandler(); public enum DispatcherQueuePriority { Low = -10, Normal = 0, High = 10 } [ComImport] [WindowsRuntimeImport] [Guid("603E88E4-A338-4FFE-A457-A5CFB9CEB899")] internal interface IDispatcherQueue { // This returns a DispatcherQueueTimer but we don't use this method, so I // just made it 'object' to avoid declaring it. object CreateTimer(); bool TryEnqueue(DispatcherQueueHandler callback); bool TryEnqueue(DispatcherQueuePriority priority, DispatcherQueueHandler callback); } #region class WinRTSynchronizationContextFactory internal sealed class WinRTSynchronizationContextFactory : WinRTSynchronizationContextFactoryBase { // // It's important that we always return the same SynchronizationContext object for any particular ICoreDispatcher // object, as long as any existing instance is still reachable. This allows reference equality checks against the // SynchronizationContext to determine if two instances represent the same dispatcher. Async frameworks rely on this. // To accomplish this, we use a ConditionalWeakTable to track which instances of WinRTSynchronizationContext are bound // to each ICoreDispatcher instance. // private static readonly ConditionalWeakTable<CoreDispatcher, WinRTCoreDispatcherBasedSynchronizationContext> s_coreDispatcherContextCache = new ConditionalWeakTable<CoreDispatcher, WinRTCoreDispatcherBasedSynchronizationContext>(); private static readonly ConditionalWeakTable<IDispatcherQueue, WinRTDispatcherQueueBasedSynchronizationContext> s_dispatcherQueueContextCache = new ConditionalWeakTable<IDispatcherQueue, WinRTDispatcherQueueBasedSynchronizationContext>(); public override SynchronizationContext Create(object dispatcherObj) { Debug.Assert(dispatcherObj != null); Debug.Assert(dispatcherObj is CoreDispatcher || dispatcherObj is IDispatcherQueue); if (dispatcherObj is CoreDispatcher) { // // Get the RCW for the dispatcher // CoreDispatcher dispatcher = (CoreDispatcher)dispatcherObj; // // The dispatcher is supposed to belong to this thread // Debug.Assert(dispatcher == CoreWindow.GetForCurrentThread().Dispatcher); Debug.Assert(dispatcher.HasThreadAccess); // // Get the WinRTSynchronizationContext instance that represents this CoreDispatcher. // return s_coreDispatcherContextCache.GetValue(dispatcher, _dispatcher => new WinRTCoreDispatcherBasedSynchronizationContext(_dispatcher)); } else // dispatcherObj is IDispatcherQueue { // // Get the RCW for the dispatcher // IDispatcherQueue dispatcherQueue = (IDispatcherQueue)dispatcherObj; // // Get the WinRTSynchronizationContext instance that represents this IDispatcherQueue. // return s_dispatcherQueueContextCache.GetValue(dispatcherQueue, _dispatcherQueue => new WinRTDispatcherQueueBasedSynchronizationContext(_dispatcherQueue)); } } } #endregion class WinRTSynchronizationContextFactory #region class WinRTSynchronizationContext internal sealed class WinRTCoreDispatcherBasedSynchronizationContext : WinRTSynchronizationContextBase { private readonly CoreDispatcher _dispatcher; internal WinRTCoreDispatcherBasedSynchronizationContext(CoreDispatcher dispatcher) { _dispatcher = dispatcher; } public override void Post(SendOrPostCallback d, object state) { if (d == null) throw new ArgumentNullException("d"); Contract.EndContractBlock(); var ignored = _dispatcher.RunAsync(CoreDispatcherPriority.Normal, new Invoker(d, state).Invoke); } public override SynchronizationContext CreateCopy() { return new WinRTCoreDispatcherBasedSynchronizationContext(_dispatcher); } } internal sealed class WinRTDispatcherQueueBasedSynchronizationContext : WinRTSynchronizationContextBase { private readonly IDispatcherQueue _dispatcherQueue; internal WinRTDispatcherQueueBasedSynchronizationContext(IDispatcherQueue dispatcherQueue) { _dispatcherQueue = dispatcherQueue; } public override void Post(SendOrPostCallback d, object state) { if (d == null) throw new ArgumentNullException("d"); Contract.EndContractBlock(); // We explicitly choose to ignore the return value here. This enqueue operation might fail if the // dispatcher queue was shut down before we got here. In that case, we choose to just move on and // pretend nothing happened. var ignored = _dispatcherQueue.TryEnqueue(DispatcherQueuePriority.Normal, new Invoker(d, state).Invoke); } public override SynchronizationContext CreateCopy() { return new WinRTDispatcherQueueBasedSynchronizationContext(_dispatcherQueue); } } internal abstract class WinRTSynchronizationContextBase : SynchronizationContext { #region class WinRTSynchronizationContext.Invoker protected class Invoker { private readonly ExecutionContext _executionContext; private readonly SendOrPostCallback _callback; private readonly object _state; private static readonly ContextCallback s_contextCallback = new ContextCallback(InvokeInContext); private delegate void DelEtwFireThreadTransferSendObj(object id, int kind, string info, bool multiDequeues); private delegate void DelEtwFireThreadTransferObj(object id, int kind, string info); private static DelEtwFireThreadTransferSendObj s_EtwFireThreadTransferSendObj; private static DelEtwFireThreadTransferObj s_EtwFireThreadTransferReceiveObj; private static DelEtwFireThreadTransferObj s_EtwFireThreadTransferReceiveHandledObj; private static volatile bool s_TriedGetEtwDelegates; public Invoker(SendOrPostCallback callback, object state) { _executionContext = ExecutionContext.Capture(); _callback = callback; _state = state; if (FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer)) EtwFireThreadTransferSendObj(this); } public void Invoke() { if (FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer)) EtwFireThreadTransferReceiveObj(this); if (_executionContext == null) InvokeCore(); else ExecutionContext.Run(_executionContext, s_contextCallback, this); // If there was an ETW event that fired at the top of the winrt event handling loop, ETW listeners could // use it as a marker of completion of the previous request. Since such an event does not exist we need to // fire the "done handling off-thread request" event in order to enable correct work item assignment. if (FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer)) EtwFireThreadTransferReceiveHandledObj(this); } private static void InvokeInContext(object thisObj) { ((Invoker)thisObj).InvokeCore(); } private void InvokeCore() { try { _callback(_state); } catch (Exception ex) { // // If we let exceptions propagate to CoreDispatcher, it will swallow them with the idea that someone will // observe them later using the IAsyncInfo returned by CoreDispatcher.RunAsync. However, we ignore // that IAsyncInfo, because there's nothing Post can do with it (since Post returns void). // So, to avoid these exceptions being lost forever, we post them to the ThreadPool. // if (!(ex is ThreadAbortException) && !(ex is AppDomainUnloadedException)) { if (!WindowsRuntimeMarshal.ReportUnhandledError(ex)) { var edi = ExceptionDispatchInfo.Capture(ex); ThreadPool.QueueUserWorkItem(o => ((ExceptionDispatchInfo)o).Throw(), edi); } } } } #region ETW Activity-tracing support private static void InitEtwMethods() { Type fest = typeof(FrameworkEventSource); var mi1 = fest.GetMethod("ThreadTransferSendObj", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); var mi2 = fest.GetMethod("ThreadTransferReceiveObj", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); var mi3 = fest.GetMethod("ThreadTransferReceiveHandledObj", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); if (mi1 != null && mi2 != null && mi3 != null) { s_EtwFireThreadTransferSendObj = (DelEtwFireThreadTransferSendObj)mi1.CreateDelegate(typeof(DelEtwFireThreadTransferSendObj), FrameworkEventSource.Log); s_EtwFireThreadTransferReceiveObj = (DelEtwFireThreadTransferObj)mi2.CreateDelegate(typeof(DelEtwFireThreadTransferObj), FrameworkEventSource.Log); s_EtwFireThreadTransferReceiveHandledObj = (DelEtwFireThreadTransferObj)mi3.CreateDelegate(typeof(DelEtwFireThreadTransferObj), FrameworkEventSource.Log); } s_TriedGetEtwDelegates = true; } private static void EtwFireThreadTransferSendObj(object id) { if (!s_TriedGetEtwDelegates) InitEtwMethods(); if (s_EtwFireThreadTransferSendObj != null) s_EtwFireThreadTransferSendObj(id, 3, string.Empty, false); } private static void EtwFireThreadTransferReceiveObj(object id) { if (!s_TriedGetEtwDelegates) InitEtwMethods(); if (s_EtwFireThreadTransferReceiveObj != null) s_EtwFireThreadTransferReceiveObj(id, 3, string.Empty); } private static void EtwFireThreadTransferReceiveHandledObj(object id) { if (!s_TriedGetEtwDelegates) InitEtwMethods(); if (s_EtwFireThreadTransferReceiveHandledObj != null) s_EtwFireThreadTransferReceiveHandledObj(id, 3, string.Empty); } #endregion ETW Activity-tracing support } #endregion class WinRTSynchronizationContext.Invoker public override void Send(SendOrPostCallback d, object state) { throw new NotSupportedException(SR.InvalidOperation_SendNotSupportedOnWindowsRTSynchronizationContext); } } #endregion class WinRTSynchronizationContext #endif //FEATURE_APPX } // namespace
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Services.Interfaces; using System; using System.Collections; using System.Net; using System.Reflection; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Server.Handlers.Simulation { public class ObjectHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private ISimulationService m_SimulationService; public ObjectHandler() { } public ObjectHandler(ISimulationService sim) { m_SimulationService = sim; } public Hashtable Handler(Hashtable request) { //m_log.Debug("[CONNECTION DEBUGGING]: ObjectHandler Called"); //m_log.Debug("---------------------------"); //m_log.Debug(" >> uri=" + request["uri"]); //m_log.Debug(" >> content-type=" + request["content-type"]); //m_log.Debug(" >> http-method=" + request["http-method"]); //m_log.Debug("---------------------------\n"); Hashtable responsedata = new Hashtable(); responsedata["content_type"] = "text/html"; UUID objectID; UUID regionID; string action; if (!Utils.GetParams((string)request["uri"], out objectID, out regionID, out action)) { m_log.InfoFormat("[OBJECT HANDLER]: Invalid parameters for object message {0}", request["uri"]); responsedata["int_response_code"] = 404; responsedata["str_response_string"] = "false"; return responsedata; } try { // Next, let's parse the verb string method = (string)request["http-method"]; if (method.Equals("POST")) { DoObjectPost(request, responsedata, regionID); return responsedata; } //else if (method.Equals("DELETE")) //{ // DoObjectDelete(request, responsedata, agentID, action, regionHandle); // return responsedata; //} else { m_log.InfoFormat("[OBJECT HANDLER]: method {0} not supported in object message", method); responsedata["int_response_code"] = HttpStatusCode.MethodNotAllowed; responsedata["str_response_string"] = "Method not allowed"; return responsedata; } } catch (Exception e) { m_log.WarnFormat("[OBJECT HANDLER]: Caught exception {0}", e.StackTrace); responsedata["int_response_code"] = HttpStatusCode.InternalServerError; responsedata["str_response_string"] = "Internal server error"; return responsedata; } } // subclasses can override this protected virtual bool CreateObject(GridRegion destination, Vector3 newPosition, ISceneObject sog) { return m_SimulationService.CreateObject(destination, newPosition, sog, false); } protected void DoObjectPost(Hashtable request, Hashtable responsedata, UUID regionID) { OSDMap args = Utils.GetOSDMap((string)request["body"]); if (args == null) { responsedata["int_response_code"] = 400; responsedata["str_response_string"] = "false"; return; } // retrieve the input arguments int x = 0, y = 0; UUID uuid = UUID.Zero; string regionname = string.Empty; Vector3 newPosition = Vector3.Zero; if (args.ContainsKey("destination_x") && args["destination_x"] != null) Int32.TryParse(args["destination_x"].AsString(), out x); if (args.ContainsKey("destination_y") && args["destination_y"] != null) Int32.TryParse(args["destination_y"].AsString(), out y); if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null) UUID.TryParse(args["destination_uuid"].AsString(), out uuid); if (args.ContainsKey("destination_name") && args["destination_name"] != null) regionname = args["destination_name"].ToString(); if (args.ContainsKey("new_position") && args["new_position"] != null) Vector3.TryParse(args["new_position"], out newPosition); GridRegion destination = new GridRegion(); destination.RegionID = uuid; destination.RegionLocX = x; destination.RegionLocY = y; destination.RegionName = regionname; string sogXmlStr = "", extraStr = "", stateXmlStr = ""; if (args.ContainsKey("sog") && args["sog"] != null) sogXmlStr = args["sog"].AsString(); if (args.ContainsKey("extra") && args["extra"] != null) extraStr = args["extra"].AsString(); IScene s = m_SimulationService.GetScene(destination.RegionID); ISceneObject sog = null; try { //m_log.DebugFormat("[OBJECT HANDLER]: received {0}", sogXmlStr); sog = s.DeserializeObject(sogXmlStr); sog.ExtraFromXmlString(extraStr); } catch (Exception ex) { m_log.InfoFormat("[OBJECT HANDLER]: exception on deserializing scene object {0}", ex.Message); responsedata["int_response_code"] = HttpStatusCode.BadRequest; responsedata["str_response_string"] = "Bad request"; return; } if (args.ContainsKey("modified")) sog.HasGroupChanged = args["modified"].AsBoolean(); else sog.HasGroupChanged = false; if ((args["state"] != null) && s.AllowScriptCrossings) { stateXmlStr = args["state"].AsString(); if (stateXmlStr != "") { try { sog.SetState(stateXmlStr, s); } catch (Exception ex) { m_log.InfoFormat("[OBJECT HANDLER]: exception on setting state for scene object {0}", ex.Message); // ignore and continue } } } bool result = false; try { // This is the meaning of POST object result = CreateObject(destination, newPosition, sog); } catch (Exception e) { m_log.DebugFormat("[OBJECT HANDLER]: Exception in CreateObject: {0}", e.StackTrace); } responsedata["int_response_code"] = HttpStatusCode.OK; responsedata["str_response_string"] = result.ToString(); } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Avalonia.Collections; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Controls.Templates; using Avalonia.Data; using Avalonia.Markup.Xaml.Data; using Xunit; namespace Avalonia.Controls.UnitTests.Primitives { public class SelectingItemsControlTests_Multiple { [Fact] public void Setting_SelectedIndex_Should_Add_To_SelectedItems() { var target = new TestSelector { Items = new[] { "foo", "bar" }, Template = Template(), }; target.ApplyTemplate(); target.SelectedIndex = 1; Assert.Equal(new[] { "bar" }, target.SelectedItems.Cast<object>().ToList()); } [Fact] public void Adding_SelectedItems_Should_Set_SelectedIndex() { var target = new TestSelector { Items = new[] { "foo", "bar" }, Template = Template(), }; target.ApplyTemplate(); target.SelectedItems.Add("bar"); Assert.Equal(1, target.SelectedIndex); } [Fact] public void Assigning_SelectedItems_Should_Set_SelectedIndex() { var target = new TestSelector { Items = new[] { "foo", "bar" }, Template = Template(), }; target.ApplyTemplate(); target.SelectedItems = new AvaloniaList<object>("bar"); Assert.Equal(1, target.SelectedIndex); } [Fact] public void Reassigning_SelectedItems_Should_Clear_Selection() { var target = new TestSelector { Items = new[] { "foo", "bar" }, Template = Template(), }; target.ApplyTemplate(); target.SelectedItems.Add("bar"); target.SelectedItems = new AvaloniaList<object>(); Assert.Equal(-1, target.SelectedIndex); Assert.Equal(null, target.SelectedItem); } [Fact] public void Adding_First_SelectedItem_Should_Raise_SelectedIndex_SelectedItem_Changed() { var target = new TestSelector { Items = new[] { "foo", "bar" }, Template = Template(), }; bool indexRaised = false; bool itemRaised = false; target.PropertyChanged += (s, e) => { indexRaised |= e.Property.Name == "SelectedIndex" && (int)e.OldValue == -1 && (int)e.NewValue == 1; itemRaised |= e.Property.Name == "SelectedItem" && (string)e.OldValue == null && (string)e.NewValue == "bar"; }; target.ApplyTemplate(); target.SelectedItems.Add("bar"); Assert.True(indexRaised); Assert.True(itemRaised); } [Fact] public void Adding_Subsequent_SelectedItems_Should_Not_Raise_SelectedIndex_SelectedItem_Changed() { var target = new TestSelector { Items = new[] { "foo", "bar" }, Template = Template(), }; target.ApplyTemplate(); target.SelectedItems.Add("foo"); bool raised = false; target.PropertyChanged += (s, e) => raised |= e.Property.Name == "SelectedIndex" || e.Property.Name == "SelectedItem"; target.SelectedItems.Add("bar"); Assert.False(raised); } [Fact] public void Removing_Last_SelectedItem_Should_Raise_SelectedIndex_Changed() { var target = new TestSelector { Items = new[] { "foo", "bar" }, Template = Template(), }; target.ApplyTemplate(); target.SelectedItems.Add("foo"); bool raised = false; target.PropertyChanged += (s, e) => raised |= e.Property.Name == "SelectedIndex" && (int)e.OldValue == 0 && (int)e.NewValue == -1; target.SelectedItems.RemoveAt(0); Assert.True(raised); } [Fact] public void Adding_SelectedItems_Should_Set_Item_IsSelected() { var items = new[] { new ListBoxItem(), new ListBoxItem(), new ListBoxItem(), }; var target = new TestSelector { Items = items, Template = Template(), }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); target.SelectedItems.Add(items[0]); target.SelectedItems.Add(items[1]); var foo = target.Presenter.Panel.Children[0]; Assert.True(items[0].IsSelected); Assert.True(items[1].IsSelected); Assert.False(items[2].IsSelected); } [Fact] public void Assigning_SelectedItems_Should_Set_Item_IsSelected() { var items = new[] { new ListBoxItem(), new ListBoxItem(), new ListBoxItem(), }; var target = new TestSelector { Items = items, Template = Template(), }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); target.SelectedItems = new AvaloniaList<object> { items[0], items[1] }; Assert.True(items[0].IsSelected); Assert.True(items[1].IsSelected); Assert.False(items[2].IsSelected); } [Fact] public void Removing_SelectedItems_Should_Clear_Item_IsSelected() { var items = new[] { new ListBoxItem(), new ListBoxItem(), new ListBoxItem(), }; var target = new TestSelector { Items = items, Template = Template(), }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); target.SelectedItems.Add(items[0]); target.SelectedItems.Add(items[1]); target.SelectedItems.Remove(items[1]); Assert.True(items[0].IsSelected); Assert.False(items[1].IsSelected); } [Fact] public void Reassigning_SelectedItems_Should_Clear_Item_IsSelected() { var items = new[] { new ListBoxItem(), new ListBoxItem(), new ListBoxItem(), }; var target = new TestSelector { Items = items, Template = Template(), }; target.ApplyTemplate(); target.SelectedItems.Add(items[0]); target.SelectedItems.Add(items[1]); target.SelectedItems = new AvaloniaList<object> { items[0], items[1] }; Assert.False(items[0].IsSelected); Assert.False(items[1].IsSelected); } [Fact] public void Replacing_First_SelectedItem_Should_Update_SelectedItem_SelectedIndex() { var items = new[] { new ListBoxItem(), new ListBoxItem(), new ListBoxItem(), }; var target = new TestSelector { Items = items, Template = Template(), }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); target.SelectedIndex = 1; target.SelectedItems[0] = items[2]; Assert.Equal(2, target.SelectedIndex); Assert.Equal(items[2], target.SelectedItem); Assert.False(items[0].IsSelected); Assert.False(items[1].IsSelected); Assert.True(items[2].IsSelected); } [Fact] public void Range_Select_Should_Select_Range() { var target = new TestSelector { Items = new[] { "foo", "bar", "baz", "qux", "qiz", "lol", }, SelectionMode = SelectionMode.Multiple, Template = Template(), }; target.ApplyTemplate(); target.SelectedIndex = 1; target.SelectRange(3); Assert.Equal(new[] { "bar", "baz", "qux" }, target.SelectedItems.Cast<object>().ToList()); } [Fact] public void Range_Select_Backwards_Should_Select_Range() { var target = new TestSelector { Items = new[] { "foo", "bar", "baz", "qux", "qiz", "lol", }, SelectionMode = SelectionMode.Multiple, Template = Template(), }; target.ApplyTemplate(); target.SelectedIndex = 3; target.SelectRange(1); Assert.Equal(new[] { "qux", "baz", "bar" }, target.SelectedItems.Cast<object>().ToList()); } [Fact] public void Second_Range_Select_Backwards_Should_Select_From_Original_Selection() { var target = new TestSelector { Items = new[] { "foo", "bar", "baz", "qux", "qiz", "lol", }, SelectionMode = SelectionMode.Multiple, Template = Template(), }; target.ApplyTemplate(); target.SelectedIndex = 2; target.SelectRange(5); target.SelectRange(4); Assert.Equal(new[] { "baz", "qux", "qiz" }, target.SelectedItems.Cast<object>().ToList()); } [Fact] public void Suprious_SelectedIndex_Changes_Should_Not_Be_Triggered() { var target = new TestSelector { Items = new[] { "foo", "bar", "baz" }, Template = Template(), }; target.ApplyTemplate(); var selectedIndexes = new List<int>(); target.GetObservable(TestSelector.SelectedIndexProperty).Subscribe(x => selectedIndexes.Add(x)); target.SelectedItems = new AvaloniaList<object> { "bar", "baz" }; target.SelectedItem = "foo"; Assert.Equal(0, target.SelectedIndex); Assert.Equal(new[] { -1, 1, 0 }, selectedIndexes); } /// <summary> /// Tests a problem discovered with ListBox with selection. /// </summary> /// <remarks> /// - Items is bound to DataContext first, followed by say SelectedIndex /// - When the ListBox is removed from the visual tree, DataContext becomes null (as it's /// inherited) /// - This changes Items to null, which changes SelectedIndex to null as there are no /// longer any items /// - However, the news that DataContext is now null hasn't yet reached the SelectedItems /// binding and so the unselection is sent back to the ViewModel /// /// This is a similar problem to that tested by XamlBindingTest.Should_Not_Write_To_Old_DataContext. /// However, that tests a general property binding problem: here we are writing directly /// to the SelectedItems collection - not via a binding - so it's something that the /// binding system cannot solve. Instead we solve it by not clearing SelectedItems when /// DataContext is in the process of changing. /// </remarks> [Fact] public void Should_Not_Write_To_Old_DataContext() { var vm = new OldDataContextViewModel(); var target = new TestSelector(); var itemsBinding = new Binding { Path = "Items", Mode = BindingMode.OneWay, }; var selectedItemsBinding = new Binding { Path = "SelectedItems", Mode = BindingMode.OneWay, }; // Bind Items and SelectedItems to the VM. target.Bind(TestSelector.ItemsProperty, itemsBinding); target.Bind(TestSelector.SelectedItemsProperty, selectedItemsBinding); // Set DataContext and SelectedIndex target.DataContext = vm; target.SelectedIndex = 1; // Make sure SelectedItems are written back to VM. Assert.Equal(new[] { "bar" }, vm.SelectedItems); // Clear DataContext and ensure that SelectedItems is still set in the VM. target.DataContext = null; Assert.Equal(new[] { "bar" }, vm.SelectedItems); // Ensure target's SelectedItems is now clear. Assert.Empty(target.SelectedItems); } [Fact] public void Unbound_SelectedItems_Should_Be_Cleared_When_DataContext_Cleared() { var data = new { Items = new[] { "foo", "bar", "baz" }, }; var target = new TestSelector { DataContext = data, Template = Template(), }; var itemsBinding = new Binding { Path = "Items" }; target.Bind(TestSelector.ItemsProperty, itemsBinding); Assert.Same(data.Items, target.Items); target.SelectedItems.Add("bar"); target.DataContext = null; Assert.Empty(target.SelectedItems); } [Fact] public void Adding_To_SelectedItems_Should_Raise_SelectionChanged() { var items = new[] { "foo", "bar", "baz" }; var target = new TestSelector { DataContext = items, Template = Template(), }; var called = false; target.SelectionChanged += (s, e) => { Assert.Equal(new[] { "bar" }, e.AddedItems.Cast<object>().ToList()); Assert.Empty(e.RemovedItems); called = true; }; target.SelectedItems.Add("bar"); Assert.True(called); } [Fact] public void Removing_From_SelectedItems_Should_Raise_SelectionChanged() { var items = new[] { "foo", "bar", "baz" }; var target = new TestSelector { Items = items, Template = Template(), SelectedItem = "bar", }; var called = false; target.SelectionChanged += (s, e) => { Assert.Equal(new[] { "bar" }, e.RemovedItems.Cast<object>().ToList()); Assert.Empty(e.AddedItems); called = true; }; target.SelectedItems.Remove("bar"); Assert.True(called); } [Fact] public void Assigning_SelectedItems_Should_Raise_SelectionChanged() { var items = new[] { "foo", "bar", "baz" }; var target = new TestSelector { Items = items, Template = Template(), SelectedItem = "bar", }; var called = false; target.SelectionChanged += (s, e) => { Assert.Equal(new[] { "foo", "baz" }, e.AddedItems.Cast<object>()); Assert.Equal(new[] { "bar" }, e.RemovedItems.Cast<object>()); called = true; }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); target.SelectedItems = new AvaloniaList<object>("foo", "baz"); Assert.True(called); } private FuncControlTemplate Template() { return new FuncControlTemplate<SelectingItemsControl>(control => new ItemsPresenter { Name = "PART_ItemsPresenter", [~ItemsPresenter.ItemsProperty] = control[~ItemsControl.ItemsProperty], [~ItemsPresenter.ItemsPanelProperty] = control[~ItemsControl.ItemsPanelProperty], }); } private class TestSelector : SelectingItemsControl { public static readonly new AvaloniaProperty<IList> SelectedItemsProperty = SelectingItemsControl.SelectedItemsProperty; public new IList SelectedItems { get { return base.SelectedItems; } set { base.SelectedItems = value; } } public new SelectionMode SelectionMode { get { return base.SelectionMode; } set { base.SelectionMode = value; } } public void SelectRange(int index) { UpdateSelection(index, true, true); } } private class OldDataContextViewModel { public OldDataContextViewModel() { Items = new List<string> { "foo", "bar" }; SelectedItems = new List<string>(); } public List<string> Items { get; } public List<string> SelectedItems { get; } } } }
// 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 Xunit; namespace System.IO.Tests { public class DirectoryInfo_CreateSubDirectory : FileSystemTest { #region UniversalTests [Fact] public void NullAsPath_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(null)); } [Fact] public void EmptyAsPath_ThrowsArgumentException() { Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(string.Empty)); } [Fact] public void PathAlreadyExistsAsFile() { string path = GetTestFileName(); File.Create(Path.Combine(TestDirectory, path)).Dispose(); Assert.Throws<IOException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(path)); Assert.Throws<IOException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(IOServices.AddTrailingSlashIfNeeded(path))); Assert.Throws<IOException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(IOServices.RemoveTrailingSlash(path))); } [Theory] [InlineData(FileAttributes.Hidden)] [InlineData(FileAttributes.ReadOnly)] [InlineData(FileAttributes.Normal)] public void PathAlreadyExistsAsDirectory(FileAttributes attributes) { string path = GetTestFileName(); DirectoryInfo testDir = Directory.CreateDirectory(Path.Combine(TestDirectory, path)); FileAttributes original = testDir.Attributes; try { testDir.Attributes = attributes; Assert.Equal(testDir.FullName, new DirectoryInfo(TestDirectory).CreateSubdirectory(path).FullName); } finally { testDir.Attributes = original; } } [Fact] public void DotIsCurrentDirectory() { string path = GetTestFileName(); DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(path, ".")); Assert.Equal(IOServices.RemoveTrailingSlash(Path.Combine(TestDirectory, path)), result.FullName); result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(path, ".") + Path.DirectorySeparatorChar); Assert.Equal(IOServices.AddTrailingSlashIfNeeded(Path.Combine(TestDirectory, path)), result.FullName); } [Fact] public void Conflicting_Parent_Directory() { string path = Path.Combine(TestDirectory, GetTestFileName(), "c"); Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(path)); } [Fact] public void DotDotIsParentDirectory() { DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(GetTestFileName(), "..")); Assert.Equal(IOServices.RemoveTrailingSlash(TestDirectory), result.FullName); result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(GetTestFileName(), "..") + Path.DirectorySeparatorChar); Assert.Equal(IOServices.AddTrailingSlashIfNeeded(TestDirectory), result.FullName); } [Fact] public void SubDirectoryIsParentDirectory_ThrowsArgumentException() { Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(TestDirectory, ".."))); Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory + "/path").CreateSubdirectory("../../path2")); } [Fact] public void SubdirectoryOverlappingName_ThrowsArgumentException() { // What we're looking for here is trying to create C:\FooBar under C:\Foo by passing "..\FooBar" DirectoryInfo info = Directory.CreateDirectory(GetTestFilePath()); string overlappingName = ".." + Path.DirectorySeparatorChar + info.Name + "overlap"; Assert.Throws<ArgumentException>(() => info.CreateSubdirectory(overlappingName)); // Now try with an info with a trailing separator info = new DirectoryInfo(info.FullName + Path.DirectorySeparatorChar); Assert.Throws<ArgumentException>(() => info.CreateSubdirectory(overlappingName)); } [Theory, MemberData(nameof(ValidPathComponentNames))] public void ValidPathWithTrailingSlash(string component) { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string path = component + Path.DirectorySeparatorChar; DirectoryInfo result = new DirectoryInfo(testDir.FullName).CreateSubdirectory(path); Assert.Equal(Path.Combine(testDir.FullName, path), result.FullName); Assert.True(Directory.Exists(result.FullName)); // Now try creating subdirectories when the directory info itself has a slash testDir = Directory.CreateDirectory(GetTestFilePath() + Path.DirectorySeparatorChar); result = new DirectoryInfo(testDir.FullName).CreateSubdirectory(path); Assert.Equal(Path.Combine(testDir.FullName, path), result.FullName); Assert.True(Directory.Exists(result.FullName)); } [Theory, MemberData(nameof(ValidPathComponentNames))] public void ValidPathWithoutTrailingSlash(string component) { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string path = component; DirectoryInfo result = new DirectoryInfo(testDir.FullName).CreateSubdirectory(path); Assert.Equal(Path.Combine(testDir.FullName, path), result.FullName); Assert.True(Directory.Exists(result.FullName)); // Now try creating subdirectories when the directory info itself has a slash testDir = Directory.CreateDirectory(GetTestFilePath() + Path.DirectorySeparatorChar); result = new DirectoryInfo(testDir.FullName).CreateSubdirectory(path); Assert.Equal(Path.Combine(testDir.FullName, path), result.FullName); Assert.True(Directory.Exists(result.FullName)); } [Fact] public void ValidPathWithMultipleSubdirectories() { string dirName = Path.Combine(GetTestFileName(), "Test", "Test", "Test"); DirectoryInfo dir = new DirectoryInfo(TestDirectory).CreateSubdirectory(dirName); Assert.Equal(dir.FullName, Path.Combine(TestDirectory, dirName)); } [Fact] public void AllowedSymbols() { string dirName = Path.GetRandomFileName() + "!@#$%^&"; DirectoryInfo dir = new DirectoryInfo(TestDirectory).CreateSubdirectory(dirName); Assert.Equal(dir.FullName, Path.Combine(TestDirectory, dirName)); } #endregion #region PlatformSpecific [Theory, MemberData(nameof(ControlWhiteSpace))] [PlatformSpecific(TestPlatforms.Windows)] public void WindowsControlWhiteSpace_Core(string component) { Assert.Throws<IOException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(component)); } [Theory, MemberData(nameof(SimpleWhiteSpace))] [PlatformSpecific(TestPlatforms.Windows)] public void WindowsSimpleWhiteSpaceThrowsException(string component) { Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(component)); } [Theory, MemberData(nameof(WhiteSpace))] [PlatformSpecific(TestPlatforms.AnyUnix)] // Whitespace as path allowed public void UnixWhiteSpaceAsPath_Allowed(string path) { new DirectoryInfo(TestDirectory).CreateSubdirectory(path); Assert.True(Directory.Exists(Path.Combine(TestDirectory, path))); } [Theory, MemberData(nameof(WhiteSpace))] [PlatformSpecific(TestPlatforms.AnyUnix)] // Trailing whitespace in path treated as significant public void UnixNonSignificantTrailingWhiteSpace(string component) { // Unix treats trailing/prename whitespace as significant and a part of the name. DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string path = IOServices.RemoveTrailingSlash(testDir.Name) + component; DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(path); Assert.True(Directory.Exists(result.FullName)); Assert.NotEqual(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName)); } [ConditionalFact(nameof(UsingNewNormalization))] [PlatformSpecific(TestPlatforms.Windows)] // Extended windows path public void ExtendedPathSubdirectory() { DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath()); Assert.True(testDir.Exists); DirectoryInfo subDir = testDir.CreateSubdirectory("Foo"); Assert.True(subDir.Exists); Assert.StartsWith(IOInputs.ExtendedPrefix, subDir.FullName); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // UNC shares public void UNCPathWithOnlySlashes() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Assert.Throws<ArgumentException>(() => testDir.CreateSubdirectory("//")); } [Fact] public void ParentDirectoryNameAsPrefixShouldThrow() { string randomName = GetTestFileName(); DirectoryInfo di = Directory.CreateDirectory(Path.Combine(TestDirectory, randomName)); Assert.Throws<ArgumentException>(() => di.CreateSubdirectory(Path.Combine("..", randomName + "abc", GetTestFileName()))); } #endregion } }
// <copyright file="DriverContext.cs" company="Objectivity Bespoke Software Specialists"> // Copyright (c) Objectivity Bespoke Software Specialists. All rights reserved. // </copyright> // <license> // The MIT License (MIT) // 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. // </license> namespace Ocaramba { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Configuration; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using NLog; using Ocaramba.Helpers; using Ocaramba.Logger; using Ocaramba.Types; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.IE; using OpenQA.Selenium.Remote; using OpenQA.Selenium.Safari; /// <summary> /// Contains handle to driver and methods for web browser. /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "Driver is disposed on test end")] public partial class DriverContext { #if net47 || net45 private static readonly NLog.Logger Logger = LogManager.GetCurrentClassLogger(); #endif #if netcoreapp3_1 private static readonly NLog.Logger Logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); #endif private readonly Collection<ErrorDetail> verifyMessages = new Collection<ErrorDetail>(); /// <summary> /// Gets or sets the handle to current driver. /// </summary> /// <value> /// The handle to driver. /// </value> private IWebDriver driver; private Microsoft.Edge.SeleniumTools.EdgeDriverService serviceEdgeChromium; private ChromeDriverService serviceChrome; private TestLogger logTest; /// <summary> /// Occurs when [driver options set]. /// </summary> public event EventHandler<DriverOptionsSetEventArgs> DriverOptionsSet; /// <summary> /// Gets instance of Performance PerformanceMeasures class. /// </summary> public PerformanceHelper PerformanceMeasures { get; } = new PerformanceHelper(); /// <summary> /// Gets or sets the test title. /// </summary> /// <value> /// The test title. /// </value> public string TestTitle { get; set; } /// <summary> /// Gets or sets the Environment Browsers from App.config. /// </summary> public string CrossBrowserEnvironment { get; set; } /// <summary> /// Gets Sets Folder name for ScreenShot. /// </summary> public string ScreenShotFolder { get { return FilesHelper.GetFolder(BaseConfiguration.ScreenShotFolder, this.CurrentDirectory); } } /// <summary> /// Gets Sets Folder name for Download. /// </summary> public string DownloadFolder { get { return FilesHelper.GetFolder(BaseConfiguration.DownloadFolder, this.CurrentDirectory); } } /// <summary> /// Gets Sets Folder name for PageSource. /// </summary> public string PageSourceFolder { get { return FilesHelper.GetFolder(BaseConfiguration.PageSourceFolder, this.CurrentDirectory); } } /// <summary> /// Gets or sets a value indicating whether [test failed]. /// </summary> /// <value> /// <c>true</c> if [test failed]; otherwise, <c>false</c>. /// </value> public bool IsTestFailed { get; set; } /// <summary> /// Gets or sets test logger. /// </summary> public TestLogger LogTest { get { return this.logTest ?? (this.logTest = new TestLogger()); } set { this.logTest = value; } } /// <summary> /// Gets driver Handle. /// </summary> public IWebDriver Driver { get { return this.driver; } } /// <summary> /// Gets all verify messages. /// </summary> public Collection<ErrorDetail> VerifyMessages { get { return this.verifyMessages; } } /// <summary> /// Gets or sets directory where assembly files are located. /// </summary> public string CurrentDirectory { get; set; } private FirefoxOptions FirefoxOptions { get { FirefoxOptions options = new FirefoxOptions(); if (!string.IsNullOrEmpty(BaseConfiguration.PathToFirefoxProfile)) { try { var pathToCurrentUserProfiles = BaseConfiguration.PathToFirefoxProfile; // Path to profile var pathsToProfiles = Directory.GetDirectories(pathToCurrentUserProfiles, "*.default", SearchOption.TopDirectoryOnly); options.Profile = new FirefoxProfile(pathsToProfiles[0]); } catch (DirectoryNotFoundException e) { Logger.Error(CultureInfo.CurrentCulture, "problem with loading firefox profile {0}", e.Message); } } options.SetPreference("toolkit.startup.max_resumed_crashes", "999999"); options.SetPreference("network.automatic-ntlm-auth.trusted-uris", BaseConfiguration.Host ?? string.Empty); // retrieving settings from config file NameValueCollection firefoxPreferences = new NameValueCollection(); NameValueCollection firefoxExtensions = new NameValueCollection(); #if net47 || net45 firefoxPreferences = ConfigurationManager.GetSection("FirefoxPreferences") as NameValueCollection; firefoxExtensions = ConfigurationManager.GetSection("FirefoxExtensions") as NameValueCollection; #endif #if netcoreapp3_1 firefoxPreferences = BaseConfiguration.GetNameValueCollectionFromAppsettings("FirefoxPreferences"); firefoxExtensions = BaseConfiguration.GetNameValueCollectionFromAppsettings("FirefoxExtensions"); #endif // preference for downloading files options.SetPreference("browser.download.dir", this.DownloadFolder); options.SetPreference("browser.download.folderList", 2); options.SetPreference("browser.download.managershowWhenStarting", false); options.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/vnd.ms-excel, application/x-msexcel, application/pdf, text/csv, text/html, application/octet-stream"); // disable Firefox's built-in PDF viewer options.SetPreference("pdfjs.disabled", true); // disable Adobe Acrobat PDF preview plugin options.SetPreference("plugin.scan.Acrobat", "99.0"); options.SetPreference("plugin.scan.plid.all", false); options.UseLegacyImplementation = BaseConfiguration.FirefoxUseLegacyImplementation; // set browser proxy for Firefox if (!string.IsNullOrEmpty(BaseConfiguration.Proxy)) { options.Proxy = this.CurrentProxy(); } // if there are any extensions if (firefoxExtensions != null) { // loop through all of them for (var i = 0; i < firefoxExtensions.Count; i++) { Logger.Trace(CultureInfo.CurrentCulture, "Installing extension {0}", firefoxExtensions.GetKey(i)); try { options.Profile.AddExtension(firefoxExtensions.GetKey(i)); } catch (FileNotFoundException) { Logger.Trace(CultureInfo.CurrentCulture, "Installing extension {0}", this.CurrentDirectory + FilesHelper.Separator + firefoxExtensions.GetKey(i)); options.Profile.AddExtension(this.CurrentDirectory + FilesHelper.Separator + firefoxExtensions.GetKey(i)); } } } options = this.AddFirefoxArguments(options); // custom preferences // if there are any settings if (firefoxPreferences == null) { return options; } // loop through all of them for (var i = 0; i < firefoxPreferences.Count; i++) { Logger.Trace(CultureInfo.CurrentCulture, "Set custom preference '{0},{1}'", firefoxPreferences.GetKey(i), firefoxPreferences[i]); // and verify all of them switch (firefoxPreferences[i]) { // if current settings value is "true" case "true": options.SetPreference(firefoxPreferences.GetKey(i), true); break; // if "false" case "false": options.SetPreference(firefoxPreferences.GetKey(i), false); break; // otherwise default: int temp; // an attempt to parse current settings value to an integer. Method TryParse returns True if the attempt is successful (the string is integer) or return False (if the string is just a string and cannot be cast to a number) if (int.TryParse(firefoxPreferences.Get(i), out temp)) { options.SetPreference(firefoxPreferences.GetKey(i), temp); } else { options.SetPreference(firefoxPreferences.GetKey(i), firefoxPreferences[i]); } break; } } return options; } } private ChromeOptions ChromeOptions { get { ChromeOptions options = new ChromeOptions(); // retrieving settings from config file NameValueCollection chromePreferences = null; NameValueCollection chromeExtensions = null; NameValueCollection chromeArguments = null; #if net47 || net45 chromePreferences = ConfigurationManager.GetSection("ChromePreferences") as NameValueCollection; chromeExtensions = ConfigurationManager.GetSection("ChromeExtensions") as NameValueCollection; chromeArguments = ConfigurationManager.GetSection("ChromeArguments") as NameValueCollection; #endif #if netcoreapp3_1 chromePreferences = BaseConfiguration.GetNameValueCollectionFromAppsettings("ChromePreferences"); chromeExtensions = BaseConfiguration.GetNameValueCollectionFromAppsettings("ChromeExtensions"); chromeArguments = BaseConfiguration.GetNameValueCollectionFromAppsettings("chromeArguments"); #endif options.AddUserProfilePreference("profile.default_content_settings.popups", 0); options.AddUserProfilePreference("download.default_directory", this.DownloadFolder); options.AddUserProfilePreference("download.prompt_for_download", false); // set browser proxy for chrome if (!string.IsNullOrEmpty(BaseConfiguration.Proxy)) { options.Proxy = this.CurrentProxy(); } // if there are any extensions if (chromeExtensions != null) { // loop through all of them for (var i = 0; i < chromeExtensions.Count; i++) { Logger.Trace(CultureInfo.CurrentCulture, "Installing extension {0}", chromeExtensions.GetKey(i)); try { options.AddExtension(chromeExtensions.GetKey(i)); } catch (FileNotFoundException) { Logger.Trace(CultureInfo.CurrentCulture, "Installing extension {0}", this.CurrentDirectory + FilesHelper.Separator + chromeExtensions.GetKey(i)); options.AddExtension(this.CurrentDirectory + FilesHelper.Separator + chromeExtensions.GetKey(i)); } } } // if there are any arguments if (chromeArguments != null) { // loop through all of them for (var i = 0; i < chromeArguments.Count; i++) { Logger.Trace(CultureInfo.CurrentCulture, "Setting Chrome Arguments {0}", chromeArguments.GetKey(i)); options.AddArgument(chromeArguments.GetKey(i)); } } // custom preferences // if there are any settings if (chromePreferences == null) { return options; } // loop through all of them for (var i = 0; i < chromePreferences.Count; i++) { Logger.Trace(CultureInfo.CurrentCulture, "Set custom preference '{0},{1}'", chromePreferences.GetKey(i), chromePreferences[i]); // and verify all of them switch (chromePreferences[i]) { // if current settings value is "true" case "true": options.AddUserProfilePreference(chromePreferences.GetKey(i), true); break; // if "false" case "false": options.AddUserProfilePreference(chromePreferences.GetKey(i), false); break; // otherwise default: int temp; // an attempt to parse current settings value to an integer. Method TryParse returns True if the attempt is successful (the string is integer) or return False (if the string is just a string and cannot be cast to a number) if (int.TryParse(chromePreferences.Get(i), out temp)) { options.AddUserProfilePreference(chromePreferences.GetKey(i), temp); } else { options.AddUserProfilePreference(chromePreferences.GetKey(i), chromePreferences[i]); } break; } } return options; } } private InternetExplorerOptions InternetExplorerOptions { get { // retrieving settings from config file NameValueCollection internetExplorerPreferences = null; #if net47 || net45 internetExplorerPreferences = ConfigurationManager.GetSection("InternetExplorerPreferences") as NameValueCollection; #endif #if netcoreapp3_1 internetExplorerPreferences = BaseConfiguration.GetNameValueCollectionFromAppsettings("InternetExplorerPreferences"); #endif var options = new InternetExplorerOptions { EnsureCleanSession = true, IgnoreZoomLevel = true, }; // set browser proxy for IE if (!string.IsNullOrEmpty(BaseConfiguration.Proxy)) { options.Proxy = this.CurrentProxy(); } // custom preferences // if there are any settings if (internetExplorerPreferences == null) { return options; } this.GetInternetExplorerPreferences(internetExplorerPreferences, options); return options; } } private OpenQA.Selenium.Edge.EdgeOptions EdgeOptions { get { var options = new OpenQA.Selenium.Edge.EdgeOptions(); // set browser proxy for Edge if (!string.IsNullOrEmpty(BaseConfiguration.Proxy)) { options.Proxy = this.CurrentProxy(); } options.UseInPrivateBrowsing = true; return options; } } private Microsoft.Edge.SeleniumTools.EdgeOptions EdgeOptionsChromium { get { var options = new Microsoft.Edge.SeleniumTools.EdgeOptions(); // retrieving settings from config file NameValueCollection edgeChromiumPreferences = null; NameValueCollection edgeChromiumExtensions = null; NameValueCollection edgeChromiumArguments = null; #if net47 || net45 edgeChromiumPreferences = ConfigurationManager.GetSection("EdgeChromiumPreferences") as NameValueCollection; edgeChromiumExtensions = ConfigurationManager.GetSection("EdgeChromiumExtensions") as NameValueCollection; edgeChromiumArguments = ConfigurationManager.GetSection("EdgeChromiumArguments") as NameValueCollection; #endif #if netcoreapp3_1 edgeChromiumPreferences = BaseConfiguration.GetNameValueCollectionFromAppsettings("EdgeChromiumPreferences"); edgeChromiumExtensions = BaseConfiguration.GetNameValueCollectionFromAppsettings("EdgeChromiumExtensions"); edgeChromiumArguments = BaseConfiguration.GetNameValueCollectionFromAppsettings("EdgeChromiumArguments"); #endif // set browser proxy for Edge if (!string.IsNullOrEmpty(BaseConfiguration.Proxy)) { options.Proxy = this.CurrentProxy(); } options.UseChromium = true; options.BinaryLocation = BaseConfiguration.EdgeChromiumBrowserExecutableLocation; options.AddAdditionalCapability("useAutomationExtension", false); options.AddExcludedArgument("enable-automation"); // if there are any extensions if (edgeChromiumExtensions != null) { // loop through all of them for (var i = 0; i < edgeChromiumExtensions.Count; i++) { Logger.Trace(CultureInfo.CurrentCulture, "Installing extension {0}", edgeChromiumExtensions.GetKey(i)); try { options.AddExtension(edgeChromiumExtensions.GetKey(i)); } catch (FileNotFoundException) { Logger.Trace(CultureInfo.CurrentCulture, "Installing extension {0}", this.CurrentDirectory + FilesHelper.Separator + edgeChromiumExtensions.GetKey(i)); options.AddExtension(this.CurrentDirectory + FilesHelper.Separator + edgeChromiumExtensions.GetKey(i)); } } } // if there are any arguments if (edgeChromiumArguments != null) { // loop through all of them for (var i = 0; i < edgeChromiumArguments.Count; i++) { Logger.Trace(CultureInfo.CurrentCulture, "Setting Chrome Arguments {0}", edgeChromiumArguments.GetKey(i)); options.AddArgument(edgeChromiumArguments.GetKey(i)); } } // custom preferences // if there are any settings if (edgeChromiumPreferences == null) { return options; } // loop through all of them for (var i = 0; i < edgeChromiumPreferences.Count; i++) { Logger.Trace(CultureInfo.CurrentCulture, "Set custom preference '{0},{1}'", edgeChromiumPreferences.GetKey(i), edgeChromiumPreferences[i]); // and verify all of them switch (edgeChromiumPreferences[i]) { // if current settings value is "true" case "true": options.AddUserProfilePreference(edgeChromiumPreferences.GetKey(i), true); break; // if "false" case "false": options.AddUserProfilePreference(edgeChromiumPreferences.GetKey(i), false); break; // otherwise default: int temp; // an attempt to parse current settings value to an integer. Method TryParse returns True if the attempt is successful (the string is integer) or return False (if the string is just a string and cannot be cast to a number) if (int.TryParse(edgeChromiumPreferences.Get(i), out temp)) { options.AddUserProfilePreference(edgeChromiumPreferences.GetKey(i), temp); } else { options.AddUserProfilePreference(edgeChromiumPreferences.GetKey(i), edgeChromiumPreferences[i]); } break; } } return options; } } private SafariOptions SafariOptions { get { var options = new SafariOptions(); options.AddAdditionalCapability("cleanSession", true); return options; } } /// <summary> /// Takes the screenshot. /// </summary> /// <returns>An image of the page currently loaded in the browser.</returns> public Screenshot TakeScreenshot() { try { var screenshotDriver = (ITakesScreenshot)this.driver; var screenshot = screenshotDriver.GetScreenshot(); return screenshot; } catch (NullReferenceException) { Logger.Error("Test failed but was unable to get webdriver screenshot."); } catch (UnhandledAlertException) { Logger.Error("Test failed but was unable to get webdriver screenshot."); } return null; } /// <summary> /// Starts the specified Driver. /// </summary> /// <exception cref="NotSupportedException">When driver not supported.</exception> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Driver disposed later in stop method")] public void Start() { switch (BaseConfiguration.TestBrowser) { case BrowserType.Firefox: if (!string.IsNullOrEmpty(BaseConfiguration.FirefoxBrowserExecutableLocation)) { this.FirefoxOptions.BrowserExecutableLocation = BaseConfiguration.FirefoxBrowserExecutableLocation; } #if netcoreapp3_1 FirefoxDriverService serviceFirefox = FirefoxDriverService.CreateDefaultService(); serviceFirefox.Host = "::1"; this.driver = string.IsNullOrEmpty(BaseConfiguration.PathToFirefoxDriverDirectory) ? new FirefoxDriver(serviceFirefox, this.SetDriverOptions(this.FirefoxOptions)) : new FirefoxDriver(BaseConfiguration.PathToFirefoxDriverDirectory, this.SetDriverOptions(this.FirefoxOptions)); #endif #if net47 || net45 this.driver = string.IsNullOrEmpty(BaseConfiguration.PathToFirefoxDriverDirectory) ? new FirefoxDriver(this.SetDriverOptions(this.FirefoxOptions)) : new FirefoxDriver(BaseConfiguration.PathToFirefoxDriverDirectory, this.SetDriverOptions(this.FirefoxOptions)); #endif break; case BrowserType.InternetExplorer: case BrowserType.IE: this.driver = string.IsNullOrEmpty(BaseConfiguration.PathToInternetExplorerDriverDirectory) ? new InternetExplorerDriver(this.SetDriverOptions(this.InternetExplorerOptions)) : new InternetExplorerDriver(BaseConfiguration.PathToInternetExplorerDriverDirectory, this.SetDriverOptions(this.InternetExplorerOptions)); break; case BrowserType.Chrome: if (!string.IsNullOrEmpty(BaseConfiguration.ChromeBrowserExecutableLocation)) { this.ChromeOptions.BinaryLocation = BaseConfiguration.ChromeBrowserExecutableLocation; } this.serviceChrome = ChromeDriverService.CreateDefaultService(); this.serviceChrome.LogPath = BaseConfiguration.PathToChromeDriverLog; this.serviceChrome.EnableVerboseLogging = BaseConfiguration.EnableVerboseLoggingChrome; this.driver = string.IsNullOrEmpty(BaseConfiguration.PathToChromeDriverDirectory) ? new ChromeDriver(this.serviceChrome, this.SetDriverOptions(this.ChromeOptions)) : new ChromeDriver(BaseConfiguration.PathToChromeDriverDirectory, this.SetDriverOptions(this.ChromeOptions)); break; case BrowserType.Safari: this.driver = new SafariDriver(this.SetDriverOptions(this.SafariOptions)); this.CheckIfProxySetForSafari(); break; case BrowserType.RemoteWebDriver: this.SetupRemoteWebDriver(); break; case BrowserType.Edge: this.driver = new OpenQA.Selenium.Edge.EdgeDriver(OpenQA.Selenium.Edge.EdgeDriverService.CreateDefaultService(BaseConfiguration.PathToEdgeDriverDirectory, "MicrosoftWebDriver.exe", 52296), this.SetDriverOptions(this.EdgeOptions)); break; case BrowserType.EdgeChromium: this.serviceEdgeChromium = Microsoft.Edge.SeleniumTools.EdgeDriverService.CreateChromiumService(BaseConfiguration.PathToEdgeChromiumDriverDirectory, @"msedgedriver.exe"); this.serviceEdgeChromium.UseVerboseLogging = true; this.driver = new Microsoft.Edge.SeleniumTools.EdgeDriver(this.serviceEdgeChromium, this.SetDriverOptions(this.EdgeOptionsChromium), TimeSpan.FromSeconds(BaseConfiguration.LongTimeout)); break; default: throw new NotSupportedException( string.Format(CultureInfo.CurrentCulture, "Driver {0} is not supported", BaseConfiguration.TestBrowser)); } if (BaseConfiguration.EnableEventFiringWebDriver) { this.driver = new MyEventFiringWebDriver(this.driver); } } /// <summary> /// Maximizes the current window if it is not already maximized. /// </summary> public void WindowMaximize() { this.driver.Manage().Window.Maximize(); } /// <summary> /// Deletes all cookies from the page. /// </summary> public void DeleteAllCookies() { this.driver.Manage().Cookies.DeleteAllCookies(); } /// <summary> /// Stop browser instance. /// </summary> public void Stop() { if (this.serviceEdgeChromium != null) { this.serviceEdgeChromium.Dispose(); } if (this.serviceChrome != null) { this.serviceChrome.Dispose(); } if (this.driver != null) { this.driver.Quit(); } } private void SetupRemoteWebDriver() { NameValueCollection driverCapabilitiesConf = new NameValueCollection(); NameValueCollection settings = new NameValueCollection(); #if net47 || net45 driverCapabilitiesConf = ConfigurationManager.GetSection("DriverCapabilities") as NameValueCollection; settings = ConfigurationManager.GetSection("environments/" + this.CrossBrowserEnvironment) as NameValueCollection; #endif #if netcoreapp3_1 driverCapabilitiesConf = BaseConfiguration.GetNameValueCollectionFromAppsettings("DriverCapabilities"); settings = BaseConfiguration.GetNameValueCollectionFromAppsettings("environments:" + this.CrossBrowserEnvironment); #endif var browserType = this.GetBrowserTypeForRemoteDriver(settings); switch (browserType) { case BrowserType.Firefox: FirefoxOptions firefoxOptions = new FirefoxOptions(); firefoxOptions.Proxy = this.CurrentProxy(); this.SetRemoteDriverBrowserOptions(driverCapabilitiesConf, settings, firefoxOptions); this.driver = new RemoteWebDriver(BaseConfiguration.RemoteWebDriverHub, this.SetDriverOptions(firefoxOptions).ToCapabilities()); break; case BrowserType.Android: case BrowserType.Chrome: ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.Proxy = this.CurrentProxy(); this.SetRemoteDriverBrowserOptions(driverCapabilitiesConf, settings, chromeOptions); this.driver = new RemoteWebDriver(BaseConfiguration.RemoteWebDriverHub, this.SetDriverOptions(chromeOptions).ToCapabilities()); break; case BrowserType.Iphone: case BrowserType.Safari: SafariOptions safariOptions = new SafariOptions(); safariOptions.Proxy = this.CurrentProxy(); this.SetRemoteDriverOptions(driverCapabilitiesConf, settings, safariOptions); this.driver = new RemoteWebDriver(BaseConfiguration.RemoteWebDriverHub, this.SetDriverOptions(safariOptions).ToCapabilities()); break; case BrowserType.Edge: OpenQA.Selenium.Edge.EdgeOptions egEdgeOptions = new OpenQA.Selenium.Edge.EdgeOptions(); egEdgeOptions.Proxy = this.CurrentProxy(); this.SetRemoteDriverOptions(driverCapabilitiesConf, settings, egEdgeOptions); this.driver = new RemoteWebDriver(BaseConfiguration.RemoteWebDriverHub, this.SetDriverOptions(egEdgeOptions).ToCapabilities()); break; case BrowserType.EdgeChromium: Microsoft.Edge.SeleniumTools.EdgeOptions edgeOptionsChromium = new Microsoft.Edge.SeleniumTools.EdgeOptions(); edgeOptionsChromium.Proxy = this.CurrentProxy(); this.SetRemoteDriverBrowserOptions(driverCapabilitiesConf, settings, edgeOptionsChromium); this.driver = new RemoteWebDriver(BaseConfiguration.RemoteWebDriverHub, this.SetDriverOptions(edgeOptionsChromium).ToCapabilities()); break; case BrowserType.IE: case BrowserType.InternetExplorer: InternetExplorerOptions internetExplorerOptions = new InternetExplorerOptions(); internetExplorerOptions.Proxy = this.CurrentProxy(); this.SetRemoteDriverBrowserOptions(driverCapabilitiesConf, settings, internetExplorerOptions); this.driver = new RemoteWebDriver(BaseConfiguration.RemoteWebDriverHub, this.SetDriverOptions(internetExplorerOptions).ToCapabilities()); break; default: throw new NotSupportedException( string.Format(CultureInfo.CurrentCulture, "Driver {0} is not supported", this.CrossBrowserEnvironment)); } } } }
using UnityEditor; using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml; public class UnitySequencerIO { #region Constants const string Machinima = "machinima"; #endregion #region Variables CutsceneEditor m_Timeline; BMLParser m_BMLParser; CutsceneEvent m_UtteranceAudioEvent; #endregion #region Properties CutsceneEditor Timeline { get { return m_Timeline; } } public bool UseMecanimEvents { set { m_BMLParser.EventCategoryName = value ? GenericEventNames.Mecanim : GenericEventNames.SmartBody; } } #endregion #region Functions public UnitySequencerIO(CutsceneEditor sequencer) { m_Timeline = sequencer; m_BMLParser = new BMLParser(OnAddBmlTiming, OnAddVisemeTiming, ParsedBMLEvent, OnFinishedReading, OnParsedCustomEvent); UseMecanimEvents = true; } public void OnAddBmlTiming(BMLParser.BMLTiming bmlTiming) { bool prevVal = Timeline.CreateBMLEvents; Timeline.CreateBMLEvents = true; Timeline.AddBmlTiming(bmlTiming.id, bmlTiming.time, bmlTiming.text); // reset Timeline.CreateBMLEvents = prevVal; } public void OnAddVisemeTiming(BMLParser.LipData lipData) { bool prevVal = Timeline.CreateBMLEvents; Timeline.CreateBMLEvents = true; Timeline.AddVisemeTiming(lipData.viseme, lipData.startTime, lipData.endTime); // reset Timeline.CreateBMLEvents = prevVal; } public bool LoadXMLString(string character, string xmlStr) { return m_BMLParser.LoadXMLString(character, xmlStr); } public bool LoadFile(string filePathAndName) { return m_BMLParser.LoadFile(filePathAndName); } void OnFinishedReading(bool succeeded, List<CutsceneEvent> createdEvents) { // get the name of the character that these events are associated with foreach (CutsceneEvent ce in createdEvents) { CutsceneEventParam characterParam = ce.FindParameter("character"); if (characterParam != null && !string.IsNullOrEmpty(characterParam.stringData)) { m_UtteranceAudioEvent.FindParameter("character").stringData = characterParam.stringData; break; } } // The sendvhmsg events from the parser have the correct timings, so copy them over // for the timeline event to use foreach (CutsceneEvent ce in createdEvents) { if (ce.FunctionName == "SendVHMsg") { CutsceneEvent timeLineEvent = Timeline.FindEventByID(ce.UniqueId); timeLineEvent.StartTime = ce.StartTime; } } } void OnParsedCustomEvent(XmlTextReader reader) { if (reader.Name == Machinima) { float zoom = 0; if (float.TryParse(reader["zoom"], out zoom)) { Timeline.Zoom = zoom; } int numTrackGroups = 0; if (int.TryParse(reader["numGroups"], out numTrackGroups)) { for (int i = Timeline.GroupManager.NumGroups; i < numTrackGroups; i++) { Timeline.AddTrackGroup(); } } } } public void ParsedBMLEvent(XmlTextReader reader, string type, CutsceneEvent ce) { if (ce != null && ce.FunctionName.Contains("SendVHMsg")) { string message = ce.FindParameter("message").stringData; if (message.Contains("vrAgentSpeech partial") || message.Contains("vrSpoke")) { // we don't want these messages return; } } else if (ce != null && ce.FunctionName.Contains("PlayViseme")) { if (reader["messageType"] == "visemeStop") { // we don't want these messages return; } } const float minPosition = TimelineWindow.TrackStartingY + TimelineWindow.TrackHeight * 2; // the first 2 tracks are reserved float eventYPos = minPosition; // the first 2 tracks are reserved if (!string.IsNullOrEmpty(reader["ypos"])) { eventYPos = float.Parse(reader["ypos"]); } if (eventYPos < minPosition) { eventYPos = minPosition; } Vector2 eventPos = new Vector2(Timeline.GetPositionFromTime(Timeline.StartTime, Timeline.EndTime, ce.StartTime, Timeline.m_TrackScrollArea), eventYPos); CutsceneEvent newEvent = Timeline.CreateEventAtPosition(eventPos) as CutsceneEvent; ce.CloneData(newEvent); newEvent.m_UniqueId = ce.UniqueId; newEvent.StartTime = ce.StartTime; Timeline.ChangedCutsceneEventType(ce.EventType, newEvent); Timeline.ChangedEventFunction(newEvent, ce.FunctionName, ce.FunctionOverloadIndex); Timeline.CalculateTimelineLength(); newEvent.GuiPosition.width = Timeline.GetWidthFromTime(newEvent.EndTime, newEvent.GuiPosition.x); newEvent.SetParameters(reader); // try to setup the reference to the character on the event using xml data if (newEvent.EventType == GenericEventNames.SmartBody || newEvent.EventType == GenericEventNames.Mecanim) { CutsceneEventParam characterParam = newEvent.FindParameter("character"); characterParam.SetObjData(ce.FindParameter("character").objData); characterParam.stringData = ce.FindParameter("character").stringData; } // setup the length float length = ce.Length; CutsceneEventParam lengthParam = newEvent.GetLengthParameter(); if (lengthParam != null) { lengthParam.SetLength(length); newEvent.SetEventLengthFromParameter(lengthParam.Name); } if (type == "speech") { m_UtteranceAudioEvent = newEvent; } } public void CreateXml(string filePathAndName, Cutscene cutscene) { StreamWriter outfile = null; for (int i = 0; i < cutscene.CutsceneEvents.Count; i++) { if (cutscene.CutsceneEvents[i].FunctionName == "Marker") { continue; } for (int j = i + 1; j < cutscene.CutsceneEvents.Count; j++) { if (cutscene.CutsceneEvents[i].Name == cutscene.CutsceneEvents[j].Name) { EditorUtility.DisplayDialog("Error", string.Format("You can't have 2 events with the same name \'{0}\'. XML Not Saved!", cutscene.CutsceneEvents[i].Name), "Ok"); return; } } } try { outfile = new StreamWriter(string.Format("{0}", filePathAndName)); outfile.WriteLine(@"<?xml version=""1.0""?>"); outfile.WriteLine(@"<act>"); outfile.WriteLine(@" <bml xmlns:sbm=""http://sourceforge.net/apps/mediawiki/smartbody/index.php?title=SmartBody_BML"" xmlns:mm=""https://confluence.ict.usc.edu/display/VHTK/Home"">"); //outfile.WriteLine(@" <bml xmlns:mm=""https://vhtoolkit.ict.usc.edu/"">"); outfile.WriteLine(string.Format(@" <speech id=""visSeq_3"" ref=""{0}"" type=""application/ssml+xml"" />", Path.GetFileNameWithoutExtension(filePathAndName))); // write out mm cutscene meta data outfile.WriteLine(string.Format(@" <{0} numGroups=""{1}"" numEvents=""{2}"" zoom=""{3}"" />", Machinima, cutscene.GroupManager.NumGroups, cutscene.NumEvents, Timeline.Zoom)); //for (int i = 0; i < cutscene.GroupManager.NumGroups // sort the events by chronological order List<CutsceneEvent> timeSortedEvents = new List<CutsceneEvent>(); timeSortedEvents.AddRange(cutscene.CutsceneEvents); timeSortedEvents.Sort(delegate(CutsceneEvent a, CutsceneEvent b) { return a.StartTime > b.StartTime ? 1 : -1; }); // save out the events foreach (CutsceneEvent ce in timeSortedEvents) { string xmlString = ce.GetXMLString(); if (!string.IsNullOrEmpty(xmlString)) { outfile.WriteLine(string.Format(" {0}", xmlString)); } } outfile.WriteLine(@" </bml>"); outfile.WriteLine(@"</act>"); } catch (Exception e) { Debug.LogError(string.Format("CreateXml failed: {0}", e.Message)); EditorUtility.DisplayDialog("Error", string.Format("An error occured when saving \'{0}\'. XML was not properly saved!", Path.GetFileNameWithoutExtension(filePathAndName)), "Ok"); outfile.WriteLine(@" </bml>"); outfile.WriteLine(@"</act>"); } finally { if (outfile != null) { outfile.Close(); } } } public void ListenToNVBG(bool listen) { VHMsgBase vhmsg = VHMsgBase.Get(); if (vhmsg == null) { Debug.LogError(string.Format("Machinima Maker can't listen to NVBG because there is no VHMsgManager in the scene")); return; } if (listen) { vhmsg.SubscribeMessage("vrSpeak"); vhmsg.RemoveMessageEventHandler(VHMsg_MessageEventHandler); vhmsg.AddMessageEventHandler(VHMsg_MessageEventHandler); } else { vhmsg.RemoveMessageEventHandler(VHMsg_MessageEventHandler); } } void VHMsg_MessageEventHandler(object sender, VHMsgBase.Message message) { Debug.Log("msg received: " + message.s); string[] splitargs = message.s.Split(" ".ToCharArray()); if (splitargs[0] == "vrSpeak") { if (splitargs.Length > 4) { if (splitargs[3].Contains("idle")) { // we don't want random idle fidgets // i.e. vrSpeak Brad all idle-1193041418-823 return; } Cutscene selectedCutscene = Timeline.GetSelectedCutscene(); if (selectedCutscene == null) { EditorUtility.DisplayDialog("Error", "You need to create a cutscene so that NVBG can be listened to", "Ok"); return; } if (EditorUtility.DisplayDialog("Warning", string.Format("Do you want to overwrite cutscene {0} with the message from NVBG. You will lose all the current events?", selectedCutscene.CutsceneName), "Yes", "No")) { //Timeline.AddCutscene(); Timeline.RemoveEvents(selectedCutscene.CutsceneEvents); string character = splitargs[1]; string xml = String.Join(" ", splitargs, 4, splitargs.Length - 4); m_BMLParser.LoadXMLString(character, xml); } } } } #endregion }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsAzureCompositeModelClient { 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; /// <summary> /// Composite Swagger Client that represents merging body complex and /// complex model swagger clients /// </summary> public partial class AzureCompositeModel : ServiceClient<AzureCompositeModel>, IAzureCompositeModel, 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> /// Subscription ID. /// </summary> public string SubscriptionId { 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> /// Gets the IBasicOperations. /// </summary> public virtual IBasicOperations Basic { get; private set; } /// <summary> /// Gets the IPrimitiveOperations. /// </summary> public virtual IPrimitiveOperations Primitive { get; private set; } /// <summary> /// Gets the IArrayOperations. /// </summary> public virtual IArrayOperations Array { get; private set; } /// <summary> /// Gets the IDictionaryOperations. /// </summary> public virtual IDictionaryOperations Dictionary { get; private set; } /// <summary> /// Gets the IInheritanceOperations. /// </summary> public virtual IInheritanceOperations Inheritance { get; private set; } /// <summary> /// Gets the IPolymorphismOperations. /// </summary> public virtual IPolymorphismOperations Polymorphism { get; private set; } /// <summary> /// Gets the IPolymorphicrecursiveOperations. /// </summary> public virtual IPolymorphicrecursiveOperations Polymorphicrecursive { get; private set; } /// <summary> /// Gets the IReadonlypropertyOperations. /// </summary> public virtual IReadonlypropertyOperations Readonlyproperty { get; private set; } /// <summary> /// Initializes a new instance of the AzureCompositeModel class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AzureCompositeModel(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AzureCompositeModel 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 AzureCompositeModel(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AzureCompositeModel 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 AzureCompositeModel(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 AzureCompositeModel 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 AzureCompositeModel(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 AzureCompositeModel 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 AzureCompositeModel(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 AzureCompositeModel 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 AzureCompositeModel(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 AzureCompositeModel 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 AzureCompositeModel(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 AzureCompositeModel 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 AzureCompositeModel(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() { Basic = new BasicOperations(this); Primitive = new PrimitiveOperations(this); Array = new ArrayOperations(this); Dictionary = new DictionaryOperations(this); Inheritance = new InheritanceOperations(this); Polymorphism = new PolymorphismOperations(this); Polymorphicrecursive = new PolymorphicrecursiveOperations(this); Readonlyproperty = new ReadonlypropertyOperations(this); BaseUri = new System.Uri("http://localhost"); SubscriptionId = "123456"; 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() } }; SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<FishInner>("fishtype")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<FishInner>("fishtype")); CustomInitialize(); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } /// <summary> /// Product Types /// </summary> /// <remarks> /// The Products endpoint returns information about the Uber products offered /// at a given location. The response includes the display name and other /// details about each product, and lists the products in the proper display /// order. /// </remarks> /// <param name='resourceGroupName'> /// Resource Group ID. /// </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<CatalogArrayInner>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } string apiVersion = "2014-04-01-preview"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/Microsoft.Cache/Redis").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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<CatalogArrayInner>(); _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<CatalogArrayInner>(_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; } /// <summary> /// Create products /// </summary> /// <remarks> /// Resets products. /// </remarks> /// <param name='subscriptionId'> /// Subscription ID. /// </param> /// <param name='resourceGroupName'> /// Resource Group ID. /// </param> /// <param name='productDictionaryOfArray'> /// Dictionary of Array of product /// </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<CatalogDictionaryInner>> CreateWithHttpMessagesAsync(string subscriptionId, string resourceGroupName, IDictionary<string, IList<ProductInner>> productDictionaryOfArray = default(IDictionary<string, IList<ProductInner>>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (subscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } string apiVersion = "2014-04-01-preview"; CatalogDictionaryOfArray bodyParameter = new CatalogDictionaryOfArray(); if (productDictionaryOfArray != null) { bodyParameter.ProductDictionaryOfArray = productDictionaryOfArray; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("bodyParameter", bodyParameter); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/Microsoft.Cache/Redis").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(subscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("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; if(bodyParameter != null) { _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (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<CatalogDictionaryInner>(); _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<CatalogDictionaryInner>(_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; } /// <summary> /// Update products /// </summary> /// <remarks> /// Resets products. /// </remarks> /// <param name='subscriptionId'> /// Subscription ID. /// </param> /// <param name='resourceGroupName'> /// Resource Group ID. /// </param> /// <param name='productArrayOfDictionary'> /// Array of dictionary of products /// </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<CatalogArrayInner>> UpdateWithHttpMessagesAsync(string subscriptionId, string resourceGroupName, IList<IDictionary<string, ProductInner>> productArrayOfDictionary = default(IList<IDictionary<string, ProductInner>>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (subscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } string apiVersion = "2014-04-01-preview"; CatalogArrayOfDictionary bodyParameter = new CatalogArrayOfDictionary(); if (productArrayOfDictionary != null) { bodyParameter.ProductArrayOfDictionary = productArrayOfDictionary; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("bodyParameter", bodyParameter); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/Microsoft.Cache/Redis").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(subscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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; if(bodyParameter != null) { _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (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<CatalogArrayInner>(); _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<CatalogArrayInner>(_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; } } }
using System; using NUnit.Framework; using System.Collections.ObjectModel; using System.Threading; using System.Threading.Tasks; using Zu.AsyncWebDriver; using Zu.WebBrowser.AsyncInteractions; using Zu.WebBrowser.BasicTypes; namespace Zu.AsyncChromeDriver.Tests { [TestFixture] public class ExecutingAsyncJavascriptTest : DriverTestFixture { private IJavaScriptExecutor executor; private TimeSpan originalTimeout = TimeSpan.MinValue; [SetUp] public async Task SetUpEnvironment() { if (driver is IJavaScriptExecutor scriptExecutor) { executor = scriptExecutor; } try { originalTimeout = await driver.Options().Timeouts.GetAsynchronousJavaScript(); } catch (NotImplementedException) { // For driver implementations that do not support getting timeouts, // just set a default 30-second timeout. originalTimeout = TimeSpan.FromSeconds(30); } await driver.Options().Timeouts.SetAsynchronousJavaScript(TimeSpan.FromSeconds(1)); } [TearDown] public async Task TearDownEnvironment() { await driver.Options().Timeouts.SetAsynchronousJavaScript(originalTimeout); } [Test] public async Task ShouldNotTimeoutIfCallbackInvokedImmediately() { await driver.GoToUrl(ajaxyPage); object result = await executor.ExecuteAsyncScript("arguments[arguments.length - 1](123);"); Assert.That(result, Is.InstanceOf<long>()); Assert.That((long)result, Is.EqualTo(123)); } [Test] public async Task ShouldBeAbleToReturnJavascriptPrimitivesFromAsyncScripts_NeitherNullNorUndefined() { await driver.GoToUrl(ajaxyPage); Assert.That((long)await executor.ExecuteAsyncScript("arguments[arguments.length - 1](123);"), Is.EqualTo(123)); await driver.GoToUrl(ajaxyPage); Assert.That((await executor.ExecuteAsyncScript("arguments[arguments.length - 1]('abc');")).ToString(), Is.EqualTo("abc")); await driver.GoToUrl(ajaxyPage); Assert.That((bool)await executor.ExecuteAsyncScript("arguments[arguments.length - 1](false);"), Is.False); await driver.GoToUrl(ajaxyPage); Assert.That((bool)await executor.ExecuteAsyncScript("arguments[arguments.length - 1](true);"), Is.True); } [Test] public async Task ShouldBeAbleToReturnJavascriptPrimitivesFromAsyncScripts_NullAndUndefined() { await driver.GoToUrl(ajaxyPage); Assert.That(await executor.ExecuteAsyncScript("arguments[arguments.length - 1](null);"), Is.Null); Assert.That(await executor.ExecuteAsyncScript("arguments[arguments.length - 1]();"), Is.Null); } [Test] public async Task ShouldBeAbleToReturnAnArrayLiteralFromAnAsyncScript() { await driver.GoToUrl(ajaxyPage); object result = await executor.ExecuteAsyncScript("arguments[arguments.length - 1]([]);"); Assert.That(result, Is.Not.Null); Assert.That(result, Is.InstanceOf<ReadOnlyCollection<object>>()); Assert.That((ReadOnlyCollection<object>)result, Has.Count.EqualTo(0)); } [Test] public async Task ShouldBeAbleToReturnAnArrayObjectFromAnAsyncScript() { await driver.GoToUrl(ajaxyPage); object result = await executor.ExecuteAsyncScript("arguments[arguments.length - 1](new Array());"); Assert.That(result, Is.Not.Null); Assert.That(result, Is.InstanceOf<ReadOnlyCollection<object>>()); Assert.That((ReadOnlyCollection<object>)result, Has.Count.EqualTo(0)); } [Test] public async Task ShouldBeAbleToReturnArraysOfPrimitivesFromAsyncScripts() { await driver.GoToUrl(ajaxyPage); object result = await executor.ExecuteAsyncScript("arguments[arguments.length - 1]([null, 123, 'abc', true, false]);"); Assert.That(result, Is.Not.Null); Assert.That(result, Is.InstanceOf<ReadOnlyCollection<object>>()); ReadOnlyCollection<object> resultList = result as ReadOnlyCollection<object>; Assert.That(resultList.Count, Is.EqualTo(5)); Assert.That(resultList[0], Is.Null); Assert.That((long)resultList[1], Is.EqualTo(123)); Assert.That(resultList[2].ToString(), Is.EqualTo("abc")); Assert.That((bool)resultList[3], Is.True); Assert.That((bool)resultList[4], Is.False); } [Test] public async Task ShouldBeAbleToReturnWebElementsFromAsyncScripts() { await driver.GoToUrl(ajaxyPage); object result = await executor.ExecuteAsyncScript("arguments[arguments.length - 1](document.body);"); Assert.That(result, Is.InstanceOf<IWebElement>()); Assert.That((await ((IWebElement)result).TagName()).ToLower(), Is.EqualTo("body")); } [Test] public async Task ShouldBeAbleToReturnArraysOfWebElementsFromAsyncScripts() { await driver.GoToUrl(ajaxyPage); object result = await executor.ExecuteAsyncScript("arguments[arguments.length - 1]([document.body, document.body]);"); Assert.That(result, Is.Not.Null); Assert.That(result, Is.InstanceOf<ReadOnlyCollection<IWebElement>>()); ReadOnlyCollection<IWebElement> resultsList = (ReadOnlyCollection<IWebElement>)result; Assert.That(resultsList, Has.Count.EqualTo(2)); Assert.That(resultsList[0], Is.InstanceOf<IWebElement>()); Assert.That(resultsList[1], Is.InstanceOf<IWebElement>()); Assert.That((await ((IWebElement)resultsList[0]).TagName()).ToLower(), Is.EqualTo("body")); Assert.That(((IWebElement)resultsList[0]), Is.EqualTo((IWebElement)resultsList[1])); } [Test] public async Task ShouldTimeoutIfScriptDoesNotInvokeCallback() { await driver.GoToUrl(ajaxyPage); //Assert.That(async () => await executor.ExecuteAsyncScript("return 1 + 2;"), Throws.InstanceOf<WebDriverTimeoutException>()); await AssertEx.ThrowsAsync<WebBrowserException>(async () => await executor.ExecuteAsyncScript("return 1 + 2;"), exception => Assert.AreEqual("WebDriverTimeoutException", exception.Error)); } [Test] public async Task ShouldTimeoutIfScriptDoesNotInvokeCallbackWithAZeroTimeout() { await driver.GoToUrl(ajaxyPage); //Assert.That(async () => await executor.ExecuteAsyncScript("window.setTimeout(function() {}, 0);"), Throws.InstanceOf<WebDriverTimeoutException>()); await AssertEx.ThrowsAsync<WebBrowserException>(async () => await executor.ExecuteAsyncScript("window.setTimeout(function() {}, 0);"), exception => Assert.AreEqual("WebDriverTimeoutException", exception.Error)); } [Test] public async Task ShouldNotTimeoutIfScriptCallsbackInsideAZeroTimeout() { await driver.GoToUrl(ajaxyPage); await executor.ExecuteAsyncScript( "var callback = arguments[arguments.length - 1];" + "window.setTimeout(function() { callback(123); }, 0)"); } [Test] public async Task ShouldTimeoutIfScriptDoesNotInvokeCallbackWithLongTimeout() { await driver.Options().Timeouts.SetAsynchronousJavaScript(TimeSpan.FromMilliseconds(500)); await driver.GoToUrl(ajaxyPage); //Assert.That(async () => await executor.ExecuteAsyncScript( // "var callback = arguments[arguments.length - 1];" + // "window.setTimeout(callback, 1500);"), Throws.InstanceOf<WebDriverTimeoutException>()); await AssertEx.ThrowsAsync<WebBrowserException>(async () => await executor.ExecuteAsyncScript( "var callback = arguments[arguments.length - 1];" + "window.setTimeout(callback, 1500);"), exception => Assert.AreEqual("WebDriverTimeoutException", exception.Error)); } [Test] public async Task ShouldDetectPageLoadsWhileWaitingOnAnAsyncScriptAndReturnAnError() { await driver.GoToUrl(ajaxyPage); //Assert.That(async () => await executor.ExecuteAsyncScript("window.location = '" + dynamicPage + "';"), Throws.InstanceOf<WebDriverException>()); await AssertEx.ThrowsAsync<WebBrowserException>(async () => await executor.ExecuteAsyncScript("window.location = '" + dynamicPage + "';"), exception => Assert.AreEqual("WebDriverException", exception.Error)); } [Test] public async Task ShouldCatchErrorsWhenExecutingInitialScript() { await driver.GoToUrl(ajaxyPage); //Assert.That(async () => await executor.ExecuteAsyncScript("throw Error('you should catch this!');"), Throws.InstanceOf<WebDriverException>()); await AssertEx.ThrowsAsync<WebBrowserException>(async () => await executor.ExecuteAsyncScript("throw Error('you should catch this!');"), exception => Assert.AreEqual("WebDriverException", exception.Error)); } [Test] public async Task ShouldNotTimeoutWithMultipleCallsTheFirstOneBeingSynchronous() { await driver.GoToUrl(ajaxyPage); await driver.Options().Timeouts.SetAsynchronousJavaScript(TimeSpan.FromMilliseconds(1000)); Assert.That((bool)await executor.ExecuteAsyncScript("arguments[arguments.length - 1](true);"), Is.True); Assert.That((bool)await executor.ExecuteAsyncScript("var cb = arguments[arguments.length - 1]; window.setTimeout(function(){cb(true);}, 9);"), Is.True); } [Test] public async Task ShouldBeAbleToExecuteAsynchronousScripts() { // Reset the timeout to the 30-second default instead of zero. await driver.Options().Timeouts.SetAsynchronousJavaScript(TimeSpan.FromSeconds(30)); await driver.GoToUrl(ajaxyPage); IWebElement typer = await driver.FindElement(By.Name("typer")); await typer.SendKeys("bob"); Assert.AreEqual("bob", typer.GetAttribute("value")); await driver.FindElement(By.Id("red")).Click(); await driver.FindElement(By.Name("submit")).Click(); Assert.AreEqual(1, await GetNumberOfDivElements(), "There should only be 1 DIV at this point, which is used for the butter message"); await driver.Options().Timeouts.SetAsynchronousJavaScript(TimeSpan.FromSeconds(10)); string text = (string)await executor.ExecuteAsyncScript( "var callback = arguments[arguments.length - 1];" + "window.registerListener(arguments[arguments.length - 1]);"); Assert.AreEqual("bob", text); Assert.AreEqual("", await typer.GetAttribute("value")); Assert.AreEqual(2, await GetNumberOfDivElements(), "There should be 1 DIV (for the butter message) + 1 DIV (for the new label)"); } [Test] public async Task ShouldBeAbleToPassMultipleArgumentsToAsyncScripts() { await driver.GoToUrl(ajaxyPage); long result = (long)await executor.ExecuteAsyncScript("arguments[arguments.length - 1](arguments[0] + arguments[1]);", new CancellationToken(), 1, 2); Assert.AreEqual(3, result); } [Test] public async Task ShouldBeAbleToMakeXMLHttpRequestsAndWaitForTheResponse() { string script = "var url = arguments[0];" + "var callback = arguments[arguments.length - 1];" + // Adapted from http://www.quirksmode.org/js/xmlhttp.html "var XMLHttpFactories = [" + " function () {return new XMLHttpRequest()}," + " function () {return new ActiveXObject('Msxml2.XMLHTTP')}," + " function () {return new ActiveXObject('Msxml3.XMLHTTP')}," + " function () {return new ActiveXObject('Microsoft.XMLHTTP')}" + "];" + "var xhr = false;" + "while (!xhr && XMLHttpFactories.length) {" + " try {" + " xhr = XMLHttpFactories.shift().call();" + " } catch (e) {}" + "}" + "if (!xhr) throw Error('unable to create XHR object');" + "xhr.open('GET', url, true);" + "xhr.onreadystatechange = function() {" + " if (xhr.readyState == 4) callback(xhr.responseText);" + "};" + "xhr.send();"; await driver.GoToUrl(ajaxyPage); await driver.Options().Timeouts.SetAsynchronousJavaScript(TimeSpan.FromSeconds(3)); string response = (string)await executor.ExecuteAsyncScript(script, new CancellationToken(), sleepingPage + "?time=2"); Assert.AreEqual("<html><head><title>Done</title></head><body>Slept for 2s</body></html>", response.Trim()); } private async Task<long> GetNumberOfDivElements() { IJavaScriptExecutor jsExecutor = driver as IJavaScriptExecutor; // Selenium does not support "findElements" yet, so we have to do this through a script. return (long)await jsExecutor.ExecuteScript("return document.getElementsByTagName('div').length;"); } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // TargetRegistry.cs // // // A store of registered targets with a target block. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; namespace System.Threading.Tasks.Dataflow.Internal { /// <summary>Stores targets registered with a source.</summary> /// <typeparam name="T">Specifies the type of data accepted by the targets.</typeparam> /// <remarks>This type is not thread-safe.</remarks> [DebuggerDisplay("Count={Count}")] [DebuggerTypeProxy(typeof(TargetRegistry<>.DebugView))] internal sealed class TargetRegistry<T> { /// <summary> /// Information about a registered target. This class represents a self-sufficient node in a linked list. /// </summary> internal sealed class LinkedTargetInfo { /// <summary>Initializes the LinkedTargetInfo.</summary> /// <param name="target">The target block reference for this entry.</param> /// <param name="linkOptions">The link options.</param> internal LinkedTargetInfo(ITargetBlock<T> target, DataflowLinkOptions linkOptions) { Debug.Assert(target != null, "The target that is supposed to be linked must not be null."); Debug.Assert(linkOptions != null, "The linkOptions must not be null."); Target = target; PropagateCompletion = linkOptions.PropagateCompletion; RemainingMessages = linkOptions.MaxMessages; } /// <summary>The target block reference for this entry.</summary> internal readonly ITargetBlock<T> Target; /// <summary>The value of the PropagateCompletion link option.</summary> internal readonly bool PropagateCompletion; /// <summary>Number of remaining messages to propagate. /// This counter is initialized to the MaxMessages option and /// gets decremented after each successful propagation.</summary> internal int RemainingMessages; /// <summary>The previous node in the list.</summary> internal LinkedTargetInfo Previous; /// <summary>The next node in the list.</summary> internal LinkedTargetInfo Next; } /// <summary>A reference to the owning source block.</summary> private readonly ISourceBlock<T> _owningSource; /// <summary>A mapping of targets to information about them.</summary> private readonly Dictionary<ITargetBlock<T>, LinkedTargetInfo> _targetInformation; /// <summary>The first node of an ordered list of targets. Messages should be offered to targets starting from First and following Next.</summary> private LinkedTargetInfo _firstTarget; /// <summary>The last node of the ordered list of targets. This field is used purely as a perf optimization to avoid traversing the list for each Add.</summary> private LinkedTargetInfo _lastTarget; /// <summary>Number of links with positive RemainingMessages counters. /// This is an optimization that allows us to skip dictionary lookup when this counter is 0.</summary> private int _linksWithRemainingMessages; /// <summary>Initializes the registry.</summary> internal TargetRegistry(ISourceBlock<T> owningSource) { Debug.Assert(owningSource != null, "The TargetRegistry instance must be owned by a source block."); _owningSource = owningSource; _targetInformation = new Dictionary<ITargetBlock<T>, LinkedTargetInfo>(); } /// <summary>Adds a target to the registry.</summary> /// <param name="target">The target to add.</param> /// <param name="linkOptions">The link options.</param> internal void Add(ref ITargetBlock<T> target, DataflowLinkOptions linkOptions) { Debug.Assert(target != null, "The target that is supposed to be linked must not be null."); Debug.Assert(linkOptions != null, "The link options must not be null."); LinkedTargetInfo targetInfo; // If the target already exists in the registry, replace it with a new NopLinkPropagator to maintain uniqueness if (_targetInformation.TryGetValue(target, out targetInfo)) target = new NopLinkPropagator(_owningSource, target); // Add the target to both stores, the list and the dictionary, which are used for different purposes var node = new LinkedTargetInfo(target, linkOptions); AddToList(node, linkOptions.Append); _targetInformation.Add(target, node); // Increment the optimization counter if needed Debug.Assert(_linksWithRemainingMessages >= 0, "_linksWithRemainingMessages must be non-negative at any time."); if (node.RemainingMessages > 0) _linksWithRemainingMessages++; #if FEATURE_TRACING DataflowEtwProvider etwLog = DataflowEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.DataflowBlockLinking(_owningSource, target); } #endif } /// <summary>Gets whether the registry contains a particular target.</summary> /// <param name="target">The target.</param> /// <returns>true if the registry contains the target; otherwise, false.</returns> internal bool Contains(ITargetBlock<T> target) { return _targetInformation.ContainsKey(target); } /// <summary>Removes the target from the registry.</summary> /// <param name="target">The target to remove.</param> /// <param name="onlyIfReachedMaxMessages"> /// Only remove the target if it's configured to be unlinked after one propagation. /// </param> internal void Remove(ITargetBlock<T> target, bool onlyIfReachedMaxMessages = false) { Debug.Assert(target != null, "Target to remove is required."); // If we are implicitly unlinking and there is nothing to be unlinked implicitly, bail Debug.Assert(_linksWithRemainingMessages >= 0, "_linksWithRemainingMessages must be non-negative at any time."); if (onlyIfReachedMaxMessages && _linksWithRemainingMessages == 0) return; // Otherwise take the slow path Remove_Slow(target, onlyIfReachedMaxMessages); } /// <summary>Actually removes the target from the registry.</summary> /// <param name="target">The target to remove.</param> /// <param name="onlyIfReachedMaxMessages"> /// Only remove the target if it's configured to be unlinked after one propagation. /// </param> private void Remove_Slow(ITargetBlock<T> target, bool onlyIfReachedMaxMessages) { Debug.Assert(target != null, "Target to remove is required."); // Make sure we've intended to go the slow route Debug.Assert(_linksWithRemainingMessages >= 0, "_linksWithRemainingMessages must be non-negative at any time."); Debug.Assert(!onlyIfReachedMaxMessages || _linksWithRemainingMessages > 0, "We shouldn't have ended on the slow path."); // If the target is registered... LinkedTargetInfo node; if (_targetInformation.TryGetValue(target, out node)) { Debug.Assert(node != null, "The LinkedTargetInfo node referenced in the Dictionary must be non-null."); // Remove the target, if either there's no constraint on the removal // or if this was the last remaining message. if (!onlyIfReachedMaxMessages || node.RemainingMessages == 1) { RemoveFromList(node); _targetInformation.Remove(target); // Decrement the optimization counter if needed if (node.RemainingMessages == 0) _linksWithRemainingMessages--; Debug.Assert(_linksWithRemainingMessages >= 0, "_linksWithRemainingMessages must be non-negative at any time."); #if FEATURE_TRACING DataflowEtwProvider etwLog = DataflowEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.DataflowBlockUnlinking(_owningSource, target); } #endif } // If the target is to stay and we are counting the remaining messages for this link, decrement the counter else if (node.RemainingMessages > 0) { Debug.Assert(node.RemainingMessages > 1, "The target should have been removed, because there are no remaining messages."); node.RemainingMessages--; } } } /// <summary>Clears the target registry entry points while allowing subsequent traversals of the linked list.</summary> internal LinkedTargetInfo ClearEntryPoints() { // Save _firstTarget so we can return it LinkedTargetInfo firstTarget = _firstTarget; // Clear out the entry points _firstTarget = _lastTarget = null; _targetInformation.Clear(); Debug.Assert(_linksWithRemainingMessages >= 0, "_linksWithRemainingMessages must be non-negative at any time."); _linksWithRemainingMessages = 0; return firstTarget; } /// <summary>Propagated completion to the targets of the given linked list.</summary> /// <param name="firstTarget">The head of a saved linked list.</param> internal void PropagateCompletion(LinkedTargetInfo firstTarget) { Debug.Assert(_owningSource.Completion.IsCompleted, "The owning source must have completed before propagating completion."); // Cache the owning source's completion task to avoid calling the getter many times Task owningSourceCompletion = _owningSource.Completion; // Propagate completion to those targets that have requested it for (LinkedTargetInfo node = firstTarget; node != null; node = node.Next) { if (node.PropagateCompletion) Common.PropagateCompletion(owningSourceCompletion, node.Target, Common.AsyncExceptionHandler); } } /// <summary>Gets the first node of the ordered target list.</summary> internal LinkedTargetInfo FirstTargetNode { get { return _firstTarget; } } /// <summary>Adds a LinkedTargetInfo node to the doubly-linked list.</summary> /// <param name="node">The node to be added.</param> /// <param name="append">Whether to append or to prepend the node.</param> internal void AddToList(LinkedTargetInfo node, bool append) { Debug.Assert(node != null, "Requires a node to be added."); // If the list is empty, assign the ends to point to the new node and we are done if (_firstTarget == null && _lastTarget == null) { _firstTarget = _lastTarget = node; } else { Debug.Assert(_firstTarget != null && _lastTarget != null, "Both first and last node must either be null or non-null."); Debug.Assert(_lastTarget.Next == null, "The last node must not have a successor."); Debug.Assert(_firstTarget.Previous == null, "The first node must not have a predecessor."); if (append) { // Link the new node to the end of the existing list node.Previous = _lastTarget; _lastTarget.Next = node; _lastTarget = node; } else { // Link the new node to the front of the existing list node.Next = _firstTarget; _firstTarget.Previous = node; _firstTarget = node; } } Debug.Assert(_firstTarget != null && _lastTarget != null, "Both first and last node must be non-null after AddToList."); } /// <summary>Removes the LinkedTargetInfo node from the doubly-linked list.</summary> /// <param name="node">The node to be removed.</param> internal void RemoveFromList(LinkedTargetInfo node) { Debug.Assert(node != null, "Node to remove is required."); Debug.Assert(_firstTarget != null && _lastTarget != null, "Both first and last node must be non-null before RemoveFromList."); LinkedTargetInfo previous = node.Previous; LinkedTargetInfo next = node.Next; // Remove the node by linking the adjacent nodes if (node.Previous != null) { node.Previous.Next = next; node.Previous = null; } if (node.Next != null) { node.Next.Previous = previous; node.Next = null; } // Adjust the list ends if (_firstTarget == node) _firstTarget = next; if (_lastTarget == node) _lastTarget = previous; Debug.Assert((_firstTarget != null) == (_lastTarget != null), "Both first and last node must either be null or non-null after RemoveFromList."); } /// <summary>Gets the number of items in the registry.</summary> private int Count { get { return _targetInformation.Count; } } /// <summary>Converts the linked list of targets to an array for rendering in a debugger.</summary> private ITargetBlock<T>[] TargetsForDebugger { get { var targets = new ITargetBlock<T>[Count]; int i = 0; for (LinkedTargetInfo node = _firstTarget; node != null; node = node.Next) { targets[i++] = node.Target; } return targets; } } /// <summary>Provides a nop passthrough for use with TargetRegistry.</summary> [DebuggerDisplay("{DebuggerDisplayContent,nq}")] [DebuggerTypeProxy(typeof(TargetRegistry<>.NopLinkPropagator.DebugView))] private sealed class NopLinkPropagator : IPropagatorBlock<T, T>, ISourceBlock<T>, IDebuggerDisplay { /// <summary>The source that encapsulates this block.</summary> private readonly ISourceBlock<T> _owningSource; /// <summary>The target with which this block is associated.</summary> private readonly ITargetBlock<T> _target; /// <summary>Initializes the passthrough.</summary> /// <param name="owningSource">The source that encapsulates this block.</param> /// <param name="target">The target to which messages should be forwarded.</param> internal NopLinkPropagator(ISourceBlock<T> owningSource, ITargetBlock<T> target) { Debug.Assert(owningSource != null, "Propagator must be associated with a source."); Debug.Assert(target != null, "Target to propagate to is required."); // Store the arguments _owningSource = owningSource; _target = target; } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="OfferMessage"]/*' /> DataflowMessageStatus ITargetBlock<T>.OfferMessage(DataflowMessageHeader messageHeader, T messageValue, ISourceBlock<T> source, Boolean consumeToAccept) { Debug.Assert(source == _owningSource, "Only valid to be used with the source for which it was created."); return _target.OfferMessage(messageHeader, messageValue, this, consumeToAccept); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ConsumeMessage"]/*' /> T ISourceBlock<T>.ConsumeMessage(DataflowMessageHeader messageHeader, ITargetBlock<T> target, out Boolean messageConsumed) { return _owningSource.ConsumeMessage(messageHeader, this, out messageConsumed); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReserveMessage"]/*' /> bool ISourceBlock<T>.ReserveMessage(DataflowMessageHeader messageHeader, ITargetBlock<T> target) { return _owningSource.ReserveMessage(messageHeader, this); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReleaseReservation"]/*' /> void ISourceBlock<T>.ReleaseReservation(DataflowMessageHeader messageHeader, ITargetBlock<T> target) { _owningSource.ReleaseReservation(messageHeader, this); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' /> Task IDataflowBlock.Completion { get { return _owningSource.Completion; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' /> void IDataflowBlock.Complete() { _target.Complete(); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' /> void IDataflowBlock.Fault(Exception exception) { _target.Fault(exception); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="LinkTo"]/*' /> IDisposable ISourceBlock<T>.LinkTo(ITargetBlock<T> target, DataflowLinkOptions linkOptions) { throw new NotSupportedException(SR.NotSupported_MemberNotNeeded); } /// <summary>The data to display in the debugger display attribute.</summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")] private object DebuggerDisplayContent { get { var displaySource = _owningSource as IDebuggerDisplay; var displayTarget = _target as IDebuggerDisplay; return string.Format("{0} Source=\"{1}\", Target=\"{2}\"", Common.GetNameForDebugger(this), displaySource != null ? displaySource.Content : _owningSource, displayTarget != null ? displayTarget.Content : _target); } } /// <summary>Gets the data to display in the debugger display attribute for this instance.</summary> object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } } /// <summary>Provides a debugger type proxy for a passthrough.</summary> private sealed class DebugView { /// <summary>The passthrough.</summary> private readonly NopLinkPropagator _passthrough; /// <summary>Initializes the debug view.</summary> /// <param name="passthrough">The passthrough to view.</param> public DebugView(NopLinkPropagator passthrough) { Debug.Assert(passthrough != null, "Need a propagator with which to construct the debug view."); _passthrough = passthrough; } /// <summary>The linked target for this block.</summary> public ITargetBlock<T> LinkedTarget { get { return _passthrough._target; } } } } /// <summary>Provides a debugger type proxy for the target registry.</summary> private sealed class DebugView { /// <summary>The registry being debugged.</summary> private readonly TargetRegistry<T> _registry; /// <summary>Initializes the type proxy.</summary> /// <param name="registry">The target registry.</param> public DebugView(TargetRegistry<T> registry) { Debug.Assert(registry != null, "Need a registry with which to construct the debug view."); _registry = registry; } /// <summary>Gets a list of all targets to show in the debugger.</summary> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public ITargetBlock<T>[] Targets { get { return _registry.TargetsForDebugger; } } } } }
//////////////////////////////////////////////////////////////////////////////// // // // MIT X11 license, Copyright (c) 2005-2006 by: // // // // Authors: // // Michael Dominic K. <michaldominik@gmail.com> // // // // Permission is hereby granted, free of charge, to any person obtaining a // // copy of this software and associated documentation files (the "Software"), // // to deal in the Software without restriction, including without limitation // // the rights to use, copy, modify, merge, publish, distribute, sublicense, // // and/or sell copies of the Software, and to permit persons to whom the // // Software is furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included // // in all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // // USE OR OTHER DEALINGS IN THE SOFTWARE. // // // //////////////////////////////////////////////////////////////////////////////// /* Okay, I hate this code. Looks like a "I'm in college and I just learned about * objective programming" shit. but it works. NEEDS a rewrite in future */ namespace Diva.Editor.Model { using System; using System.Collections.Generic; using Gtk; public class StoreHelper { // Private holders ///////////////////////////////////////////// private class Node { public TreeIter Iter; public int Count; public int Id; public List <SubNode> SubNodes; } private class SubNode { public TreeIter Iter; public Core.Stuff Stuff; } // Fields ////////////////////////////////////////////////////// Dictionary <int, Node> idToNode; // Id -> Node Dictionary <TreeIter, Core.Stuff> iterToStuff; // TreeIter -> Stuff // Public methods ////////////////////////////////////////////// /* CONSTRUCTOR */ public StoreHelper () { idToNode = new Dictionary <int, Node> (); iterToStuff = new Dictionary <TreeIter, Core.Stuff> (); } /* Add a node with a given id */ public void AddNode (int id, TreeIter iter) { if (HasNode (id)) throw new Exception ("Node already present"); Node node = new Node ();; node.Iter = iter; node.Id = id; node.Count = 0; node.SubNodes = new List <SubNode> (); idToNode [id] = node; } /* Remove a node */ public void RemoveNode (int id) { idToNode.Remove (id); } /* Remove a node */ public void RemoveSubNode (int id, Core.Stuff stuff) { Node node = idToNode [id]; SubNode targetSubNode = null; foreach (SubNode subNode in node.SubNodes) if (subNode.Stuff == stuff) { targetSubNode = subNode; break; } if (targetSubNode == null) throw new Exception (); node.SubNodes.Remove (targetSubNode); node.Count--; iterToStuff.Remove (targetSubNode.Iter); } /* Get iter for the given stuff in the given node */ public TreeIter GetIterForSubNode (int id, Core.Stuff stuff) { Node node = idToNode [id]; SubNode targetSubNode = null; foreach (SubNode subNode in node.SubNodes) if (subNode.Stuff == stuff) { targetSubNode = subNode; break; } if (targetSubNode == null) throw new Exception (); return targetSubNode.Iter; } /* Adds a sub-node to a node */ public void AddSubNode (int parentId, TreeIter iter, Core.Stuff stuff) { Node node = idToNode [parentId]; SubNode subnode = new SubNode (); subnode.Iter = iter; subnode.Stuff = stuff; node.SubNodes.Add (subnode); iterToStuff [subnode.Iter] = stuff; node.Count++; } /* Return the node-ids this stuff is in */ public int[] GetIdsForStuff (Core.Stuff stuff) { List <int> ret = new List <int> (); foreach (Node node in idToNode.Values) foreach (SubNode subnode in node.SubNodes) if (subnode.Stuff == stuff) { ret.Add (node.Id); continue; } return ret.ToArray (); } /* Return the iters representing the stuff */ public TreeIter[] GetItersForStuff (Core.Stuff stuff) { List <TreeIter> ret = new List <TreeIter> (); foreach (Node node in idToNode.Values) foreach (SubNode subnode in node.SubNodes) if (subnode.Stuff == stuff) { ret.Add (subnode.Iter); break; } return ret.ToArray (); } /* Check if we have a node with a given id */ public bool HasNode (int id) { return idToNode.ContainsKey (id); } /* Get iter for the given id */ public TreeIter GetIterForNode (int id) { if (! HasNode (id)) throw new Exception ("Node not present"); return idToNode [id].Iter; } /* Return the count of sub-items for this node */ public int GetCountForNode (int id) { if (! HasNode (id)) throw new Exception ("Node not present"); return idToNode [id].Count; } /* Get a stuff for a given treeiter. Null it iter * represents a node */ public Core.Stuff GetStuffForIter (TreeIter iter) { if (iterToStuff.ContainsKey (iter)) return iterToStuff [iter]; else return null; } } }
using System; using System.IO; using System.Text; using NUnit.Framework; namespace MSBuild.Community.Tasks.Tests { /// <summary> /// Summary description for VersionTest /// </summary> [TestFixture] public class VersionTest { private string testDirectory; private Version task; private string versionFile; [OneTimeSetUp] public void TestFixtureSetup() { testDirectory = TaskUtility.makeTestDirectory(new MockBuild()); versionFile = Path.Combine(testDirectory, @"version.txt"); } [OneTimeTearDown] public void OneTimeTearDown() { if (File.Exists(versionFile)) { File.Delete(versionFile); } } [SetUp] public void TestSetup() { if (File.Exists(versionFile)) { File.Delete(versionFile); } task = new Version(); task.BuildEngine = new MockBuild(); } [Test] public void SpecifyFile_FileDoesNotExist_CreateWith1_0_0_0() { task.VersionFile = versionFile; Assert.IsTrue(task.Execute(), "Execute Failed"); Assert.AreEqual(1, task.Major); Assert.AreEqual(0, task.Minor); Assert.AreEqual(0, task.Build); Assert.AreEqual(0, task.Revision); string fileContents = File.ReadAllText(versionFile); Assert.AreEqual("1.0.0.0", fileContents); } [Test] public void SpecifyFile_FileExists_IncrementAndOverwrite() { File.AppendAllText(versionFile, "1.2.3.4"); task.VersionFile = versionFile; task.BuildType = "Increment"; task.RevisionType = "Increment"; Assert.IsTrue(task.Execute(), "Execute Failed"); Assert.AreEqual(1, task.Major); Assert.AreEqual(2, task.Minor); Assert.AreEqual(4, task.Build); Assert.AreEqual(5, task.Revision); string fileContents = File.ReadAllText(versionFile); Assert.AreEqual("1.2.4.5", fileContents); } [Test] public void SpecifyFile_FileExists_NotWrittenWhenUnchanged() { File.WriteAllText(versionFile, "1.2.3.4"); DateTime startMtime = File.GetLastWriteTimeUtc(versionFile); task.VersionFile = versionFile; Assert.IsTrue(task.Execute(), "Execute Failed"); Assert.AreEqual(1, task.Major); Assert.AreEqual(2, task.Minor); Assert.AreEqual(3, task.Build); Assert.AreEqual(4, task.Revision); string fileContents = File.ReadAllText(versionFile); Assert.AreEqual("1.2.3.4", fileContents); Assert.AreEqual(startMtime, File.GetLastWriteTimeUtc(versionFile)); } [Test] public void SpecifyFile_FileDoesNotContainValidVersion_TaskFails() { File.AppendAllText(versionFile, "1234"); task.VersionFile = versionFile; Assert.IsFalse(task.Execute(), "Task should have failed"); } [Test] public void BuildType_Increment() { task.Build = 7; task.BuildType = "Increment"; Assert.IsTrue(task.Execute(), "Execute Failed"); Assert.AreEqual(8, task.Build); } [Test] public void BuildType_Automatic_NoStartDate_DaysSinceMillenium() { task.BuildType = "Automatic"; Assert.IsTrue(task.Execute(), "Execute Failed"); int expected = (int)DateTime.Today.Subtract(new DateTime(2000, 1, 1)).Days; Assert.AreEqual(expected, task.Build); } [Test] public void BuildType_Automatic_WithStartDate_DaysSinceStartDate() { DateTime startDate = new DateTime(2002, 12, 5); int daysSinceStartDate = DateTime.Today.Subtract(startDate).Days; task.StartDate = startDate.ToString(); task.BuildType = "Automatic"; Assert.IsTrue(task.Execute(), "Execute Failed"); Assert.AreEqual(task.Build, daysSinceStartDate); } [Test] public void BuildType_Date_CausesError() { task.BuildType = "Date"; Assert.IsFalse(task.Execute(), "Task should have failed."); } [Test] public void BuildType_DateIncrement_CausesError() { task.BuildType = "DateIncrement"; Assert.IsFalse(task.Execute(), "Task should have failed."); } [Test] public void BuildType_None_NoChange() { task.BuildType = "None"; task.Build = 42; Assert.IsTrue(task.Execute(), "Execute Failed"); Assert.AreEqual(42, task.Build); } [Test] public void RevisionType_Automatic_IncreasingSinceMidnight() { task.RevisionType = "Automatic"; Assert.IsTrue(task.Execute(), "Execute Failed"); float factor = (float)(UInt16.MaxValue - 1) / (24 * 60 * 60); int expected = (int)(DateTime.Now.TimeOfDay.TotalSeconds * factor); // task should execute within a second Assert.Greater(task.Revision, expected - 2); Assert.Less(task.Revision, expected + 2); } [Test] public void RevisionType_Increment() { task.Build = 1; task.Revision = 4; task.BuildType = "Automatic"; task.RevisionType = "Increment"; Assert.IsTrue(task.Execute(), "Execute Failed"); Assert.AreEqual(5, task.Revision); } [Test] public void RevisionType_Increment_WithBuildChanged_StillIncrements() { task.StartDate = DateTime.Today.ToString(); task.Build = 1; task.Revision = 4; task.BuildType = "Automatic"; task.RevisionType = "Increment"; Assert.IsTrue(task.Execute(), "Execute Failed"); Assert.AreEqual(5, task.Revision); } [Test] public void RevisionType_BuildIncrement_BuildUnChanged_RevisionIncrements() { task.Revision = 4; task.Build = 7; task.BuildType = "None"; task.RevisionType = "BuildIncrement"; Assert.IsTrue(task.Execute(), "Execute Failed"); Assert.AreEqual(5, task.Revision); } [Test] public void RevisionType_BuildIncrement_BuildChanged_RevisionResetToZero() { task.Revision = 4; task.Build = 7; task.BuildType = "Increment"; task.RevisionType = "BuildIncrement"; Assert.IsTrue(task.Execute(), "Execute Failed"); Assert.AreEqual(0, task.Revision); } [Test] public void RevisionType_None_NoChange() { task.RevisionType = "None"; task.Revision = 24; Assert.IsTrue(task.Execute(), "Execute Failed"); Assert.AreEqual(24, task.Revision); } [Test] public void RevisionType_NonIncrement_CausesError() { task.RevisionType = "NonIncrement"; Assert.IsFalse(task.Execute(), "Task should have failed."); } [Test] public void VerifyDefaults() { Assert.AreEqual(1, task.Major); Assert.AreEqual(0, task.Minor); Assert.AreEqual(0, task.Build); Assert.AreEqual(0, task.Revision); Assert.AreEqual("None", task.BuildType); Assert.AreEqual("None", task.RevisionType); } [Test] public void Unrecognized_BuildType() { task.BuildType = "Invalid"; Assert.IsFalse(task.Execute(), "Task should have failed."); } [Test] public void Unrecognized_RevisionType() { task.RevisionType = "Invalid"; Assert.IsFalse(task.Execute(), "Task should have failed."); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: A wrapper class for the primitive type float. ** ** ===========================================================*/ using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; namespace System { [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct Single : IComparable, IConvertible, IFormattable, IComparable<Single>, IEquatable<Single> { private float m_value; // Do not rename (binary serialization) // // Public constants // public const float MinValue = (float)-3.40282346638528859e+38; public const float Epsilon = (float)1.4e-45; public const float MaxValue = (float)3.40282346638528859e+38; public const float PositiveInfinity = (float)1.0 / (float)0.0; public const float NegativeInfinity = (float)-1.0 / (float)0.0; public const float NaN = (float)0.0 / (float)0.0; // We use this explicit definition to avoid the confusion between 0.0 and -0.0. internal const float NegativeZero = (float)-0.0; /// <summary>Determines whether the specified value is finite (zero, subnormal, or normal).</summary> [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsFinite(float f) { var bits = BitConverter.SingleToInt32Bits(f); return (bits & 0x7FFFFFFF) < 0x7F800000; } /// <summary>Determines whether the specified value is infinite.</summary> [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsInfinity(float f) { var bits = BitConverter.SingleToInt32Bits(f); return (bits & 0x7FFFFFFF) == 0x7F800000; } /// <summary>Determines whether the specified value is NaN.</summary> [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsNaN(float f) { var bits = BitConverter.SingleToInt32Bits(f); return (bits & 0x7FFFFFFF) > 0x7F800000; } /// <summary>Determines whether the specified value is negative.</summary> [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsNegative(float f) { var bits = unchecked((uint)BitConverter.SingleToInt32Bits(f)); return (bits & 0x80000000) == 0x80000000; } /// <summary>Determines whether the specified value is negative infinity.</summary> [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsNegativeInfinity(float f) { return (f == float.NegativeInfinity); } /// <summary>Determines whether the specified value is normal.</summary> [Pure] [NonVersionable] // This is probably not worth inlining, it has branches and should be rarely called public unsafe static bool IsNormal(float f) { var bits = BitConverter.SingleToInt32Bits(f); bits &= 0x7FFFFFFF; return (bits < 0x7F800000) && (bits != 0) && ((bits & 0x7F800000) != 0); } /// <summary>Determines whether the specified value is positive infinity.</summary> [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsPositiveInfinity(float f) { return (f == float.PositiveInfinity); } /// <summary>Determines whether the specified value is subnormal.</summary> [Pure] [NonVersionable] // This is probably not worth inlining, it has branches and should be rarely called public unsafe static bool IsSubnormal(float f) { var bits = BitConverter.SingleToInt32Bits(f); bits &= 0x7FFFFFFF; return (bits < 0x7F800000) && (bits != 0) && ((bits & 0x7F800000) == 0); } // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type Single, this method throws an ArgumentException. // public int CompareTo(Object value) { if (value == null) { return 1; } if (value is Single) { float f = (float)value; if (m_value < f) return -1; if (m_value > f) return 1; if (m_value == f) return 0; // At least one of the values is NaN. if (IsNaN(m_value)) return (IsNaN(f) ? 0 : -1); else // f is NaN. return 1; } throw new ArgumentException(SR.Arg_MustBeSingle); } public int CompareTo(Single value) { if (m_value < value) return -1; if (m_value > value) return 1; if (m_value == value) return 0; // At least one of the values is NaN. if (IsNaN(m_value)) return (IsNaN(value) ? 0 : -1); else // f is NaN. return 1; } [NonVersionable] public static bool operator ==(Single left, Single right) { return left == right; } [NonVersionable] public static bool operator !=(Single left, Single right) { return left != right; } [NonVersionable] public static bool operator <(Single left, Single right) { return left < right; } [NonVersionable] public static bool operator >(Single left, Single right) { return left > right; } [NonVersionable] public static bool operator <=(Single left, Single right) { return left <= right; } [NonVersionable] public static bool operator >=(Single left, Single right) { return left >= right; } public override bool Equals(Object obj) { if (!(obj is Single)) { return false; } float temp = ((Single)obj).m_value; if (temp == m_value) { return true; } return IsNaN(temp) && IsNaN(m_value); } public bool Equals(Single obj) { if (obj == m_value) { return true; } return IsNaN(obj) && IsNaN(m_value); } public unsafe override int GetHashCode() { float f = m_value; if (f == 0) { // Ensure that 0 and -0 have the same hash code return 0; } int v = *(int*)(&f); return v; } public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatSingle(m_value, null, NumberFormatInfo.CurrentInfo); } public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatSingle(m_value, null, NumberFormatInfo.GetInstance(provider)); } public String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatSingle(m_value, format, NumberFormatInfo.CurrentInfo); } public String ToString(String format, IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatSingle(m_value, format, NumberFormatInfo.GetInstance(provider)); } // Parses a float from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // // This method will not throw an OverflowException, but will return // PositiveInfinity or NegativeInfinity for a number that is too // large or too small. // public static float Parse(String s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseSingle(s.AsReadOnlySpan(), NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo); } public static float Parse(String s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseSingle(s.AsReadOnlySpan(), style, NumberFormatInfo.CurrentInfo); } public static float Parse(String s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseSingle(s.AsReadOnlySpan(), NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider)); } public static float Parse(String s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseSingle(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider)); } public static float Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return Number.ParseSingle(s, style, NumberFormatInfo.GetInstance(provider)); } public static Boolean TryParse(String s, out Single result) { if (s == null) { result = 0; return false; } return TryParse(s.AsReadOnlySpan(), NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result); } public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Single result) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) { result = 0; return false; } return TryParse(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider), out result); } public static Boolean TryParse(ReadOnlySpan<char> s, out Single result, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static Boolean TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out Single result) { bool success = Number.TryParseSingle(s, style, info, out result); if (!success) { ReadOnlySpan<char> sTrim = s.Trim(); if (StringSpanHelpers.Equals(sTrim, info.PositiveInfinitySymbol)) { result = PositiveInfinity; } else if (StringSpanHelpers.Equals(sTrim, info.NegativeInfinitySymbol)) { result = NegativeInfinity; } else if (StringSpanHelpers.Equals(sTrim, info.NaNSymbol)) { result = NaN; } else { return false; // We really failed } } return true; } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Single; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } char IConvertible.ToChar(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Single", "Char")); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider provider) { return m_value; } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Single", "DateTime")); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: api@infopluscommerce.com * 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 NUnit.Framework; using System; using System.Linq; using System.IO; using System.Collections.Generic; using Infoplus.Api; using Infoplus.Model; using Infoplus.Client; using System.Reflection; namespace Infoplus.Test { /// <summary> /// Class for testing Order /// </summary> /// <remarks> /// This file is automatically generated by Swagger Codegen. /// Please update the test case below to test the model. /// </remarks> [TestFixture] public class OrderTests { // TODO uncomment below to declare an instance variable for Order //private Order instance; /// <summary> /// Setup before each test /// </summary> [SetUp] public void Init() { // TODO uncomment below to create an instance of Order //instance = new Order(); } /// <summary> /// Clean up after each test /// </summary> [TearDown] public void Cleanup() { } /// <summary> /// Test an instance of Order /// </summary> [Test] public void OrderInstanceTest() { // TODO uncomment below to test "IsInstanceOfType" Order //Assert.IsInstanceOfType<Order> (instance, "variable 'instance' is a Order"); } /// <summary> /// Test the property 'OrderNo' /// </summary> [Test] public void OrderNoTest() { // TODO unit test for the property 'OrderNo' } /// <summary> /// Test the property 'CustomerOrderNo' /// </summary> [Test] public void CustomerOrderNoTest() { // TODO unit test for the property 'CustomerOrderNo' } /// <summary> /// Test the property 'LobId' /// </summary> [Test] public void LobIdTest() { // TODO unit test for the property 'LobId' } /// <summary> /// Test the property 'WarehouseId' /// </summary> [Test] public void WarehouseIdTest() { // TODO unit test for the property 'WarehouseId' } /// <summary> /// Test the property 'OrderDate' /// </summary> [Test] public void OrderDateTest() { // TODO unit test for the property 'OrderDate' } /// <summary> /// Test the property 'CustomerNo' /// </summary> [Test] public void CustomerNoTest() { // TODO unit test for the property 'CustomerNo' } /// <summary> /// Test the property 'FirstShipDate' /// </summary> [Test] public void FirstShipDateTest() { // TODO unit test for the property 'FirstShipDate' } /// <summary> /// Test the property 'LastShipDate' /// </summary> [Test] public void LastShipDateTest() { // TODO unit test for the property 'LastShipDate' } /// <summary> /// Test the property 'DeliverOnDate' /// </summary> [Test] public void DeliverOnDateTest() { // TODO unit test for the property 'DeliverOnDate' } /// <summary> /// Test the property 'NeedByDate' /// </summary> [Test] public void NeedByDateTest() { // TODO unit test for the property 'NeedByDate' } /// <summary> /// Test the property 'CarrierId' /// </summary> [Test] public void CarrierIdTest() { // TODO unit test for the property 'CarrierId' } /// <summary> /// Test the property 'ServiceTypeId' /// </summary> [Test] public void ServiceTypeIdTest() { // TODO unit test for the property 'ServiceTypeId' } /// <summary> /// Test the property 'ShipVia' /// </summary> [Test] public void ShipViaTest() { // TODO unit test for the property 'ShipVia' } /// <summary> /// Test the property 'MediaCode' /// </summary> [Test] public void MediaCodeTest() { // TODO unit test for the property 'MediaCode' } /// <summary> /// Test the property 'LegacyRestrictionType' /// </summary> [Test] public void LegacyRestrictionTypeTest() { // TODO unit test for the property 'LegacyRestrictionType' } /// <summary> /// Test the property 'AlcoholOrderType' /// </summary> [Test] public void AlcoholOrderTypeTest() { // TODO unit test for the property 'AlcoholOrderType' } /// <summary> /// Test the property 'AlternateUsage' /// </summary> [Test] public void AlternateUsageTest() { // TODO unit test for the property 'AlternateUsage' } /// <summary> /// Test the property 'AuthorizationAmount' /// </summary> [Test] public void AuthorizationAmountTest() { // TODO unit test for the property 'AuthorizationAmount' } /// <summary> /// Test the property 'AuthorizedBy' /// </summary> [Test] public void AuthorizedByTest() { // TODO unit test for the property 'AuthorizedBy' } /// <summary> /// Test the property 'BalanceDue' /// </summary> [Test] public void BalanceDueTest() { // TODO unit test for the property 'BalanceDue' } /// <summary> /// Test the property 'BatchNo' /// </summary> [Test] public void BatchNoTest() { // TODO unit test for the property 'BatchNo' } /// <summary> /// Test the property 'BillToAttention' /// </summary> [Test] public void BillToAttentionTest() { // TODO unit test for the property 'BillToAttention' } /// <summary> /// Test the property 'BillToCompany' /// </summary> [Test] public void BillToCompanyTest() { // TODO unit test for the property 'BillToCompany' } /// <summary> /// Test the property 'BillToStreet' /// </summary> [Test] public void BillToStreetTest() { // TODO unit test for the property 'BillToStreet' } /// <summary> /// Test the property 'BillToStreet2' /// </summary> [Test] public void BillToStreet2Test() { // TODO unit test for the property 'BillToStreet2' } /// <summary> /// Test the property 'BillToStreet3' /// </summary> [Test] public void BillToStreet3Test() { // TODO unit test for the property 'BillToStreet3' } /// <summary> /// Test the property 'BillToCity' /// </summary> [Test] public void BillToCityTest() { // TODO unit test for the property 'BillToCity' } /// <summary> /// Test the property 'BillToState' /// </summary> [Test] public void BillToStateTest() { // TODO unit test for the property 'BillToState' } /// <summary> /// Test the property 'BillToZip' /// </summary> [Test] public void BillToZipTest() { // TODO unit test for the property 'BillToZip' } /// <summary> /// Test the property 'BillToCountry' /// </summary> [Test] public void BillToCountryTest() { // TODO unit test for the property 'BillToCountry' } /// <summary> /// Test the property 'BillToPhone' /// </summary> [Test] public void BillToPhoneTest() { // TODO unit test for the property 'BillToPhone' } /// <summary> /// Test the property 'BillToEmail' /// </summary> [Test] public void BillToEmailTest() { // TODO unit test for the property 'BillToEmail' } /// <summary> /// Test the property 'NumberOfCartons' /// </summary> [Test] public void NumberOfCartonsTest() { // TODO unit test for the property 'NumberOfCartons' } /// <summary> /// Test the property 'NumberOfPallets' /// </summary> [Test] public void NumberOfPalletsTest() { // TODO unit test for the property 'NumberOfPallets' } /// <summary> /// Test the property 'CompletionStatus' /// </summary> [Test] public void CompletionStatusTest() { // TODO unit test for the property 'CompletionStatus' } /// <summary> /// Test the property 'ParcelAccountId' /// </summary> [Test] public void ParcelAccountIdTest() { // TODO unit test for the property 'ParcelAccountId' } /// <summary> /// Test the property 'CostCenter' /// </summary> [Test] public void CostCenterTest() { // TODO unit test for the property 'CostCenter' } /// <summary> /// Test the property 'CreateDate' /// </summary> [Test] public void CreateDateTest() { // TODO unit test for the property 'CreateDate' } /// <summary> /// Test the property 'CustomerPONo' /// </summary> [Test] public void CustomerPONoTest() { // TODO unit test for the property 'CustomerPONo' } /// <summary> /// Test the property 'DistributionChannel' /// </summary> [Test] public void DistributionChannelTest() { // TODO unit test for the property 'DistributionChannel' } /// <summary> /// Test the property 'DistributionCharges' /// </summary> [Test] public void DistributionChargesTest() { // TODO unit test for the property 'DistributionCharges' } /// <summary> /// Test the property 'Division' /// </summary> [Test] public void DivisionTest() { // TODO unit test for the property 'Division' } /// <summary> /// Test the property 'EnteredBy' /// </summary> [Test] public void EnteredByTest() { // TODO unit test for the property 'EnteredBy' } /// <summary> /// Test the property 'EstimatedWeightLbs' /// </summary> [Test] public void EstimatedWeightLbsTest() { // TODO unit test for the property 'EstimatedWeightLbs' } /// <summary> /// Test the property 'Freight' /// </summary> [Test] public void FreightTest() { // TODO unit test for the property 'Freight' } /// <summary> /// Test the property 'GiftMessage' /// </summary> [Test] public void GiftMessageTest() { // TODO unit test for the property 'GiftMessage' } /// <summary> /// Test the property 'GroupOrderId' /// </summary> [Test] public void GroupOrderIdTest() { // TODO unit test for the property 'GroupOrderId' } /// <summary> /// Test the property 'HoldCode' /// </summary> [Test] public void HoldCodeTest() { // TODO unit test for the property 'HoldCode' } /// <summary> /// Test the property 'IntegrationPartnerId' /// </summary> [Test] public void IntegrationPartnerIdTest() { // TODO unit test for the property 'IntegrationPartnerId' } /// <summary> /// Test the property 'NumberOfLineItems' /// </summary> [Test] public void NumberOfLineItemsTest() { // TODO unit test for the property 'NumberOfLineItems' } /// <summary> /// Test the property 'ModifyDate' /// </summary> [Test] public void ModifyDateTest() { // TODO unit test for the property 'ModifyDate' } /// <summary> /// Test the property 'OmsOrderId' /// </summary> [Test] public void OmsOrderIdTest() { // TODO unit test for the property 'OmsOrderId' } /// <summary> /// Test the property 'OmsOrderNo' /// </summary> [Test] public void OmsOrderNoTest() { // TODO unit test for the property 'OmsOrderNo' } /// <summary> /// Test the property 'OrderLoadProgramId' /// </summary> [Test] public void OrderLoadProgramIdTest() { // TODO unit test for the property 'OrderLoadProgramId' } /// <summary> /// Test the property 'OrderMessage' /// </summary> [Test] public void OrderMessageTest() { // TODO unit test for the property 'OrderMessage' } /// <summary> /// Test the property 'OrderReason' /// </summary> [Test] public void OrderReasonTest() { // TODO unit test for the property 'OrderReason' } /// <summary> /// Test the property 'OrderSourceId' /// </summary> [Test] public void OrderSourceIdTest() { // TODO unit test for the property 'OrderSourceId' } /// <summary> /// Test the property 'PackingSlipTemplateId' /// </summary> [Test] public void PackingSlipTemplateIdTest() { // TODO unit test for the property 'PackingSlipTemplateId' } /// <summary> /// Test the property 'OrderConfirmationEmailTemplateId' /// </summary> [Test] public void OrderConfirmationEmailTemplateIdTest() { // TODO unit test for the property 'OrderConfirmationEmailTemplateId' } /// <summary> /// Test the property 'ShipmentConfirmationEmailTemplateId' /// </summary> [Test] public void ShipmentConfirmationEmailTemplateIdTest() { // TODO unit test for the property 'ShipmentConfirmationEmailTemplateId' } /// <summary> /// Test the property 'PriceLevel' /// </summary> [Test] public void PriceLevelTest() { // TODO unit test for the property 'PriceLevel' } /// <summary> /// Test the property 'PriorityCode' /// </summary> [Test] public void PriorityCodeTest() { // TODO unit test for the property 'PriorityCode' } /// <summary> /// Test the property 'FulfillmentProcessId' /// </summary> [Test] public void FulfillmentProcessIdTest() { // TODO unit test for the property 'FulfillmentProcessId' } /// <summary> /// Test the property 'ShipBy' /// </summary> [Test] public void ShipByTest() { // TODO unit test for the property 'ShipBy' } /// <summary> /// Test the property 'ShipCode' /// </summary> [Test] public void ShipCodeTest() { // TODO unit test for the property 'ShipCode' } /// <summary> /// Test the property 'ShipDate' /// </summary> [Test] public void ShipDateTest() { // TODO unit test for the property 'ShipDate' } /// <summary> /// Test the property 'ShipToAttention' /// </summary> [Test] public void ShipToAttentionTest() { // TODO unit test for the property 'ShipToAttention' } /// <summary> /// Test the property 'ShipToCompany' /// </summary> [Test] public void ShipToCompanyTest() { // TODO unit test for the property 'ShipToCompany' } /// <summary> /// Test the property 'ShipToStreet' /// </summary> [Test] public void ShipToStreetTest() { // TODO unit test for the property 'ShipToStreet' } /// <summary> /// Test the property 'ShipToStreet2' /// </summary> [Test] public void ShipToStreet2Test() { // TODO unit test for the property 'ShipToStreet2' } /// <summary> /// Test the property 'ShipToStreet3' /// </summary> [Test] public void ShipToStreet3Test() { // TODO unit test for the property 'ShipToStreet3' } /// <summary> /// Test the property 'ShipToCity' /// </summary> [Test] public void ShipToCityTest() { // TODO unit test for the property 'ShipToCity' } /// <summary> /// Test the property 'ShipToState' /// </summary> [Test] public void ShipToStateTest() { // TODO unit test for the property 'ShipToState' } /// <summary> /// Test the property 'ShipToZip' /// </summary> [Test] public void ShipToZipTest() { // TODO unit test for the property 'ShipToZip' } /// <summary> /// Test the property 'ShipToCountry' /// </summary> [Test] public void ShipToCountryTest() { // TODO unit test for the property 'ShipToCountry' } /// <summary> /// Test the property 'ShipToPhone' /// </summary> [Test] public void ShipToPhoneTest() { // TODO unit test for the property 'ShipToPhone' } /// <summary> /// Test the property 'ShipToEmail' /// </summary> [Test] public void ShipToEmailTest() { // TODO unit test for the property 'ShipToEmail' } /// <summary> /// Test the property 'ShippingCharge' /// </summary> [Test] public void ShippingChargeTest() { // TODO unit test for the property 'ShippingCharge' } /// <summary> /// Test the property 'Status' /// </summary> [Test] public void StatusTest() { // TODO unit test for the property 'Status' } /// <summary> /// Test the property 'StopBackOrders' /// </summary> [Test] public void StopBackOrdersTest() { // TODO unit test for the property 'StopBackOrders' } /// <summary> /// Test the property 'Subtotal' /// </summary> [Test] public void SubtotalTest() { // TODO unit test for the property 'Subtotal' } /// <summary> /// Test the property 'Tax' /// </summary> [Test] public void TaxTest() { // TODO unit test for the property 'Tax' } /// <summary> /// Test the property 'Total' /// </summary> [Test] public void TotalTest() { // TODO unit test for the property 'Total' } /// <summary> /// Test the property 'TotalPaid' /// </summary> [Test] public void TotalPaidTest() { // TODO unit test for the property 'TotalPaid' } /// <summary> /// Test the property 'TotalQty' /// </summary> [Test] public void TotalQtyTest() { // TODO unit test for the property 'TotalQty' } /// <summary> /// Test the property 'WeightLbs' /// </summary> [Test] public void WeightLbsTest() { // TODO unit test for the property 'WeightLbs' } /// <summary> /// Test the property 'LineItems' /// </summary> [Test] public void LineItemsTest() { // TODO unit test for the property 'LineItems' } } }
// // SyncGateway.cs // // Author: // Jim Borden <jim.borden@couchbase.com> // // Copyright (c) 2015 Couchbase, Inc All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Couchbase.Lite.Util; using NUnit.Framework; #if NET_3_5 using WebRequest = System.Net.Couchbase.WebRequest; using HttpWebResponse = System.Net.Couchbase.HttpWebResponse; using WebException = System.Net.Couchbase.WebException; #endif namespace Couchbase.Lite.Tests { public sealed class RemoteDatabase : IDisposable { private const string Tag = "RemoteDatabase"; private readonly Uri _adminRemoteUri; private readonly Uri _remoteUri; private readonly HttpClient _httpClient; public readonly string Name; public Uri RemoteUri { get { return _remoteUri; } } internal RemoteDatabase(RemoteEndpoint parent, string name, string username = null, string password = null) { _adminRemoteUri = parent.AdminUri.AppendPath(name); _remoteUri = parent.RegularUri.AppendPath(name); var handler = new HttpClientHandler(); if (!String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password)) { handler.Credentials = new NetworkCredential(username, password); handler.PreAuthenticate = true; } _httpClient = new HttpClient(handler, true); Name = name; } public void Create() { var putRequest = new HttpRequestMessage(HttpMethod.Put, _adminRemoteUri + "/"); putRequest.Content = new StringContent(@"{""server"":""walrus:"", ""users"": { ""GUEST"": {""disabled"": false, ""admin_channels"": [""*""]}, ""jim"" : { ""password"": ""borden"", ""admin_channels"": [""*""]}, ""test_user"" : { ""password"": ""1234"", ""admin_channels"": [""unit_test""]} }, ""facebook"": { ""register"": true }, ""bucket"":""" + Name + @""", ""sync"":""function(doc) {channel(doc.channels);}""}"); putRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); try { var putResponse = _httpClient.SendAsync(putRequest).Result; if(putResponse.StatusCode != HttpStatusCode.PreconditionFailed) { Assert.AreEqual(HttpStatusCode.Created, putResponse.StatusCode); } else { Delete().ContinueWith(t => Create()).Wait(); return; } } catch(AggregateException e) { var ex = e.InnerException as WebException; if(ex == null) { ex = (e.InnerException as HttpRequestException)?.InnerException as WebException; } if (ex != null && ex.Status == WebExceptionStatus.ProtocolError) { var response = ex.Response as HttpWebResponse; if (response != null) { Assert.AreEqual(HttpStatusCode.PreconditionFailed, response.StatusCode); Delete().ContinueWith(t => Create()).Wait(); return; } else { Assert.Inconclusive("Error from remote when trying to create DB:", ex); } } else { Assert.Inconclusive("Error from remote when trying to create DB:", ex); } } catch(HttpResponseException e) { if(e.StatusCode == HttpStatusCode.PreconditionFailed) { Delete().ContinueWith(t => Create()).Wait(); return; } else { Assert.Inconclusive("Error from remote when trying to create DB:", e); } } Thread.Sleep(500); } public Task Delete() { return Task.Delay(1000).ContinueWith(t => { var server = _adminRemoteUri; var deleteRequest = new HttpRequestMessage(HttpMethod.Delete, server); try { var response = _httpClient.SendAsync(deleteRequest).Result; Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError) { var response = ex.Response as HttpWebResponse; if (response != null) { Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); } else { Assert.Inconclusive("Error from remote when trying to delete DB: {0}", response.StatusCode); } } else { Assert.Inconclusive("Error from remote when trying to delete DB: {0}", ex); } } }); } public void VerifyDocumentExists(string docId) { var pathToDoc = _remoteUri.AppendPath(docId); LiteTestCase.WriteDebug("Send http request to " + pathToDoc); var httpRequestDoneSignal = new CountdownEvent(1); var t = Task.Factory.StartNew(() => { HttpResponseMessage response; string responseString = null; var responseTask = _httpClient.GetAsync(pathToDoc.ToString()); response = responseTask.Result; var statusLine = response.StatusCode; try { Assert.IsTrue(statusLine == HttpStatusCode.OK); if(statusLine == HttpStatusCode.OK) { var responseStringTask = response.Content.ReadAsStringAsync(); responseStringTask.Wait(TimeSpan.FromSeconds(10)); responseString = responseStringTask.Result; Assert.IsTrue(responseString.Contains(docId)); LiteTestCase.WriteDebug("result: {0}", responseString); } else { var statusReason = response.ReasonPhrase; response.Dispose(); throw new IOException(statusReason); } } finally { httpRequestDoneSignal.Signal(); } }); var result = httpRequestDoneSignal.Wait(TimeSpan.FromSeconds(30)); Assert.IsTrue(result, "Could not retrieve the new doc from the sync gateway."); Assert.IsNull(t.Exception); } public void DisableGuestAccess() { var url = _adminRemoteUri.AppendPath("_user/GUEST"); var request = new HttpRequestMessage(HttpMethod.Put, url); var data = Manager.GetObjectMapper().WriteValueAsBytes(new Dictionary<string, object> { { "disabled", true } }).ToArray(); request.Content = new ByteArrayContent(data); _httpClient.SendAsync(request).Wait(); } public void RestoreGuestAccess() { var url = _adminRemoteUri.AppendPath("_user/GUEST"); var request = new HttpRequestMessage(HttpMethod.Put, url); var data = Manager.GetObjectMapper().WriteValueAsBytes(new Dictionary<string, object> { { "disabled", false }, { "admin_channels", new List<object> { "*" }} }).ToArray(); request.Content = new ByteArrayContent(data); _httpClient.SendAsync(request).Wait(); } public HashSet<string> AddDocuments(int count, bool withAttachment) { var docList = new HashSet<string>(); var json = Manager.GetObjectMapper().WriteValueAsString(CreateDocumentJson(withAttachment ? "attachment.png" : null)) .Substring(1); var beginning = Encoding.UTF8.GetBytes(@"{""docs"":["); var request = new HttpRequestMessage(HttpMethod.Post, _remoteUri.AppendPath("_bulk_docs")); var stream = new MemoryStream(); request.Content = new StreamContent(stream); stream.Write(beginning, 0, beginning.Length); for (int i = 0; i < count; i++) { var docIdTimestamp = Convert.ToString((ulong)DateTime.UtcNow.TimeSinceEpoch().TotalMilliseconds); var docId = string.Format("doc{0}-{1}", i, docIdTimestamp); docList.Add(docId); string nextJson = null; if(i != count-1) { nextJson = String.Format(@"{{""_id"":""{0}"",{1},", docId, json); } else { nextJson = String.Format(@"{{""_id"":""{0}"",{1}]}}", docId, json); } var jsonBytes = Encoding.UTF8.GetBytes(nextJson); stream.Write(jsonBytes, 0, jsonBytes.Length); } stream.Seek(0, SeekOrigin.Begin); var response = _httpClient.SendAsync(request).Result; stream.Dispose(); Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); return docList; } public void AddDocuments(IList<IDictionary<string, object>> properties) { var bulkJson = new Dictionary<string, object> { { "docs", properties } }; var content = Manager.GetObjectMapper().WriteValueAsBytes(bulkJson); var request = new HttpRequestMessage(HttpMethod.Post, _remoteUri.AppendPath("_bulk_docs")); request.Content = new ByteArrayContent(content.ToArray()); var response = _httpClient.SendAsync(request).Result; Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); } public void AddDocument(string docId, IDictionary<string, object> properties) { var docJson = Manager.GetObjectMapper().WriteValueAsString(properties); // push a document to server var replicationUrlTrailingDoc1 = new Uri(string.Format("{0}/{1}", _remoteUri, docId)); var pathToDoc1 = new Uri(replicationUrlTrailingDoc1, docId); LiteTestCase.WriteDebug("Send http request to " + pathToDoc1); try { HttpResponseMessage response; var request = new HttpRequestMessage(); request.Headers.Add("Accept", "*/*"); var postTask = _httpClient.PutAsync(pathToDoc1.AbsoluteUri, new StringContent(docJson, Encoding.UTF8, "application/json")); response = postTask.Result; var statusLine = response.StatusCode; LiteTestCase.WriteDebug("Got response: " + statusLine); Assert.IsTrue(statusLine == HttpStatusCode.Created); } catch (ProtocolViolationException e) { Assert.IsNull(e, "Got ClientProtocolException: " + e.Message); } catch (IOException e) { Assert.IsNull(e, "Got IOException: " + e.Message); } WorkaroundSyncGatewayRaceCondition(); } public void AddDocument(string docId, string attachmentName) { var docJson = CreateDocumentJson(attachmentName); AddDocument(docId, docJson); } private IDictionary<string, object> CreateDocumentJson(string attachmentName) { if (attachmentName != null) { // add attachment to document var attachmentStream = GetAsset(attachmentName); var baos = new MemoryStream(); attachmentStream.CopyTo(baos); attachmentStream.Dispose(); var attachmentBase64 = Convert.ToBase64String(baos.ToArray()); baos.Dispose(); return new Dictionary<string, object> { { "foo", 1 }, { "bar", false }, { "_attachments", new Dictionary<string, object> { { "i_use_couchdb.png", new Dictionary<string, object> { { "content_type", "image/png" }, { "data", attachmentBase64 } } } } } }; } else { return new Dictionary<string, object> { { "foo", 1 }, { "bar", false } }; } } private Stream GetAsset(string name) { var assetPath = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + ".Assets." + name; LiteTestCase.WriteDebug("Fetching assembly resource: " + assetPath); var stream = GetType().Assembly.GetManifestResourceStream(assetPath); return stream; } private void WorkaroundSyncGatewayRaceCondition() { Thread.Sleep(2 * 100); } public void Dispose() { Delete().ContinueWith(t => _httpClient.Dispose()); } } public sealed class SyncGateway : RemoteEndpoint { protected override string Type { get { return "SyncGateway"; } } public SyncGateway(string protocol, string server) : base(protocol, server, 4984, 4985) {} public void SetOnline(string dbName) { var uri = new Uri(AdminUri, String.Format("{0}/_online", dbName)); var message = WebRequest.CreateHttp(uri); message.Method = "POST"; using (var response = (HttpWebResponse)message.GetResponse()) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); } } public void SetOffline(string dbName) { var uri = new Uri(AdminUri, String.Format("{0}/_offline", dbName)); var message = WebRequest.CreateHttp(uri); message.Method = "POST"; using (var response = (HttpWebResponse)message.GetResponse()) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); } } } public sealed class CouchDB : RemoteEndpoint { protected override string Type { get { return "CouchDB"; } } public CouchDB(string protocol, string server) : base(protocol, server, 5984, 5984) {} } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.CommandLine; using System.IO; using System.Linq; using System.Threading; using Wyam.Common.IO; using Wyam.Common.Tracing; using Wyam.Configuration.Preprocessing; using Wyam.Hosting; using Wyam.Tracing; namespace Wyam.Commands { internal class BuildCommand : Command { private readonly ConcurrentQueue<string> _changedFiles = new ConcurrentQueue<string>(); private readonly AutoResetEvent _messageEvent = new AutoResetEvent(false); private readonly InterlockedBool _exit = new InterlockedBool(false); private readonly InterlockedBool _newEngine = new InterlockedBool(false); private readonly ConfigOptions _configOptions = new ConfigOptions(); private readonly Dictionary<string, string> _contentTypes = new Dictionary<string, string>(); private bool _preview = false; private int _previewPort = 5080; private DirectoryPath _previewVirtualDirectory = null; private bool _previewForceExtension = false; private FilePath _logFilePath = null; private bool _verifyConfig = false; private DirectoryPath _previewRoot = null; private bool _watch = false; private bool _noReload = false; private bool _readStdin = false; public override string Description => "Runs the build process (this is the default command)."; public override string[] SupportedDirectives => new[] { "nuget", "nuget-source", "assembly", "recipe", "theme" }; protected override void ParseOptions(ArgumentSyntax syntax) { syntax.DefineOption("w|watch", ref _watch, "Watches the input folder for any changes."); _preview = syntax.DefineOption("p|preview", ref _previewPort, false, "Start the preview web server on the specified port (default is " + _previewPort + ").").IsSpecified; if (syntax.DefineOption("force-ext", ref _previewForceExtension, "Force the use of extensions in the preview web server (by default, extensionless URLs may be used).").IsSpecified && !_preview) { syntax.ReportError("force-ext can only be specified if the preview server is running."); } if (syntax.DefineOption("virtual-dir", ref _previewVirtualDirectory, DirectoryPathFromArg, "Serve files in the preview web server under the specified virtual directory.").IsSpecified && !_preview) { syntax.ReportError("virtual-dir can only be specified if the preview server is running."); } if (syntax.DefineOption("preview-root", ref _previewRoot, DirectoryPathFromArg, "The path to the root of the preview server, if not the output folder.").IsSpecified && !_preview) { syntax.ReportError("preview-root can only be specified if the preview server is running."); } if (syntax.DefineOption("noreload", ref _noReload, "Turns off LiveReload support in the preview server.").IsSpecified && (!_preview || !_watch)) { syntax.ReportError("noreload can only be specified if both the preview server is running and watching is enabled."); } IReadOnlyList<string> contentTypes = null; if (syntax.DefineOptionList("content-type", ref contentTypes, "Specifies additional supported content types for the preview server as extension=contenttype.").IsSpecified) { if (!_preview) { syntax.ReportError("content-type can only be specified if the preview server is running."); } else { PreviewCommand.AddContentTypes(contentTypes, _contentTypes, syntax); } } syntax.DefineOptionList("i|input", ref _configOptions.InputPaths, DirectoryPathFromArg, "The path(s) of input files, can be absolute or relative to the current folder."); syntax.DefineOption("o|output", ref _configOptions.OutputPath, DirectoryPathFromArg, "The path to output files, can be absolute or relative to the current folder."); syntax.DefineOption("c|config", ref _configOptions.ConfigFilePath, FilePath.FromString, "Configuration file (by default, config.wyam is used)."); syntax.DefineOption("u|update-packages", ref _configOptions.UpdatePackages, "Check the NuGet server for more recent versions of each package and update them if applicable."); syntax.DefineOption("use-local-packages", ref _configOptions.UseLocalPackages, "Toggles the use of a local NuGet packages folder."); syntax.DefineOption("use-global-sources", ref _configOptions.UseGlobalSources, "Toggles the use of the global NuGet sources (default is false)."); syntax.DefineOption("ignore-default-sources", ref _configOptions.IgnoreDefaultSources, "Ignores default NuGet sources like the NuGet Gallery (default is false)."); syntax.DefineOption("packages-path", ref _configOptions.PackagesPath, DirectoryPathFromArg, "The packages path to use (only if use-local is true)."); syntax.DefineOption("no-output-config-assembly", ref _configOptions.NoOutputConfigAssembly, "Disable caching configuration file compulation."); syntax.DefineOption("ignore-config-hash", ref _configOptions.IgnoreConfigHash, "Force evaluating the configuration file, even when no changes were detected."); syntax.DefineOption("output-script", ref _configOptions.OutputScript, "Outputs the config script after it's been processed for further debugging. The directive --ignore-config-hash is required when using this option."); syntax.DefineOption("verify-config", ref _verifyConfig, false, "Compile the configuration but do not execute. The directive --ignore-config-hash is required when using this option."); if (_configOptions.OutputScript && !_configOptions.IgnoreConfigHash) { syntax.ReportError("The directive --output-script can only be specified if --ignore-config-hash is also specified."); } if (_verifyConfig && !_configOptions.IgnoreConfigHash) { syntax.ReportError("The directive --verify-config can only be specified if --ignore-config-hash is also specified."); } syntax.DefineOption("noclean", ref _configOptions.NoClean, "Prevents cleaning of the output path on each execution."); syntax.DefineOption("nocache", ref _configOptions.NoCache, "Prevents caching information during execution (less memory usage but slower execution)."); syntax.DefineOption("read-stdin", ref _readStdin, "Reads standard input at startup and sets ApplicationInput in the config script and execution context."); _logFilePath = $"wyam-{DateTime.Now:yyyyMMddHHmmssfff}.txt"; if (!syntax.DefineOption("l|log", ref _logFilePath, FilePath.FromString, false, "Log all trace messages to the specified log file (by default, wyam-[datetime].txt).").IsSpecified) { _logFilePath = null; } // Metadata // TODO: Remove this dictionary and initial/global options Dictionary<string, object> settingsDictionary = new Dictionary<string, object>(); IReadOnlyList<string> globalMetadata = null; if (syntax.DefineOptionList("g|global", ref globalMetadata, "Deprecated, do not use.").IsSpecified) { Trace.Warning("-g/--global is deprecated and will be removed in a future version. Please use -s/--setting instead."); AddSettings(settingsDictionary, globalMetadata); } IReadOnlyList<string> initialMetadata = null; if (syntax.DefineOptionList("initial", ref initialMetadata, "Deprecated, do not use.").IsSpecified) { Trace.Warning("--initial is deprecated and will be removed in a future version. Please use -s/--setting instead."); AddSettings(settingsDictionary, initialMetadata); } IReadOnlyList<string> settings = null; if (syntax.DefineOptionList("s|setting", ref settings, "Specifies a setting as a key=value pair. Use the syntax [x,y] to specify an array value.").IsSpecified) { // _configOptions.Settings = MetadataParser.Parse(settings); TODO: Use this when AddSettings() is removed AddSettings(settingsDictionary, settings); } if (settingsDictionary.Count > 0) { _configOptions.Settings = settingsDictionary; } } // TODO: Remove this method and the global/initial support in the parser private static void AddSettings(IDictionary<string, object> settings, IReadOnlyList<string> value) { foreach (KeyValuePair<string, object> kvp in MetadataParser.Parse(value)) { settings[kvp.Key] = kvp.Value; } } protected override void ParseParameters(ArgumentSyntax syntax) { ParseRootPathParameter(syntax, _configOptions); } protected override ExitCode RunCommand(Preprocessor preprocessor) { // Get the standard input stream if (_readStdin) { using (StreamReader reader = new StreamReader(Console.OpenStandardInput(), Console.InputEncoding)) { _configOptions.Stdin = reader.ReadToEnd(); } } // Fix the root folder and other files DirectoryPath currentDirectory = Environment.CurrentDirectory; _configOptions.RootPath = _configOptions.RootPath == null ? currentDirectory : currentDirectory.Combine(_configOptions.RootPath); _logFilePath = _logFilePath == null ? null : _configOptions.RootPath.CombineFile(_logFilePath); _configOptions.ConfigFilePath = _configOptions.RootPath.CombineFile(_configOptions.ConfigFilePath ?? "config.wyam"); // Set up the log file if (_logFilePath != null) { // Delete an exiting log file if one exists if (File.Exists(_logFilePath.FullPath)) { try { File.Delete(_logFilePath.FullPath); } catch (Exception) { } } Trace.AddListener(new SimpleFileTraceListener(_logFilePath.FullPath)); } // Get the engine and configurator EngineManager engineManager = EngineManager.Get(preprocessor, _configOptions); if (engineManager == null) { return ExitCode.CommandLineError; } // Configure and execute if (!engineManager.Configure()) { return ExitCode.ConfigurationError; } if (_verifyConfig) { Trace.Information("No errors. Exiting."); return ExitCode.Normal; } TraceEnviornment(engineManager); if (!engineManager.Execute()) { return ExitCode.ExecutionError; } bool messagePump = false; // Start the preview server Server previewServer = null; if (_preview) { messagePump = true; DirectoryPath previewPath = _previewRoot == null ? engineManager.Engine.FileSystem.GetOutputDirectory().Path : engineManager.Engine.FileSystem.GetOutputDirectory(_previewRoot).Path; previewServer = PreviewServer.Start(previewPath, _previewPort, _previewForceExtension, _previewVirtualDirectory, _watch && !_noReload, _contentTypes); } // Start the watchers IDisposable inputFolderWatcher = null; IDisposable configFileWatcher = null; if (_watch) { messagePump = true; Trace.Information("Watching paths(s) {0}", string.Join(", ", engineManager.Engine.FileSystem.InputPaths)); inputFolderWatcher = new ActionFileSystemWatcher( engineManager.Engine.FileSystem.GetOutputDirectory().Path, engineManager.Engine.FileSystem.GetInputDirectories().Select(x => x.Path), true, "*.*", path => { _changedFiles.Enqueue(path); _messageEvent.Set(); }); if (_configOptions.ConfigFilePath != null) { Trace.Information("Watching configuration file {0}", _configOptions.ConfigFilePath); configFileWatcher = new ActionFileSystemWatcher( engineManager.Engine.FileSystem.GetOutputDirectory().Path, new[] { _configOptions.ConfigFilePath.Directory }, false, _configOptions.ConfigFilePath.FileName.FullPath, path => { FilePath filePath = new FilePath(path); if (_configOptions.ConfigFilePath.Equals(filePath)) { _newEngine.Set(); _messageEvent.Set(); } }); } } // Start the message pump if an async process is running ExitCode exitCode = ExitCode.Normal; if (messagePump) { // Only wait for a key if console input has not been redirected, otherwise it's on the caller to exit if (!Console.IsInputRedirected) { // Start the key listening thread Thread thread = new Thread(() => { Trace.Information("Hit Ctrl-C to exit"); Console.TreatControlCAsInput = true; while (true) { // Would have prefered to use Console.CancelKeyPress, but that bubbles up to calling batch files // The (ConsoleKey)3 check is to support a bug in VS Code: https://github.com/Microsoft/vscode/issues/9347 ConsoleKeyInfo consoleKey = Console.ReadKey(true); if (consoleKey.Key == (ConsoleKey)3 || (consoleKey.Key == ConsoleKey.C && (consoleKey.Modifiers & ConsoleModifiers.Control) != 0)) { _exit.Set(); _messageEvent.Set(); break; } } }) { IsBackground = true }; thread.Start(); } // Wait for activity while (true) { _messageEvent.WaitOne(); // Blocks the current thread until a signal if (_exit) { break; } // See if we need a new engine if (_newEngine) { // Get a new engine Trace.Information("Configuration file {0} has changed, re-running", _configOptions.ConfigFilePath); engineManager.Dispose(); engineManager = EngineManager.Get(preprocessor, _configOptions); // Configure and execute if (!engineManager.Configure()) { exitCode = ExitCode.ConfigurationError; break; } TraceEnviornment(engineManager); if (!engineManager.Execute()) { exitCode = ExitCode.ExecutionError; } // Clear the changed files since we just re-ran string changedFile; while (_changedFiles.TryDequeue(out changedFile)) { } _newEngine.Unset(); } else { // Execute if files have changed HashSet<string> changedFiles = new HashSet<string>(); string changedFile; while (_changedFiles.TryDequeue(out changedFile)) { if (changedFiles.Add(changedFile)) { Trace.Verbose("{0} has changed", changedFile); } } if (changedFiles.Count > 0) { Trace.Information("{0} files have changed, re-executing", changedFiles.Count); if (!engineManager.Execute()) { exitCode = ExitCode.ExecutionError; } previewServer?.TriggerReloadAsync().GetAwaiter().GetResult(); } } // Check one more time for exit if (_exit) { break; } Trace.Information("Hit Ctrl-C to exit"); _messageEvent.Reset(); } // Shutdown Trace.Information("Shutting down"); engineManager.Dispose(); inputFolderWatcher?.Dispose(); configFileWatcher?.Dispose(); previewServer?.Dispose(); } return exitCode; } private void TraceEnviornment(EngineManager engineManager) { Trace.Information($"Root path:{Environment.NewLine} {engineManager.Engine.FileSystem.RootPath}"); Trace.Information($"Input path(s):{Environment.NewLine} {string.Join(Environment.NewLine + " ", engineManager.Engine.FileSystem.InputPaths)}"); Trace.Information($"Output path:{Environment.NewLine} {engineManager.Engine.FileSystem.OutputPath}"); Trace.Information($"Temp path:{Environment.NewLine} {engineManager.Engine.FileSystem.TempPath}"); Trace.Verbose($"Settings:{Environment.NewLine} {string.Join(Environment.NewLine + " ", engineManager.Engine.Settings.Select(x => $"{x.Key}: {x.Value?.ToString() ?? "null"}"))}"); } } }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using System; using System.IO; using System.Linq.Expressions; using System.Web.UI; using Glass.Mapper.Sc.IoC; using Sitecore.Data.Items; using Sitecore.Web.UI; namespace Glass.Mapper.Sc.Web.Ui { /// <summary> /// Class AbstractGlassUserControl /// </summary> public abstract class AbstractGlassWebControl : WebControl { protected IRenderingContext RenderingContext { get; set; } private TextWriter _writer; protected TextWriter Output { get { return _writer ?? System.Web.HttpContext.Current.Response.Output; } } private ISitecoreContext _sitecoreContext; private IGlassHtml _glassHtml; public AbstractGlassWebControl(ISitecoreContext context, IGlassHtml glassHtml, IRenderingContext renderingContext) { RenderingContext = renderingContext ?? new RenderingContextUserControlWrapper(this); _glassHtml = glassHtml; _sitecoreContext = context; } /// <summary> /// Initializes a new instance of the <see cref="AbstractGlassUserControl" /> class. /// </summary> /// <param name="context">The context.</param> /// <param name="glassHtml"></param> public AbstractGlassWebControl(ISitecoreContext context, IGlassHtml glassHtml) : this(context, glassHtml, null) { } /// <summary> /// Initializes a new instance of the <see cref="AbstractGlassUserControl" /> class. /// </summary> public AbstractGlassWebControl() : this(null, null) { } protected override void OnInit(EventArgs e) { //we have to activate it here because of //some weird lifecycle stuff in the page editor if (_sitecoreContext == null) { _sitecoreContext = SitecoreContextFactory.Default.GetSitecoreContext(); _glassHtml = _sitecoreContext.GlassHtml; } base.OnInit(e); } /// <summary> /// Gets a value indicating whether this instance is in editing mode. /// </summary> /// <value> /// <c>true</c> if this instance is in editing mode; otherwise, <c>false</c>. /// </value> public bool IsInEditingMode { get { return Sc.GlassHtml.IsInEditingMode; } } /// <summary> /// Represents the current Sitecore context /// </summary> /// <value>The sitecore context.</value> public ISitecoreContext SitecoreContext { get { return _sitecoreContext; } } /// <summary> /// Access to rendering helpers /// </summary> /// <value>The glass HTML.</value> protected virtual IGlassHtml GlassHtml { get { return _glassHtml; } set { _glassHtml = value; } } private string _dataSource; /// <summary> /// The custom data source for the sublayout /// </summary> /// <value>The data source.</value> public new string DataSource { get { if (_dataSource == null) { _dataSource = RenderingContext.GetRenderingParameters(); } return _dataSource; } set { _dataSource = value; } } /// <summary> /// Returns either the item specified by the DataSource or the current context item /// </summary> /// <value>The layout item.</value> public Item LayoutItem { get { return DataSourceItem ?? Sitecore.Context.Item; } } /// <summary> /// The Sitecore Item pulled from either the DataSource or Context. /// </summary> public Item DataSourceItem { get { return DataSource.IsNullOrEmpty() ? null : Sitecore.Context.Database.GetItem(DataSource); } } /// <summary> /// Makes a field editable via the Page Editor. Use the Model property as the target item, e.g. model =&gt; model.Title where Title is field name. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="model">The model.</param> /// <param name="field">The field.</param> /// <param name="parameters">The parameters.</param> /// <returns>System.String.</returns> public string Editable<T>(T model, Expression<Func<T, object>> field, object parameters = null) { return GlassHtml.Editable(model, field, parameters); } /// <summary> /// Makes a field editable via the Page Editor. Use the Model property as the target item, e.g. model =&gt; model.Title where Title is field name. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="model">The model.</param> /// <param name="field">The field.</param> /// <param name="standardOutput">The standard output.</param> /// <param name="parameters">The parameters.</param> /// <returns>System.String.</returns> public string Editable<T>(T model, Expression<Func<T, object>> field, Expression<Func<T, string>> standardOutput, object parameters = null) { return GlassHtml.Editable(model, field, standardOutput, parameters); } /// <summary> /// Renders an image allowing simple page editor support /// </summary> /// <typeparam name="T">The model type</typeparam> /// <param name="model">The model that contains the image field</param> /// <param name="field">A lambda expression to the image field, should be of type Glass.Mapper.Sc.Fields.Image</param> /// <param name="parameters">Image parameters, e.g. width, height</param> /// <param name="isEditable">Indicates if the field should be editable</param> /// <param name="outputHeightWidth">Indicates if the height and width attributes should be outputted when rendering the image</param> /// <returns></returns> public virtual string RenderImage<T>(T model, Expression<Func<T, object>> field, object parameters = null, bool isEditable = false, bool outputHeightWidth = true) { return GlassHtml.RenderImage(model, field, parameters, isEditable, outputHeightWidth); } /// <summary> /// Returns an Sitecore Edit Frame /// </summary> /// <param name="model">The model that contains the image field</param> /// <param name="title">The title for the edit frame</param> /// <param name="fields">A lambda expression to the image field, should be of type Glass.Mapper.Sc.Fields.Image</param> /// <returns> /// GlassEditFrame. /// </returns> public GlassEditFrame BeginEditFrame<T>(T model, string title = null, params Expression<Func<T, object>>[] fields) where T : class { return GlassHtml.EditFrame(model, title, Output, fields); } /// <summary> /// Render HTML for a link with contents /// </summary> /// <typeparam name="T">The model type</typeparam> /// <param name="model">The model</param> /// <param name="field">The link field to user</param> /// <param name="attributes">Any additional link attributes</param> /// <param name="isEditable">Make the link editable</param> /// <returns></returns> public virtual RenderingResult BeginRenderLink<T>(T model, Expression<Func<T, object>> field, object attributes = null, bool isEditable = false) { return GlassHtml.BeginRenderLink(model, field, Output, attributes, isEditable); } /// <summary> /// Render HTML for a link /// </summary> /// <typeparam name="T">The model type</typeparam> /// <param name="model">The model</param> /// <param name="field">The link field to user</param> /// <param name="attributes">Any additional link attributes</param> /// <param name="isEditable">Make the link editable</param> /// <param name="contents">Content to override the default decription or item name</param> /// <returns></returns> public virtual string RenderLink<T>(T model, Expression<Func<T, object>> field, object attributes = null, bool isEditable = false, string contents = null) { return GlassHtml.RenderLink(model, field, attributes, isEditable, contents); } public override void RenderControl(HtmlTextWriter writer) { this._writer = writer; base.RenderControl(writer); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using System.Text; internal partial class Interop { internal partial class WinHttp { [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] public static extern SafeWinHttpHandle WinHttpOpen( IntPtr userAgent, uint accessType, string proxyName, string proxyBypass, int flags); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpCloseHandle( IntPtr handle); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] public static extern SafeWinHttpHandle WinHttpConnect( SafeWinHttpHandle sessionHandle, string serverName, ushort serverPort, uint reserved); // NOTE: except for the return type, this refers to the same function as WinHttpConnect. [DllImport(Interop.Libraries.WinHttp, EntryPoint = "WinHttpConnect", CharSet = CharSet.Unicode, SetLastError = true)] public static extern SafeWinHttpHandleWithCallback WinHttpConnectWithCallback( SafeWinHttpHandle sessionHandle, string serverName, ushort serverPort, uint reserved); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] public static extern SafeWinHttpHandle WinHttpOpenRequest( SafeWinHttpHandle connectHandle, string verb, string objectName, string version, string referrer, string acceptTypes, uint flags); // NOTE: except for the return type, this refers to the same function as WinHttpOpenRequest. [DllImport(Interop.Libraries.WinHttp, EntryPoint = "WinHttpOpenRequest", CharSet = CharSet.Unicode, SetLastError = true)] public static extern SafeWinHttpHandleWithCallback WinHttpOpenRequestWithCallback( SafeWinHttpHandle connectHandle, string verb, string objectName, string version, string referrer, string acceptTypes, uint flags); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpAddRequestHeaders( SafeWinHttpHandle requestHandle, [In] StringBuilder headers, uint headersLength, uint modifiers); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpAddRequestHeaders( SafeWinHttpHandle requestHandle, string headers, uint headersLength, uint modifiers); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpSendRequest( SafeWinHttpHandle requestHandle, [In] StringBuilder headers, uint headersLength, IntPtr optional, uint optionalLength, uint totalLength, IntPtr context); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpReceiveResponse( SafeWinHttpHandle requestHandle, IntPtr reserved); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpQueryDataAvailable( SafeWinHttpHandle requestHandle, out uint bytesAvailable); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpQueryDataAvailable( SafeWinHttpHandle requestHandle, IntPtr parameterIgnoredAndShouldBeNullForAsync); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpReadData( SafeWinHttpHandle requestHandle, IntPtr buffer, uint bufferSize, out uint bytesRead); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpReadData( SafeWinHttpHandle requestHandle, IntPtr buffer, uint bufferSize, IntPtr parameterIgnoredAndShouldBeNullForAsync); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpQueryHeaders( SafeWinHttpHandle requestHandle, uint infoLevel, string name, [Out] StringBuilder buffer, ref uint bufferLength, IntPtr index); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpQueryHeaders( SafeWinHttpHandle requestHandle, uint infoLevel, string name, [Out] StringBuilder buffer, ref uint bufferLength, ref uint index); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpQueryHeaders( SafeWinHttpHandle requestHandle, uint infoLevel, string name, ref uint number, ref uint bufferLength, IntPtr index); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpQueryOption( SafeWinHttpHandle handle, uint option, [Out] StringBuilder buffer, ref uint bufferSize); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpQueryOption( SafeWinHttpHandle handle, uint option, ref IntPtr buffer, ref uint bufferSize); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpQueryOption( SafeWinHttpHandle handle, uint option, IntPtr buffer, ref uint bufferSize); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpWriteData( SafeWinHttpHandle requestHandle, IntPtr buffer, uint bufferSize, out uint bytesWritten); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpWriteData( SafeWinHttpHandle requestHandle, IntPtr buffer, uint bufferSize, IntPtr parameterIgnoredAndShouldBeNullForAsync); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpSetOption( SafeWinHttpHandle handle, uint option, ref uint optionData, uint optionLength = sizeof(uint)); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpSetOption( SafeWinHttpHandle handle, uint option, string optionData, uint optionLength); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpSetOption( SafeWinHttpHandle handle, uint option, IntPtr optionData, uint optionLength); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpSetCredentials( SafeWinHttpHandle requestHandle, uint authTargets, uint authScheme, string userName, string password, IntPtr reserved); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpQueryAuthSchemes( SafeWinHttpHandle requestHandle, out uint supportedSchemes, out uint firstScheme, out uint authTarget); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpSetTimeouts( SafeWinHttpHandle handle, int resolveTimeout, int connectTimeout, int sendTimeout, int receiveTimeout); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpGetIEProxyConfigForCurrentUser( out WINHTTP_CURRENT_USER_IE_PROXY_CONFIG proxyConfig); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpGetProxyForUrl( SafeWinHttpHandle sessionHandle, string url, ref WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions, out WINHTTP_PROXY_INFO proxyInfo); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] public static extern IntPtr WinHttpSetStatusCallback( SafeWinHttpHandle handle, WINHTTP_STATUS_CALLBACK callback, uint notificationFlags, IntPtr reserved); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] public static extern SafeWinHttpHandleWithCallback WinHttpWebSocketCompleteUpgrade( SafeWinHttpHandle requestHandle, IntPtr context); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = false)] public static extern uint WinHttpWebSocketSend( SafeWinHttpHandle webSocketHandle, WINHTTP_WEB_SOCKET_BUFFER_TYPE bufferType, IntPtr buffer, uint bufferLength); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = false)] public static extern uint WinHttpWebSocketReceive( SafeWinHttpHandle webSocketHandle, IntPtr buffer, uint bufferLength, out uint bytesRead, out WINHTTP_WEB_SOCKET_BUFFER_TYPE bufferType); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = false)] public static extern uint WinHttpWebSocketShutdown( SafeWinHttpHandle webSocketHandle, ushort status, byte[] reason, uint reasonLength); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = false)] public static extern uint WinHttpWebSocketShutdown( SafeWinHttpHandle webSocketHandle, ushort status, IntPtr reason, uint reasonLength); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = false)] public static extern uint WinHttpWebSocketClose( SafeWinHttpHandle webSocketHandle, ushort status, byte[] reason, uint reasonLength); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = false)] public static extern uint WinHttpWebSocketClose( SafeWinHttpHandle webSocketHandle, ushort status, IntPtr reason, uint reasonLength); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = false)] public static extern uint WinHttpWebSocketQueryCloseStatus( SafeWinHttpHandle webSocketHandle, out ushort status, byte[] reason, uint reasonLength, out uint reasonLengthConsumed); } }
using System; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Xml; using System.Xml.Serialization; using MetX.Standard.Interfaces; using MetX.Standard.Library.Extensions; using MetX.Standard.Library.ML; using MetX.Standard.Library.Strings; namespace XLG.Pipeliner.Pipelines { /// <summary> /// Represents a library to generate /// </summary> [Serializable, XmlType(Namespace = "", AnonymousType = true)] public class XlgSource { [XmlAttribute] public string BasePath; [XmlAttribute] public string ParentNamespace; [XmlAttribute] public string ConnectionName; [XmlAttribute] public string DisplayName; [XmlAttribute] public string XlgDocFilename; [XmlAttribute] public string XslFilename; //[XmlAttribute] public string ConfigFilename; [XmlAttribute] public string OutputFilename; [XmlAttribute] public string OutputXml; [XmlAttribute] public string ConnectionString; [XmlAttribute] public string ProviderName; [XmlAttribute] public bool Selected; [XmlAttribute] public DateTime DateCreated; [XmlAttribute] public DateTime DateModified; [XmlAttribute] public DateTime LastGenerated; [XmlAttribute] public DateTime LastRegenerated; [XmlAttribute] public Guid LastXlgInstanceId; [XmlAttribute] public bool RegenerateOnly; [XmlAttribute] public string SqlToXml; private bool _mGenInProgress; private object _mSyncRoot = new(); public XmlDocument LoadXlgDoc() { var ret = new XmlDocument(); if (File.Exists(OutputXml)) { ret.Load(OutputXml); } return ret; } [XmlIgnore] public string OutputPath { get { if (!string.IsNullOrEmpty(OutputFilename)) return OutputFilename.TokensBeforeLast(@"\") + @"\"; return BasePath + ConnectionName; } } public class OpParams { public readonly int Op; [XmlIgnore] public IGenerationHost Gui { get; } public OpParams(int op, IGenerationHost gui) { Op = op; Gui = gui; } } private void InternalOp(object @params) { var o = (OpParams)@params; if (o.Op == 1) Regenerate(o.Gui); else Generate(o.Gui); } public void RegenerateAsync(IGenerationHost host) { ThreadPool.QueueUserWorkItem(InternalOp, new OpParams(1, host)); } public void GenerateAsync(IGenerationHost host) { ThreadPool.QueueUserWorkItem(InternalOp, new OpParams(2, host)); } public int Regenerate(IGenerationHost host) { Host ??= host; if (_mGenInProgress) return 0; lock (_mSyncRoot) { if (_mGenInProgress) return 0; _mGenInProgress = true; var originalDirectory = Environment.CurrentDirectory; try { Environment.CurrentDirectory = OutputPath; if (string.IsNullOrEmpty(XlgDocFilename)) XlgDocFilename = OutputPath + ConnectionName + ".xlgd"; var gen = new CodeGenerator(XlgDocFilename, XslFilename, OutputPath, host); File.WriteAllText(OutputFilename, gen.RegenerateCode(LoadXlgDoc())); LastRegenerated = DateTime.Now; return 1; } catch (Exception ex) { host.MessageBox.Show(ex.ToString()); } finally { _mGenInProgress = false; Environment.CurrentDirectory = originalDirectory; } } return -1; } public int Generate(IGenerationHost host) { Host ??= host; if (_mGenInProgress) return 0; lock (_mSyncRoot) { if (_mGenInProgress) return 0; _mGenInProgress = true; var originalDirectory = Environment.CurrentDirectory; try { if (string.IsNullOrEmpty(XlgDocFilename)) XlgDocFilename = OutputPath + ConnectionName + ".xlgd"; DataService.Instance = DataService.GetDataServiceManually(ConnectionName, ConnectionString, ProviderName); CodeGenerator gen = null; StringBuilder sb; string output; Environment.CurrentDirectory = OutputPath; var gatherParameters = GatherParameters(); switch (DataService.Instance.ProviderType) { case ProviderTypeEnum.DataAndGather: if (string.IsNullOrEmpty(SqlToXml)) { gen = new CodeGenerator(XlgDocFilename, XslFilename, OutputPath, host) { OutputFolder = MetX.Standard.IO.FileSystem.InsureFolderExists(host, OutputFilename, true) }; if (string.IsNullOrEmpty(gen.OutputFolder)) return -1; // User chose not to create output folder var generatedCode = gen.GenerateCode(ConnectionString); if (generatedCode == null) return -1; File.WriteAllText(OutputFilename, generatedCode); } else { sb = new StringBuilder(); DataService.Instance.Gatherer.GatherNow(sb, gatherParameters); output = sb.ToString(); if (output.StartsWith("<?xml ")) { gen = new CodeGenerator(XlgDocFilename, XslFilename, OutputPath, host); gen.CodeXmlDocument = new XmlDocument(); gen.CodeXmlDocument.LoadXml(output); gen.CodeXmlDocument.Save(OutputXml); var generatedCode = gen.RegenerateCode(gen.CodeXmlDocument); if (string.IsNullOrEmpty(generatedCode)) return -1; File.WriteAllText(OutputFilename, generatedCode); } else { File.WriteAllText(OutputFilename, output); } LastRegenerated = DateTime.Now; } break; case ProviderTypeEnum.Data: gen = new CodeGenerator(XlgDocFilename, XslFilename, OutputPath, host) { OutputFolder = MetX.Standard.IO.FileSystem.InsureFolderExists(host, OutputFilename, true) }; if (string.IsNullOrEmpty(gen.OutputFolder)) return -1; // User chose not to create output folder File.WriteAllText(OutputFilename, gen.GenerateCode(ConnectionString)); break; case ProviderTypeEnum.Gather: sb = new StringBuilder(); if (ConnectionName.IsEmpty()) DataService.Instance.Gatherer.GatherNow(sb, gatherParameters); DataService.Instance.Gatherer.GatherNow(sb, gatherParameters); output = sb.ToString(); if (output.StartsWith("<?xml ")) { gen = new CodeGenerator(XlgDocFilename, XslFilename, OutputPath, host) { CodeXmlDocument = new XmlDocument() }; gen.CodeXmlDocument.LoadXml(output); File.WriteAllText(OutputFilename, gen.RegenerateCode(gen.CodeXmlDocument)); } else { File.WriteAllText(OutputFilename, output); } LastRegenerated = DateTime.Now; break; } if (gen != null) { if (string.IsNullOrEmpty(OutputXml)) { OutputXml = Path.ChangeExtension(OutputFilename, ".xml"); } using var sw = File.CreateText(OutputXml ?? string.Empty); using var xw = Xml.Writer(sw); gen.CodeXmlDocument.WriteTo(xw); } LastGenerated = DateTime.Now; LastXlgInstanceId = gen?.XlgInstanceId ?? Guid.NewGuid(); return 1; } catch (Exception ex) { Host.MessageBox.Show(ex.ToString()); } finally { _mGenInProgress = false; Environment.CurrentDirectory = originalDirectory; } } return -1; } private string[] GatherParameters() { return new[] { ConnectionName, ConnectionString, SqlToXml } .Where(p => p .IsNotEmpty()) .ToArray(); } [XmlIgnore] public IGenerationHost Host { get; set; } public XlgSource() { /* XmlSerializer */ } public XlgSource(string basePath, string parentNamespace, string displayName, string connectionName, string xlgDocFilename, string xslFilename, string outputFilename) { if (!basePath.EndsWith(@"\")) basePath += @"\"; BasePath = basePath; ParentNamespace = parentNamespace; ConnectionName = connectionName; DisplayName = displayName; XlgDocFilename = xlgDocFilename; XslFilename = xslFilename; //this.ConfigFilename = ConfigFilename; OutputFilename = outputFilename; DateCreated = DateTime.Now; } public XlgSource(string basePath, string parentNamespace, string displayName, string connectionName, bool selected) : this(basePath, parentNamespace, displayName, connectionName) { Selected = selected; } public XlgSource(string basePath, string parentNamespace, string displayName, string connectionName) { if (!basePath.EndsWith(@"\")) basePath += @"\"; BasePath = basePath; ParentNamespace = parentNamespace; DisplayName = displayName; ConnectionName = connectionName; XlgDocFilename = basePath + parentNamespace + "." + connectionName + @"\" + connectionName + ".xlgd"; XslFilename = basePath + @"Support\app.xlg.xsl"; //this.ConfigFilename = BasePath + @"Support\app.config"; OutputFilename = basePath + parentNamespace + "." + connectionName + @"\" + connectionName + ".Glove.cs"; DateCreated = DateTime.Now; } public override string ToString() { return DisplayName; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Speech.Synthesis; using System.Speech.Synthesis.TtsEngine; using System.Speech.Recognition; using System.Diagnostics; using System.IO; namespace eDocumentReader.Hubs { /// <summary> /// A speech synthesizer. The system will use this class to generate /// the synthesized speech and save it to a log (the log will in the same /// format as you do in recording mode). The synthesized speech can be /// play in replay mode. /// </summary> public class EBookSpeechSynthesizer { private static EBookSpeechSynthesizer instance; private static SpeechSynthesizer synthesizer; private static readonly int MAXLEN = 4; //max length of the audio file's numeric name private static readonly int synthesisSpeakRate = -2; private static bool saveData; //tell whether to save the current speaking utterance in files private string logResultFile; private double totalSentenceDuration; private int startIndex;//the start index of current sentence private double startTime; private static string prompt; private EBookSpeechSynthesizer(){ if (synthesizer == null) { synthesizer = new SpeechSynthesizer(); synthesizer.PhonemeReached += synthesizer_PhonemeReached; synthesizer.StateChanged += synthesizer_StateChanged; synthesizer.SpeakCompleted += synthesizer_SpeakCompleted; synthesizer.SpeakProgress += synthesizer_SpeakProgress; //synthesizer.SetOutputToDefaultAudioDevice(); } } void synthesizer_SpeakProgress(object sender, SpeakProgressEventArgs e) { //phoneme = ""; if(saveData){ // double rate = 1+synthesisSpeakRate * 0.1; if (rate > 1) { rate = 1; } totalSentenceDuration = e.AudioPosition.TotalMilliseconds*(rate); prompt += e.Text+" "; string data = "time::" + (startTime + totalSentenceDuration) + "|confidence::0.99|textResult::" + prompt.Trim() + "|isHypothesis::True|grammarName::|ruleName::index_"+startIndex+"|duration::-1|wavePath::\n"; writeToFile(data); } } void synthesizer_SpeakCompleted(object sender, SpeakCompletedEventArgs e) { } void synthesizer_StateChanged(object sender, System.Speech.Synthesis.StateChangedEventArgs e) { Debug.WriteLine(e.State.ToString()); } public void speak(string utts) { //force to terminate all queued prompts synthesizer.SpeakAsyncCancelAll(); string[] separator = {"!","?","."}; string[] sentences = utts.Split(separator, StringSplitOptions.RemoveEmptyEntries); int index = 0; foreach (string ea in sentences) { string path = "C:\\temp\\audio"+index+".wav"; synthesizer.SetOutputToWaveFile(@path); PromptBuilder pb = new PromptBuilder(); synthesizer.Rate = -1; synthesizer.Speak(ea); index++; } //Debug.WriteLine("Phonetics: " + phoneme); } public void generateSynthesisData(Story story) { saveData = true; foreach (InstalledVoice iv in synthesizer.GetInstalledVoices()) { string voiceName = iv.VoiceInfo.Name; Debug.WriteLine("installed voice :" + voiceName); synthesizer.SelectVoice(voiceName); string path = story.getFullPath() + "\\" + EBookInteractiveSystem.voice_dir + "\\" + voiceName.Replace(" ", "_"); Directory.CreateDirectory(path); int index = 0; Page p = story.GetFirstPage(); logResultFile = path + "\\" + StoryLoggingDevice.logFileName; if (File.Exists(logResultFile)) { Debug.WriteLine("skip gnerating synthesis data, data found in " + path); return; } startTime = (long)LogPlayer.GetUnixTimestamp(); while(p != null){ //reset startIndex when start a new page startIndex = 0; List<string[]> textArray = p.GetListOfTextArray(); string whole = ""; foreach(string[] text in textArray){ if (text != null) { foreach (string ea in text) { whole += ea + " "; } } } string[] separator = { "!", "?", "." }; string[] sp = whole.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries); List<string> sentences = new List<string>(); string tmpStr = ""; foreach (string ea in sp) { tmpStr += ea + " "; foreach (string punc in separator) { if (ea.Contains(punc)) { sentences.Add(tmpStr.TrimEnd()); tmpStr = ""; break; } } } foreach (string ea in sentences) { Debug.WriteLine("generating tts for:" + ea); string audioPath = path + "\\" + getPrefix(index)+".wav"; synthesizer.SetOutputToWaveFile(@audioPath); PromptBuilder pb = new PromptBuilder(); synthesizer.Rate = synthesisSpeakRate; prompt = ""; writeToFile("start::" + startTime+"\n"); startTime += 10; synthesizer.Speak(ea); index++; startTime += (totalSentenceDuration); string data = "time::" + startTime + "|confidence::0.99|textResult::" + prompt.Trim() + "|isHypothesis::False|key::startIndex|value::" + startIndex + "|grammarName::|ruleName::index_" + startIndex + "|duration::" + totalSentenceDuration + "|wavePath::" + EBookUtil.convertAudioToRelativePath(@audioPath) + "\n"; writeToFile(data); string[] tmp = ea.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries); startIndex += tmp.Length; startTime += 1000;//one second pause } writeToFile("finishPage\n"); p = story.GetNextPage(); } } saveData = false; } private void writeToFile(string data) { if (!File.Exists(logResultFile)) { File.WriteAllText(logResultFile, data); } else { File.AppendAllText(logResultFile, data); } } private string getPrefix(int n) { string x = n + ""; while (x.Length < MAXLEN) { x = "0" + x; } return x; } void synthesizer_PhonemeReached(object sender, PhonemeReachedEventArgs e) { Debug.WriteLine(e.Prompt.ToString()+"\t"+e.Prompt.IsCompleted+"\t"+e.Phoneme); } public static EBookSpeechSynthesizer getInstance(){ if(instance == null){ instance = new EBookSpeechSynthesizer(); } return instance; } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Runtime.Versioning; using NuGet.Resources; namespace NuGet { public class InstallWalker : PackageWalker, IPackageOperationResolver { private readonly bool _ignoreDependencies; private readonly bool _allowPrereleaseVersions; private readonly OperationLookup _operations; // This acts as a "retainment" queue. It contains packages that are already installed but need to be kept during // a package walk. This is to prevent those from being uninstalled in subsequent encounters. private readonly HashSet<IPackage> _packagesToKeep = new HashSet<IPackage>(PackageEqualityComparer.IdAndVersion); // this ctor is used for unit tests internal InstallWalker(IPackageRepository localRepository, IPackageRepository sourceRepository, ILogger logger, bool ignoreDependencies, bool allowPrereleaseVersions) : this(localRepository, sourceRepository, null, logger, ignoreDependencies, allowPrereleaseVersions) { } public InstallWalker(IPackageRepository localRepository, IPackageRepository sourceRepository, FrameworkName targetFramework, ILogger logger, bool ignoreDependencies, bool allowPrereleaseVersions) : this(localRepository, sourceRepository, constraintProvider: NullConstraintProvider.Instance, targetFramework: targetFramework, logger: logger, ignoreDependencies: ignoreDependencies, allowPrereleaseVersions: allowPrereleaseVersions) { } public InstallWalker(IPackageRepository localRepository, IPackageRepository sourceRepository, IPackageConstraintProvider constraintProvider, FrameworkName targetFramework, ILogger logger, bool ignoreDependencies, bool allowPrereleaseVersions) : base(targetFramework) { if (sourceRepository == null) { throw new ArgumentNullException("sourceRepository"); } if (localRepository == null) { throw new ArgumentNullException("localRepository"); } if (logger == null) { throw new ArgumentNullException("logger"); } Repository = localRepository; Logger = logger; SourceRepository = sourceRepository; _ignoreDependencies = ignoreDependencies; ConstraintProvider = constraintProvider; _operations = new OperationLookup(); _allowPrereleaseVersions = allowPrereleaseVersions; } internal bool DisableWalkInfo { get; set; } protected override bool IgnoreWalkInfo { get { return DisableWalkInfo ? true : base.IgnoreWalkInfo; } } protected ILogger Logger { get; private set; } protected IPackageRepository Repository { get; private set; } protected override bool IgnoreDependencies { get { return _ignoreDependencies; } } protected override bool AllowPrereleaseVersions { get { return _allowPrereleaseVersions; } } protected IPackageRepository SourceRepository { get; private set; } private IPackageConstraintProvider ConstraintProvider { get; set; } protected IList<PackageOperation> Operations { get { return _operations.ToList(); } } protected virtual ConflictResult GetConflict(IPackage package) { var conflictingPackage = Marker.FindPackage(package.Id); if (conflictingPackage != null) { return new ConflictResult(conflictingPackage, Marker, Marker); } return null; } protected override void OnBeforePackageWalk(IPackage package) { ConflictResult conflictResult = GetConflict(package); if (conflictResult == null) { return; } // If the conflicting package is the same as the package being installed // then no-op if (PackageEqualityComparer.IdAndVersion.Equals(package, conflictResult.Package)) { return; } // First we get a list of dependents for the installed package. // Then we find the dependency in the foreach dependent that this installed package used to satisfy. // We then check if the resolved package also meets that dependency and if it doesn't it's added to the list // i.e. A1 -> C >= 1 // B1 -> C >= 1 // C2 -> [] // Given the above graph, if we upgrade from C1 to C2, we need to see if A and B can work with the new C var incompatiblePackages = from dependentPackage in GetDependents(conflictResult) let dependency = dependentPackage.FindDependency(package.Id, TargetFramework) where dependency != null && !dependency.VersionSpec.Satisfies(package.Version) select dependentPackage; // If there were incompatible packages that we failed to update then we throw an exception if (incompatiblePackages.Any() && !TryUpdate(incompatiblePackages, conflictResult, package, out incompatiblePackages)) { throw CreatePackageConflictException(package, conflictResult.Package, incompatiblePackages); } else if (package.Version < conflictResult.Package.Version) { // REVIEW: Should we have a flag to allow downgrading? throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, NuGetResources.NewerVersionAlreadyReferenced, package.Id)); } else if (package.Version > conflictResult.Package.Version) { Uninstall(conflictResult.Package, conflictResult.DependentsResolver, conflictResult.Repository); } } private void Uninstall(IPackage package, IDependentsResolver dependentsResolver, IPackageRepository repository) { // If we explicitly want to uninstall this package, then remove it from the retainment queue. _packagesToKeep.Remove(package); // If this package isn't part of the current graph (i.e. hasn't been visited yet) and // is marked for removal, then do nothing. This is so we don't get unnecessary duplicates. if (!Marker.Contains(package) && _operations.Contains(package, PackageAction.Uninstall)) { return; } // Uninstall the conflicting package. We set throw on conflicts to false since we've // already decided that there were no conflicts based on the above code. var resolver = new UninstallWalker(repository, dependentsResolver, TargetFramework, NullLogger.Instance, removeDependencies: !IgnoreDependencies, forceRemove: false) { ThrowOnConflicts = false }; foreach (var operation in resolver.ResolveOperations(package)) { // If the operation is Uninstall, we don't want to uninstall the package if it is in the "retainment" queue. if (operation.Action == PackageAction.Install || !_packagesToKeep.Contains(operation.Package)) { _operations.AddOperation(operation); } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We re-throw a more specific exception later on")] private bool TryUpdate(IEnumerable<IPackage> dependents, ConflictResult conflictResult, IPackage package, out IEnumerable<IPackage> incompatiblePackages) { // Key dependents by id so we can look up the old package later var dependentsLookup = dependents.ToDictionary(d => d.Id, StringComparer.OrdinalIgnoreCase); var compatiblePackages = new Dictionary<IPackage, IPackage>(); // Initialize each compatible package to null foreach (var dependent in dependents) { compatiblePackages[dependent] = null; } // Get compatible packages in one batch so we don't have to make requests for each one var packages = from p in SourceRepository.FindCompatiblePackages(ConstraintProvider, dependentsLookup.Keys, package, TargetFramework, AllowPrereleaseVersions) group p by p.Id into g let oldPackage = dependentsLookup[g.Key] select new { OldPackage = oldPackage, NewPackage = g.Where(p => p.Version > oldPackage.Version) .OrderBy(p => p.Version) .ResolveSafeVersion() }; foreach (var p in packages) { compatiblePackages[p.OldPackage] = p.NewPackage; } // Get all packages that have an incompatibility with the specified package i.e. // We couldn't find a version in the repository that works with the specified package. incompatiblePackages = compatiblePackages.Where(p => p.Value == null) .Select(p => p.Key); if (incompatiblePackages.Any()) { return false; } IPackageConstraintProvider currentConstraintProvider = ConstraintProvider; try { // Add a constraint for the incoming package so we don't try to update it by mistake. // Scenario: // A 1.0 -> B [1.0] // B 1.0.1, B 1.5, B 2.0 // A 2.0 -> B (any version) // We have A 1.0 and B 1.0 installed. When trying to update to B 1.0.1, we'll end up trying // to find a version of A that works with B 1.0.1. The version in the above case is A 2.0. // When we go to install A 2.0 we need to make sure that when we resolve it's dependencies that we stay within bounds // i.e. when we resolve B for A 2.0 we want to keep the B 1.0.1 we've already chosen instead of trying to grab // B 1.5 or B 2.0. In order to achieve this, we add a constraint for version of B 1.0.1 so we stay within those bounds for B. // Respect all existing constraints plus an additional one that we specify based on the incoming package var constraintProvider = new DefaultConstraintProvider(); constraintProvider.AddConstraint(package.Id, new VersionSpec(package.Version)); ConstraintProvider = new AggregateConstraintProvider(ConstraintProvider, constraintProvider); // Mark the incoming package as visited so that we don't try walking the graph again Marker.MarkVisited(package); var failedPackages = new List<IPackage>(); // Update each of the existing packages to more compatible one foreach (var pair in compatiblePackages) { try { // Remove the old package Uninstall(pair.Key, conflictResult.DependentsResolver, conflictResult.Repository); // Install the new package Walk(pair.Value); } catch { // If we failed to update this package (most likely because of a conflict further up the dependency chain) // we keep track of it so we can report an error about the top level package. failedPackages.Add(pair.Key); } } incompatiblePackages = failedPackages; return !incompatiblePackages.Any(); } finally { // Restore the current constraint provider ConstraintProvider = currentConstraintProvider; // Mark the package as processing again Marker.MarkProcessing(package); } } protected override void OnAfterPackageWalk(IPackage package) { if (!Repository.Exists(package)) { // Don't add the package for installation if it already exists in the repository _operations.AddOperation(new PackageOperation(package, PackageAction.Install)); } else { // If we already added an entry for removing this package then remove it // (it's equivalent for doing +P since we're removing a -P from the list) _operations.RemoveOperation(package, PackageAction.Uninstall); // and mark the package as being "retained". _packagesToKeep.Add(package); } } protected override IPackage ResolveDependency(PackageDependency dependency) { Logger.Log(MessageLevel.Info, NuGetResources.Log_AttemptingToRetrievePackageFromSource, dependency); // First try to get a local copy of the package // Bug1638: Include prereleases when resolving locally installed dependencies. IPackage package = Repository.ResolveDependency(dependency, ConstraintProvider, allowPrereleaseVersions: true, preferListedPackages: false); if (package != null) { return package; } // Next, query the source repo for the same dependency IPackage sourcePackage = SourceRepository.ResolveDependency(dependency, ConstraintProvider, AllowPrereleaseVersions, preferListedPackages: true); return sourcePackage; } protected override void OnDependencyResolveError(PackageDependency dependency) { IVersionSpec spec = ConstraintProvider.GetConstraint(dependency.Id); string message = String.Empty; if (spec != null) { message = String.Format(CultureInfo.CurrentCulture, NuGetResources.AdditonalConstraintsDefined, dependency.Id, VersionUtility.PrettyPrint(spec), ConstraintProvider.Source); } throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, NuGetResources.UnableToResolveDependency + message, dependency)); } public IEnumerable<PackageOperation> ResolveOperations(IPackage package) { _operations.Clear(); Marker.Clear(); _packagesToKeep.Clear(); Walk(package); return Operations.Reduce(); } private IEnumerable<IPackage> GetDependents(ConflictResult conflict) { // Skip all dependents that are marked for uninstall IEnumerable<IPackage> packages = _operations.GetPackages(PackageAction.Uninstall); return conflict.DependentsResolver.GetDependents(conflict.Package) .Except<IPackage>(packages, PackageEqualityComparer.IdAndVersion); } private static InvalidOperationException CreatePackageConflictException(IPackage resolvedPackage, IPackage package, IEnumerable<IPackage> dependents) { if (dependents.Count() == 1) { return new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, NuGetResources.ConflictErrorWithDependent, package.GetFullName(), resolvedPackage.GetFullName(), dependents.Single().Id)); } return new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, NuGetResources.ConflictErrorWithDependents, package.GetFullName(), resolvedPackage.GetFullName(), String.Join(", ", dependents.Select(d => d.Id)))); } /// <summary> /// Operation lookup encapsulates an operation list and another efficient data structure for finding package operations /// by package id, version and PackageAction. /// </summary> private class OperationLookup { private readonly List<PackageOperation> _operations = new List<PackageOperation>(); private readonly Dictionary<PackageAction, Dictionary<IPackage, PackageOperation>> _operationLookup = new Dictionary<PackageAction, Dictionary<IPackage, PackageOperation>>(); internal void Clear() { _operations.Clear(); _operationLookup.Clear(); } internal IList<PackageOperation> ToList() { return _operations; } internal IEnumerable<IPackage> GetPackages(PackageAction action) { Dictionary<IPackage, PackageOperation> dictionary = GetPackageLookup(action); if (dictionary != null) { return dictionary.Keys; } return Enumerable.Empty<IPackage>(); } internal void AddOperation(PackageOperation operation) { Dictionary<IPackage, PackageOperation> dictionary = GetPackageLookup(operation.Action, createIfNotExists: true); if (!dictionary.ContainsKey(operation.Package)) { dictionary.Add(operation.Package, operation); _operations.Add(operation); } } internal void RemoveOperation(IPackage package, PackageAction action) { Dictionary<IPackage, PackageOperation> dictionary = GetPackageLookup(action); PackageOperation operation; if (dictionary != null && dictionary.TryGetValue(package, out operation)) { dictionary.Remove(package); _operations.Remove(operation); } } internal bool Contains(IPackage package, PackageAction action) { Dictionary<IPackage, PackageOperation> dictionary = GetPackageLookup(action); return dictionary != null && dictionary.ContainsKey(package); } private Dictionary<IPackage, PackageOperation> GetPackageLookup(PackageAction action, bool createIfNotExists = false) { Dictionary<IPackage, PackageOperation> packages; if (!_operationLookup.TryGetValue(action, out packages) && createIfNotExists) { packages = new Dictionary<IPackage, PackageOperation>(PackageEqualityComparer.IdAndVersion); _operationLookup.Add(action, packages); } return packages; } } } }
// 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.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public class Assign { private class PropertyAndFields { #pragma warning disable 649 // Assigned through expressions. public string StringProperty { get; set; } public string StringField; public readonly string ReadonlyStringField; public string ReadonlyStringProperty { get { return ""; } } public static string StaticStringProperty { get; set; } public static string StaticStringField; public static readonly string ReadonlyStaticStringField; public static string ReadonlyStaticStringProperty { get { return ""; } } public const string ConstantString = "Constant"; public string WriteOnlyString { set { } } public static string WriteOnlyStaticString { set { } } public BaseClass BaseClassProperty { get; set; } public int Int32Property { get; set; } public int Int32Field; public readonly int ReadonlyInt32Field; public int ReadonlyInt32Property { get { return 42; } } public static int StaticInt32Property1 { get; set; } public static int StaticInt32Field; public static readonly int ReadonlyStaticInt32Field; public static int ReadonlyStaticInt32Property { get { return 321; } } public const int ConstantInt32 = 12; public int WriteOnlyInt32 { set { } } public static int WriteOnlyStaticInt32 { set { } } private int _underlyingIndexerField1; public int this[int i] { get { return _underlyingIndexerField1; } set { Assert.Equal(1, i); _underlyingIndexerField1 = value; } } private int _underlyingIndexerField2; public int this[int i, int j] { get { return _underlyingIndexerField2; } set { Assert.Equal(1, i); Assert.Equal(2, j); _underlyingIndexerField2 = value; } } public static int StaticInt32Property2 { get; set; } #pragma warning restore 649 } private class ReadOnlyIndexer { public int this[int i] { get { return 0; } } } private class WriteOnlyIndexer { public int this[int i] { set { } } } private struct StructWithPropertiesAndFields { private int _underlyingIndexerField; public int this[int i] { get { return _underlyingIndexerField; } set { Assert.Equal(1, i); _underlyingIndexerField = value; } } } private static IEnumerable<object[]> ReadOnlyExpressions() { Expression obj = Expression.Constant(new PropertyAndFields()); yield return new object[] { Expression.Field(obj, typeof(PropertyAndFields), nameof(PropertyAndFields.ReadonlyInt32Field)) }; yield return new object[] { Expression.Property(obj, typeof(PropertyAndFields), nameof(PropertyAndFields.ReadonlyInt32Property)) }; yield return new object[] { Expression.Field(obj, typeof(PropertyAndFields), nameof(PropertyAndFields.ReadonlyStringField)) }; yield return new object[] { Expression.Property(obj, typeof(PropertyAndFields), nameof(PropertyAndFields.ReadonlyStringProperty)) }; yield return new object[] { Expression.Field(null, typeof(PropertyAndFields), nameof(PropertyAndFields.ConstantInt32)) }; yield return new object[] { Expression.Field(null, typeof(PropertyAndFields), nameof(PropertyAndFields.ConstantString)) }; yield return new object[] { Expression.Field(null, typeof(PropertyAndFields), nameof(PropertyAndFields.ReadonlyStaticInt32Field)) }; yield return new object[] { Expression.Property(null, typeof(PropertyAndFields), nameof(PropertyAndFields.ReadonlyStaticInt32Property)) }; yield return new object[] { Expression.Field(null, typeof(PropertyAndFields), nameof(PropertyAndFields.ReadonlyStaticStringField)) }; yield return new object[] { Expression.Property(null, typeof(PropertyAndFields), nameof(PropertyAndFields.ReadonlyStaticStringProperty)) }; yield return new object[] { Expression.Default(typeof(int)) }; yield return new object[] { Expression.Default(typeof(string)) }; yield return new object[] { Expression.Default(typeof(DateTime)) }; yield return new object[] { Expression.Constant(1) }; yield return new object[] { Expression.Property(Expression.Constant(new ReadOnlyIndexer()), "Item", new Expression[] { Expression.Constant(1) }) }; } private static IEnumerable<object> WriteOnlyExpressions() { Expression obj = Expression.Constant(new PropertyAndFields()); yield return new object[] { Expression.Property(obj, typeof(PropertyAndFields), nameof(PropertyAndFields.WriteOnlyInt32)) }; yield return new object[] { Expression.Property(obj, typeof(PropertyAndFields), nameof(PropertyAndFields.WriteOnlyString)) }; yield return new object[] { Expression.Property(null, typeof(PropertyAndFields), nameof(PropertyAndFields.WriteOnlyStaticInt32)) }; yield return new object[] { Expression.Property(null, typeof(PropertyAndFields), nameof(PropertyAndFields.WriteOnlyStaticString)) }; yield return new object[] { Expression.Property(Expression.Constant(new WriteOnlyIndexer()), "Item", new Expression[] { Expression.Constant(1) }) }; } private static IEnumerable<object> MemberAssignments() { Expression obj = Expression.Constant(new PropertyAndFields()); yield return new object[] { Expression.Field(null, typeof(PropertyAndFields), nameof(PropertyAndFields.StaticInt32Field)), 1 }; yield return new object[] { Expression.Property(null, typeof(PropertyAndFields), nameof(PropertyAndFields.StaticInt32Property1)), 2 }; yield return new object[] { Expression.Field(obj, typeof(PropertyAndFields), nameof(PropertyAndFields.Int32Field)), 3 }; yield return new object[] { Expression.Property(obj, typeof(PropertyAndFields), nameof(PropertyAndFields.Int32Property)), 4 }; yield return new object[] { Expression.Field(null, typeof(PropertyAndFields), nameof(PropertyAndFields.StaticStringField)), "a" }; yield return new object[] { Expression.Property(null, typeof(PropertyAndFields), nameof(PropertyAndFields.StaticStringProperty)), "b" }; yield return new object[] { Expression.Field(obj, typeof(PropertyAndFields), nameof(PropertyAndFields.StringField)), "c" }; yield return new object[] { Expression.Property(obj, typeof(PropertyAndFields), nameof(PropertyAndFields.StringProperty)), "d" }; yield return new object[] { Expression.Property(obj, typeof(PropertyAndFields), nameof(PropertyAndFields.BaseClassProperty)), new BaseClass() }; yield return new object[] { Expression.Property(obj, typeof(PropertyAndFields), nameof(PropertyAndFields.BaseClassProperty)), new SubClass() }; // IndexExpression for indexed property PropertyInfo simpleIndexer = typeof(PropertyAndFields).GetProperties().First(prop => prop.GetIndexParameters().Length == 1); yield return new object[] { Expression.Property(obj, simpleIndexer, new Expression[] { Expression.Constant(1) }), 5 }; PropertyInfo advancedIndexer = typeof(PropertyAndFields).GetProperties().First(prop => prop.GetIndexParameters().Length == 2); yield return new object[] { Expression.Property(obj, advancedIndexer, new Expression[] { Expression.Constant(1), Expression.Constant(2) }), 5 }; // IndexExpression for non-indexed property yield return new object[] { Expression.Property(null, typeof(PropertyAndFields).GetProperty(nameof(PropertyAndFields.StaticInt32Property2)), new Expression[0]), 6 }; yield return new object[] { Expression.Property(obj, nameof(PropertyAndFields.Int32Property), new Expression[0]), 7 }; } [Fact] public static void BasicAssignmentExpressionTest() { ParameterExpression left = Expression.Parameter(typeof(int)); ParameterExpression right = Expression.Parameter(typeof(int)); BinaryExpression actual = Expression.Assign(left, right); Assert.Same(left, actual.Left); Assert.Same(right, actual.Right); Assert.Null(actual.Conversion); Assert.False(actual.IsLifted); Assert.False(actual.IsLiftedToNull); Assert.Equal(typeof(int), actual.Type); Assert.Equal(ExpressionType.Assign, actual.NodeType); } [Theory, ClassData(typeof(CompilationTypes))] public void SimpleAssignment(bool useInterpreter) { ParameterExpression variable = Expression.Variable(typeof(int)); LabelTarget target = Expression.Label(typeof(int)); Expression exp = Expression.Block( new ParameterExpression[] { variable }, Expression.Assign(variable, Expression.Constant(42)), Expression.Return(target, variable), Expression.Label(target, Expression.Default(typeof(int))) ); Assert.Equal(42, Expression.Lambda<Func<int>>(exp).Compile(useInterpreter)()); } [Theory, ClassData(typeof(CompilationTypes))] public void AssignmentHasValueItself(bool useInterpreter) { ParameterExpression variable = Expression.Variable(typeof(int)); Expression exp = Expression.Block( new ParameterExpression[] { variable }, Expression.Assign(variable, Expression.Constant(42)) ); Assert.Equal(42, Expression.Lambda<Func<int>>(exp).Compile(useInterpreter)()); } [Theory, PerCompilationType(nameof(MemberAssignments))] public void AssignToMember(Expression memberExp, object value, bool useInterpreter) { Func<bool> func = Expression.Lambda<Func<bool>>( Expression.Block( Expression.Assign(memberExp, Expression.Constant(value)), Expression.Equal(memberExp, Expression.Constant(value)) ) ).Compile(useInterpreter); Assert.True(func()); } [Fact] public void CannotReduce() { Expression exp = Expression.Assign(Expression.Variable(typeof(int)), Expression.Constant(0)); Assert.False(exp.CanReduce); Assert.Same(exp, exp.Reduce()); AssertExtensions.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public void LeftNull_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.Assign(null, Expression.Constant(""))); } [Fact] public void RightNull_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("right", () => Expression.Assign(Expression.Variable(typeof(int)), null)); } [Theory] [InlineData(typeof(int), "Hello", typeof(string))] [InlineData(typeof(long), 1, typeof(int))] [InlineData(typeof(int?), 1, typeof(int))] [InlineData(typeof(SubClass), null, typeof(BaseClass))] [InlineData(typeof(int), null, typeof(BaseClass))] [InlineData(typeof(BaseClass), 1, typeof(int))] public void MismatchTypes(Type variableType, object constantValue, Type constantType) { AssertExtensions.Throws<ArgumentException>(null, () => Expression.Assign(Expression.Variable(variableType), Expression.Constant(constantValue, constantType))); } [Theory, ClassData(typeof(CompilationTypes))] public void ReferenceAssignable(bool useInterpreter) { ParameterExpression variable = Expression.Variable(typeof(object)); LabelTarget target = Expression.Label(typeof(object)); Expression exp = Expression.Block( new ParameterExpression[] { variable }, Expression.Assign(variable, Expression.Constant("Hello")), Expression.Return(target, variable), Expression.Label(target, Expression.Default(typeof(object))) ); Assert.Equal("Hello", Expression.Lambda<Func<object>>(exp).Compile(useInterpreter)()); } [Theory] [MemberData(nameof(ReadOnlyExpressions))] public void LeftReadOnly_ThrowsArgumentException(Expression readonlyExp) { AssertExtensions.Throws<ArgumentException>("left", () => Expression.Assign(readonlyExp, Expression.Default(readonlyExp.Type))); } [Theory] [MemberData(nameof(WriteOnlyExpressions))] public static void Right_WriteOnly_ThrowsArgumentException(Expression writeOnlyExp) { ParameterExpression variable = Expression.Variable(writeOnlyExp.Type); AssertExtensions.Throws<ArgumentException>("right", () => Expression.Assign(variable, writeOnlyExp)); } [Theory] [ClassData(typeof(InvalidTypesData))] public static void Left_InvalidType_ThrowsArgumentException(Type type) { Expression left = new FakeExpression(ExpressionType.Parameter, type); AssertExtensions.Throws<ArgumentException>("left", () => Expression.Assign(left, Expression.Parameter(typeof(int)))); } [Theory] [ClassData(typeof(InvalidTypesData))] public static void Right_InvalidType_ThrowsArgumentException(Type type) { Expression right = new FakeExpression(ExpressionType.Parameter, type); AssertExtensions.Throws<ArgumentException>("right", () => Expression.Assign(Expression.Variable(typeof(object)), right)); } [Theory] [ClassData(typeof(CompilationTypes))] [ActiveIssue(13007)] public static void Left_ValueTypeContainsChildTryExpression(bool useInterpreter) { Expression tryExpression = Expression.TryFinally( Expression.Constant(1), Expression.Empty() ); Expression index = Expression.Property(Expression.Constant(new StructWithPropertiesAndFields()), typeof(StructWithPropertiesAndFields).GetProperty("Item"), new Expression[] { tryExpression }); Expression<Func<bool>> func = Expression.Lambda<Func<bool>>( Expression.Block( Expression.Assign(index, Expression.Constant(123)), Expression.Equal(index, Expression.Constant(123)) ) ); Assert.True(func.Compile(useInterpreter)()); } [Theory] [ClassData(typeof(CompilationTypes))] [ActiveIssue(13007)] public static void ValueTypeIndexAssign(bool useInterpreter) { Expression index = Expression.Property(Expression.Constant(new StructWithPropertiesAndFields()), typeof(StructWithPropertiesAndFields).GetProperty("Item"), new Expression[] { Expression.Constant(1) }); Expression<Func<bool>> func = Expression.Lambda<Func<bool>>( Expression.Block( Expression.Assign(index, Expression.Constant(123)), Expression.Equal(index, Expression.Constant(123)) ) ); Assert.True(func.Compile(useInterpreter)()); } [Theory] [ClassData(typeof(CompilationTypes))] public static void Left_ReferenceTypeContainsChildTryExpression_Compiles(bool useInterpreter) { Expression tryExpression = Expression.TryFinally( Expression.Constant(1), Expression.Empty() ); PropertyInfo simpleIndexer = typeof(PropertyAndFields).GetProperties().First(prop => prop.GetIndexParameters().Length == 1); Expression index = Expression.Property(Expression.Constant(new PropertyAndFields()), simpleIndexer, new Expression[] { tryExpression }); Func<bool> func = Expression.Lambda<Func<bool>>( Expression.Block( Expression.Assign(index, Expression.Constant(123)), Expression.Equal(index, Expression.Constant(123)) ) ).Compile(useInterpreter); Assert.True(func()); } [Fact] public static void ToStringTest() { BinaryExpression e = Expression.Assign(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b")); Assert.Equal("(a = b)", e.ToString()); } class BaseClass { } class SubClass : BaseClass { } } }
using EpisodeInformer.Data; using EpisodeInformer.Data.Basics; using Ionic.Zip; using System; using System.ComponentModel; using System.Data; using System.Data.OleDb; using System.Drawing; using System.IO; using System.Threading; using System.Windows.Forms; namespace ServiceManager { public partial class frmDataCopy : Form { private IContainer components = (IContainer)null; private OleDbConnection con = (OleDbConnection)null; private GroupBox groupBox1; private Button btnBKFOpen; private TextBox txtBKFPath; private Label lblBKFVer; private Label lblBKFDate; private Label label3; private Label label2; private Label label1; private StatusStrip statusStrip1; private ToolStripStatusLabel lblStatus; private ToolStripProgressBar prgStatus; private GroupBox groupBox2; private Button btnCopy; private Button btnClose; private Button btnClear; protected override void Dispose(bool disposing) { if (disposing && this.components != null) this.components.Dispose(); base.Dispose(disposing); } private void InitializeComponent() { ComponentResourceManager resources = new ComponentResourceManager(typeof(frmDataCopy)); this.groupBox1 = new GroupBox(); this.btnBKFOpen = new Button(); this.txtBKFPath = new TextBox(); this.lblBKFVer = new Label(); this.lblBKFDate = new Label(); this.label3 = new Label(); this.label2 = new Label(); this.label1 = new Label(); this.statusStrip1 = new StatusStrip(); this.lblStatus = new ToolStripStatusLabel(); this.prgStatus = new ToolStripProgressBar(); this.groupBox2 = new GroupBox(); this.btnClear = new Button(); this.btnCopy = new Button(); this.btnClose = new Button(); this.groupBox1.SuspendLayout(); this.statusStrip1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.SuspendLayout(); this.groupBox1.Controls.Add((Control)this.btnBKFOpen); this.groupBox1.Controls.Add((Control)this.txtBKFPath); this.groupBox1.Controls.Add((Control)this.lblBKFVer); this.groupBox1.Controls.Add((Control)this.lblBKFDate); this.groupBox1.Controls.Add((Control)this.label3); this.groupBox1.Controls.Add((Control)this.label2); this.groupBox1.Controls.Add((Control)this.label1); this.groupBox1.Location = new Point(12, 12); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new Size(372, 123); this.groupBox1.TabIndex = 0; this.groupBox1.TabStop = false; this.btnBKFOpen.Font = new Font("Segoe UI", 9f, FontStyle.Bold, GraphicsUnit.Point, (byte)0); this.btnBKFOpen.Location = new Point(338, 13); this.btnBKFOpen.Name = "btnBKFOpen"; this.btnBKFOpen.Size = new Size(28, 26); this.btnBKFOpen.TabIndex = 6; this.btnBKFOpen.Text = "...."; this.btnBKFOpen.UseVisualStyleBackColor = true; this.btnBKFOpen.Click += new EventHandler(this.btnBKFOpen_Click); this.txtBKFPath.Font = new Font("Segoe UI", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0); this.txtBKFPath.Location = new Point(82, 16); this.txtBKFPath.Multiline = true; this.txtBKFPath.Name = "txtBKFPath"; this.txtBKFPath.ReadOnly = true; this.txtBKFPath.Size = new Size(250, 49); this.txtBKFPath.TabIndex = 5; this.txtBKFPath.TextChanged += new EventHandler(this.txtBKFPath_TextChanged); this.lblBKFVer.AutoSize = true; this.lblBKFVer.Font = new Font("Segoe UI", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0); this.lblBKFVer.Location = new Point(79, 99); this.lblBKFVer.Name = "lblBKFVer"; this.lblBKFVer.Size = new Size(58, 15); this.lblBKFVer.TabIndex = 4; this.lblBKFVer.Text = "Unknown"; this.lblBKFDate.AutoSize = true; this.lblBKFDate.Font = new Font("Segoe UI", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0); this.lblBKFDate.Location = new Point(79, 79); this.lblBKFDate.Name = "lblBKFDate"; this.lblBKFDate.Size = new Size(58, 15); this.lblBKFDate.TabIndex = 3; this.lblBKFDate.Text = "Unknown"; this.label3.AutoSize = true; this.label3.Font = new Font("Segoe UI", 9f, FontStyle.Bold, GraphicsUnit.Point, (byte)0); this.label3.Location = new Point(15, 99); this.label3.Name = "label3"; this.label3.Size = new Size(55, 15); this.label3.TabIndex = 2; this.label3.Text = "Version :"; this.label2.AutoSize = true; this.label2.Font = new Font("Segoe UI", 9f, FontStyle.Bold, GraphicsUnit.Point, (byte)0); this.label2.Location = new Point(30, 79); this.label2.Name = "label2"; this.label2.Size = new Size(40, 15); this.label2.TabIndex = 1; this.label2.Text = "Date :"; this.label1.AutoSize = true; this.label1.Font = new Font("Segoe UI", 9f, FontStyle.Bold, GraphicsUnit.Point, (byte)0); this.label1.Location = new Point(6, 21); this.label1.Name = "label1"; this.label1.Size = new Size(70, 15); this.label1.TabIndex = 0; this.label1.Text = "Old Backup"; this.statusStrip1.Items.AddRange(new ToolStripItem[2] { (ToolStripItem) this.lblStatus, (ToolStripItem) this.prgStatus }); this.statusStrip1.Location = new Point(0, 207); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.Size = new Size(396, 22); this.statusStrip1.SizingGrip = false; this.statusStrip1.TabIndex = 1; this.statusStrip1.Text = "statusStrip1"; this.lblStatus.Name = "lblStatus"; this.lblStatus.Size = new Size(45, 17); this.lblStatus.Text = "Status :"; this.prgStatus.Name = "prgStatus"; this.prgStatus.Size = new Size(100, 16); this.groupBox2.Controls.Add((Control)this.btnClear); this.groupBox2.Controls.Add((Control)this.btnCopy); this.groupBox2.Controls.Add((Control)this.btnClose); this.groupBox2.Location = new Point(12, 141); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new Size(372, 54); this.groupBox2.TabIndex = 2; this.groupBox2.TabStop = false; this.btnClear.Font = new Font("Segoe UI", 9f, FontStyle.Bold, GraphicsUnit.Point, (byte)0); this.btnClear.Location = new Point(9, 19); this.btnClear.Name = "btnClear"; this.btnClear.Size = new Size(75, 23); this.btnClear.TabIndex = 2; this.btnClear.Text = "Clear"; this.btnClear.UseVisualStyleBackColor = true; this.btnClear.Click += new EventHandler(this.btnClear_Click); this.btnCopy.Enabled = false; this.btnCopy.Font = new Font("Segoe UI", 9f, FontStyle.Bold, GraphicsUnit.Point, (byte)0); this.btnCopy.Location = new Point(210, 19); this.btnCopy.Name = "btnCopy"; this.btnCopy.Size = new Size(75, 23); this.btnCopy.TabIndex = 1; this.btnCopy.Text = "Copy"; this.btnCopy.UseVisualStyleBackColor = true; this.btnCopy.Click += new EventHandler(this.btnCopy_Click); this.btnClose.Font = new Font("Segoe UI", 9f, FontStyle.Bold, GraphicsUnit.Point, (byte)0); this.btnClose.Location = new Point(291, 19); this.btnClose.Name = "btnClose"; this.btnClose.Size = new Size(75, 23); this.btnClose.TabIndex = 0; this.btnClose.Text = "Close"; this.btnClose.UseVisualStyleBackColor = true; this.btnClose.Click += new EventHandler(this.btnClose_Click); this.AutoScaleDimensions = new SizeF(6f, 13f); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new Size(396, 229); this.Controls.Add((Control)this.groupBox2); this.Controls.Add((Control)this.statusStrip1); this.Controls.Add((Control)this.groupBox1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = (Icon)resources.GetObject("$this.Icon"); this.MaximizeBox = false; this.Name = "frmDataCopy"; this.StartPosition = FormStartPosition.CenterParent; this.Text = "Copy data from a old backup to the new database"; this.FormClosing += new FormClosingEventHandler(this.frmDataCopy_FormClosing); this.Load += new EventHandler(this.frmDataCopy_Load); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.statusStrip1.ResumeLayout(false); this.statusStrip1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } } }
using System; using System.Text.RegularExpressions; using Orleans.GrainDirectory; using Orleans.Streams; namespace Orleans { namespace Concurrency { /// <summary> /// The ReadOnly attribute is used to mark methods that do not modify the state of a grain. /// <para> /// Marking methods as ReadOnly allows the run-time system to perform a number of optimizations /// that may significantly improve the performance of your application. /// </para> /// </summary> [AttributeUsage(AttributeTargets.Method)] internal sealed class ReadOnlyAttribute : Attribute { } /// <summary> /// The Reentrant attribute is used to mark grain implementation classes that allow request interleaving within a task. /// <para> /// This is an advanced feature and should not be used unless the implications are fully understood. /// That said, allowing request interleaving allows the run-time system to perform a number of optimizations /// that may significantly improve the performance of your application. /// </para> /// </summary> [AttributeUsage(AttributeTargets.Class)] public sealed class ReentrantAttribute : Attribute { } /// <summary> /// The Unordered attribute is used to mark grain interface in which the delivery order of /// messages is not significant. /// </summary> [AttributeUsage(AttributeTargets.Interface)] public sealed class UnorderedAttribute : Attribute { } /// <summary> /// The StatelessWorker attribute is used to mark grain class in which there is no expectation /// of preservation of grain state between requests and where multiple activations of the same grain are allowed to be created by the runtime. /// </summary> [AttributeUsage(AttributeTargets.Class)] public sealed class StatelessWorkerAttribute : Attribute { /// <summary> /// Maximal number of local StatelessWorkers in a single silo. /// </summary> public int MaxLocalWorkers { get; private set; } public StatelessWorkerAttribute(int maxLocalWorkers) { MaxLocalWorkers = maxLocalWorkers; } public StatelessWorkerAttribute() { MaxLocalWorkers = -1; } } /// <summary> /// The AlwaysInterleaveAttribute attribute is used to mark methods that can interleave with any other method type, including write (non ReadOnly) requests. /// </summary> /// <remarks> /// Note that this attribute is applied to method declaration in the grain interface, /// and not to the method in the implementation class itself. /// </remarks> [AttributeUsage(AttributeTargets.Method)] public sealed class AlwaysInterleaveAttribute : Attribute { } /// <summary> /// The MayInterleaveAttribute attribute is used to mark classes /// that want to control request interleaving via supplied method callback. /// </summary> /// <remarks> /// The callback method name should point to a public static function declared on the same class /// and having the following signature: <c>public static bool MayInterleave(InvokeMethodRequest req)</c> /// </remarks> [AttributeUsage(AttributeTargets.Class)] public sealed class MayInterleaveAttribute : Attribute { /// <summary> /// The name of the callback method /// </summary> internal string CallbackMethodName { get; private set; } public MayInterleaveAttribute(string callbackMethodName) { CallbackMethodName = callbackMethodName; } } /// <summary> /// The Immutable attribute indicates that instances of the marked class or struct are never modified /// after they are created. /// </summary> /// <remarks> /// Note that this implies that sub-objects are also not modified after the instance is created. /// </remarks> [AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class)] public sealed class ImmutableAttribute : Attribute { } /// <summary> /// Indicates that a method on a grain interface is one-way and that no response message will be sent to the caller. /// </summary> [AttributeUsage(AttributeTargets.Method)] public sealed class OneWayAttribute : Attribute { } } namespace MultiCluster { /// <summary> /// base class for multi cluster registration strategies. /// </summary> [AttributeUsage(AttributeTargets.Class)] public abstract class RegistrationAttribute : Attribute { internal MultiClusterRegistrationStrategy RegistrationStrategy { get; private set; } internal RegistrationAttribute(MultiClusterRegistrationStrategy strategy) { this.RegistrationStrategy = strategy; } } /// <summary> /// This attribute indicates that instances of the marked grain class will have a single instance across all available clusters. Any requests in any clusters will be forwarded to the single activation instance. /// </summary> public class GlobalSingleInstanceAttribute : RegistrationAttribute { public GlobalSingleInstanceAttribute() : base(GlobalSingleInstanceRegistration.Singleton) { } } /// <summary> /// This attribute indicates that instances of the marked grain class /// will have an independent instance for each cluster with /// no coordination. /// </summary> public class OneInstancePerClusterAttribute : RegistrationAttribute { public OneInstancePerClusterAttribute() : base(ClusterLocalRegistration.Singleton) { } } } namespace Placement { using Orleans.Runtime; /// <summary> /// Base for all placement policy marker attributes. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public abstract class PlacementAttribute : Attribute { internal PlacementStrategy PlacementStrategy { get; private set; } protected PlacementAttribute(PlacementStrategy placement) { if (placement == null) throw new ArgumentNullException(nameof(placement)); PlacementStrategy = placement; } } /// <summary> /// Marks a grain class as using the <c>RandomPlacement</c> policy. /// </summary> /// <remarks> /// This is the default placement policy, so this attribute does not need to be used for normal grains. /// </remarks> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public sealed class RandomPlacementAttribute : PlacementAttribute { public RandomPlacementAttribute() : base(RandomPlacement.Singleton) { } } /// <summary> /// Marks a grain class as using the <c>HashBasedPlacement</c> policy. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public sealed class HashBasedPlacementAttribute : PlacementAttribute { public HashBasedPlacementAttribute() : base(HashBasedPlacement.Singleton) {} } /// <summary> /// Marks a grain class as using the <c>PreferLocalPlacement</c> policy. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public sealed class PreferLocalPlacementAttribute : PlacementAttribute { public PreferLocalPlacementAttribute() : base(PreferLocalPlacement.Singleton) { } } /// <summary> /// Marks a grain class as using the <c>ActivationCountBasedPlacement</c> policy. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public sealed class ActivationCountBasedPlacementAttribute : PlacementAttribute { public ActivationCountBasedPlacementAttribute() : base(ActivationCountBasedPlacement.Singleton) { } } } namespace CodeGeneration { /// <summary> /// The TypeCodeOverrideAttribute attribute allows to specify the grain interface ID or the grain class type code /// to override the default ones to avoid hash collisions /// </summary> [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class)] public sealed class TypeCodeOverrideAttribute : Attribute { /// <summary> /// Use a specific grain interface ID or grain class type code (e.g. to avoid hash collisions) /// </summary> public int TypeCode { get; private set; } public TypeCodeOverrideAttribute(int typeCode) { TypeCode = typeCode; } } /// <summary> /// Specifies the method id for the interface method which this attribute is declared on. /// </summary> /// <remarks> /// Method ids must be unique for all methods in a given interface. /// This attribute is only applicable for interface method declarations, not for method definitions on classes. /// </remarks> [AttributeUsage(AttributeTargets.Method)] public sealed class MethodIdAttribute : Attribute { /// <summary> /// Gets the method id for the interface method this attribute is declared on. /// </summary> public int MethodId { get; } /// <summary> /// Specifies the method id for the interface method which this attribute is declared on. /// </summary> /// <remarks> /// Method ids must be unique for all methods in a given interface. /// This attribute is only valid only on interface method declarations, not on method definitions. /// </remarks> /// <param name="methodId">The method id.</param> public MethodIdAttribute(int methodId) { this.MethodId = methodId; } } /// <summary> /// The VersionAttribute allows to specify the version number of the interface /// </summary> [AttributeUsage(AttributeTargets.Interface)] public sealed class VersionAttribute : Attribute { public ushort Version { get; private set; } public VersionAttribute(ushort version) { Version = version; } } /// <summary> /// Used to mark a method as providing a copier function for that type. /// </summary> [AttributeUsage(AttributeTargets.Method)] public sealed class CopierMethodAttribute : Attribute { } /// <summary> /// Used to mark a method as providing a serializer function for that type. /// </summary> [AttributeUsage(AttributeTargets.Method)] public sealed class SerializerMethodAttribute : Attribute { } /// <summary> /// Used to mark a method as providing a deserializer function for that type. /// </summary> [AttributeUsage(AttributeTargets.Method)] public sealed class DeserializerMethodAttribute : Attribute { } } namespace Providers { /// <summary> /// The [Orleans.Providers.StorageProvider] attribute is used to define which storage provider to use for persistence of grain state. /// <para> /// Specifying [Orleans.Providers.StorageProvider] property is recommended for all grains which extend Grain&lt;T&gt;. /// If no [Orleans.Providers.StorageProvider] attribute is specified, then a "Default" strorage provider will be used. /// If a suitable storage provider cannot be located for this grain, then the grain will fail to load into the Silo. /// </para> /// </summary> [AttributeUsage(AttributeTargets.Class)] public sealed class StorageProviderAttribute : Attribute { /// <summary> /// The name of the provider to be used for persisting of grain state /// </summary> public string ProviderName { get; set; } public StorageProviderAttribute() { ProviderName = Runtime.Constants.DEFAULT_STORAGE_PROVIDER_NAME; } } /// <summary> /// The [Orleans.Providers.LogConsistencyProvider] attribute is used to define which consistency provider to use for grains using the log-view state abstraction. /// <para> /// Specifying [Orleans.Providers.LogConsistencyProvider] property is recommended for all grains that derive /// from ILogConsistentGrain, such as JournaledGrain. /// If no [Orleans.Providers.LogConsistencyProvider] attribute is specified, then the runtime tries to locate /// one as follows. First, it looks for a /// "Default" provider in the configuration file, then it checks if the grain type defines a default. /// If a consistency provider cannot be located for this grain, then the grain will fail to load into the Silo. /// </para> /// </summary> [AttributeUsage(AttributeTargets.Class)] public sealed class LogConsistencyProviderAttribute : Attribute { /// <summary> /// The name of the provider to be used for consistency /// </summary> public string ProviderName { get; set; } public LogConsistencyProviderAttribute() { ProviderName = Runtime.Constants.DEFAULT_LOG_CONSISTENCY_PROVIDER_NAME; } } } /// <summary> /// The [Orleans.ImplicitStreamSubscription] attribute is used to mark grains as implicit stream subscriptions. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class ImplicitStreamSubscriptionAttribute : Attribute { /// <summary> /// Gets the stream namespace filter predicate. /// </summary> public IStreamNamespacePredicate Predicate { get; } /// <summary> /// Used to subscribe to all stream namespaces. /// </summary> public ImplicitStreamSubscriptionAttribute() { Predicate = new AllStreamNamespacesPredicate(); } /// <summary> /// Used to subscribe to the specified stream namespace. /// </summary> /// <param name="streamNamespace">The stream namespace to subscribe.</param> public ImplicitStreamSubscriptionAttribute(string streamNamespace) { Predicate = new ExactMatchStreamNamespacePredicate(streamNamespace.Trim()); } /// <summary> /// Allows to pass an arbitrary predicate type to filter stream namespaces to subscribe. The predicate type /// must have a constructor without parameters. /// </summary> /// <param name="predicateType">The stream namespace predicate type.</param> public ImplicitStreamSubscriptionAttribute(Type predicateType) { Predicate = (IStreamNamespacePredicate)Activator.CreateInstance(predicateType); } /// <summary> /// Allows to pass an instance of the stream namespace predicate. To be used mainly as an extensibility point /// via inheriting attributes. /// </summary> /// <param name="predicate">The stream namespace predicate.</param> public ImplicitStreamSubscriptionAttribute(IStreamNamespacePredicate predicate) { Predicate = predicate; } } /// <summary> /// The [Orleans.RegexImplicitStreamSubscription] attribute is used to mark grains as implicit stream /// subscriptions by filtering stream namespaces to subscribe using a regular expression. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public sealed class RegexImplicitStreamSubscriptionAttribute : ImplicitStreamSubscriptionAttribute { /// <summary> /// Allows to pass a regular expression to filter stream namespaces to subscribe to. /// </summary> /// <param name="pattern">The stream namespace regular expression filter.</param> public RegexImplicitStreamSubscriptionAttribute(string pattern) : base(new RegexStreamNamespacePredicate(new Regex(pattern))) { } } }
using Prism.Properties; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Linq; using System.Windows.Markup; namespace Prism.Modularity { /// <summary> /// The <see cref="ModuleCatalog"/> holds information about the modules that can be used by the /// application. Each module is described in a <see cref="ModuleInfo"/> class, that records the /// name, type and location of the module. /// /// It also verifies that the <see cref="ModuleCatalog"/> is internally valid. That means that /// it does not have: /// <list> /// <item>Circular dependencies</item> /// <item>Missing dependencies</item> /// <item> /// Invalid dependencies, such as a Module that's loaded at startup that depends on a module /// that might need to be retrieved. /// </item> /// </list> /// The <see cref="ModuleCatalog"/> also serves as a baseclass for more specialized Catalogs . /// </summary> [ContentProperty("Items")] public class ModuleCatalog : IModuleCatalog { private readonly ModuleCatalogItemCollection items; private bool isLoaded; /// <summary> /// Initializes a new instance of the <see cref="ModuleCatalog"/> class. /// </summary> public ModuleCatalog() { this.items = new ModuleCatalogItemCollection(); this.items.CollectionChanged += this.ItemsCollectionChanged; } /// <summary> /// Initializes a new instance of the <see cref="ModuleCatalog"/> class while providing an /// initial list of <see cref="ModuleInfo"/>s. /// </summary> /// <param name="modules">The initial list of modules.</param> public ModuleCatalog(IEnumerable<ModuleInfo> modules) : this() { if (modules == null) throw new ArgumentNullException(nameof(modules)); foreach (ModuleInfo moduleInfo in modules) { this.Items.Add(moduleInfo); } } /// <summary> /// Gets the items in the <see cref="ModuleCatalog"/>. This property is mainly used to add <see cref="ModuleInfoGroup"/>s or /// <see cref="ModuleInfo"/>s through XAML. /// </summary> /// <value>The items in the catalog.</value> public Collection<IModuleCatalogItem> Items { get { return this.items; } } /// <summary> /// Gets all the <see cref="ModuleInfo"/> classes that are in the <see cref="ModuleCatalog"/>, regardless /// if they are within a <see cref="ModuleInfoGroup"/> or not. /// </summary> /// <value>The modules.</value> public virtual IEnumerable<ModuleInfo> Modules { get { return this.GrouplessModules.Union(this.Groups.SelectMany(g => g)); } } /// <summary> /// Gets the <see cref="ModuleInfoGroup"/>s that have been added to the <see cref="ModuleCatalog"/>. /// </summary> /// <value>The groups.</value> public IEnumerable<ModuleInfoGroup> Groups { get { return this.Items.OfType<ModuleInfoGroup>(); } } /// <summary> /// Gets or sets a value that remembers whether the <see cref="ModuleCatalog"/> has been validated already. /// </summary> protected bool Validated { get; set; } /// <summary> /// Returns the list of <see cref="ModuleInfo"/>s that are not contained within any <see cref="ModuleInfoGroup"/>. /// </summary> /// <value>The groupless modules.</value> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Groupless")] protected IEnumerable<ModuleInfo> GrouplessModules { get { return this.Items.OfType<ModuleInfo>(); } } /// <summary> /// Creates a <see cref="ModuleCatalog"/> from XAML. /// </summary> /// <param name="xamlStream"><see cref="Stream"/> that contains the XAML declaration of the catalog.</param> /// <returns>An instance of <see cref="ModuleCatalog"/> built from the XAML.</returns> public static ModuleCatalog CreateFromXaml(Stream xamlStream) { if (xamlStream == null) { throw new ArgumentNullException(nameof(xamlStream)); } return XamlReader.Load(xamlStream) as ModuleCatalog; } /// <summary> /// Creates a <see cref="ModuleCatalog"/> from a XAML included as an Application Resource. /// </summary> /// <param name="builderResourceUri">Relative <see cref="Uri"/> that identifies the XAML included as an Application Resource.</param> /// <returns>An instance of <see cref="ModuleCatalog"/> build from the XAML.</returns> public static ModuleCatalog CreateFromXaml(Uri builderResourceUri) { var streamInfo = System.Windows.Application.GetResourceStream(builderResourceUri); if ((streamInfo != null) && (streamInfo.Stream != null)) { return CreateFromXaml(streamInfo.Stream); } return null; } /// <summary> /// Loads the catalog if necessary. /// </summary> public void Load() { this.isLoaded = true; this.InnerLoad(); } /// <summary> /// Return the list of <see cref="ModuleInfo"/>s that <paramref name="moduleInfo"/> depends on. /// </summary> /// <remarks> /// If the <see cref="ModuleCatalog"/> was not yet validated, this method will call <see cref="Validate"/>. /// </remarks> /// <param name="moduleInfo">The <see cref="ModuleInfo"/> to get the </param> /// <returns>An enumeration of <see cref="ModuleInfo"/> that <paramref name="moduleInfo"/> depends on.</returns> public virtual IEnumerable<ModuleInfo> GetDependentModules(ModuleInfo moduleInfo) { this.EnsureCatalogValidated(); return this.GetDependentModulesInner(moduleInfo); } /// <summary> /// Returns a list of <see cref="ModuleInfo"/>s that contain both the <see cref="ModuleInfo"/>s in /// <paramref name="modules"/>, but also all the modules they depend on. /// </summary> /// <param name="modules">The modules to get the dependencies for.</param> /// <returns> /// A list of <see cref="ModuleInfo"/> that contains both all <see cref="ModuleInfo"/>s in <paramref name="modules"/> /// but also all the <see cref="ModuleInfo"/> they depend on. /// </returns> public virtual IEnumerable<ModuleInfo> CompleteListWithDependencies(IEnumerable<ModuleInfo> modules) { if (modules == null) throw new ArgumentNullException(nameof(modules)); this.EnsureCatalogValidated(); List<ModuleInfo> completeList = new List<ModuleInfo>(); List<ModuleInfo> pendingList = modules.ToList(); while (pendingList.Count > 0) { ModuleInfo moduleInfo = pendingList[0]; foreach (ModuleInfo dependency in this.GetDependentModules(moduleInfo)) { if (!completeList.Contains(dependency) && !pendingList.Contains(dependency)) { pendingList.Add(dependency); } } pendingList.RemoveAt(0); completeList.Add(moduleInfo); } IEnumerable<ModuleInfo> sortedList = this.Sort(completeList); return sortedList; } /// <summary> /// Validates the <see cref="ModuleCatalog"/>. /// </summary> /// <exception cref="ModularityException">When validation of the <see cref="ModuleCatalog"/> fails.</exception> public virtual void Validate() { this.ValidateUniqueModules(); this.ValidateDependencyGraph(); this.ValidateCrossGroupDependencies(); this.ValidateDependenciesInitializationMode(); this.Validated = true; } /// <summary> /// Adds a <see cref="ModuleInfo"/> to the <see cref="ModuleCatalog"/>. /// </summary> /// <param name="moduleInfo">The <see cref="ModuleInfo"/> to add.</param> /// <returns>The <see cref="ModuleCatalog"/> for easily adding multiple modules.</returns> public virtual void AddModule(ModuleInfo moduleInfo) { this.Items.Add(moduleInfo); } /// <summary> /// Adds a groupless <see cref="ModuleInfo"/> to the catalog. /// </summary> /// <param name="moduleType"><see cref="Type"/> of the module to be added.</param> /// <param name="dependsOn">Collection of module names (<see cref="ModuleInfo.ModuleName"/>) of the modules on which the module to be added logically depends on.</param> /// <returns>The same <see cref="ModuleCatalog"/> instance with the added module.</returns> public ModuleCatalog AddModule(Type moduleType, params string[] dependsOn) { return this.AddModule(moduleType, InitializationMode.WhenAvailable, dependsOn); } /// <summary> /// Adds a groupless <see cref="ModuleInfo"/> to the catalog. /// </summary> /// <param name="moduleType"><see cref="Type"/> of the module to be added.</param> /// <param name="initializationMode">Stage on which the module to be added will be initialized.</param> /// <param name="dependsOn">Collection of module names (<see cref="ModuleInfo.ModuleName"/>) of the modules on which the module to be added logically depends on.</param> /// <returns>The same <see cref="ModuleCatalog"/> instance with the added module.</returns> public ModuleCatalog AddModule(Type moduleType, InitializationMode initializationMode, params string[] dependsOn) { if (moduleType == null) throw new ArgumentNullException(nameof(moduleType)); return this.AddModule(moduleType.Name, moduleType.AssemblyQualifiedName, initializationMode, dependsOn); } /// <summary> /// Adds a groupless <see cref="ModuleInfo"/> to the catalog. /// </summary> /// <param name="moduleName">Name of the module to be added.</param> /// <param name="moduleType"><see cref="Type"/> of the module to be added.</param> /// <param name="dependsOn">Collection of module names (<see cref="ModuleInfo.ModuleName"/>) of the modules on which the module to be added logically depends on.</param> /// <returns>The same <see cref="ModuleCatalog"/> instance with the added module.</returns> public ModuleCatalog AddModule(string moduleName, string moduleType, params string[] dependsOn) { return this.AddModule(moduleName, moduleType, InitializationMode.WhenAvailable, dependsOn); } /// <summary> /// Adds a groupless <see cref="ModuleInfo"/> to the catalog. /// </summary> /// <param name="moduleName">Name of the module to be added.</param> /// <param name="moduleType"><see cref="Type"/> of the module to be added.</param> /// <param name="initializationMode">Stage on which the module to be added will be initialized.</param> /// <param name="dependsOn">Collection of module names (<see cref="ModuleInfo.ModuleName"/>) of the modules on which the module to be added logically depends on.</param> /// <returns>The same <see cref="ModuleCatalog"/> instance with the added module.</returns> public ModuleCatalog AddModule(string moduleName, string moduleType, InitializationMode initializationMode, params string[] dependsOn) { return this.AddModule(moduleName, moduleType, null, initializationMode, dependsOn); } /// <summary> /// Adds a groupless <see cref="ModuleInfo"/> to the catalog. /// </summary> /// <param name="moduleName">Name of the module to be added.</param> /// <param name="moduleType"><see cref="Type"/> of the module to be added.</param> /// <param name="refValue">Reference to the location of the module to be added assembly.</param> /// <param name="initializationMode">Stage on which the module to be added will be initialized.</param> /// <param name="dependsOn">Collection of module names (<see cref="ModuleInfo.ModuleName"/>) of the modules on which the module to be added logically depends on.</param> /// <returns>The same <see cref="ModuleCatalog"/> instance with the added module.</returns> public ModuleCatalog AddModule(string moduleName, string moduleType, string refValue, InitializationMode initializationMode, params string[] dependsOn) { if (moduleName == null) throw new ArgumentNullException(nameof(moduleName)); if (moduleType == null) throw new ArgumentNullException(nameof(moduleType)); ModuleInfo moduleInfo = new ModuleInfo(moduleName, moduleType); moduleInfo.DependsOn.AddRange(dependsOn); moduleInfo.InitializationMode = initializationMode; moduleInfo.Ref = refValue; this.Items.Add(moduleInfo); return this; } /// <summary> /// Initializes the catalog, which may load and validate the modules. /// </summary> /// <exception cref="ModularityException">When validation of the <see cref="ModuleCatalog"/> fails, because this method calls <see cref="Validate"/>.</exception> public virtual void Initialize() { if (!this.isLoaded) { this.Load(); } this.Validate(); } /// <summary> /// Creates and adds a <see cref="ModuleInfoGroup"/> to the catalog. /// </summary> /// <param name="initializationMode">Stage on which the module group to be added will be initialized.</param> /// <param name="refValue">Reference to the location of the module group to be added.</param> /// <param name="moduleInfos">Collection of <see cref="ModuleInfo"/> included in the group.</param> /// <returns><see cref="ModuleCatalog"/> with the added module group.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] public virtual ModuleCatalog AddGroup(InitializationMode initializationMode, string refValue, params ModuleInfo[] moduleInfos) { if (moduleInfos == null) throw new ArgumentNullException(nameof(moduleInfos)); ModuleInfoGroup newGroup = new ModuleInfoGroup(); newGroup.InitializationMode = initializationMode; newGroup.Ref = refValue; foreach (ModuleInfo info in moduleInfos) { newGroup.Add(info); } this.items.Add(newGroup); return this; } /// <summary> /// Checks for cyclic dependencies, by calling the dependencysolver. /// </summary> /// <param name="modules">the.</param> /// <returns></returns> protected static string[] SolveDependencies(IEnumerable<ModuleInfo> modules) { if (modules == null) throw new ArgumentNullException(nameof(modules)); ModuleDependencySolver solver = new ModuleDependencySolver(); foreach (ModuleInfo data in modules) { solver.AddModule(data.ModuleName); if (data.DependsOn != null) { foreach (string dependency in data.DependsOn) { solver.AddDependency(data.ModuleName, dependency); } } } if (solver.ModuleCount > 0) { return solver.Solve(); } return new string[0]; } /// <summary> /// Ensures that all the dependencies within <paramref name="modules"/> refer to <see cref="ModuleInfo"/>s /// within that list. /// </summary> /// <param name="modules">The modules to validate modules for.</param> /// <exception cref="ModularityException"> /// Throws if a <see cref="ModuleInfo"/> in <paramref name="modules"/> depends on a module that's /// not in <paramref name="modules"/>. /// </exception> /// <exception cref="ArgumentNullException">Throws if <paramref name="modules"/> is <see langword="null"/>.</exception> protected static void ValidateDependencies(IEnumerable<ModuleInfo> modules) { if (modules == null) throw new ArgumentNullException(nameof(modules)); var moduleNames = modules.Select(m => m.ModuleName).ToList(); foreach (ModuleInfo moduleInfo in modules) { if (moduleInfo.DependsOn != null && moduleInfo.DependsOn.Except(moduleNames).Any()) { throw new ModularityException( moduleInfo.ModuleName, String.Format(CultureInfo.CurrentCulture, Resources.ModuleDependenciesNotMetInGroup, moduleInfo.ModuleName)); } } } /// <summary> /// Does the actual work of loading the catalog. The base implementation does nothing. /// </summary> protected virtual void InnerLoad() { } /// <summary> /// Sorts a list of <see cref="ModuleInfo"/>s. This method is called by <see cref="CompleteListWithDependencies"/> /// to return a sorted list. /// </summary> /// <param name="modules">The <see cref="ModuleInfo"/>s to sort.</param> /// <returns>Sorted list of <see cref="ModuleInfo"/>s</returns> protected virtual IEnumerable<ModuleInfo> Sort(IEnumerable<ModuleInfo> modules) { foreach (string moduleName in SolveDependencies(modules)) { yield return modules.First(m => m.ModuleName == moduleName); } } /// <summary> /// Makes sure all modules have an Unique name. /// </summary> /// <exception cref="DuplicateModuleException"> /// Thrown if the names of one or more modules are not unique. /// </exception> protected virtual void ValidateUniqueModules() { List<string> moduleNames = this.Modules.Select(m => m.ModuleName).ToList(); string duplicateModule = moduleNames.FirstOrDefault( m => moduleNames.Count(m2 => m2 == m) > 1); if (duplicateModule != null) { throw new DuplicateModuleException(duplicateModule, String.Format(CultureInfo.CurrentCulture, Resources.DuplicatedModule, duplicateModule)); } } /// <summary> /// Ensures that there are no cyclic dependencies. /// </summary> protected virtual void ValidateDependencyGraph() { SolveDependencies(this.Modules); } /// <summary> /// Ensures that there are no dependencies between modules on different groups. /// </summary> /// <remarks> /// A groupless module can only depend on other groupless modules. /// A module within a group can depend on other modules within the same group and/or on groupless modules. /// </remarks> protected virtual void ValidateCrossGroupDependencies() { ValidateDependencies(this.GrouplessModules); foreach (ModuleInfoGroup group in this.Groups) { ValidateDependencies(this.GrouplessModules.Union(group)); } } /// <summary> /// Ensures that there are no modules marked to be loaded <see cref="InitializationMode.WhenAvailable"/> /// depending on modules loaded <see cref="InitializationMode.OnDemand"/> /// </summary> protected virtual void ValidateDependenciesInitializationMode() { ModuleInfo moduleInfo = this.Modules.FirstOrDefault( m => m.InitializationMode == InitializationMode.WhenAvailable && this.GetDependentModulesInner(m) .Any(dependency => dependency.InitializationMode == InitializationMode.OnDemand)); if (moduleInfo != null) { throw new ModularityException( moduleInfo.ModuleName, String.Format(CultureInfo.CurrentCulture, Resources.StartupModuleDependsOnAnOnDemandModule, moduleInfo.ModuleName)); } } /// <summary> /// Returns the <see cref="ModuleInfo"/> on which the received module dependens on. /// </summary> /// <param name="moduleInfo">Module whose dependant modules are requested.</param> /// <returns>Collection of <see cref="ModuleInfo"/> dependants of <paramref name="moduleInfo"/>.</returns> protected virtual IEnumerable<ModuleInfo> GetDependentModulesInner(ModuleInfo moduleInfo) { return this.Modules.Where(dependantModule => moduleInfo.DependsOn.Contains(dependantModule.ModuleName)); } /// <summary> /// Ensures that the catalog is validated. /// </summary> protected virtual void EnsureCatalogValidated() { if (!this.Validated) { this.Validate(); } } private void ItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (this.Validated) { this.EnsureCatalogValidated(); } } private class ModuleCatalogItemCollection : Collection<IModuleCatalogItem>, INotifyCollectionChanged { public event NotifyCollectionChangedEventHandler CollectionChanged; protected override void InsertItem(int index, IModuleCatalogItem item) { base.InsertItem(index, item); this.OnNotifyCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index)); } protected void OnNotifyCollectionChanged(NotifyCollectionChangedEventArgs eventArgs) { if (this.CollectionChanged != null) { this.CollectionChanged(this, eventArgs); } } } } }
/* Copyright (c) 2012 Jakub Misek The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ using System; using PHP.Core; using System.Text; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; using System.ComponentModel; #if SILVERLIGHT using PHP.CoreCLR; using System.Windows.Browser; #else using System.Web; using System.Diagnostics; #endif namespace PHP.Library { #region Constants public enum FilterInput : int { [ImplementsConstant("INPUT_POST")] Post = 0, [ImplementsConstant("INPUT_GET")] Get = 1, [ImplementsConstant("INPUT_COOKIE")] Cookie = 2, [ImplementsConstant("INPUT_ENV")] Env = 4, [ImplementsConstant("INPUT_SERVER")] Server = 5, [ImplementsConstant("INPUT_SESSION")] Session = 6, [ImplementsConstant("INPUT_REQUEST")] Request = 99 } /// <summary> /// Other filter ids. /// </summary> public enum FilterIds : int { /// <summary> /// Flag used to require scalar as input /// </summary> [ImplementsConstant("FILTER_REQUIRE_SCALAR")] FILTER_REQUIRE_SCALAR = 33554432, /// <summary> /// Require an array as input. /// </summary> [ImplementsConstant("FILTER_REQUIRE_ARRAY")] FILTER_REQUIRE_ARRAY = 16777216, /// <summary> /// Always returns an array. /// </summary> [ImplementsConstant("FILTER_FORCE_ARRAY")] FILTER_FORCE_ARRAY = 67108864, /// <summary> /// Use NULL instead of FALSE on failure. /// </summary> [ImplementsConstant("FILTER_NULL_ON_FAILURE")] FILTER_NULL_ON_FAILURE = 134217728, /// <summary> /// ID of "callback" filter. /// </summary> [ImplementsConstant("FILTER_CALLBACK")] FILTER_CALLBACK = 1024, } /// <summary> /// Validation filters. /// </summary> public enum FilterValidate : int { /// <summary> /// ID of "int" filter. /// </summary> [ImplementsConstant("FILTER_VALIDATE_INT")] INT = 257, /// <summary> /// ID of "boolean" filter. /// </summary> [ImplementsConstant("FILTER_VALIDATE_BOOLEAN")] BOOLEAN = 258, /// <summary> /// ID of "float" filter. /// </summary> [ImplementsConstant("FILTER_VALIDATE_FLOAT")] FLOAT = 259, /// <summary> /// ID of "validate_regexp" filter. /// </summary> [ImplementsConstant("FILTER_VALIDATE_REGEXP")] REGEXP = 272, /// <summary> /// ID of "validate_url" filter. /// </summary> [ImplementsConstant("FILTER_VALIDATE_URL")] URL = 273, /// <summary> /// ID of "validate_email" filter. /// </summary> [ImplementsConstant("FILTER_VALIDATE_EMAIL")] EMAIL = 274, /// <summary> /// ID of "validate_ip" filter. /// </summary> [ImplementsConstant("FILTER_VALIDATE_IP")] IP = 275, } /// <summary> /// Sanitize filters. /// </summary> public enum FilterSanitize : int { /// <summary> /// ID of "string" filter. /// </summary> [ImplementsConstant("FILTER_SANITIZE_STRING")] STRING = 513, /// <summary> /// ID of "stripped" filter. /// </summary> [ImplementsConstant("FILTER_SANITIZE_STRIPPED")] STRIPPED = STRING, // alias of FILTER_SANITIZE_STRING /// <summary> /// ID of "encoded" filter. /// </summary> [ImplementsConstant("FILTER_SANITIZE_ENCODED")] ENCODED = 514, /// <summary> /// ID of "special_chars" filter. /// </summary> [ImplementsConstant("FILTER_SANITIZE_SPECIAL_CHARS")] SPECIAL_CHARS = 515, /// <summary> /// ID of "unsafe_raw" filter. /// </summary> [ImplementsConstant("FILTER_UNSAFE_RAW")] FILTER_UNSAFE_RAW = 516, /// <summary> /// ID of default ("string") filter. /// </summary> [ImplementsConstant("FILTER_DEFAULT")] FILTER_DEFAULT = FILTER_UNSAFE_RAW, // alias of FILTER_UNSAFE_RAW /// <summary> /// ID of "email" filter. /// Remove all characters except letters, digits and !#$%&amp;'*+-/=?^_`{|}~@.[]. /// </summary> [ImplementsConstant("FILTER_SANITIZE_EMAIL")] EMAIL = 517, /// <summary> /// ID of "url" filter. /// </summary> [ImplementsConstant("FILTER_SANITIZE_URL")] URL = 518, /// <summary> /// ID of "number_int" filter. /// </summary> [ImplementsConstant("FILTER_SANITIZE_NUMBER_INT")] NUMBER_INT = 519, /// <summary> /// ID of "number_float" filter. /// </summary> [ImplementsConstant("FILTER_SANITIZE_NUMBER_FLOAT")] NUMBER_FLOAT = 520, /// <summary> /// ID of "magic_quotes" filter. /// </summary> [ImplementsConstant("FILTER_SANITIZE_MAGIC_QUOTES")] MAGIC_QUOTES = 521, } [Flags] public enum FilterFlag : int { /// <summary> /// No flags. /// </summary> [ImplementsConstant("FILTER_FLAG_NONE")] NONE = 0, /// <summary> /// Allow octal notation (0[0-7]+) in "int" filter. /// </summary> [ImplementsConstant("FILTER_FLAG_ALLOW_OCTAL")] ALLOW_OCTAL = 1, /// <summary> /// Allow hex notation (0x[0-9a-fA-F]+) in "int" filter. /// </summary> [ImplementsConstant("FILTER_FLAG_ALLOW_HEX")] ALLOW_HEX = 2, /// <summary> /// Strip characters with ASCII value less than 32. /// </summary> [ImplementsConstant("FILTER_FLAG_STRIP_LOW")] STRIP_LOW = 4, /// <summary> /// Strip characters with ASCII value greater than 127. /// </summary> [ImplementsConstant("FILTER_FLAG_STRIP_HIGH")] STRIP_HIGH = 8, /// <summary> /// Encode characters with ASCII value less than 32. /// </summary> [ImplementsConstant("FILTER_FLAG_ENCODE_LOW")] ENCODE_LOW = 16, /// <summary> /// Encode characters with ASCII value greater than 127. /// </summary> [ImplementsConstant("FILTER_FLAG_ENCODE_HIGH")] ENCODE_HIGH = 32, /// <summary> /// Encode &amp;. /// </summary> [ImplementsConstant("FILTER_FLAG_ENCODE_AMP")] ENCODE_AMP = 64, /// <summary> /// Don't encode ' and ". /// </summary> [ImplementsConstant("FILTER_FLAG_NO_ENCODE_QUOTES")] NO_ENCODE_QUOTES = 128, /// <summary> /// ? /// </summary> [ImplementsConstant("FILTER_FLAG_EMPTY_STRING_NULL")] EMPTY_STRING_NULL = 256, /// <summary> /// Allow fractional part in "number_float" filter. /// </summary> [ImplementsConstant("FILTER_FLAG_ALLOW_FRACTION")] ALLOW_FRACTION = 4096, /// <summary> /// Allow thousand separator (,) in "number_float" filter. /// </summary> [ImplementsConstant("FILTER_FLAG_ALLOW_THOUSAND")] ALLOW_THOUSAND = 8192, /// <summary> /// Allow scientific notation (e, E) in "number_float" filter. /// </summary> [ImplementsConstant("FILTER_FLAG_ALLOW_SCIENTIFIC")] ALLOW_SCIENTIFIC = 16384, /// <summary> /// Require path in "validate_url" filter. /// </summary> [ImplementsConstant("FILTER_FLAG_PATH_REQUIRED")] PATH_REQUIRED = 262144, /// <summary> /// Require query in "validate_url" filter. /// </summary> [ImplementsConstant("FILTER_FLAG_QUERY_REQUIRED")] QUERY_REQUIRED = 524288, /// <summary> /// Allow only IPv4 address in "validate_ip" filter. /// </summary> [ImplementsConstant("FILTER_FLAG_IPV4")] IPV4 = 1048576, /// <summary> /// Allow only IPv6 address in "validate_ip" filter. /// </summary> [ImplementsConstant("FILTER_FLAG_IPV6")] IPV6 = 2097152, /// <summary> /// Deny reserved addresses in "validate_ip" filter. /// </summary> [ImplementsConstant("FILTER_FLAG_NO_RES_RANGE")] NO_RES_RANGE = 4194304, /// <summary> /// Deny private addresses in "validate_ip" filter. /// </summary> [ImplementsConstant("FILTER_FLAG_NO_PRIV_RANGE")] NO_PRIV_RANGE = 8388608 } #endregion [ImplementsExtension("filter")] public static class PhpFiltering { #region (NS) filter_input_array, filter_var_array, filter_id, filter_list [ImplementsFunction("filter_input_array", FunctionImplOptions.NotSupported)] public static object filter_input_array(int type) { return filter_input_array(type, null); } /// <summary> /// Gets external variables and optionally filters them. /// </summary> [ImplementsFunction("filter_input_array", FunctionImplOptions.NotSupported)] public static object filter_input_array(int type, object definition) { return false; } /// <summary> /// Returns the filter ID belonging to a named filter. /// </summary> [ImplementsFunction("filter_id", FunctionImplOptions.NotSupported)] [return: CastToFalse] public static int filter_id(string filtername) { return -1; } /// <summary> /// Returns a list of all supported filters. /// </summary> [ImplementsFunction("filter_list", FunctionImplOptions.NotSupported)] public static PhpArray/*!*/filter_list() { return new PhpArray(); } [ImplementsFunction("filter_var_array", FunctionImplOptions.NotSupported)] public static object filter_var_array(PhpArray data) { return filter_var_array(data, null); } /// <summary> /// Gets multiple variables and optionally filters them. /// </summary> /// <returns></returns> [ImplementsFunction("filter_var_array", FunctionImplOptions.NotSupported)] public static object filter_var_array(PhpArray data, object definition) { return null; } #endregion #region filter_input [ImplementsFunction("filter_input")] public static object filter_input(ScriptContext/*!*/context, FilterInput type, string variable_name) { return filter_input(context, type, variable_name, (int)FilterSanitize.FILTER_DEFAULT, null); } [ImplementsFunction("filter_input")] public static object filter_input(ScriptContext/*!*/context, FilterInput type, string variable_name, int filter) { return filter_input(context, type, variable_name, filter, null); } /// <summary> /// Gets a specific external variable by name and optionally filters it. /// </summary> [ImplementsFunction("filter_input")] public static object filter_input(ScriptContext/*!*/context, FilterInput type, string variable_name, int filter /*= FILTER_DEFAULT*/ , object options) { var arrayobj = GetArrayByInput(context, type); object value; if (arrayobj == null || !arrayobj.TryGetValue(variable_name, out value)) return null; return filter_var(value, filter, options); } #endregion #region filter_var, filter_has_var /// <summary> /// Checks if variable of specified type exists /// </summary> [ImplementsFunction("filter_has_var")] public static bool filter_has_var(ScriptContext/*!*/context, FilterInput type, string variable_name) { var arrayobj = GetArrayByInput(context, type); if (arrayobj != null) return arrayobj.ContainsKey(variable_name); else return false; } /// <summary> /// Returns <see cref="PhpArray"/> containing required input. /// </summary> /// <param name="context">CUrrent <see cref="ScriptContext"/>.</param> /// <param name="type"><see cref="FilterInput"/> value.</param> /// <returns>An instance of <see cref="PhpArray"/> or <c>null</c> if there is no such input.</returns> private static PhpArray GetArrayByInput(ScriptContext/*!*/context, FilterInput type) { object arrayobj = null; switch (type) { case FilterInput.Get: arrayobj = context.AutoGlobals.Get.Value; break; case FilterInput.Post: arrayobj = context.AutoGlobals.Post.Value; break; case FilterInput.Server: arrayobj = context.AutoGlobals.Server.Value; break; case FilterInput.Request: arrayobj = context.AutoGlobals.Request.Value; break; case FilterInput.Env: arrayobj = context.AutoGlobals.Env.Value; break; case FilterInput.Cookie: arrayobj = context.AutoGlobals.Cookie.Value; break; case FilterInput.Session: arrayobj = context.AutoGlobals.Session.Value; break; default: return null; } // cast arrayobj to PhpArray if possible: return PhpArray.AsPhpArray(arrayobj); } [ImplementsFunction("filter_var")] public static object filter_var(object variable) { return filter_var(variable, (int)FilterSanitize.FILTER_DEFAULT, null); } [ImplementsFunction("filter_var")] public static object filter_var(object variable, int filter) { return filter_var(variable, filter, null); } /// <summary> /// Filters a variable with a specified filter. /// </summary> /// <param name="variable">Value to filter.</param> /// <param name="filter">The ID of the filter to apply.</param> /// <param name="options">Associative array of options or bitwise disjunction of flags. If filter accepts options, flags can be provided in "flags" field of array. For the "callback" filter, callback type should be passed. The callback must accept one argument, the value to be filtered, and return the value after filtering/sanitizing it.</param> /// <returns>Returns the filtered data, or <c>false</c> if the filter fails.</returns> [ImplementsFunction("filter_var")] public static object filter_var(object variable, int filter /*= FILTER_DEFAULT*/ , object options) { switch (filter) { // // SANITIZE // case (int)FilterSanitize.FILTER_DEFAULT: return Core.Convert.ObjectToString(variable); case (int)FilterSanitize.EMAIL: // Remove all characters except letters, digits and !#$%&'*+-/=?^_`{|}~@.[]. return FilterSanitizeString(PHP.Core.Convert.ObjectToString(variable), (c) => (int)c <= 0x7f && (Char.IsLetterOrDigit(c) || c == '!' || c == '#' || c == '$' || c == '%' || c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' || c == '/' || c == '=' || c == '!' || c == '?' || c == '^' || c == '_' || c == '`' || c == '{' || c == '|' || c == '}' || c == '~' || c == '@' || c == '.' || c == '[' || c == ']')); // // VALIDATE // case (int)FilterValidate.EMAIL: { var str = PHP.Core.Convert.ObjectToString(variable); return RegexUtilities.IsValidEmail(str) ? str : (object)false; } case (int)FilterValidate.INT: { int result; if (int.TryParse((PhpVariable.AsString(variable) ?? string.Empty).Trim(), out result)) { if (options != null) PhpException.ArgumentValueNotSupported("options", "!null"); return result; // TODO: options: min_range, max_range } else return false; } case (int)FilterValidate.REGEXP: { PhpArray optarray; // options = options['options']['regexp'] if ((optarray = PhpArray.AsPhpArray(options)) != null && optarray.TryGetValue("options", out options) && (optarray = PhpArray.AsPhpArray(options)) != null && optarray.TryGetValue("regexp", out options)) { if (PerlRegExp.Match(options, variable) > 0) return variable; } else PhpException.InvalidArgument("options", LibResources.GetString("option_missing", "regexp")); return false; } default: PhpException.ArgumentValueNotSupported("filter", filter); break; } return false; } #endregion #region Helper filter methods private static class RegexUtilities { private static readonly Regex ValidEmailRegex = new Regex( @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" + @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$", RegexOptions.IgnoreCase | RegexOptions.Compiled); public static bool IsValidEmail(string strIn) { if (String.IsNullOrEmpty(strIn) || strIn.Length > 320) return false; // Use IdnMapping class to convert Unicode domain names. try { strIn = Regex.Replace(strIn, @"(@)(.+)$", DomainMapper); } catch (ArgumentException) { return false; } // Return true if strIn is in valid e-mail format. return ValidEmailRegex.IsMatch(strIn); } private static string DomainMapper(Match match) { // IdnMapping class with default property values. var idn = new System.Globalization.IdnMapping(); string domainName = match.Groups[2].Value; //try //{ domainName = idn.GetAscii(domainName); //} //catch (ArgumentException) //{ // invalid = true; //} return match.Groups[1].Value + domainName; } } /// <summary> /// Remove all characters not valid by given <paramref name="predicate"/>. /// </summary> private static string FilterSanitizeString(string str, Predicate<char>/*!*/predicate) { Debug.Assert(predicate != null); // nothing to sanitize: if (string.IsNullOrEmpty(str)) return string.Empty; // check if all the characters are valid first: bool allvalid = true; foreach (var c in str) if (!predicate(c)) { allvalid = false; break; } if (allvalid) { return str; } else { // remove not allowed characters: StringBuilder newstr = new StringBuilder(str.Length); foreach (char c in str) if (predicate(c)) newstr.Append(c); return newstr.ToString(); } } #endregion } }
using System; using System.Collections.Generic; using System.Text; /* Copyright 2015 Glen Boothby http://www.codehack.uk */ namespace glboothby.Models { public class NumberString { #region Properties public bool IsNegative { get; set; } public bool LongScale { get; set; } public List<char> IntegerPart { get; set; } public List<char> DecimalPart { get; set; } public StringBuilder IntergerWords { get; set; } public StringBuilder DecimalWords { get; set; } public bool HasDecimal { get { return this.DecimalPart.Count > 0; } } public bool HasInteger { get { return this.IntegerPart.Count > 0; } } public bool DecimalAllZero { get { bool returnValue = true; string[] parts = this.DecimalWords.ToString().Split(' '); foreach (string part in parts) { if (!string.IsNullOrWhiteSpace(part) && part.Trim() != "zero") { returnValue = false; break; } } return returnValue; } } #endregion #region Constructors public NumberString(bool longScale = false) { Clear(); this.LongScale = longScale; } #endregion public void Clear() { this.LongScale = false; this.IsNegative = false; this.IntegerPart = new List<char>(); this.DecimalPart = new List<char>(); this.IntergerWords = new StringBuilder(); this.DecimalWords = new StringBuilder(); } public override string ToString() { string returnValue = String.Empty; if (HasInteger || HasDecimal) { string i = IntergerWords.ToString(); string d = DecimalWords.ToString(); returnValue = String.IsNullOrWhiteSpace(i) ? "zero " : i; if (HasDecimal && !DecimalAllZero) { returnValue += "point " + d; } } else { returnValue = "empty"; } return FirstLetterUpper(returnValue); } private string FirstLetterUpper(string input) { if (!string.IsNullOrWhiteSpace(input)) { input = input.Trim().ToLower(); if (input != "zero" && input != "empty") { if (this.IsNegative) { input = "minus " + input; } } if (input.Length > 1) { input = input.Substring(0, 1).ToUpper() + input.Substring(1); } else { input = input.ToUpper(); } input += "."; } return input; } public void MakeParts(string input) { if (!String.IsNullOrWhiteSpace(input)) { input = input.Trim(); this.IsNegative = input.Substring(0, 1) == "-"; string[] parts = input.Split('.'); if (parts.Length > 0) { this.IntegerPart = MakePart(parts[0]); WordInteger(); } if (parts.Length > 1) { this.DecimalPart = MakePart(parts[1]); WordDecimal(); } } } private List<char> MakePart(string part) { List<char> returnValue = new List<char>(); if (!String.IsNullOrWhiteSpace(part)) { part = part.ToLower(); foreach (char c in part) { if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z')) { returnValue.Add(c); } } } return returnValue; } private void WordDecimal() { foreach (char c in this.DecimalPart) { this.DecimalWords.Append(GetUnit(c)); } } private void WordInteger() { List<char[]> threes = SplitThrees(this.IntegerPart); int place = 0; bool addAnd = false; foreach (char[] chars in threes) { bool threeZeros = true; foreach (char c in chars) { if (NonZero(c)) { threeZeros = false; break; } } if (!threeZeros) { string seperator = " "; if (addAnd) { this.IntergerWords.Insert(0, "and "); addAnd = false; } else if (this.IntergerWords.Length > 1) { seperator = ", "; } this.IntergerWords.Insert(0, GetPlace(place, seperator)); if (NonZero(chars[0])) { if (chars[1] != '1') { this.IntergerWords.Insert(0, GetUnit(chars[0])); if (NonZero(chars[1])) { this.IntergerWords.Insert(0, GetTens(chars[1])); } } else { this.IntergerWords.Insert(0, GetTeens(chars[0])); } addAnd = true; } else if (NonZero(chars[1])) { this.IntergerWords.Insert(0, GetTens(chars[1])); addAnd = true; } if (NonZero(chars[2])) { if (addAnd) { this.IntergerWords.Insert(0, "and "); addAnd = false; } this.IntergerWords.Insert(0, GetUnit(chars[2]) + "hundred "); } } place = place + 3; } } private bool NonZero(char c) { return c != '0' && c != ' '; } private List<char[]> SplitThrees(List<char> list) { List<char[]> returnValue = new List<char[]>(); for (int i = list.Count - 1; i >= 0; i = i - 3) { char[] chars = new char[3]; chars[0] = list[i]; if (i - 1 >= 0) { chars[1] = list[i - 1]; if (i - 2 >= 0) { chars[2] = list[i - 2]; } else { chars[2] = ' '; } } else { chars[1] = ' '; chars[2] = ' '; } returnValue.Add(chars); } return returnValue; } private static string GetUnit(char c) { string returnValue = String.Empty; if (c != ' ') { switch (c) { case '0': returnValue = "zero"; break; case '1': returnValue = "one"; break; case '2': returnValue = "two"; break; case '3': returnValue = "three"; break; case '4': returnValue = "four"; break; case '5': returnValue = "five"; break; case '6': returnValue = "six"; break; case '7': returnValue = "seven"; break; case '8': returnValue = "eight"; break; case '9': returnValue = "nine"; break; default: returnValue = c.ToString(); break; } if (String.IsNullOrWhiteSpace(returnValue)) { throw new ArgumentOutOfRangeException(String.Format("Cannot conver char to unit: {0}", c)); } } return returnValue + " "; } private static string GetTens(char c) { string returnValue = string.Empty; if (c != ' ') { switch (c) { case '1': returnValue = "ten"; break; case '2': returnValue = "twenty"; break; case '3': returnValue = "thirty"; break; case '4': returnValue = "forty"; break; case '5': returnValue = "fifty"; break; case '6': returnValue = "sixty"; break; case '7': returnValue = "seventy"; break; case '8': returnValue = "eighty"; break; case '9': returnValue = "ninety"; break; default: returnValue = c.ToString(); break; } if (string.IsNullOrWhiteSpace(returnValue)) { throw new ArgumentOutOfRangeException(String.Format("Cannot conver char to Tens: {0}", c)); } } return returnValue + " "; } private static string GetTeens(char c) { string returnValue = string.Empty; switch (c) { case '1': returnValue = "eleven"; break; case '2': returnValue = "twelve"; break; case '3': returnValue = "thirteen"; break; case '4': returnValue = "fourteen"; break; case '5': returnValue = "fifteen"; break; case '6': returnValue = "sixteen"; break; case '7': returnValue = "seventeen"; break; case '8': returnValue = "eighteen"; break; case '9': returnValue = "nineteen"; break; default: returnValue = "1" + c.ToString(); break; } if (string.IsNullOrWhiteSpace(returnValue)) { throw new ArgumentOutOfRangeException(String.Format("Cannot convert char to Teens: {0}", c)); } return returnValue + " "; } private string GetPlace(int place, string seperator = " ") { string returnValue = String.Empty; switch (place) { case 0: returnValue = String.Empty; break; case 3: returnValue = "thousand"; break; case 6: returnValue = "million"; break; case 9: returnValue = this.LongScale ? "milliard" : "billion"; break; case 12: returnValue = this.LongScale ? "billion" : "trillion"; break; case 15: returnValue = this.LongScale ? "billiard" : "quadrillion"; break; case 18: returnValue = this.LongScale ? "trillion" : "quintillion"; break; case 21: returnValue = this.LongScale ? "trilliard" : "sextillion"; break; case 24: returnValue = this.LongScale ? "quadrillion" : "septillion"; break; case 27: returnValue = this.LongScale ? "quadrilliard" : "octillion"; break; case 30: returnValue = this.LongScale ? "quintillion" : "nonillion"; break; case 33: returnValue = this.LongScale ? "quintilliard" : "decillion"; break; case 36: returnValue = this.LongScale ? "sextillion" : "undecillion"; break; case 39: returnValue = this.LongScale ? "sextilliard" : "duodecillion"; break; case 42: returnValue = this.LongScale ? "septillion" : "tredecillion"; break; case 45: returnValue = this.LongScale ? "septilliard" : "quattuordecillion"; break; case 48: returnValue = this.LongScale ? "octillion" : "quindecillion"; break; case 51: returnValue = this.LongScale ? "octilliard" : "sexdecillion"; break; case 54: returnValue = this.LongScale ? "nonillion" : "septendecillion"; break; case 57: returnValue = this.LongScale ? "nonilliard" : "octodecillion"; break; case 60: returnValue = this.LongScale ? "decillion" : "novemdecillion"; break; case 63: returnValue = this.LongScale ? "decilliard" : "vigintillion"; break; case 66: returnValue = this.LongScale ? "undecillion" : "unvigintillion"; break; case 69: returnValue = this.LongScale ? "undecilliard" : "dovigintillion"; break; case 72: returnValue = this.LongScale ? "duodecillion" : "trevigintillion"; break; case 75: returnValue = this.LongScale ? "duodecilliard" : "quattuorvigintillion"; break; case 78: returnValue = this.LongScale ? "tredecillion" : "quinvigintillion"; break; case 81: returnValue = this.LongScale ? "tredecilliard" : "sexvigintillion"; break; case 84: returnValue = this.LongScale ? "quattuordecillion" : "septenvigintillion"; break; case 87: returnValue = this.LongScale ? "quattuordecilliard" : "octovigintillion"; break; case 90: returnValue = this.LongScale ? "quindecillion" : "novemvigintillion"; break; case 93: returnValue = this.LongScale ? "quindecilliard" : "trigintillion"; break; case 96: returnValue = this.LongScale ? "sexdecillion" : "untrigintillion"; break; case 99: returnValue = this.LongScale ? "sexdecilliard" : "dotrigintillion"; break; case 102:returnValue = this.LongScale ? "septendecillion" : "tretrigintillion"; break; case 105:returnValue = this.LongScale ? "septendecilliard" : "quattuortrigintillion"; break; case 108:returnValue = this.LongScale ? "octodecillion" : "quintrigintillion"; break; case 111:returnValue = this.LongScale ? "octodecilliard" : "sextrigintillion";break; case 114:returnValue = this.LongScale ? "novemdecillion" : "septentrigintillion";break; case 117:returnValue = this.LongScale ? "novemdecilliard" : "octotrigintillion"; break; case 120:returnValue = this.LongScale ? "vigintillion" : "novemtrigintillion"; break; case 123:returnValue = this.LongScale ? "vigintilliard" : "quadragintillion"; break; case 126: returnValue = this.LongScale ? "unvigintillion" : "unquadragintillion"; break; case 129: returnValue = this.LongScale ? "unvigintilliard" : "duoquadragintillion"; break; case 132: returnValue = this.LongScale ? "duovigintillion" : "trequadragintillion"; break; case 135: returnValue = this.LongScale ? "duovigintilliard" : "quattuorquadragintillion"; break; case 138: returnValue = this.LongScale ? "trevigintillion" : "quinquadragintillion"; break; case 141: returnValue = this.LongScale ? "trevigintilliard" : "sexquadragintillion"; break; case 144: returnValue = this.LongScale ? "quattuorvigintillion" : "septquadragintillion"; break; case 147: returnValue = this.LongScale ? "quattuorvigintilliard" : "octoquadragintillion"; break; case 150: returnValue = this.LongScale ? "quinvigintillion" : "novemquadragintillion"; break; case 153: returnValue = this.LongScale ? "quinvigintilliard" : "quinquagintillion"; break; case 156: returnValue = this.LongScale ? "sexvigintillion" : "unquinquagintillion"; break; case 159: returnValue = this.LongScale ? "sexvigintilliard" : "duoquinquagintillion"; break; case 162: returnValue = this.LongScale ? "septenvigintillion" : "trequinquagintillion"; break; case 165: returnValue = this.LongScale ? "septenvigintilliard" : "quattuorquinquagintillion"; break; case 168: returnValue = this.LongScale ? "octovigintillion" : "quinquinquagintillion"; break; case 171: returnValue = this.LongScale ? "octovigintilliard" : "sexquinquagintillion"; break; case 174: returnValue = this.LongScale ? "novemvigintillion" : "septquinquagintillion"; break; case 177: returnValue = this.LongScale ? "novemvigintilliard" : "octoquinquagintillion"; break; case 180: returnValue = this.LongScale ? "trigintillion" : "novemquinquagintillion"; break; case 183: returnValue = this.LongScale ? "trigintilliard" : "sexagintillion"; break; case 186: returnValue = this.LongScale ? "untrigintillion" : "unsexagintillion"; break; case 189: returnValue = this.LongScale ? "untrigintilliard" : "duosexagintillion"; break; case 192: returnValue = this.LongScale ? "duotrigintillion" : "tresexagintillion"; break; case 195: returnValue = this.LongScale ? "duotrigintilliard" : "quattuorsexagintillion"; break; case 198: returnValue = this.LongScale ? "tretrigintillion" : "quinsexagintillion"; break; case 201: returnValue = this.LongScale ? "tretrigintilliard" : "sexsexagintillion"; break; case 204: returnValue = this.LongScale ? "quattuortrigintillion" : "septsexagintillion"; break; case 207: returnValue = this.LongScale ? "quattuortrigintilliard" : "octosexagintillion"; break; case 210: returnValue = this.LongScale ? "quintrigintillion" : "novemsexagintillion"; break; case 213: returnValue = this.LongScale ? "quintrigintilliard" : "septuagintillion"; break; case 216: returnValue = this.LongScale ? "sextrigintillion" : "unseptuagintillion"; break; case 219: returnValue = this.LongScale ? "sextrigintilliard" : "duoseptuagintillion"; break; case 222: returnValue = this.LongScale ? "septentrigintillion" : "treseptuagintillion"; break; case 225: returnValue = this.LongScale ? "septentrigintilliard" : "quattuorseptuagintillion"; break; case 228: returnValue = this.LongScale ? "octotrigintillion" : "quinseptuagintillion"; break; case 231: returnValue = this.LongScale ? "octotrigintilliard" : "sexseptuagintillion"; break; case 234: returnValue = this.LongScale ? "octotrigintilliard" : "septseptuagintillion"; break; case 237: returnValue = this.LongScale ? "novemtrigintilliard" : "octoseptuagintillion"; break; case 240: returnValue = this.LongScale ? "quadragintillion" : "novemseptuagintillion"; break; case 243: returnValue = this.LongScale ? "quadragintilliard" : "octogintillion"; break; case 246: returnValue = this.LongScale ? "unquadragintillion" : "unoctogintillion"; break; case 249: returnValue = this.LongScale ? "unquadragintilliard" : "duooctogintillion"; break; case 252: returnValue = this.LongScale ? "duoquadragintillion" : "treoctogintillion"; break; case 255: returnValue = this.LongScale ? "duoquadragintilliard" : "quattuoroctogintillion"; break; case 258: returnValue = this.LongScale ? "trequadragintillion" : "quinoctogintillion"; break; case 261: returnValue = this.LongScale ? "trequadragintilliard" : "sexoctogintillion"; break; case 264: returnValue = this.LongScale ? "quattuorquadragintillion" : "septoctogintillion"; break; case 267: returnValue = this.LongScale ? "quattuorquadragintilliard" : "octooctogintillion"; break; case 270: returnValue = this.LongScale ? "quinquadragintillion" : "novemoctogintillion"; break; case 273: returnValue = this.LongScale ? "quinquadragintilliard" : "nonagintillion"; break; case 276: returnValue = this.LongScale ? "sexquadragintillion" : "unnonagintillion"; break; case 279: returnValue = this.LongScale ? "sexquadragintilliard" : "duononagintillion"; break; case 282: returnValue = this.LongScale ? "septenquadragintillion" : "trenonagintillion"; break; case 285: returnValue = this.LongScale ? "septenquadragintilliard" : "quattuornonagintillion"; break; case 288: returnValue = this.LongScale ? "octoquadragintillion" : "quinnonagintillion"; break; case 291: returnValue = this.LongScale ? "octoquadragintilliard" : "sexnonagintillion"; break; case 294: returnValue = this.LongScale ? "novemquadragintillion" : "septnonagintillion"; break; case 297: returnValue = this.LongScale ? "novemquadragintilliard" : "octononagintillion"; break; case 300: returnValue = this.LongScale ? "quinquagintillion" : "novemnonagintillion"; break; case 303: returnValue = this.LongScale ? "quinquagintilliard" : "centillion"; break; default: returnValue = "error"; break; } if (returnValue == "error") { throw new ArgumentOutOfRangeException(String.Format("Do not have place name for 10^{0}.", place)); } return returnValue + seperator; } } }
using System.Text; using System.Web; using Ninject; using NuGet.Resources; using NuGet.Server.DataServices; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.Versioning; using System.Threading.Tasks; using System.Web.Configuration; namespace NuGet.Server.Infrastructure { /// <summary> /// ServerPackageRepository represents a folder of nupkgs on disk. All packages are cached during the first request in order /// to correctly determine attributes such as IsAbsoluteLatestVersion. Adding, removing, or making changes to packages on disk /// will clear the cache. /// </summary> public class ServerPackageRepository : PackageRepositoryBase, IServerPackageRepository, IPackageLookup, IDisposable { private IDictionary<IPackage, DerivedPackageData> _packages; private readonly object _lockObj = new object(); private readonly IFileSystem _fileSystem; private readonly IPackagePathResolver _pathResolver; private readonly Func<string, bool, bool> _getSetting; private FileSystemWatcher _fileWatcher; private readonly string _filter = String.Format(CultureInfo.InvariantCulture, "*{0}", Constants.PackageExtension); private bool _monitoringFiles = false; private const string NupkgHashExtension = ".hash"; private const string NupkgTempHashExtension = ".thash"; public ServerPackageRepository(string path) : this(new DefaultPackagePathResolver(path), new PhysicalFileSystem(path)) { } public ServerPackageRepository(IPackagePathResolver pathResolver, IFileSystem fileSystem, Func<string, bool, bool> getSetting = null) { if (pathResolver == null) { throw new ArgumentNullException("pathResolver"); } if (fileSystem == null) { throw new ArgumentNullException("fileSystem"); } _fileSystem = fileSystem; _pathResolver = pathResolver; _getSetting = getSetting ?? GetBooleanAppSetting; } [Inject] public IHashProvider HashProvider { get; set; } public override IQueryable<IPackage> GetPackages() { return PackageCache.Keys.AsQueryable<IPackage>(); } public IQueryable<Package> GetPackagesWithDerivedData() { var cache = PackageCache; return cache.Keys.Select(p => new Package(p, cache[p])).AsQueryable(); } public bool Exists(string packageId, SemanticVersion version) { return FindPackage(packageId, version) != null; } public IPackage FindPackage(string packageId, SemanticVersion version) { return FindPackagesById(packageId).Where(p => p.Version.Equals(version)).FirstOrDefault(); } public IEnumerable<IPackage> FindPackagesById(string packageId) { return GetPackages().Where(p => StringComparer.OrdinalIgnoreCase.Compare(p.Id, packageId) == 0); } /// <summary> /// Gives the Package containing both the IPackage and the derived metadata. /// The returned Package will be null if <paramref name="package" /> no longer exists in the cache. /// </summary> public Package GetMetadataPackage(IPackage package) { Package metadata = null; // The cache may have changed, and the metadata may no longer exist DerivedPackageData data = null; if (PackageCache.TryGetValue(package, out data)) { metadata = new Package(package, data); } return metadata; } public IQueryable<IPackage> Search(string searchTerm, IEnumerable<string> targetFrameworks, bool allowPrereleaseVersions) { var cache = PackageCache; var packages = cache.Keys.AsQueryable().Find(searchTerm) .FilterByPrerelease(allowPrereleaseVersions) .Where(p => p.Listed) .AsQueryable(); if (EnableFrameworkFiltering && targetFrameworks.Any()) { // Get the list of framework names var frameworkNames = targetFrameworks.Select(frameworkName => VersionUtility.ParseFrameworkName(frameworkName)); packages = packages.Where(package => frameworkNames.Any(frameworkName => VersionUtility.IsCompatible(frameworkName, cache[package].SupportedFrameworks))); } return packages; } public IEnumerable<IPackage> GetUpdates(IEnumerable<IPackageName> packages, bool includePrerelease, bool includeAllVersions, IEnumerable<FrameworkName> targetFrameworks, IEnumerable<IVersionSpec> versionConstraints) { return this.GetUpdatesCore(packages, includePrerelease, includeAllVersions, targetFrameworks, versionConstraints); } public override string Source { get { return _fileSystem.Root; } } public override bool SupportsPrereleasePackages { get { return true; } } /// <summary> /// Add a file to the repository. /// </summary> public override void AddPackage(IPackage package) { string fileName = _pathResolver.GetPackageFileName(package); if (_fileSystem.FileExists(fileName) && !AllowOverrideExistingPackageOnPush) { throw new InvalidOperationException(String.Format(NuGetResources.Error_PackageAlreadyExists, package)); } lock (_lockObj) { using (Stream stream = package.GetStream()) { _fileSystem.AddFile(fileName, stream); } InvalidatePackages(); } } /// <summary> /// Unlist or delete a package /// </summary> public override void RemovePackage(IPackage package) { if (package != null) { string fileName = _pathResolver.GetPackageFileName(package); lock (_lockObj) { if (EnableDelisting) { var fullPath = _fileSystem.GetFullPath(fileName); if (File.Exists(fullPath)) { File.SetAttributes(fullPath, File.GetAttributes(fullPath) | FileAttributes.Hidden); // Delisted files can still be queried, therefore not deleting persisted hashes if present. // Also, no need to flip hidden attribute on these since only the one from the nupkg is queried. } else { Debug.Fail("unable to find file"); } } else { _fileSystem.DeleteFile(fileName); if (EnablePersistNupkgHash) { _fileSystem.DeleteFile(GetHashFile(fileName, false)); _fileSystem.DeleteFile(GetHashFile(fileName, true)); } } InvalidatePackages(); } } } /// <summary> /// Remove a package from the respository. /// </summary> public void RemovePackage(string packageId, SemanticVersion version) { IPackage package = FindPackage(packageId, version); RemovePackage(package); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { DetachEvents(); } /// <summary> /// *.nupkg files in the root folder /// </summary> private IEnumerable<string> GetPackageFiles() { // Check top level directory foreach (var path in _fileSystem.GetFiles(String.Empty, _filter)) { yield return path; } } /// <summary> /// Internal package cache containing both the packages and their metadata. /// This data is generated if it does not exist already. /// </summary> private IDictionary<IPackage, DerivedPackageData> PackageCache { get { lock (_lockObj) { if (_packages == null) { if (!_monitoringFiles) { // attach events the first time _monitoringFiles = true; AttachEvents(); } _packages = CreateCache(); } return _packages; } } } /// <summary> /// Sets the current cache to null so it will be regenerated next time. /// </summary> public void InvalidatePackages() { lock (_lockObj) { _packages = null; } } private string GetHashFile(string pathToNupkg, bool isTempFile) { // path_to_nupkg\package.nupkg => path_to_nupkg\package.hash or path_to_nupkg\package.thash // reason for replacing extension instead of appending: elimination potential file-system file name length limits. if (string.IsNullOrEmpty(pathToNupkg)) { return pathToNupkg; } return Path.ChangeExtension(pathToNupkg, isTempFile ? NupkgTempHashExtension : NupkgHashExtension); } /// <summary> /// CreateCache loads all packages and determines additional metadata such as the hash, IsAbsoluteLatestVersion, and IsLatestVersion. /// </summary> private IDictionary<IPackage, DerivedPackageData> CreateCache() { ConcurrentDictionary<IPackage, DerivedPackageData> packages = new ConcurrentDictionary<IPackage, DerivedPackageData>(); ParallelOptions opts = new ParallelOptions(); opts.MaxDegreeOfParallelism = 4; ConcurrentDictionary<string, Tuple<IPackage, DerivedPackageData>> absoluteLatest = new ConcurrentDictionary<string, Tuple<IPackage, DerivedPackageData>>(); ConcurrentDictionary<string, Tuple<IPackage, DerivedPackageData>> latest = new ConcurrentDictionary<string, Tuple<IPackage, DerivedPackageData>>(); // get settings bool checkFrameworks = EnableFrameworkFiltering; bool enableDelisting = EnableDelisting; // we need to save the current context because it's stored in TLS and we're computing hashes on different threads. var context = HttpContext.Current; // load and cache all packages. // Note that we can't pass GetPackageFiles() to Parallel.ForEach() because // the file could be added/deleted from _fileSystem, and if this happens, // we'll get error "Collection was modified; enumeration operation may not execute." // So we have to materialize the IEnumerable into a list first. var packageFiles = GetPackageFiles().ToList(); Parallel.ForEach(packageFiles, opts, path => { OptimizedZipPackage zip = OpenPackage(path); Debug.Assert(zip != null, "Unable to open " + path); if (zip == null) { return; } if (enableDelisting) { // hidden packages are considered delisted zip.Listed = !File.GetAttributes(_fileSystem.GetFullPath(path)).HasFlag(FileAttributes.Hidden); } string packageHash = null; long packageSize = 0; string persistedHashFile = EnablePersistNupkgHash ? GetHashFile(path, false) : null; bool hashComputeNeeded = true; ReadHashFile(context, path, persistedHashFile, ref packageSize, ref packageHash, ref hashComputeNeeded); if (hashComputeNeeded) { using (var stream = _fileSystem.OpenFile(path)) { packageSize = stream.Length; packageHash = Convert.ToBase64String(HashProvider.CalculateHash(stream)); } WriteHashFile(context, path, persistedHashFile, packageSize, packageHash); } var data = new DerivedPackageData { PackageSize = packageSize, PackageHash = packageHash, LastUpdated = _fileSystem.GetLastModified(path), Created = _fileSystem.GetCreated(path), Path = path, FullPath = _fileSystem.GetFullPath(path), // default to false, these will be set later IsAbsoluteLatestVersion = false, IsLatestVersion = false }; if (checkFrameworks) { data.SupportedFrameworks = zip.GetSupportedFrameworks(); } var entry = new Tuple<IPackage, DerivedPackageData>(zip, data); // find the latest versions string id = zip.Id.ToLowerInvariant(); // update with the highest version absoluteLatest.AddOrUpdate(id, entry, (oldId, oldEntry) => oldEntry.Item1.Version < entry.Item1.Version ? entry : oldEntry); // update latest for release versions if (zip.IsReleaseVersion()) { latest.AddOrUpdate(id, entry, (oldId, oldEntry) => oldEntry.Item1.Version < entry.Item1.Version ? entry : oldEntry); } // add the package to the cache, it should not exist already Debug.Assert(packages.ContainsKey(zip) == false, "duplicate package added"); packages.AddOrUpdate(zip, entry.Item2, (oldPkg, oldData) => oldData); }); // Set additional attributes after visiting all packages foreach (var entry in absoluteLatest.Values) { entry.Item2.IsAbsoluteLatestVersion = true; } foreach (var entry in latest.Values) { entry.Item2.IsLatestVersion = true; } return packages; } private void WriteHashFile(HttpContext context, string nupkgPath, string hashFilePath, long packageSize, string packageHash) { if (hashFilePath == null) { return; // feature not enabled. } try { var tempHashFilePath = GetHashFile(nupkgPath, true); _fileSystem.DeleteFile(tempHashFilePath); _fileSystem.DeleteFile(hashFilePath); var content = new StringBuilder(); content.AppendLine(packageSize.ToString(CultureInfo.InvariantCulture)); content.AppendLine(packageHash); using (var stream = new MemoryStream(Encoding.ASCII.GetBytes(content.ToString()))) { _fileSystem.AddFile(tempHashFilePath, stream); } // move temp file to official location when previous operation completed successfully to minimize impact of potential errors (ex: machine crash in the middle of saving the file). _fileSystem.MoveFile(tempHashFilePath, hashFilePath); } catch (Exception e) { // Hashing persistence is a perf optimization feature; we chose to degrade perf over degrading functionality in case of failure. Log(context, string.Format("Unable to create hash file '{0}'.", hashFilePath), e); } } private void ReadHashFile(HttpContext context, string nupkgPath, string hashFilePath, ref long packageSize, ref string packageHash, ref bool hashComputeNeeded) { if (hashFilePath == null) { return; // feature not enabled. } try { if (!_fileSystem.FileExists(hashFilePath) || _fileSystem.GetLastModified(hashFilePath) < _fileSystem.GetLastModified(nupkgPath)) { return; // hash does not exist or is not current. } using (var stream = _fileSystem.OpenFile(hashFilePath)) { var reader = new StreamReader(stream); packageSize = long.Parse(reader.ReadLine(), CultureInfo.InvariantCulture); packageHash = reader.ReadLine(); } hashComputeNeeded = false; } catch (Exception e) { // Hashing persistence is a perf optimization feature; we chose to degrade perf over degrading functionality in case of failure. Log(context, string.Format("Unable to read hash file '{0}'.", hashFilePath), e); } } private static void Log(HttpContext context, string message, Exception innerException) { try { // Elmah.ErrorSignal.FromContext(context).Raise(new Exception(message, innerException)); } catch { // best effort } } private OptimizedZipPackage OpenPackage(string path) { OptimizedZipPackage zip = null; if (_fileSystem.FileExists(path)) { try { zip = new OptimizedZipPackage(_fileSystem, path); } catch (FileFormatException ex) { throw new InvalidDataException(String.Format(CultureInfo.CurrentCulture, NuGetResources.ErrorReadingPackage, path), ex); } // Set the last modified date on the package zip.Published = _fileSystem.GetLastModified(path); } return zip; } // Add the file watcher to monitor changes on disk private void AttachEvents() { // skip invalid paths if (_fileWatcher == null && !String.IsNullOrEmpty(Source) && Directory.Exists(Source)) { _fileWatcher = new FileSystemWatcher(Source); _fileWatcher.Filter = _filter; _fileWatcher.IncludeSubdirectories = false; _fileWatcher.Changed += FileChanged; _fileWatcher.Created += FileChanged; _fileWatcher.Deleted += FileChanged; _fileWatcher.Renamed += FileChanged; _fileWatcher.EnableRaisingEvents = true; } } // clean up events private void DetachEvents() { if (_fileWatcher != null) { _fileWatcher.EnableRaisingEvents = false; _fileWatcher.Changed -= FileChanged; _fileWatcher.Created -= FileChanged; _fileWatcher.Deleted -= FileChanged; _fileWatcher.Renamed -= FileChanged; _fileWatcher.Dispose(); _fileWatcher = null; } } private void FileChanged(object sender, FileSystemEventArgs e) { // invalidate the cache when a nupkg in the root folder changes // TODO: invalidating *all* packages for every nupkg change under this folder seems more expensive than it should. // Recommend using e.FullPath to figure out which nupkgs need to be (re)computed. InvalidatePackages(); } private bool AllowOverrideExistingPackageOnPush { get { // If the setting is misconfigured, treat it as success (backwards compatibility). return _getSetting("allowOverrideExistingPackageOnPush", true); } } private bool EnableDelisting { get { // If the setting is misconfigured, treat it as off (backwards compatibility). return _getSetting("enableDelisting", false); } } private bool EnableFrameworkFiltering { get { // If the setting is misconfigured, treat it as off (backwards compatibility). return _getSetting("enableFrameworkFiltering", false); } } private bool EnablePersistNupkgHash { get { // If the setting is misconfigured, treat it as off (backwards compatibility). return _getSetting("enablePersistNupkgHash", false); } } private static bool GetBooleanAppSetting(string key, bool defaultValue) { var appSettings = WebConfigurationManager.AppSettings; bool value; return !Boolean.TryParse(appSettings[key], out value) ? defaultValue : value; } } }
using System.Diagnostics; using System; using System.Collections; using System.Collections.Generic; using Common; using Fairweather.Service; using System.Linq; using Common.Sage; using System.Globalization; using Versioning; namespace Common.Posting { #warning modifies the data /// <summary> /// * type correctness /// * maximum string length /// </summary> public class General_Rules : Rule_Base { readonly Record_Type type; readonly Dict_ro<string, Sage_Field> dict; public General_Rules(Record_Type type) { this.type = type; this.dict = Common.Sage.Sage_Fields.Fields(type); } public override bool Inspect_Line(Data_Line line, int ix, bool is_last, out bool to_skip, out IEnumerable<Validation_Error> errors) { to_skip = false; //var to_change = new List<Pair<string, object>>(line.Dict.Count); var errors_lst = new List<Validation_Error>(3 + line.Dict.Count); foreach (var kvp in line.Dict.lst()) { var key = kvp.Key; var value = kvp.Value; Sage_Field field; if (!dict.TryGetValue(key, out field)) { // not our problem continue; } if (value.IsNullOrEmpty()) { // not our problem continue; } var name = field.Name; var type = field.Type; if (type == TypeCode.String) { var as_str = value.strdef(); if (name == "ACCOUNT_REF" || name == "STOCK_CODE") as_str = as_str.ToUpper(); var len = as_str.Length; var max_len = field.Length; if (len > max_len) { var error = new Validation_Error(ix, "Field '" + key + "' should be " + max_len + " characters or shorter."); errors_lst.Add(error); } if (!(value is string)) line[key] = as_str; } else { string error_msg; object coerced; if (Check_Type(value, field, out error_msg, out coerced)) { line[key] = coerced; } else { var error = new Validation_Error(ix, error_msg); errors_lst.Add(error); to_skip = true; } } } errors = errors_lst; return errors_lst.Count == 0; } static bool Known_Flag(string name) { switch (name) { case "ELEC_TRANS": case "STATUS": case "BACS": case "BANK_FLAG": case "DELETED_FLAG": case "IGNORE_STK_LVL_FLAG": case "NO_RECONCILIATION_FLAG": case "PAID_FLAG": case "POSTED_CODE": case "PRINTED_CODE": case "QUICK_RATIO_FLAG": case "SEND_VIA_EMAIL": case "SERVICE_FLAG": case "TAX_FLAG": case "TERMS_AGREED_FLAG": case "VAT_FLAG": case "WEB_PUBLISH": //case "ELEC_TRANS": // present in version 11! //case "FINANCE_CHARGE": //case "RECORD_DELETED": return true; } return false; #region grepped /*grep flag -i * | grep Byte BankRecord11.txt:NO_RECONCILIATION_FLAG Ignore Reconciliation 1 Optional Byte HeaderData11.txt:BANK_FLAG Bank Reconciled Flag 1 Optional Byte HeaderData11.txt:FINANCE_CHARGE Finance Charge Flag 1 Optional Byte HeaderData11.txt:PAID_FLAG Transaction Paid Flag 1 Optional Byte HeaderData11.txt:PRINTED_FLAG Printed Flag 1 Optional Byte HeaderData11.txt:VAT_FLAG Vat Flag 1 Optional Byte InvoiceData.txt:POSTED_CODE Posted Flag - Yes/No 1 Optional Byte InvoiceData.txt:PRINTED_CODE Printed Flag - Yes/No 1 Optional Byte invoiceitem.txt:SERVICE_FLAG Service Item Flag 1 Optional Byte invoiceitem.txt:TAX_FLAG 1 Optional Byte InvoicePost11.txt:POSTED_CODE Posted Flag - Yes/No 1 Optional Byte InvoicePost11.txt:PRINTED_CODE Printed Flag - Yes/No 1 Optional Byte InvoiceRecord11.txt:POSTED_CODE Posted Flag - Yes/No 1 Optional Byte InvoiceRecord11.txt:PRINTED_CODE Printed Flag - Yes/No 1 Optional Byte SplitData11.txt:BANK_FLAG Bank Reconciled Flag 1 Optional Byte SplitData11.txt:PAID_FLAG Paid Flag 1 Optional Byte SplitData11.txt:VAT_FLAG Vat Reconciled Flag 1 Optional Byte StockRecord.txt:IGNORE_STK_LVL_FLAG Ignore Stock Levels Flag 1 Optional Byte TransactionPost.txt:BANK_FLAG Bank Reconciled Flag 1 Optional Byte TransactionPost.txt:FINANCE_CHARGE Finance Charge Flag 1 Optional Byte TransactionPost.txt:PAID_FLAG Transaction Paid Flag 1 Optional Byte TransactionPost.txt:PRINTED_FLAG Printed Flag 1 Optional Byte TransactionPost.txt:VAT_FLAG Vat Flag 1 Optional Byte */ // **************************** /*grep flag -i * * BankRecord11.txt:DELETED_FLAG Is Deleted 2 Optional Small Integer BankRecord11.txt:NO_RECONCILIATION_FLAG Ignore Reconciliation 1 Optional Byte HeaderData11.txt:BANK_FLAG Bank Reconciled Flag 1 Optional Byte HeaderData11.txt:DELETED_FLAG Transaction Deleted Flag 2 Optional Small Integer HeaderData11.txt:ELEC_TRANS Electronic Transaction Flag 2 Optional Small Integer HeaderData11.txt:FINANCE_CHARGE Finance Charge Flag 1 Optional Byte HeaderData11.txt:PAID_FLAG Transaction Paid Flag 1 Optional Byte HeaderData11.txt:PRINTED_FLAG Printed Flag 1 Optional Byte HeaderData11.txt:VAT_FLAG Vat Flag 1 Optional Byte InvoiceData.txt:DELETED_FLAG Is Deleted 2 Optional Small Integer InvoiceData.txt:POSTED_CODE Posted Flag - Yes/No 1 Optional Byte InvoiceData.txt:PRINTED_CODE Printed Flag - Yes/No 1 Optional Byte invoiceitem.txt:SERVICE_FLAG Service Item Flag 1 Optional Byte invoiceitem.txt:TAX_FLAG 1 Optional Byte InvoicePost11.txt:DELETED_FLAG Is Deleted 2 Optional Small Integer InvoicePost11.txt:POSTED_CODE Posted Flag - Yes/No 1 Optional Byte InvoicePost11.txt:PRINTED_CODE Printed Flag - Yes/No 1 Optional Byte InvoiceRecord11.txt:DELETED_FLAG Is Deleted 2 Optional Small Integer InvoiceRecord11.txt:POSTED_CODE Posted Flag - Yes/No 1 Optional Byte InvoiceRecord11.txt:PRINTED_CODE Printed Flag - Yes/No 1 Optional Byte SalesData.txt:BACS Account Flagged for BACS 2 Optional Small Integer SalesData.txt:DELETED_FLAG Reserved for Future Use 2 Optional Small Integer SalesData.txt:TERMS_AGREED_FLAG Terms Agreed Flag 2 Optional Small Integer SalesRecord.txt:BACS Account Flagged for BACS 2 Optional Small Integer SalesRecord.txt:DELETED_FLAG Reserved for Future Use 2 Optional Small Integer SalesRecord.txt:TERMS_AGREED_FLAG Terms Agreed Flag 2 Optional Small Integer SplitData11.txt:BANK_FLAG Bank Reconciled Flag 1 Optional Byte SplitData11.txt:DELETED_FLAG Transaction Deleted Flag 2 Optional Small Integer SplitData11.txt:PAID_FLAG Paid Flag 1 Optional Byte SplitData11.txt:STATUS Status Flag 2 Optional Small Integer SplitData11.txt:VAT_FLAG Vat Reconciled Flag 1 Optional Byte StockRecord.txt:DELETED_FLAG Reserved for Future Use 2 Optional Small Integer StockRecord.txt:IGNORE_STK_LVL_FLAG Ignore Stock Levels Flag 1 Optional Byte StockRecord.txt:WEB_PUBLISH Web Publish Flag 2 Optional Small Integer TransactionPost.txt:BANK_FLAG Bank Reconciled Flag 1 Optional Byte TransactionPost.txt:DELETED_FLAG Transaction Deleted Flag 2 Optional Small Integer TransactionPost.txt:ELEC_TRANS Electronic Transaction Flag 2 Optional Small Integer TransactionPost.txt:FINANCE_CHARGE Finance Charge Flag 1 Optional Byte TransactionPost.txt:PAID_FLAG Transaction Paid Flag 1 Optional Byte TransactionPost.txt:PRINTED_FLAG Printed Flag 1 Optional Byte TransactionPost.txt:VAT_FLAG Vat Flag 1 Optional Byte * */ // **************************** //BankRecord11.txt:DELETED_FLAG Is Deleted 2 Optional Small Integer //HeaderData11.txt:DELETED_FLAG Transaction Deleted Flag 2 Optional Small Integer //HeaderData11.txt:ELEC_TRANS Electronic Transaction Flag 2 Optional Small Integer //InvoiceData.txt:DELETED_FLAG Is Deleted 2 Optional Small Integer //InvoicePost11.txt:DELETED_FLAG Is Deleted 2 Optional Small Integer //InvoiceRecord11.txt:DELETED_FLAG Is Deleted 2 Optional Small Integer //SalesData.txt:BACS Account Flagged for BACS 2 Optional Small Integer //SalesData.txt:DELETED_FLAG Reserved for Future Use 2 Optional Small Integer //SalesData.txt:TERMS_AGREED_FLAG Terms Agreed Flag 2 Optional Small Integer //SalesRecord.txt:BACS Account Flagged for BACS 2 Optional Small Integer //SalesRecord.txt:DELETED_FLAG Reserved for Future Use 2 Optional Small Integer //SalesRecord.txt:TERMS_AGREED_FLAG Terms Agreed Flag 2 Optional Small Integer //SplitData11.txt:DELETED_FLAG Transaction Deleted Flag 2 Optional Small Integer //SplitData11.txt:STATUS Status Flag 2 Optional Small Integer //StockRecord.txt:DELETED_FLAG Reserved for Future Use 2 Optional Small Integer //StockRecord.txt:WEB_PUBLISH Web Publish Flag 2 Optional Small Integer //TransactionPost.txt:DELETED_FLAG Transaction Deleted Flag 2 Optional Small Integer //TransactionPost.txt:ELEC_TRANS Electronic Transaction Flag 2 Optional Small Integer #endregion } // **************************** bool Check_Type(object value, Sage_Field field, out string error_msg, out object coerced) { coerced = value; error_msg = null; var description = ""; var ret = false; var field_name = field.Name; var field_type = field.Type; bool is_enum = false; if (field_type == TypeCode.SByte || (is_enum = Known_Flag(field_name))) { // flags ARE enums Triple<Type, string, IDictionary> triple; if (is_enum) triple = yes_no; else is_enum = enum_data.TryGetValue(Pair.Make(type, field_name), out triple); if (is_enum) { description = triple.Second; ret = Check_Sbyte_Enum_Value( value, triple.First, triple.Third, out coerced); } else { ret = Check_Integer(value, 1, out description, out coerced); } } else if (field_name.Contains("TAX_CODE")) { description = "Tax Code"; ret = Check_Tax_Code(value, out coerced); } else { switch (field_type) { case TypeCode.Int16: ret = Check_Integer(value, 2, out description, out coerced); break; case TypeCode.Int32: ret = Check_Integer(value, 4, out description, out coerced); break; case TypeCode.Double: case TypeCode.Decimal: ret = Check_Decimal(value, field, out description, out coerced); break; case TypeCode.DateTime: ret = Check_Date_Time(value, out description, out coerced); break; default: error_msg = "Field '" + field_name + "' is of unrecognized type: " + field_type + "."; return false; } } if (!ret) error_msg = "Field '" + field_name + "' should be a(n) " + description + "."; return ret; } static bool Check_Sbyte_Enum_Value( object value, Type enum_type, IDictionary synonyms, out object coerced) { coerced = value; var as_str = value.strdef().ToUpper(); if (as_str.IsNullOrEmpty()) return true; int as_int; bool is_int; if (synonyms.Contains(as_str)) { as_int = synonyms[as_str].ToInt32(); is_int = true; } //else if (enum_strs[enum_type].TryGetValue(as_str, out as_int)) { // is_int = true; //} else { is_int = int.TryParse(as_str, out as_int) && enum_vals[enum_type][as_int]; } if (is_int) coerced = (sbyte)as_int; //if (!is_int) // Debugger.Break(); return is_int; } static bool Check_Date_Time( object value, out string description, out object coerced) { description = null; coerced = value; if (value is DateTime) return true; var as_str = value.strdef().ToUpper(); if (as_str.IsNullOrEmpty()) return true; const string STR_DdMMyyyy = "dd/MM/yyyy"; const string STR_DdMyyyy = "dd/M/yyyy"; const string STR_DMyyyy = "d/M/yyyy"; const string STR_DMMyyyy = "d/MM/yyyy"; try { /* interesting... * If format is a custom format pattern that does not include date or * time separators (such as "yyyyMMdd HHmm"), use the invariant culture * for the provider parameter and the widest form of each custom format * specifier. For example, if you want to specify hours in the format * pattern, specify the wider form, "HH", instead of the narrower form, * "H". **/ var as_date_time = DateTime.ParseExact( as_str.Trim(), new[] { STR_DdMMyyyy, STR_DdMyyyy, STR_DMyyyy, STR_DMMyyyy }, culture, DateTimeStyles.AllowWhiteSpaces); coerced = as_date_time; return true; } catch (FormatException) { description = "Date in " + STR_DdMMyyyy + " format"; return false; } } static bool Check_Decimal( object value, Sage_Field field, out string description, out object coerced) { description = null; coerced = value; var as_str = value.strdef().ToUpper(); if (as_str.IsNullOrEmpty()) return true; decimal as_dec; var name = field.Name; var prec = (//name == "FOREIGN_RATE" || name.Contains("RATE") || name == "QTY" || name == "SALES_PRICE") ? 6 : 2; bool cast = false; if (value is decimal) { as_dec = (decimal)value; cast = true; } else if (decimal.TryParse(as_str.Trim(), out as_dec)) { cast = true; } if (cast && as_dec == as_dec.RoundDown(prec) && as_dec >= 0.00m) { coerced = as_dec; return true; } description = "valid positive number with precision no more than " + prec + " digits"; if (as_dec < 0.00m) description = "non-negative " + description; return false; } static bool Check_Integer( object value, int bytes, out string description, out object coerced) { description = null; coerced = value; var as_str = value.strdef(); if (as_str.IsNullOrEmpty()) return true; int as_int; long max = ((long)1) << (8 * bytes); if (int.TryParse(as_str, out as_int) && as_int <= max) return true; description = "Integer less than " + max; return false; } static bool Check_Tax_Code( object value, out object coerced) { coerced = value; var as_str = value.strdef(); if (as_str.IsNullOrEmpty()) return true; if (as_str[0].ToUpper() == 'T') as_str = as_str.Substring(1); if (as_str.Length == 0 || as_str.Length > 2) return false; const int ch0 = '0', ch9 = '9'; foreach (var ch in as_str) { if (ch < ch0 || ch > ch9) return false; } coerced = ushort.Parse(as_str); return true; } // **************************** static readonly System.Globalization.CultureInfo culture = null; // **************************** /* Enumerations */ // **************************** static readonly Lazy_Dict<Type, Set<int>> enum_vals = new Lazy_Dict<Type, Set<int>>(_t => new Set<int>(from _v in Enum.GetValues(_t).Cast<Enum>() select _v.ToInt32())); static readonly Lazy_Dict<Type, Dictionary<string, int>> enum_strs = new Lazy_Dict<Type, Dictionary<string, int>>( _t => //new Dictionary<string, int> ( from _value in Enum.GetValues(_t).Cast<object>() let _name = _value.ToString().ToUpper() //from _name in Enum.GetNames(_t) //let _value = Enum.Parse(_t, _name, true).ToInt32() select new KeyValuePair<string, int>(_name, _value.ToInt32()) ).ToDictionary(_kvp => _kvp.Key, _kvp => _kvp.Value) ); // synonyms static readonly Dictionary<string, TransType> trans_types = Versioning.Service.tt_to_short_str.ToDictionary(_p => _p.Second, _p => _p.First); static readonly Dictionary<string, StockTransType> stock_trans_types = Versioning.Service.stt_to_short_str.ToDictionary(_p => _p.Second, _p => _p.First); // 588f3694-1ec4-48bb-88e5-41c80250dc9e static readonly Dictionary<string, InvoiceType> invoice_types = new Dictionary<string, InvoiceType> { {"INV", InvoiceType.sdoProductInvoice}, {"CRD", InvoiceType.sdoProductCredit}, }; static readonly Dictionary<string, ItemType> stock_item_types = new Dictionary<string, ItemType> { {"STOCK", ItemType.sdoStockItem}, {"NONSTOCK", ItemType.sdoNonStockItem}, {"SERVICE", ItemType.sdoServiceItem}, }; static readonly Dictionary<string, BankType> bank_types = new Dictionary<string, BankType> { {"CHEQUE", BankType.sdoTypeCheque}, {"CASH", BankType.sdoTypeCash}, // **************************** {"CREDIT", BankType.sdoTypeCredit}, {"CREDIT CARD", BankType.sdoTypeCredit}, {"CARD", BankType.sdoTypeCredit}, // {"VISA", BankType.sdoTypeCredit}, }; static readonly Dictionary<string, TransType> payment_types = new Dictionary<string, TransType> { {"SR", TransType.sdoSR}, {"SA", TransType.sdoSA}, }; static readonly Dictionary<string, NominalType> nominal_types = new Dictionary<string, NominalType> { #warning is the user allowed to specify this? {"NORMAL", NominalType.sdoTypeNormal}, {"BANK", NominalType.sdoTypeBank}, {"CONTROL", NominalType.sdoTypeControl}, }; static Triple<Type, string, IDictionary> yes_no = Triple.Make(typeof(YesNo), "Yes/No, True/False or 1/0 value", (IDictionary)new Dictionary<string, YesNo> { {"YES", YesNo.Yes}, {"TRUE", YesNo.Yes}, {"NO", YesNo.No}, {"FALSE", YesNo.No}, }); static Pair_Key_Dict<Record_Type, string, Triple<Type, string, IDictionary>> enum_data = new Pair_Key_Dict<Record_Type, string, Triple<Type, string, IDictionary>> { {Record_Type.Stock,"ITEM_TYPE", Triple.Make( typeof(ItemType), "valid Stock Item Type for a Stock Record", (IDictionary)stock_item_types)}, {Record_Type.Bank,"ACCOUNT_TYPE", Triple.Make( typeof(BankType), "valid Account Type for a Bank Record", (IDictionary)bank_types)}, {Record_Type.Expense,"ACCOUNT_TYPE", Triple.Make( typeof(NominalType), "valid Account Type for a Nominal Record", (IDictionary)nominal_types)}, {Record_Type.Audit_Trail, "TYPE", Triple.Make( typeof(TransType), "valid Type for an Audit Trail Transaction", (IDictionary)trans_types)}, {Record_Type.Stock_Tran, "TYPE", Triple.Make( typeof(StockTransType), "valid Type for a Stock Transaction", (IDictionary)stock_trans_types)}, {Record_Type.Audit_Trail, "STATUS", yes_no}, {Record_Type.Document, "INVOICE_TYPE_CODE", Triple.Make(typeof(InvoiceType), "valid Document Type", (IDictionary)invoice_types)}, {Record_Type.Document, "PAYMENT_TYPE", Triple.Make(typeof(TransType), "valid Invoice Payment Type", (IDictionary)payment_types)}, // HACK!!!! {Record_Type.Invoice_Or_Credit, "INVOICE_TYPE_CODE", Triple.Make(typeof(InvoiceType), "valid Document Type", (IDictionary)invoice_types)}, {Record_Type.Invoice_Or_Credit, "PAYMENT_TYPE", Triple.Make(typeof(TransType), "valid Invoice Payment Type", (IDictionary)payment_types)}, }; enum YesNo { No = 0x0, Yes = 0x1, } } }
// 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.Xml; using System.Text; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Threading; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.Build.BackEnd; using Microsoft.Build.Execution; using Microsoft.Build.Evaluation; using Microsoft.Build.Collections; namespace Microsoft.Build.UnitTests.QA { /// <summary> /// Steps to write the tests /// 1) Create a TestProjectDefinition object for each project file or a build request that you will submit /// 2) Call Build() on the object to submit the build request /// 3) Call ValidateResults() on the object to wait till the build completes and the results sent were what we expected /// NOTE: It is not valid to submit multiple build requests simultinously without waiting for the previous one to complete /// </summary> [TestClass] [Ignore] // "Test infrastructure is out of sync with the BuildRequestEngine/Scheduler." public class RequestBuilder_Tests { #region Data members private Common_Tests _commonTests; private ResultsCache _resultsCache; private string _tempPath; #endregion #region Constructor /// <summary> /// Setup the object /// </summary> public RequestBuilder_Tests() { _commonTests = new Common_Tests(this.GetComponent, true); _resultsCache = null; _tempPath = System.IO.Path.GetTempPath(); } #endregion #region Common /// <summary> /// Delegate to common test setup /// </summary> [TestInitialize] public void Setup() { _resultsCache = new ResultsCache(); _commonTests.Setup(); } /// <summary> /// Delegate to common test teardown /// </summary> [TestCleanup] public void TearDown() { _commonTests.TearDown(); _resultsCache = null; } #endregion #region GetComponent delegate /// <summary> /// Provides the components required by the tests /// </summary> internal IBuildComponent GetComponent(BuildComponentType type) { switch (type) { case BuildComponentType.RequestBuilder: RequestBuilder requestBuilder = new RequestBuilder(); return (IBuildComponent)requestBuilder; case BuildComponentType.TaskBuilder: TaskBuilder taskBuilder = new TaskBuilder(); return (IBuildComponent)taskBuilder; case BuildComponentType.TargetBuilder: QAMockTargetBuilder targetBuilder = new QAMockTargetBuilder(); return (IBuildComponent)targetBuilder; case BuildComponentType.ResultsCache: return (IBuildComponent)_resultsCache; default: throw new ArgumentException("Unexpected type requested. Type = " + type.ToString()); } } #endregion #region Project build /// <summary> /// Build 1 project containing a single target /// </summary> [TestMethod] public void Build1ProjectWith1Target() { RequestDefinition p1 = CreateRequestDefinition("1.proj", null, null, 0); p1.SubmitBuildRequest(); p1.ValidateBuildResult(); } /// <summary> /// Build 1 project containing a 4 targets /// </summary> [TestMethod] public void Build1ProjectWith4Targets() { RequestDefinition p1 = CreateRequestDefinition("1.proj", new string[4] { "target1", "target2", "target3", "target4" }, null, 0); p1.SubmitBuildRequest(); p1.ValidateBuildResult(); } /// <summary> /// Build 4 project containing a single target /// </summary> [TestMethod] public void Build4ProjectWith1Target() { RequestDefinition p1 = CreateRequestDefinition("1.proj", null, null, 0); RequestDefinition p2 = CreateRequestDefinition("2.proj", null, null, 0); RequestDefinition p3 = CreateRequestDefinition("3.proj", null, null, 0); RequestDefinition p4 = CreateRequestDefinition("4.proj", null, null, 0); p1.SubmitBuildRequest(); p1.ValidateBuildResult(); p2.SubmitBuildRequest(); p2.ValidateBuildResult(); p3.SubmitBuildRequest(); p3.ValidateBuildResult(); p4.SubmitBuildRequest(); p4.ValidateBuildResult(); } /// <summary> /// Build 4 project containing a 4 target each /// </summary> [TestMethod] public void Build4ProjectWith4Targets() { RequestDefinition p1 = CreateRequestDefinition("1.proj", new string[4] { "target1", "target2", "target3", "target4" }, null, 0); RequestDefinition p2 = CreateRequestDefinition("2.proj", new string[4] { "target1", "target2", "target3", "target4" }, null, 0); RequestDefinition p3 = CreateRequestDefinition("3.proj", new string[4] { "target1", "target2", "target3", "target4" }, null, 0); RequestDefinition p4 = CreateRequestDefinition("4.proj", new string[4] { "target1", "target2", "target3", "target4" }, null, 0); p1.SubmitBuildRequest(); p1.ValidateBuildResult(); p2.SubmitBuildRequest(); p2.ValidateBuildResult(); p3.SubmitBuildRequest(); p3.ValidateBuildResult(); p4.SubmitBuildRequest(); p4.ValidateBuildResult(); } /// <summary> /// Build a single project with a target that takes time to execute. Send a cancel by shutting down the engine /// </summary> [TestMethod] public void TestCancellingRequest() { RequestDefinition p1 = CreateRequestDefinition("1.proj", null, null, 0); p1.WaitForCancel = true; p1.SubmitBuildRequest(); _commonTests.Host.AbortBuild(); p1.ValidateBuildAbortedResult(); } #endregion #region Common Tests /// <summary> /// Delegate to common tests /// </summary> [TestMethod] public void BuildOneProject() { _commonTests.BuildOneProject(); } /// <summary> /// Delegate to common tests /// </summary> [TestMethod] public void Build4Projects() { _commonTests.Build4DifferentProjects(); } /// <summary> /// Delegate to common tests /// </summary> [TestMethod] public void BuildingTheSameProjectTwiceWithDifferentToolsVersion() { _commonTests.BuildingTheSameProjectTwiceWithDifferentToolsVersion(); } /// <summary> /// Delegate to common tests /// </summary> [TestMethod] public void BuildingTheSameProjectTwiceWithDifferentToolsGlobalProperties() { _commonTests.BuildingTheSameProjectTwiceWithDifferentGlobalProperties(); } /// <summary> /// Delegate to common tests /// </summary> [TestMethod] public void ReferenceAProjectAlreadyBuiltInTheNode() { _commonTests.ReferenceAProjectAlreadyBuiltInTheNode(); } /// <summary> /// Delegate to common tests /// </summary> [TestMethod] public void ReferenceAProjectAlreadyBuiltInTheNodeButWithDifferentToolsVersion() { _commonTests.ReferenceAProjectAlreadyBuiltInTheNodeButWithDifferentToolsVersion(); } /// <summary> /// Delegate to common tests /// </summary> [TestMethod] public void ReferenceAProjectAlreadyBuiltInTheNodeButWithDifferentGlobalProperties() { _commonTests.ReferenceAProjectAlreadyBuiltInTheNodeButWithDifferentGlobalProperties(); } /// <summary> /// Delegate to common tests /// </summary> [TestMethod] public void BuildOneProjectWith1Reference() { _commonTests.BuildOneProjectWith1Reference(); } /// <summary> /// Delegate to common tests /// </summary> [TestMethod] public void BuildOneProjectWith3Reference() { _commonTests.BuildOneProjectWith3Reference(); } /// <summary> /// Delegate to common tests /// </summary> [TestMethod] public void BuildOneProjectWith3ReferenceWhere2AreTheSame() { _commonTests.BuildOneProjectWith3ReferenceWhere2AreTheSame(); } /// <summary> /// Delegate to common tests /// </summary> [TestMethod] public void BuildMultipleProjectsWithMiddleProjectHavingReferenceToANewProject() { _commonTests.BuildMultipleProjectsWithMiddleProjectHavingReferenceToANewProject(); } /// <summary> /// Delegate to common tests /// </summary> [TestMethod] public void BuildMultipleProjectsWithTheFirstProjectHavingReferenceToANewProject() { _commonTests.BuildMultipleProjectsWithTheFirstProjectHavingReferenceToANewProject(); } /// <summary> /// Delegate to common tests /// </summary> [TestMethod] public void BuildMultipleProjectsWithTheLastProjectHavingReferenceToANewProject() { _commonTests.BuildMultipleProjectsWithTheLastProjectHavingReferenceToANewProject(); } /// <summary> /// Delegate to common tests /// </summary> [TestMethod] public void BuildMultipleProjectsWithEachReferencingANewProject() { _commonTests.BuildMultipleProjectsWithEachReferencingANewProject(); } /// <summary> /// Delegate to common tests /// </summary> [TestMethod] public void BuildMultipleProjectsWhereFirstReferencesMultipleNewProjects() { _commonTests.BuildMultipleProjectsWhereFirstReferencesMultipleNewProjects(); } /// <summary> /// Delegate to common tests /// </summary> [TestMethod] public void BuildMultipleProjectsWhereFirstAndLastReferencesMultipleNewProjects() { _commonTests.BuildMultipleProjectsWhereFirstAndLastReferencesMultipleNewProjects(); } /// <summary> /// Delegate to common tests /// </summary> [TestMethod] public void BuildMultipleProjectsWithReferencesWhereSomeReferencesAreAlreadyBuilt() { _commonTests.BuildMultipleProjectsWithReferencesWhereSomeReferencesAreAlreadyBuilt(); } [TestMethod] public void BuildMultipleProjectsWithReferencesAndDifferentGlobalProperties() { _commonTests.BuildMultipleProjectsWithReferencesAndDifferentGlobalProperties(); } /// <summary> /// Delegate to common tests /// </summary> [TestMethod] public void BuildMultipleProjectsWithReferencesAndDifferentToolsVersion() { _commonTests.BuildMultipleProjectsWithReferencesAndDifferentToolsVersion(); } /// <summary> /// Delegate to common tests /// </summary> [TestMethod] public void Build3ProjectsWhere1HasAReferenceTo3() { _commonTests.Build3ProjectsWhere1HasAReferenceTo3(); } /// <summary> /// Delegate to common tests /// </summary> [TestMethod] public void Build3ProjectsWhere2HasAReferenceTo3() { _commonTests.Build3ProjectsWhere2HasAReferenceTo3(); } /// <summary> /// Delegate to common tests /// </summary> [TestMethod] public void Build3ProjectsWhere3HasAReferenceTo1() { _commonTests.Build3ProjectsWhere3HasAReferenceTo1(); } #endregion /// <summary> /// Returns a new Request definition object created using the parameters passed in /// </summary> /// <param name="filename">Name of the project file in the request. This needs to be a rooted path</param> /// <param name="targets">Targets to build in that project file</param> /// <param name="toolsVersion">Tools version for that project file</param> /// <param name="executionTime">Simulated time the request should take to complete</param> private RequestDefinition CreateRequestDefinition(string filename, string[] targets, string toolsVersion, int executionTime) { if (targets == null) { targets = new string[1] { RequestDefinition.defaultTargetName }; } if (toolsVersion == null) { toolsVersion = "2.0"; } filename = System.IO.Path.Combine(_tempPath, filename); RequestDefinition request = new RequestDefinition(filename, toolsVersion, targets, null, executionTime, null, (IBuildComponentHost)_commonTests.Host); request.CreateMSBuildProject = true; return request; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace Phonix.Parse { public class ParamList : Dictionary<string, object> { } public class RuleContext { public List<IRuleSegment> Left; public List<IRuleSegment> Right; public RuleContext() { Left = new List<IRuleSegment>(); Right = new List<IRuleSegment>(); } } public static class Util { public static Feature MakeFeature(string name, ParamList plist, Phonology phono) { Feature f = null; bool isNode = false; IEnumerable<Feature> childList = null; bool isScalar = false; int? scalarMin = null; int? scalarMax = null; if (plist == null) { f = new BinaryFeature(name); } else { // set the type to binary if it doesn't exist yet if (!plist.ContainsKey("type")) { plist["type"] = "binary"; } foreach (string key in plist.Keys) { object val = plist[key]; switch (key) { case "type": { Debug.Assert(val is string); string type = val as string; switch (type) { case "unary": f = new UnaryFeature(name); break; case "binary": f = new BinaryFeature(name); break; case "scalar": isScalar = true; break; case "node": isNode = true; break; default: throw new InvalidParameterValueException(key, type); } } break; case "children": { var list = new List<Feature>(); foreach (string child in (val as string).Split(',')) { list.Add(phono.FeatureSet.Get<Feature>(child.Trim())); } childList = list; } break; case "min": { int intVal; if (!Int32.TryParse(val as string, out intVal)) { throw new InvalidParameterValueException(key, "not an integer"); } scalarMin = intVal; } break; case "max": { int intVal; if (!Int32.TryParse(val as string, out intVal)) { throw new InvalidParameterValueException(key, "not an integer"); } scalarMax = intVal; } break; default: throw new UnknownParameterException(key); } } } // resolve node features based on parameters if (isNode) { if (childList == null) { throw new InvalidParameterValueException("node", "no 'children' parameter found"); } f = new NodeFeature(name, childList); } else if (childList != null) { throw new InvalidParameterValueException("children", "not allowed except on feature nodes"); } // resolve scalar features based on parameters if (scalarMin.HasValue || scalarMax.HasValue) { if (!isScalar) { throw new InvalidParameterValueException("min/max", "not allowed except on scalar features"); } else if (!(scalarMin.HasValue && scalarMax.HasValue)) { throw new InvalidParameterValueException("min/max", "both min and max required"); } else { f = new ScalarFeature(name, scalarMin.Value, scalarMax.Value); } } else if (isScalar) { f = new ScalarFeature(name); } Debug.Assert(f != null, "f != null"); return f; } public static void MakeAndAddSymbol(string label, FeatureMatrix matrix, ParamList plist, SymbolSet symbolSet) { if (plist != null && plist.ContainsKey("diacritic")) { if (plist["diacritic"] != null) { throw new InvalidParameterValueException("diacritic", plist["diacritic"].ToString()); } symbolSet.AddDiacritic(new Diacritic(label, matrix)); } else { symbolSet.Add(new Symbol(label, matrix)); } } public static void MakeAndAddRule(string name, IEnumerable<IRuleSegment> action, RuleContext context, RuleContext excluded, ParamList plist, RuleSet ruleSet) { var contextSegs = new List<IRuleSegment>(); var excludedSegs = new List<IRuleSegment>(); if (context == null) { context = new RuleContext(); } if (excluded == null) { // always add a non-matching segment to the excluded context if it's null excluded = new RuleContext(); excluded.Right.Add(new ContextSegment(MatrixMatcher.NeverMatches)); } // add the context segments into their list contextSegs.AddRange(context.Left); contextSegs.AddRange(action); contextSegs.AddRange(context.Right); // the left sides of the context and the exclusion need to // be aligned. We add StepSegments (which only advance the // cursor) or BackstepSegments (which only move back the // cursor) to accomplish this int diff = context.Left.Count - excluded.Left.Count; if (diff > 0) { for (int i = 0; i < diff; i++) { excludedSegs.Add(new StepSegment()); } } else if (diff < 0) { for (int i = 0; i > diff; i--) { excludedSegs.Add(new BackstepSegment()); } } excludedSegs.AddRange(excluded.Left); for (int i = 0; i < action.Count(); i++) { excludedSegs.Add(new StepSegment()); } excludedSegs.AddRange(excluded.Right); var rule = new Rule(name, contextSegs, excludedSegs); if (plist != null) { foreach (string key in plist.Keys) { object val = plist[key]; switch (key) { case "filter": Debug.Assert(val is FeatureMatrix); rule.Filter = new MatrixMatcher(val as FeatureMatrix); break; case "direction": { string dir = val as string; Debug.Assert(dir != null); switch (dir.ToLowerInvariant()) { case "right-to-left": rule.Direction = Direction.Leftward; break; case "left-to-right": rule.Direction = Direction.Rightward; break; default: throw new InvalidParameterValueException(key, dir); } } break; case "applicationRate": { double rate; string strRate = val as string; if (!double.TryParse(strRate, out rate)) { throw new InvalidParameterValueException(key, strRate + " (value was not a decimal)"); } try { rule.ApplicationRate = rate; } catch (ArgumentException) { throw new InvalidParameterValueException(key, strRate + " (value was not between 0 and 1)"); } } break; case "persist": // no-op, persistent rules are handled below break; default: throw new UnknownParameterException(key); } } } if (plist != null && plist.ContainsKey("persist")) { if (plist["persist"] != null) { throw new InvalidParameterValueException("persist", plist["persist"].ToString()); } ruleSet.AddPersistent(rule); } else { ruleSet.Add(rule); } } public static void MakeAndAddSyllable(SyllableBuilder syll, ParamList plist, RuleSet ruleSet) { bool onsetRequired = false; bool codaRequired = false; bool persist = false; if (plist != null) { foreach (var key in plist.Keys) { switch (key) { case "onsetRequired": onsetRequired = true; break; case "codaRequired": codaRequired = true; break; case "nucleusPreference": { var pref = plist["nucleusPreference"]; if (pref == null) { throw new InvalidParameterValueException("nucleusPreference", "<empty"); } else if (pref.Equals("left")) { syll.Direction = SyllableBuilder.NucleusDirection.Left; } else if (pref.Equals("right")) { syll.Direction = SyllableBuilder.NucleusDirection.Right; } else { throw new InvalidParameterValueException("nucleusPreference", pref.ToString()); } break; } case "persist": persist = true; break; default: throw new UnknownParameterException(key); } } } if (!onsetRequired) { // onsets not required, so add the implicit empty onset syll.Onsets.Add(Enumerable.Empty<IMatrixMatcher>()); } if (!codaRequired) { // codas not required, so add the implicit empty coda syll.Codas.Add(Enumerable.Empty<IMatrixMatcher>()); } var rule = syll.GetSyllableRule(); if (persist) { ruleSet.AddPersistent(rule); } else { ruleSet.Add(rule); } } public static List<IRuleSegment> MakeRuleAction( List<IMatrixMatcher> left, List<IMatrixCombiner> right) { if (left.Count != right.Count) { var msg = String.Format( "Unbalanced rule action ({0} segments before '=>', {1} segments after)", left.Count, right.Count); throw new RuleFormatException(msg); } var result = new List<IRuleSegment>(); var leftObj = left.GetEnumerator(); var rightObj = right.GetEnumerator(); bool inserting = false; bool deleting = false; while (leftObj.MoveNext() && rightObj.MoveNext()) { if (leftObj.Current == null && rightObj.Current == null) { throw new RuleFormatException("Can't map zero to zero"); } else if (leftObj.Current == null) { result.Add(new InsertingSegment(rightObj.Current)); inserting = true; } else if (rightObj.Current == null) { result.Add(new DeletingSegment(leftObj.Current)); deleting = true; } else { result.Add(new ActionSegment(leftObj.Current, rightObj.Current)); } } if (inserting && deleting) { throw new RuleFormatException("Can't insert and delete as part of the same rule"); } return result; } } }
/** * LookupService.cs * * Copyright (C) 2008 MaxMind Inc. All Rights Reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; using System.IO; using System.Net; using System.Runtime.CompilerServices; public class LookupService{ private FileStream file = null; private DatabaseInfo databaseInfo = null; byte databaseType = Convert.ToByte(DatabaseInfo.COUNTRY_EDITION); int[] databaseSegments; int recordLength; int dboptions; byte[] dbbuffer; String licenseKey; int dnsService = 0; private static Country UNKNOWN_COUNTRY = new Country("--", "N/A"); private static int COUNTRY_BEGIN = 16776960; private static int STATE_BEGIN = 16700000; private static int STRUCTURE_INFO_MAX_SIZE = 20; private static int DATABASE_INFO_MAX_SIZE = 100; private static int FULL_RECORD_LENGTH = 100;//??? private static int SEGMENT_RECORD_LENGTH = 3; private static int STANDARD_RECORD_LENGTH = 3; private static int ORG_RECORD_LENGTH = 4; private static int MAX_RECORD_LENGTH = 4; private static int MAX_ORG_RECORD_LENGTH = 1000;//??? private static int FIPS_RANGE = 360; private static int STATE_BEGIN_REV0 = 16700000; private static int STATE_BEGIN_REV1 = 16000000; private static int US_OFFSET = 1; private static int CANADA_OFFSET = 677; private static int WORLD_OFFSET = 1353; public static int GEOIP_STANDARD = 0; public static int GEOIP_MEMORY_CACHE = 1; public static int GEOIP_UNKNOWN_SPEED = 0; public static int GEOIP_DIALUP_SPEED = 1; public static int GEOIP_CABLEDSL_SPEED = 2; public static int GEOIP_CORPORATE_SPEED = 3; private static String[] countryCode = { "--","AP","EU","AD","AE","AF","AG","AI","AL","AM","CW", "AO","AQ","AR","AS","AT","AU","AW","AZ","BA","BB", "BD","BE","BF","BG","BH","BI","BJ","BM","BN","BO", "BR","BS","BT","BV","BW","BY","BZ","CA","CC","CD", "CF","CG","CH","CI","CK","CL","CM","CN","CO","CR", "CU","CV","CX","CY","CZ","DE","DJ","DK","DM","DO", "DZ","EC","EE","EG","EH","ER","ES","ET","FI","FJ", "FK","FM","FO","FR","SX","GA","GB","GD","GE","GF", "GH","GI","GL","GM","GN","GP","GQ","GR","GS","GT", "GU","GW","GY","HK","HM","HN","HR","HT","HU","ID", "IE","IL","IN","IO","IQ","IR","IS","IT","JM","JO", "JP","KE","KG","KH","KI","KM","KN","KP","KR","KW", "KY","KZ","LA","LB","LC","LI","LK","LR","LS","LT", "LU","LV","LY","MA","MC","MD","MG","MH","MK","ML", "MM","MN","MO","MP","MQ","MR","MS","MT","MU","MV", "MW","MX","MY","MZ","NA","NC","NE","NF","NG","NI", "NL","NO","NP","NR","NU","NZ","OM","PA","PE","PF", "PG","PH","PK","PL","PM","PN","PR","PS","PT","PW", "PY","QA","RE","RO","RU","RW","SA","SB","SC","SD", "SE","SG","SH","SI","SJ","SK","SL","SM","SN","SO", "SR","ST","SV","SY","SZ","TC","TD","TF","TG","TH", "TJ","TK","TM","TN","TO","TL","TR","TT","TV","TW", "TZ","UA","UG","UM","US","UY","UZ","VA","VC","VE", "VG","VI","VN","VU","WF","WS","YE","YT","RS","ZA", "ZM","ME","ZW","A1","A2","O1","AX","GG","IM","JE", "BL","MF", "BQ" }; private static String[] countryName = { "N/A","Asia/Pacific Region","Europe","Andorra","United Arab Emirates","Afghanistan","Antigua and Barbuda","Anguilla","Albania","Armenia","Curacao", "Angola","Antarctica","Argentina","American Samoa","Austria","Australia","Aruba","Azerbaijan","Bosnia and Herzegovina","Barbados", "Bangladesh","Belgium","Burkina Faso","Bulgaria","Bahrain","Burundi","Benin","Bermuda","Brunei Darussalam","Bolivia", "Brazil","Bahamas","Bhutan","Bouvet Island","Botswana","Belarus","Belize","Canada","Cocos (Keeling) Islands","Congo, The Democratic Republic of the", "Central African Republic","Congo","Switzerland","Cote D'Ivoire","Cook Islands","Chile","Cameroon","China","Colombia","Costa Rica", "Cuba","Cape Verde","Christmas Island","Cyprus","Czech Republic","Germany","Djibouti","Denmark","Dominica","Dominican Republic", "Algeria","Ecuador","Estonia","Egypt","Western Sahara","Eritrea","Spain","Ethiopia","Finland","Fiji", "Falkland Islands (Malvinas)","Micronesia, Federated States of","Faroe Islands","France","Sint Maarten (Dutch part)","Gabon","United Kingdom","Grenada","Georgia","French Guiana", "Ghana","Gibraltar","Greenland","Gambia","Guinea","Guadeloupe","Equatorial Guinea","Greece","South Georgia and the South Sandwich Islands","Guatemala", "Guam","Guinea-Bissau","Guyana","Hong Kong","Heard Island and McDonald Islands","Honduras","Croatia","Haiti","Hungary","Indonesia", "Ireland","Israel","India","British Indian Ocean Territory","Iraq","Iran, Islamic Republic of","Iceland","Italy","Jamaica","Jordan", "Japan","Kenya","Kyrgyzstan","Cambodia","Kiribati","Comoros","Saint Kitts and Nevis","Korea, Democratic People's Republic of","Korea, Republic of","Kuwait", "Cayman Islands","Kazakhstan","Lao People's Democratic Republic","Lebanon","Saint Lucia","Liechtenstein","Sri Lanka","Liberia","Lesotho","Lithuania", "Luxembourg","Latvia","Libya","Morocco","Monaco","Moldova, Republic of","Madagascar","Marshall Islands","Macedonia","Mali", "Myanmar","Mongolia","Macau","Northern Mariana Islands","Martinique","Mauritania","Montserrat","Malta","Mauritius","Maldives", "Malawi","Mexico","Malaysia","Mozambique","Namibia","New Caledonia","Niger","Norfolk Island","Nigeria","Nicaragua", "Netherlands","Norway","Nepal","Nauru","Niue","New Zealand","Oman","Panama","Peru","French Polynesia", "Papua New Guinea","Philippines","Pakistan","Poland","Saint Pierre and Miquelon","Pitcairn Islands","Puerto Rico","Palestinian Territory","Portugal","Palau", "Paraguay","Qatar","Reunion","Romania","Russian Federation","Rwanda","Saudi Arabia","Solomon Islands","Seychelles","Sudan", "Sweden","Singapore","Saint Helena","Slovenia","Svalbard and Jan Mayen","Slovakia","Sierra Leone","San Marino","Senegal","Somalia","Suriname", "Sao Tome and Principe","El Salvador","Syrian Arab Republic","Swaziland","Turks and Caicos Islands","Chad","French Southern Territories","Togo","Thailand", "Tajikistan","Tokelau","Turkmenistan","Tunisia","Tonga","Timor-Leste","Turkey","Trinidad and Tobago","Tuvalu","Taiwan", "Tanzania, United Republic of","Ukraine","Uganda","United States Minor Outlying Islands","United States","Uruguay","Uzbekistan","Holy See (Vatican City State)","Saint Vincent and the Grenadines","Venezuela", "Virgin Islands, British","Virgin Islands, U.S.","Vietnam","Vanuatu","Wallis and Futuna","Samoa","Yemen","Mayotte","Serbia","South Africa", "Zambia","Montenegro","Zimbabwe","Anonymous Proxy","Satellite Provider","Other","Aland Islands","Guernsey","Isle of Man","Jersey", "Saint Barthelemy","Saint Martin", "Bonaire, Saint Eustatius and Saba"}; public LookupService(String databaseFile, int options){ try { this.file = new FileStream(databaseFile, FileMode.Open, FileAccess.Read); dboptions = options; init(); } catch(System.SystemException) { Console.Write("cannot open file " + databaseFile + "\n"); } } public LookupService(String databaseFile):this(databaseFile, GEOIP_STANDARD){ } private void init(){ int i, j; byte [] delim = new byte[3]; byte [] buf = new byte[SEGMENT_RECORD_LENGTH]; databaseType = (byte)DatabaseInfo.COUNTRY_EDITION; recordLength = STANDARD_RECORD_LENGTH; //file.Seek(file.Length() - 3,SeekOrigin.Begin); file.Seek(-3,SeekOrigin.End); for (i = 0; i < STRUCTURE_INFO_MAX_SIZE; i++) { file.Read(delim,0,3); if (delim[0] == 255 && delim[1] == 255 && delim[2] == 255){ databaseType = Convert.ToByte(file.ReadByte()); if (databaseType >= 106) { // Backward compatibility with databases from April 2003 and earlier databaseType -= 105; } // Determine the database type. if (databaseType == DatabaseInfo.REGION_EDITION_REV0) { databaseSegments = new int[1]; databaseSegments[0] = STATE_BEGIN_REV0; recordLength = STANDARD_RECORD_LENGTH; } else if (databaseType == DatabaseInfo.REGION_EDITION_REV1) { databaseSegments = new int[1]; databaseSegments[0] = STATE_BEGIN_REV1; recordLength = STANDARD_RECORD_LENGTH; } else if (databaseType == DatabaseInfo.CITY_EDITION_REV0 || databaseType == DatabaseInfo.CITY_EDITION_REV1 || databaseType == DatabaseInfo.ORG_EDITION || databaseType == DatabaseInfo.ORG_EDITION_V6 || databaseType == DatabaseInfo.ISP_EDITION || databaseType == DatabaseInfo.ISP_EDITION_V6 || databaseType == DatabaseInfo.ASNUM_EDITION || databaseType == DatabaseInfo.ASNUM_EDITION_V6 || databaseType == DatabaseInfo.NETSPEED_EDITION_REV1 || databaseType == DatabaseInfo.NETSPEED_EDITION_REV1_V6 || databaseType == DatabaseInfo.CITY_EDITION_REV0_V6 || databaseType == DatabaseInfo.CITY_EDITION_REV1_V6 ) { databaseSegments = new int[1]; databaseSegments[0] = 0; if (databaseType == DatabaseInfo.CITY_EDITION_REV0 || databaseType == DatabaseInfo.CITY_EDITION_REV1 || databaseType == DatabaseInfo.ASNUM_EDITION_V6 || databaseType == DatabaseInfo.NETSPEED_EDITION_REV1 || databaseType == DatabaseInfo.NETSPEED_EDITION_REV1_V6 || databaseType == DatabaseInfo.CITY_EDITION_REV0_V6 || databaseType == DatabaseInfo.CITY_EDITION_REV1_V6 || databaseType == DatabaseInfo.ASNUM_EDITION ) { recordLength = STANDARD_RECORD_LENGTH; } else { recordLength = ORG_RECORD_LENGTH; } file.Read(buf,0,SEGMENT_RECORD_LENGTH); for (j = 0; j < SEGMENT_RECORD_LENGTH; j++) { databaseSegments[0] += (unsignedByteToInt(buf[j]) << (j * 8)); } } break; } else { //file.Seek(file.getFilePointer() - 4); file.Seek(-4,SeekOrigin.Current); //file.Seek(file.position-4,SeekOrigin.Begin); } } if ((databaseType == DatabaseInfo.COUNTRY_EDITION) || (databaseType == DatabaseInfo.COUNTRY_EDITION_V6) || (databaseType == DatabaseInfo.PROXY_EDITION) || (databaseType == DatabaseInfo.NETSPEED_EDITION)) { databaseSegments = new int[1]; databaseSegments[0] = COUNTRY_BEGIN; recordLength = STANDARD_RECORD_LENGTH; } if ((dboptions & GEOIP_MEMORY_CACHE) == 1) { int l = (int) file.Length; dbbuffer = new byte[l]; file.Seek(0,SeekOrigin.Begin); file.Read(dbbuffer,0,l); } } public void close(){ try { file.Close(); file = null; } catch (Exception) { } } public Country getCountry(IPAddress ipAddress) { return getCountry(bytestoLong(ipAddress.GetAddressBytes())); } public Country getCountryV6(String ipAddress){ IPAddress addr; try { addr = IPAddress.Parse(ipAddress); } //catch (UnknownHostException e) { catch (Exception e) { Console.Write(e.Message); return UNKNOWN_COUNTRY; } return getCountryV6(addr); } public Country getCountry(String ipAddress){ IPAddress addr; try { addr = IPAddress.Parse(ipAddress); } //catch (UnknownHostException e) { catch (Exception e) { Console.Write(e.Message); return UNKNOWN_COUNTRY; } // return getCountry(bytestoLong(addr.GetAddressBytes())); return getCountry(bytestoLong(addr.GetAddressBytes())); } public Country getCountryV6(IPAddress ipAddress){ if (file == null) { //throw new IllegalStateException("Database has been closed."); throw new Exception("Database has been closed."); } if ((databaseType == DatabaseInfo.CITY_EDITION_REV1) | (databaseType == DatabaseInfo.CITY_EDITION_REV0)) { Location l = getLocation(ipAddress); if (l == null) { return UNKNOWN_COUNTRY; } else { return new Country(l.countryCode, l.countryName); } } else { int ret = SeekCountryV6(ipAddress) - COUNTRY_BEGIN; if (ret == 0) { return UNKNOWN_COUNTRY; } else { return new Country(countryCode[ret], countryName[ret]); } } } public Country getCountry(long ipAddress){ if (file == null) { //throw new IllegalStateException("Database has been closed."); throw new Exception("Database has been closed."); } if ((databaseType == DatabaseInfo.CITY_EDITION_REV1) | (databaseType == DatabaseInfo.CITY_EDITION_REV0)) { Location l = getLocation(ipAddress); if (l == null) { return UNKNOWN_COUNTRY; } else { return new Country(l.countryCode, l.countryName); } } else { int ret = SeekCountry(ipAddress) - COUNTRY_BEGIN; if (ret == 0) { return UNKNOWN_COUNTRY; } else { return new Country(countryCode[ret], countryName[ret]); } } } public int getID(String ipAddress){ IPAddress addr; try { addr = IPAddress.Parse(ipAddress); } catch (Exception e) { Console.Write(e.Message); return 0; } return getID(bytestoLong(addr.GetAddressBytes())); } public int getID(IPAddress ipAddress) { return getID(bytestoLong(ipAddress.GetAddressBytes())); } public int getID(long ipAddress){ if (file == null) { throw new Exception("Database has been closed."); } int ret = SeekCountry(ipAddress) - databaseSegments[0]; return ret; } public DatabaseInfo getDatabaseInfo(){ if (databaseInfo != null) { return databaseInfo; } try { // Synchronize since we're accessing the database file. lock (this) { bool hasStructureInfo = false; byte [] delim = new byte[3]; // Advance to part of file where database info is stored. file.Seek(-3,SeekOrigin.End); for (int i=0; i<STRUCTURE_INFO_MAX_SIZE; i++) { file.Read(delim,0,3); if (delim[0] == 255 && delim[1] == 255 && delim[2] == 255) { hasStructureInfo = true; break; } } if (hasStructureInfo) { file.Seek(-3,SeekOrigin.Current); } else { // No structure info, must be pre Sep 2002 database, go back to end. file.Seek(-3,SeekOrigin.End); } // Find the database info string. for (int i=0; i<DATABASE_INFO_MAX_SIZE; i++) { file.Read(delim,0,3); if (delim[0]==0 && delim[1]==0 && delim[2]==0) { byte[] dbInfo = new byte[i]; char[] dbInfo2 = new char[i]; file.Read(dbInfo,0,i); for (int a0 = 0;a0 < i;a0++){ dbInfo2[a0] = Convert.ToChar(dbInfo[a0]); } // Create the database info object using the string. this.databaseInfo = new DatabaseInfo(new String(dbInfo2)); return databaseInfo; } file.Seek(-4,SeekOrigin.Current); } } } catch (Exception e) { Console.Write(e.Message); //e.printStackTrace(); } return new DatabaseInfo(""); } public Region getRegion(IPAddress ipAddress) { return getRegion(bytestoLong(ipAddress.GetAddressBytes())); } public Region getRegion(String str){ IPAddress addr; try { addr = IPAddress.Parse(str); } catch (Exception e) { Console.Write(e.Message); return null; } return getRegion(bytestoLong(addr.GetAddressBytes())); } [MethodImpl(MethodImplOptions.Synchronized)] public Region getRegion(long ipnum){ Region record = new Region(); int seek_region = 0; if (databaseType == DatabaseInfo.REGION_EDITION_REV0) { seek_region = SeekCountry(ipnum) - STATE_BEGIN_REV0; char [] ch = new char[2]; if (seek_region >= 1000){ record.countryCode = "US"; record.countryName = "United States"; ch[0] = (char)(((seek_region - 1000)/26) + 65); ch[1] = (char)(((seek_region - 1000)%26) + 65); record.region = new String(ch); } else { record.countryCode = countryCode[seek_region]; record.countryName = countryName[seek_region]; record.region = ""; } } else if (databaseType == DatabaseInfo.REGION_EDITION_REV1) { seek_region = SeekCountry(ipnum) - STATE_BEGIN_REV1; char [] ch = new char[2]; if (seek_region < US_OFFSET) { record.countryCode = ""; record.countryName = ""; record.region = ""; } else if (seek_region < CANADA_OFFSET) { record.countryCode = "US"; record.countryName = "United States"; ch[0] = (char)(((seek_region - US_OFFSET)/26) + 65); ch[1] = (char)(((seek_region - US_OFFSET)%26) + 65); record.region = new String(ch); } else if (seek_region < WORLD_OFFSET) { record.countryCode = "CA"; record.countryName = "Canada"; ch[0] = (char)(((seek_region - CANADA_OFFSET)/26) + 65); ch[1] = (char)(((seek_region - CANADA_OFFSET)%26) + 65); record.region = new String(ch); } else { record.countryCode = countryCode[(seek_region - WORLD_OFFSET) / FIPS_RANGE]; record.countryName = countryName[(seek_region - WORLD_OFFSET) / FIPS_RANGE]; record.region = ""; } } return record; } public Location getLocation(IPAddress addr){ return getLocation(bytestoLong(addr.GetAddressBytes())); } public Location getLocationV6(String str){ IPAddress addr; try { addr = IPAddress.Parse(str); } catch (Exception e) { Console.Write(e.Message); return null; } return getLocationV6(addr); } public Location getLocation(String str){ IPAddress addr; try { addr = IPAddress.Parse(str); } catch (Exception e) { Console.Write(e.Message); return null; } return getLocation(bytestoLong(addr.GetAddressBytes())); } [MethodImpl(MethodImplOptions.Synchronized)] public Location getLocationV6(IPAddress addr){ int record_pointer; byte[] record_buf = new byte[FULL_RECORD_LENGTH]; char[] record_buf2 = new char[FULL_RECORD_LENGTH]; int record_buf_offset = 0; Location record = new Location(); int str_length = 0; int j, Seek_country; double latitude = 0, longitude = 0; try { Seek_country = SeekCountryV6(addr); if (Seek_country == databaseSegments[0]) { return null; } record_pointer = Seek_country + ((2 * recordLength - 1) * databaseSegments[0]); if ((dboptions & GEOIP_MEMORY_CACHE) == 1){ Array.Copy(dbbuffer, record_pointer, record_buf, 0, Math.Min(dbbuffer.Length - record_pointer, FULL_RECORD_LENGTH)); } else { file.Seek(record_pointer,SeekOrigin.Begin); file.Read(record_buf,0,FULL_RECORD_LENGTH); } for (int a0 = 0;a0 < FULL_RECORD_LENGTH;a0++){ record_buf2[a0] = Convert.ToChar(record_buf[a0]); } // get country record.countryCode = countryCode[unsignedByteToInt(record_buf[0])]; record.countryName = countryName[unsignedByteToInt(record_buf[0])]; record_buf_offset++; // get region while (record_buf[record_buf_offset + str_length] != '\0') str_length++; if (str_length > 0) { record.region = new String(record_buf2, record_buf_offset, str_length); } record_buf_offset += str_length + 1; str_length = 0; // get region_name record.regionName = RegionName.getRegionName( record.countryCode, record.region ); // get city while (record_buf[record_buf_offset + str_length] != '\0') str_length++; if (str_length > 0) { record.city = new String(record_buf2, record_buf_offset, str_length); } record_buf_offset += (str_length + 1); str_length = 0; // get postal code while (record_buf[record_buf_offset + str_length] != '\0') str_length++; if (str_length > 0) { record.postalCode = new String(record_buf2, record_buf_offset, str_length); } record_buf_offset += (str_length + 1); // get latitude for (j = 0; j < 3; j++) latitude += (unsignedByteToInt(record_buf[record_buf_offset + j]) << (j * 8)); record.latitude = (float) latitude/10000 - 180; record_buf_offset += 3; // get longitude for (j = 0; j < 3; j++) longitude += (unsignedByteToInt(record_buf[record_buf_offset + j]) << (j * 8)); record.longitude = (float) longitude/10000 - 180; record.metro_code = record.dma_code = 0; record.area_code = 0; if (databaseType == DatabaseInfo.CITY_EDITION_REV1 ||databaseType == DatabaseInfo.CITY_EDITION_REV1_V6) { // get metro_code int metroarea_combo = 0; if (record.countryCode == "US"){ record_buf_offset += 3; for (j = 0; j < 3; j++) metroarea_combo += (unsignedByteToInt(record_buf[record_buf_offset + j]) << (j * 8)); record.metro_code = record.dma_code = metroarea_combo/1000; record.area_code = metroarea_combo % 1000; } } } catch (IOException) { Console.Write("IO Exception while seting up segments"); } return record; } [MethodImpl(MethodImplOptions.Synchronized)] public Location getLocation(long ipnum){ int record_pointer; byte[] record_buf = new byte[FULL_RECORD_LENGTH]; char[] record_buf2 = new char[FULL_RECORD_LENGTH]; int record_buf_offset = 0; Location record = new Location(); int str_length = 0; int j, Seek_country; double latitude = 0, longitude = 0; try { Seek_country = SeekCountry(ipnum); if (Seek_country == databaseSegments[0]) { return null; } record_pointer = Seek_country + ((2 * recordLength - 1) * databaseSegments[0]); if ((dboptions & GEOIP_MEMORY_CACHE) == 1){ Array.Copy(dbbuffer, record_pointer, record_buf, 0, Math.Min(dbbuffer.Length - record_pointer, FULL_RECORD_LENGTH)); } else { file.Seek(record_pointer,SeekOrigin.Begin); file.Read(record_buf,0,FULL_RECORD_LENGTH); } for (int a0 = 0;a0 < FULL_RECORD_LENGTH;a0++){ record_buf2[a0] = Convert.ToChar(record_buf[a0]); } // get country record.countryCode = countryCode[unsignedByteToInt(record_buf[0])]; record.countryName = countryName[unsignedByteToInt(record_buf[0])]; record_buf_offset++; // get region while (record_buf[record_buf_offset + str_length] != '\0') str_length++; if (str_length > 0) { record.region = new String(record_buf2, record_buf_offset, str_length); } record_buf_offset += str_length + 1; str_length = 0; // get region_name record.regionName = RegionName.getRegionName( record.countryCode, record.region ); // get city while (record_buf[record_buf_offset + str_length] != '\0') str_length++; if (str_length > 0) { record.city = new String(record_buf2, record_buf_offset, str_length); } record_buf_offset += (str_length + 1); str_length = 0; // get postal code while (record_buf[record_buf_offset + str_length] != '\0') str_length++; if (str_length > 0) { record.postalCode = new String(record_buf2, record_buf_offset, str_length); } record_buf_offset += (str_length + 1); // get latitude for (j = 0; j < 3; j++) latitude += (unsignedByteToInt(record_buf[record_buf_offset + j]) << (j * 8)); record.latitude = (float) latitude/10000 - 180; record_buf_offset += 3; // get longitude for (j = 0; j < 3; j++) longitude += (unsignedByteToInt(record_buf[record_buf_offset + j]) << (j * 8)); record.longitude = (float) longitude/10000 - 180; record.metro_code = record.dma_code = 0; record.area_code = 0; if (databaseType == DatabaseInfo.CITY_EDITION_REV1) { // get metro_code int metroarea_combo = 0; if (record.countryCode == "US"){ record_buf_offset += 3; for (j = 0; j < 3; j++) metroarea_combo += (unsignedByteToInt(record_buf[record_buf_offset + j]) << (j * 8)); record.metro_code = record.dma_code = metroarea_combo/1000; record.area_code = metroarea_combo % 1000; } } } catch (IOException) { Console.Write("IO Exception while seting up segments"); } return record; } public String getOrg(IPAddress addr) { return getOrg(bytestoLong(addr.GetAddressBytes())); } public String getOrgV6(String str){ IPAddress addr; try { addr = IPAddress.Parse(str); } //catch (UnknownHostException e) { catch (Exception e){ Console.Write(e.Message); return null; } return getOrgV6(addr); } public String getOrg(String str){ IPAddress addr; try { addr = IPAddress.Parse(str); } //catch (UnknownHostException e) { catch (Exception e){ Console.Write(e.Message); return null; } return getOrg(bytestoLong(addr.GetAddressBytes())); } [MethodImpl(MethodImplOptions.Synchronized)] public String getOrgV6( IPAddress addr){ int Seek_org; int record_pointer; int str_length = 0; byte [] buf = new byte[MAX_ORG_RECORD_LENGTH]; char [] buf2 = new char[MAX_ORG_RECORD_LENGTH]; String org_buf; try { Seek_org = SeekCountryV6(addr); if (Seek_org == databaseSegments[0]) { return null; } record_pointer = Seek_org + (2 * recordLength - 1) * databaseSegments[0]; if ((dboptions & GEOIP_MEMORY_CACHE) == 1) { Array.Copy(dbbuffer, record_pointer, buf, 0, Math.Min(dbbuffer.Length - record_pointer, MAX_ORG_RECORD_LENGTH)); } else { file.Seek(record_pointer,SeekOrigin.Begin); file.Read(buf,0,MAX_ORG_RECORD_LENGTH); } while (buf[str_length] != 0) { buf2[str_length] = Convert.ToChar(buf[str_length]); str_length++; } buf2[str_length] = '\0'; org_buf = new String(buf2,0,str_length); return org_buf; } catch (IOException) { Console.Write("IO Exception"); return null; } } [MethodImpl(MethodImplOptions.Synchronized)] public String getOrg(long ipnum){ int Seek_org; int record_pointer; int str_length = 0; byte [] buf = new byte[MAX_ORG_RECORD_LENGTH]; char [] buf2 = new char[MAX_ORG_RECORD_LENGTH]; String org_buf; try { Seek_org = SeekCountry(ipnum); if (Seek_org == databaseSegments[0]) { return null; } record_pointer = Seek_org + (2 * recordLength - 1) * databaseSegments[0]; if ((dboptions & GEOIP_MEMORY_CACHE) == 1) { Array.Copy(dbbuffer, record_pointer, buf, 0, Math.Min(dbbuffer.Length - record_pointer, MAX_ORG_RECORD_LENGTH)); } else { file.Seek(record_pointer,SeekOrigin.Begin); file.Read(buf,0,MAX_ORG_RECORD_LENGTH); } while (buf[str_length] != 0) { buf2[str_length] = Convert.ToChar(buf[str_length]); str_length++; } buf2[str_length] = '\0'; org_buf = new String(buf2,0,str_length); return org_buf; } catch (IOException) { Console.Write("IO Exception"); return null; } } [MethodImpl(MethodImplOptions.Synchronized)] private int SeekCountryV6(IPAddress ipAddress){ byte [] v6vec = ipAddress.GetAddressBytes(); byte [] buf = new byte[2 * MAX_RECORD_LENGTH]; int [] x = new int[2]; int offset = 0; for (int depth = 127; depth >= 0; depth--) { try { if ((dboptions & GEOIP_MEMORY_CACHE) == 1) { for (int i = 0;i < (2 * MAX_RECORD_LENGTH);i++) { buf[i] = dbbuffer[i+(2 * recordLength * offset)]; } } else { file.Seek(2 * recordLength * offset,SeekOrigin.Begin); file.Read(buf,0,2 * MAX_RECORD_LENGTH); } } catch (IOException) { Console.Write("IO Exception"); } for (int i = 0; i<2; i++) { x[i] = 0; for (int j = 0; j<recordLength; j++) { int y = buf[(i*recordLength)+j]; if (y < 0) { y+= 256; } x[i] += (y << (j * 8)); } } int bnum = 127 - depth; int idx = bnum >> 3; int b_mask = 1 << ( bnum & 7 ^ 7 ); if ((v6vec[idx] & b_mask) > 0) { if (x[1] >= databaseSegments[0]) { return x[1]; } offset = x[1]; } else { if (x[0] >= databaseSegments[0]) { return x[0]; } offset = x[0]; } } // shouldn't reach here Console.Write("Error Seeking country while Seeking " + ipAddress); return 0; } [MethodImpl(MethodImplOptions.Synchronized)] private int SeekCountry(long ipAddress){ byte [] buf = new byte[2 * MAX_RECORD_LENGTH]; int [] x = new int[2]; int offset = 0; for (int depth = 31; depth >= 0; depth--) { try { if ((dboptions & GEOIP_MEMORY_CACHE) == 1) { for (int i = 0;i < (2 * MAX_RECORD_LENGTH);i++) { buf[i] = dbbuffer[i+(2 * recordLength * offset)]; } } else { file.Seek(2 * recordLength * offset,SeekOrigin.Begin); file.Read(buf,0,2 * MAX_RECORD_LENGTH); } } catch (IOException) { Console.Write("IO Exception"); } for (int i = 0; i<2; i++) { x[i] = 0; for (int j = 0; j<recordLength; j++) { int y = buf[(i*recordLength)+j]; if (y < 0) { y+= 256; } x[i] += (y << (j * 8)); } } if ((ipAddress & (1 << depth)) > 0) { if (x[1] >= databaseSegments[0]) { return x[1]; } offset = x[1]; } else { if (x[0] >= databaseSegments[0]) { return x[0]; } offset = x[0]; } } // shouldn't reach here Console.Write("Error Seeking country while Seeking " + ipAddress); return 0; } private static long swapbytes(long ipAddress){ return (((ipAddress>>0) & 255) << 24) | (((ipAddress>>8) & 255) << 16) | (((ipAddress>>16) & 255) << 8) | (((ipAddress>>24) & 255) << 0); } private static long bytestoLong(byte [] address){ long ipnum = 0; for (int i = 0; i < 4; ++i) { long y = address[i]; if (y < 0) { y+= 256; } ipnum += y << ((3-i)*8); } return ipnum; } private static int unsignedByteToInt(byte b) { return (int) b & 0xFF; } }
/********************************************************************++ * Copyright (c) Microsoft Corporation. All rights reserved. * --********************************************************************/ using System.Management.Automation.Remoting; using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation { internal sealed class RemoteSessionNegotiationEventArgs : EventArgs { #region Constructors internal RemoteSessionNegotiationEventArgs(RemoteSessionCapability remoteSessionCapability) { Dbg.Assert(remoteSessionCapability != null, "caller should validate the parameter"); if (remoteSessionCapability == null) { throw PSTraceSource.NewArgumentNullException("remoteSessionCapability"); } RemoteSessionCapability = remoteSessionCapability; } #endregion Constructors /// <summary> /// Data from network converted to type RemoteSessionCapability. /// </summary> internal RemoteSessionCapability RemoteSessionCapability { get; } /// <summary> /// Actual data received from the network. /// </summary> internal RemoteDataObject<PSObject> RemoteData { get; set; } } /// <summary> /// This event arg is designed to contain generic data received from the other side of the connection. /// It can be used for both the client side and for the server side. /// </summary> internal sealed class RemoteDataEventArgs : EventArgs { #region Constructors internal RemoteDataEventArgs(RemoteDataObject<PSObject> receivedData) { Dbg.Assert(receivedData != null, "caller should validate the parameter"); if (receivedData == null) { throw PSTraceSource.NewArgumentNullException("receivedData"); } ReceivedData = receivedData; } #endregion Constructors /// <summary> /// Received data. /// </summary> public RemoteDataObject<PSObject> ReceivedData { get; } } /// <summary> /// This event arg contains data received and is used to pass information /// from a data structure handler to its object /// </summary> /// <typeparam name="T">type of data that's associated</typeparam> internal sealed class RemoteDataEventArgs<T> : EventArgs { #region Private Members #endregion Private Members #region Properties /// <summary> /// The data contained within this event /// </summary> internal T Data { get; } #endregion Properties #region Constructor internal RemoteDataEventArgs(object data) { //Dbg.Assert(data != null, "data passed should not be null"); Data = (T)data; } #endregion Constructor } /// <summary> /// This defines the various states a remote connection can be in. /// </summary> internal enum RemoteSessionState { /// <summary> /// Undefined state /// </summary> UndefinedState = 0, /// <summary> /// This is the state a connect start with. When a connection is closed, /// the connection will eventually come back to this Idle state. /// /// </summary> Idle = 1, /// <summary> /// A connection operation has been initiated. /// </summary> Connecting = 2, /// <summary> /// A connection operation has completed successfully. /// </summary> Connected = 3, /// <summary> /// The capability negotiation message is in the process being sent on a create operation /// </summary> NegotiationSending = 4, /// <summary> /// The capability negotiation message is in the process being sent on a connect operation /// </summary> NegotiationSendingOnConnect = 5, /// <summary> /// The capability negotiation message is sent successfully from a sender point of view. /// </summary> NegotiationSent = 6, /// <summary> /// A capability negotiation message is received. /// </summary> NegotiationReceived = 7, /// <summary> /// Used by server to wait for negotation from client. /// </summary> NegotiationPending = 8, /// <summary> /// The connection is in the progress of getting closed. /// </summary> ClosingConnection = 9, /// <summary> /// The connection is closed completely. /// </summary> Closed = 10, /// <summary> /// The capability negotiation has been successfully completed. /// </summary> Established = 11, /// <summary> /// Have sent a public key to the remote end, /// awaiting a response /// </summary> /// <remarks>Applicable only to client</remarks> EstablishedAndKeySent = 12, /// <summary> /// Have received a public key from the remote /// end, need to send a response /// </summary> /// <remarks>Applicable only to server</remarks> EstablishedAndKeyReceived = 13, /// <summary> /// for Server - Have sent a request to the remote end to /// send a public key /// for Cleint - have received a PK request from server /// </summary> /// <remarks>Applicable to both cleint and server</remarks> EstablishedAndKeyRequested = 14, /// <summary> /// Key exchange complete. This can mean /// (a) Sent an encrypted session key to the /// remote end in response to receiving /// a public key - this is for the server /// (b) Received an encrypted session key from /// remote end after sending a public key - /// this is for the client /// </summary> EstablishedAndKeyExchanged = 15, /// <summary> /// /// </summary> Disconnecting = 16, /// <summary> /// /// </summary> Disconnected = 17, /// <summary> /// /// </summary> Reconnecting = 18, /// <summary> /// A disconnect operation initiated by the WinRM robust connection /// layer and *not* by the user. /// </summary> RCDisconnecting = 19, /// <summary> /// Number of states /// </summary> MaxState = 20 } /// <summary> /// This defines the internal events that the finite state machine for the connection /// uses to take action and perform state transitions. /// </summary> internal enum RemoteSessionEvent { InvalidEvent = 0, CreateSession = 1, ConnectSession = 2, NegotiationSending = 3, NegotiationSendingOnConnect = 4, NegotiationSendCompleted = 5, NegotiationReceived = 6, NegotiationCompleted = 7, NegotiationPending = 8, Close = 9, CloseCompleted = 10, CloseFailed = 11, ConnectFailed = 12, NegotiationFailed = 13, NegotiationTimeout = 14, SendFailed = 15, ReceiveFailed = 16, FatalError = 17, MessageReceived = 18, KeySent = 19, KeySendFailed = 20, KeyReceived = 21, KeyReceiveFailed = 22, KeyRequested = 23, KeyRequestFailed = 24, DisconnectStart = 25, DisconnectCompleted = 26, DisconnectFailed = 27, ReconnectStart = 28, ReconnectCompleted = 29, ReconnectFailed = 30, RCDisconnectStarted = 31, MaxEvent = 32 } /// <summary> /// This is a wrapper class for RemoteSessionState. /// </summary> internal class RemoteSessionStateInfo { #region Constructors internal RemoteSessionStateInfo(RemoteSessionState state) : this(state, null) { } internal RemoteSessionStateInfo(RemoteSessionState state, Exception reason) { State = state; Reason = reason; } internal RemoteSessionStateInfo(RemoteSessionStateInfo sessionStateInfo) { State = sessionStateInfo.State; Reason = sessionStateInfo.Reason; } #endregion Constructors #region Public_Properties /// <summary> /// State of the connection /// </summary> internal RemoteSessionState State { get; } /// <summary> /// If the connection is closed, this provides reason why it had happened. /// </summary> internal Exception Reason { get; } #endregion Public_Properties } /// <summary> /// /// This is the event arg that contains the state information. /// </summary> internal class RemoteSessionStateEventArgs : EventArgs { #region Constructors internal RemoteSessionStateEventArgs(RemoteSessionStateInfo remoteSessionStateInfo) { Dbg.Assert(remoteSessionStateInfo != null, "caller should validate the parameter"); if (remoteSessionStateInfo == null) { PSTraceSource.NewArgumentNullException("remoteSessionStateInfo"); } SessionStateInfo = remoteSessionStateInfo; } #endregion Constructors #region Public_Properties /// <summary> /// State information about the connection. /// </summary> public RemoteSessionStateInfo SessionStateInfo { get; } #endregion Public_Properties } internal class RemoteSessionStateMachineEventArgs : EventArgs { #region Constructors internal RemoteSessionStateMachineEventArgs(RemoteSessionEvent stateEvent) : this(stateEvent, null) { } internal RemoteSessionStateMachineEventArgs(RemoteSessionEvent stateEvent, Exception reason) { StateEvent = stateEvent; Reason = reason; } #endregion Constructors internal RemoteSessionEvent StateEvent { get; } internal Exception Reason { get; } internal RemoteSessionCapability RemoteSessionCapability { get; set; } internal RemoteDataObject<PSObject> RemoteData { get; set; } } /// <summary> /// Defines the various types of remoting behaviour that a cmdlet may /// desire when used in a context that supports ambient / automatic remoting. /// </summary> public enum RemotingCapability { /// <summary> /// In the presence of ambient remoting, this command should /// still be run locally. /// </summary> None, /// <summary> /// In the presence of ambient remoting, this command should /// be run on the target computer using PowerShell Remoting. /// </summary> PowerShell, /// <summary> /// In the presence of ambient remoting, this command supports /// its own form of remoting which can be used instead to target /// the remote computer. /// </summary> SupportedByCommand, /// <summary> /// In the presence of ambient remoting, the command assumes /// all responsibility for targetting the remote computer; /// PowerShell Remoting is not supported. /// </summary> OwnedByCommand } /// <summary> /// Controls or overrides the remoting behavior, during invocation, of a /// command that supports ambient remoting. /// </summary> public enum RemotingBehavior { /// <summary> /// In the presence of ambient remoting, run this command locally. /// </summary> None, /// <summary> /// In the presence of ambient remoting, run this command on the target /// computer using PowerShell Remoting. /// </summary> PowerShell, /// <summary> /// In the presence of ambient remoting, and a command that declares /// 'SupportedByCommand' remoting capability, run this command on the /// target computer using the command's custom remoting facilities. /// </summary> Custom } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.PetstoreV2 { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json; using Microsoft.Rest; using Models; /// <summary> /// This is a sample server Petstore server. You can find out more about /// Swagger at &lt;a /// href="http://swagger.io"&gt;http://swagger.io&lt;/a&gt; or on /// irc.freenode.net, #swagger. For this sample, you can use the api key /// "special-key" to test the authorization filters /// </summary> public partial interface ISwaggerPetstoreV2 { /// <summary> /// The base URI of the service. /// </summary> Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> JsonSerializerSettings SerializationSettings { get; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> JsonSerializerSettings DeserializationSettings { get; } /// <summary> /// Add a new pet to the store /// </summary> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Pet>> AddPetWithHttpMessagesAsync(Pet body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Update an existing pet /// </summary> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> UpdatePetWithHttpMessagesAsync(Pet body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Finds Pets by status /// </summary> /// Multiple status values can be provided with comma seperated strings /// <param name='status'> /// Status values that need to be considered for filter /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<Pet>>> FindPetsByStatusWithHttpMessagesAsync(IList<string> status, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Finds Pets by tags /// </summary> /// Muliple tags can be provided with comma seperated strings. Use /// tag1, tag2, tag3 for testing. /// <param name='tags'> /// Tags to filter by /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<Pet>>> FindPetsByTagsWithHttpMessagesAsync(IList<string> tags, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Find pet by Id /// </summary> /// Returns a single pet /// <param name='petId'> /// Id of pet to return /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Pet>> GetPetByIdWithHttpMessagesAsync(long? petId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates a pet in the store with form data /// </summary> /// <param name='petId'> /// Id of pet that needs to be updated /// </param> /// <param name='name'> /// Updated name of the pet /// </param> /// <param name='status'> /// Updated status of the pet /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> UpdatePetWithFormWithHttpMessagesAsync(long? petId, string name = default(string), string status = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a pet /// </summary> /// <param name='petId'> /// Pet id to delete /// </param> /// <param name='apiKey'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> DeletePetWithHttpMessagesAsync(long? petId, string apiKey = "", Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns pet inventories by status /// </summary> /// Returns a map of status codes to quantities /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, int?>>> GetInventoryWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Place an order for a pet /// </summary> /// <param name='body'> /// order placed for purchasing the pet /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Order>> PlaceOrderWithHttpMessagesAsync(Order body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Find purchase order by Id /// </summary> /// For valid response try integer IDs with value &lt;= 5 or &gt; 10. /// Other values will generated exceptions /// <param name='orderId'> /// Id of pet that needs to be fetched /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Order>> GetOrderByIdWithHttpMessagesAsync(string orderId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Delete purchase order by Id /// </summary> /// For valid response try integer IDs with value &lt; 1000. Anything /// above 1000 or nonintegers will generate API errors /// <param name='orderId'> /// Id of the order that needs to be deleted /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> DeleteOrderWithHttpMessagesAsync(string orderId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Create user /// </summary> /// This can only be done by the logged in user. /// <param name='body'> /// Created user object /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> CreateUserWithHttpMessagesAsync(User body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='body'> /// List of user object /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> CreateUsersWithArrayInputWithHttpMessagesAsync(IList<User> body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='body'> /// List of user object /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> CreateUsersWithListInputWithHttpMessagesAsync(IList<User> body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Logs user into the system /// </summary> /// <param name='username'> /// The user name for login /// </param> /// <param name='password'> /// The password for login in clear text /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<string>> LoginUserWithHttpMessagesAsync(string username, string password, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Logs out current logged in user session /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> LogoutUserWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get user by user name /// </summary> /// <param name='username'> /// The name that needs to be fetched. Use user1 for testing. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<User>> GetUserByNameWithHttpMessagesAsync(string username, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updated user /// </summary> /// This can only be done by the logged in user. /// <param name='username'> /// name that need to be deleted /// </param> /// <param name='body'> /// Updated user object /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> UpdateUserWithHttpMessagesAsync(string username, User body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Delete user /// </summary> /// This can only be done by the logged in user. /// <param name='username'> /// The name that needs to be deleted /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> DeleteUserWithHttpMessagesAsync(string username, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // using System; using System.Diagnostics; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Reflection; using MS.Internal; using MS.Internal.WindowsBase; using System.Text; using System.Collections; using System.Globalization; using System.Windows; using System.Windows.Media; using System.Runtime.InteropServices; using System.Security; // IMPORTANT // // Rules for using matrix types. // // internal enum MatrixTypes // { // TRANSFORM_IS_IDENTITY = 0, // TRANSFORM_IS_TRANSLATION = 1, // TRANSFORM_IS_SCALING = 2, // TRANSFORM_IS_UNKNOWN = 4 // } // // 1. Matrix type must be one of 0, 1, 2, 4, or 3 (for scale and translation) // 2. Matrix types are true but not exact! (E.G. A scale or identity transform could be marked as unknown or scale+translate.) // 3. Therefore read-only operations can ignore the type with one exception // EXCEPTION: A matrix tagged identity might have any coefficients instead of 1,0,0,1,0,0 // This is the (now) classic no default constructor for structs issue // 4. Matrix._type must be maintained by mutation operations // 5. MS.Internal.MatrixUtil uses unsafe code to access the private members of Matrix including _type. // // In Jan 2005 the matrix types were changed from being EXACT (i.e. a // scale matrix is always tagged as a scale and not something more // general.) This resulted in about a 2% speed up in matrix // multiplication. // // The special cases for matrix multiplication speed up scale*scale // and translation*translation by 30% compared to a single "no-branch" // multiplication algorithm. Matrix multiplication of two unknown // matrices is slowed by 20% compared to the no-branch algorithm. // // windows/wcp/DevTest/Drts/MediaApi/MediaPerf.cs includes the // simple test of matrix multiplication speed used for these results. namespace System.Windows.Media { ///<summary> /// Matrix ///</summary> public partial struct Matrix: IFormattable { // the transform is identity by default // Actually fill in the fields - some (internal) code uses the fields directly for perf. private static Matrix s_identity = CreateIdentity(); #region Constructor /// <summary> /// Creates a matrix of the form /// / m11, m12, 0 \ /// | m21, m22, 0 | /// \ offsetX, offsetY, 1 / /// </summary> public Matrix(double m11, double m12, double m21, double m22, double offsetX, double offsetY) { this._m11 = m11; this._m12 = m12; this._m21 = m21; this._m22 = m22; this._offsetX = offsetX; this._offsetY = offsetY; _type = MatrixTypes.TRANSFORM_IS_UNKNOWN; _padding = 0; // We will detect EXACT identity, scale, translation or // scale+translation and use special case algorithms. DeriveMatrixType(); } #endregion Constructor #region Identity /// <summary> /// Identity /// </summary> public static Matrix Identity { get { return s_identity; } } /// <summary> /// Sets the matrix to identity. /// </summary> public void SetIdentity() { _type = MatrixTypes.TRANSFORM_IS_IDENTITY; } /// <summary> /// Tests whether or not a given transform is an identity transform /// </summary> public bool IsIdentity { get { return (_type == MatrixTypes.TRANSFORM_IS_IDENTITY || (_m11 == 1 && _m12 == 0 && _m21 == 0 && _m22 == 1 && _offsetX == 0 && _offsetY == 0)); } } #endregion Identity #region Operators /// <summary> /// Multiplies two transformations. /// </summary> public static Matrix operator *(Matrix trans1, Matrix trans2) { MatrixUtil.MultiplyMatrix(ref trans1, ref trans2); trans1.Debug_CheckType(); return trans1; } /// <summary> /// Multiply /// </summary> public static Matrix Multiply(Matrix trans1, Matrix trans2) { MatrixUtil.MultiplyMatrix(ref trans1, ref trans2); trans1.Debug_CheckType(); return trans1; } #endregion Operators #region Combine Methods /// <summary> /// Append - "this" becomes this * matrix, the same as this *= matrix. /// </summary> /// <param name="matrix"> The Matrix to append to this Matrix </param> public void Append(Matrix matrix) { this *= matrix; } /// <summary> /// Prepend - "this" becomes matrix * this, the same as this = matrix * this. /// </summary> /// <param name="matrix"> The Matrix to prepend to this Matrix </param> public void Prepend(Matrix matrix) { this = matrix * this; } /// <summary> /// Rotates this matrix about the origin /// </summary> /// <param name='angle'>The angle to rotate specified in degrees</param> public void Rotate(double angle) { angle %= 360.0; // Doing the modulo before converting to radians reduces total error this *= CreateRotationRadians(angle * (Math.PI/180.0)); } /// <summary> /// Prepends a rotation about the origin to "this" /// </summary> /// <param name='angle'>The angle to rotate specified in degrees</param> public void RotatePrepend(double angle) { angle %= 360.0; // Doing the modulo before converting to radians reduces total error this = CreateRotationRadians(angle * (Math.PI/180.0)) * this; } /// <summary> /// Rotates this matrix about the given point /// </summary> /// <param name='angle'>The angle to rotate specified in degrees</param> /// <param name='centerX'>The centerX of rotation</param> /// <param name='centerY'>The centerY of rotation</param> public void RotateAt(double angle, double centerX, double centerY) { angle %= 360.0; // Doing the modulo before converting to radians reduces total error this *= CreateRotationRadians(angle * (Math.PI/180.0), centerX, centerY); } /// <summary> /// Prepends a rotation about the given point to "this" /// </summary> /// <param name='angle'>The angle to rotate specified in degrees</param> /// <param name='centerX'>The centerX of rotation</param> /// <param name='centerY'>The centerY of rotation</param> public void RotateAtPrepend(double angle, double centerX, double centerY) { angle %= 360.0; // Doing the modulo before converting to radians reduces total error this = CreateRotationRadians(angle * (Math.PI/180.0), centerX, centerY) * this; } /// <summary> /// Scales this matrix around the origin /// </summary> /// <param name='scaleX'>The scale factor in the x dimension</param> /// <param name='scaleY'>The scale factor in the y dimension</param> public void Scale(double scaleX, double scaleY) { this *= CreateScaling(scaleX, scaleY); } /// <summary> /// Prepends a scale around the origin to "this" /// </summary> /// <param name='scaleX'>The scale factor in the x dimension</param> /// <param name='scaleY'>The scale factor in the y dimension</param> public void ScalePrepend(double scaleX, double scaleY) { this = CreateScaling(scaleX, scaleY) * this; } /// <summary> /// Scales this matrix around the center provided /// </summary> /// <param name='scaleX'>The scale factor in the x dimension</param> /// <param name='scaleY'>The scale factor in the y dimension</param> /// <param name="centerX">The centerX about which to scale</param> /// <param name="centerY">The centerY about which to scale</param> public void ScaleAt(double scaleX, double scaleY, double centerX, double centerY) { this *= CreateScaling(scaleX, scaleY, centerX, centerY); } /// <summary> /// Prepends a scale around the center provided to "this" /// </summary> /// <param name='scaleX'>The scale factor in the x dimension</param> /// <param name='scaleY'>The scale factor in the y dimension</param> /// <param name="centerX">The centerX about which to scale</param> /// <param name="centerY">The centerY about which to scale</param> public void ScaleAtPrepend(double scaleX, double scaleY, double centerX, double centerY) { this = CreateScaling(scaleX, scaleY, centerX, centerY) * this; } /// <summary> /// Skews this matrix /// </summary> /// <param name='skewX'>The skew angle in the x dimension in degrees</param> /// <param name='skewY'>The skew angle in the y dimension in degrees</param> public void Skew(double skewX, double skewY) { skewX %= 360; skewY %= 360; this *= CreateSkewRadians(skewX * (Math.PI/180.0), skewY * (Math.PI/180.0)); } /// <summary> /// Prepends a skew to this matrix /// </summary> /// <param name='skewX'>The skew angle in the x dimension in degrees</param> /// <param name='skewY'>The skew angle in the y dimension in degrees</param> public void SkewPrepend(double skewX, double skewY) { skewX %= 360; skewY %= 360; this = CreateSkewRadians(skewX * (Math.PI/180.0), skewY * (Math.PI/180.0)) * this; } /// <summary> /// Translates this matrix /// </summary> /// <param name='offsetX'>The offset in the x dimension</param> /// <param name='offsetY'>The offset in the y dimension</param> public void Translate(double offsetX, double offsetY) { // // / a b 0 \ / 1 0 0 \ / a b 0 \ // | c d 0 | * | 0 1 0 | = | c d 0 | // \ e f 1 / \ x y 1 / \ e+x f+y 1 / // // (where e = _offsetX and f == _offsetY) // if (_type == MatrixTypes.TRANSFORM_IS_IDENTITY) { // Values would be incorrect if matrix was created using default constructor. // or if SetIdentity was called on a matrix which had values. // SetMatrix(1, 0, 0, 1, offsetX, offsetY, MatrixTypes.TRANSFORM_IS_TRANSLATION); } else if (_type == MatrixTypes.TRANSFORM_IS_UNKNOWN) { _offsetX += offsetX; _offsetY += offsetY; } else { _offsetX += offsetX; _offsetY += offsetY; // If matrix wasn't unknown we added a translation _type |= MatrixTypes.TRANSFORM_IS_TRANSLATION; } Debug_CheckType(); } /// <summary> /// Prepends a translation to this matrix /// </summary> /// <param name='offsetX'>The offset in the x dimension</param> /// <param name='offsetY'>The offset in the y dimension</param> public void TranslatePrepend(double offsetX, double offsetY) { this = CreateTranslation(offsetX, offsetY) * this; } #endregion Set Methods #region Transformation Services /// <summary> /// Transform - returns the result of transforming the point by this matrix /// </summary> /// <returns> /// The transformed point /// </returns> /// <param name="point"> The Point to transform </param> public Point Transform(Point point) { Point newPoint = point; var x = newPoint.X; var y = newPoint.Y; MultiplyPoint(ref x, ref y); return new Point(x,y); } /// <summary> /// Transform - Transforms each point in the array by this matrix /// </summary> /// <param name="points"> The Point array to transform </param> public void Transform(Point[] points) { if (points != null) { for (int i = 0; i < points.Length; i++) { var point = points[i]; var x = point.X; var y = point.Y; MultiplyPoint(ref x, ref y); points[i]=new Point(x,y); } } } /// <summary> /// Transform - returns the result of transforming the Vector by this matrix. /// </summary> /// <returns> /// The transformed vector /// </returns> /// <param name="vector"> The Vector to transform </param> public Vector Transform(Vector vector) { var x = vector.X; var y = vector.Y; MultiplyVector(ref x, ref y); Vector newVector = new Vector(x,y); return newVector; } /// <summary> /// Transform - Transforms each Vector in the array by this matrix. /// </summary> /// <param name="vectors"> The Vector array to transform </param> public void Transform(Vector[] vectors) { if (vectors != null) { for (int i = 0; i < vectors.Length; i++) { var vector = vectors[i]; var x = vector.X; var y = vector.Y; MultiplyVector(ref x, ref y); Vector newVector = new Vector(x, y); vectors[i] = newVector; } } } #endregion Transformation Services #region Inversion /// <summary> /// The determinant of this matrix /// </summary> public double Determinant { get { switch (_type) { case MatrixTypes.TRANSFORM_IS_IDENTITY: case MatrixTypes.TRANSFORM_IS_TRANSLATION: return 1.0; case MatrixTypes.TRANSFORM_IS_SCALING: case MatrixTypes.TRANSFORM_IS_SCALING | MatrixTypes.TRANSFORM_IS_TRANSLATION: return(_m11 * _m22); default: return(_m11 * _m22) - (_m12 * _m21); } } } /// <summary> /// HasInverse Property - returns true if this matrix is invertable, false otherwise. /// </summary> public bool HasInverse { get { return !DoubleUtil.IsZero(Determinant); } } /// <summary> /// Replaces matrix with the inverse of the transformation. This will throw an InvalidOperationException /// if !HasInverse /// </summary> /// <exception cref="InvalidOperationException"> /// This will throw an InvalidOperationException if the matrix is non-invertable /// </exception> public void Invert() { double determinant = Determinant; if (DoubleUtil.IsZero(determinant)) { throw new System.InvalidOperationException(SR.Get(SRID.Transform_NotInvertible)); } // Inversion does not change the type of a matrix. switch (_type) { case MatrixTypes.TRANSFORM_IS_IDENTITY: break; case MatrixTypes.TRANSFORM_IS_SCALING: { _m11 = 1.0 / _m11; _m22 = 1.0 / _m22; } break; case MatrixTypes.TRANSFORM_IS_TRANSLATION: _offsetX = -_offsetX; _offsetY = -_offsetY; break; case MatrixTypes.TRANSFORM_IS_SCALING | MatrixTypes.TRANSFORM_IS_TRANSLATION: { _m11 = 1.0 / _m11; _m22 = 1.0 / _m22; _offsetX = -_offsetX * _m11; _offsetY = -_offsetY * _m22; } break; default: { double invdet = 1.0/determinant; SetMatrix(_m22 * invdet, -_m12 * invdet, -_m21 * invdet, _m11 * invdet, (_m21 * _offsetY - _offsetX * _m22) * invdet, (_offsetX * _m12 - _m11 * _offsetY) * invdet, MatrixTypes.TRANSFORM_IS_UNKNOWN); } break; } } #endregion Inversion #region Public Properties /// <summary> /// M11 /// </summary> public double M11 { get { if (_type == MatrixTypes.TRANSFORM_IS_IDENTITY) { return 1.0; } else { return _m11; } } set { if (_type == MatrixTypes.TRANSFORM_IS_IDENTITY) { SetMatrix(value, 0, 0, 1, 0, 0, MatrixTypes.TRANSFORM_IS_SCALING); } else { _m11 = value; if (_type != MatrixTypes.TRANSFORM_IS_UNKNOWN) { _type |= MatrixTypes.TRANSFORM_IS_SCALING; } } } } /// <summary> /// M12 /// </summary> public double M12 { get { if (_type == MatrixTypes.TRANSFORM_IS_IDENTITY) { return 0; } else { return _m12; } } set { if (_type == MatrixTypes.TRANSFORM_IS_IDENTITY) { SetMatrix(1, value, 0, 1, 0, 0, MatrixTypes.TRANSFORM_IS_UNKNOWN); } else { _m12 = value; _type = MatrixTypes.TRANSFORM_IS_UNKNOWN; } } } /// <summary> /// M22 /// </summary> public double M21 { get { if (_type == MatrixTypes.TRANSFORM_IS_IDENTITY) { return 0; } else { return _m21; } } set { if (_type == MatrixTypes.TRANSFORM_IS_IDENTITY) { SetMatrix(1, 0, value, 1, 0, 0, MatrixTypes.TRANSFORM_IS_UNKNOWN); } else { _m21 = value; _type = MatrixTypes.TRANSFORM_IS_UNKNOWN; } } } /// <summary> /// M22 /// </summary> public double M22 { get { if (_type == MatrixTypes.TRANSFORM_IS_IDENTITY) { return 1.0; } else { return _m22; } } set { if (_type == MatrixTypes.TRANSFORM_IS_IDENTITY) { SetMatrix(1, 0, 0, value, 0, 0, MatrixTypes.TRANSFORM_IS_SCALING); } else { _m22 = value; if (_type != MatrixTypes.TRANSFORM_IS_UNKNOWN) { _type |= MatrixTypes.TRANSFORM_IS_SCALING; } } } } /// <summary> /// OffsetX /// </summary> public double OffsetX { get { if (_type == MatrixTypes.TRANSFORM_IS_IDENTITY) { return 0; } else { return _offsetX; } } set { if (_type == MatrixTypes.TRANSFORM_IS_IDENTITY) { SetMatrix(1, 0, 0, 1, value, 0, MatrixTypes.TRANSFORM_IS_TRANSLATION); } else { _offsetX = value; if (_type != MatrixTypes.TRANSFORM_IS_UNKNOWN) { _type |= MatrixTypes.TRANSFORM_IS_TRANSLATION; } } } } /// <summary> /// OffsetY /// </summary> public double OffsetY { get { if (_type == MatrixTypes.TRANSFORM_IS_IDENTITY) { return 0; } else { return _offsetY; } } set { if (_type == MatrixTypes.TRANSFORM_IS_IDENTITY) { SetMatrix(1, 0, 0, 1, 0, value, MatrixTypes.TRANSFORM_IS_TRANSLATION); } else { _offsetY = value; if (_type != MatrixTypes.TRANSFORM_IS_UNKNOWN) { _type |= MatrixTypes.TRANSFORM_IS_TRANSLATION; } } } } #endregion Public Properties #region Internal Methods /// <summary> /// MultiplyVector /// </summary> internal void MultiplyVector(ref double x, ref double y) { switch (_type) { case MatrixTypes.TRANSFORM_IS_IDENTITY: case MatrixTypes.TRANSFORM_IS_TRANSLATION: return; case MatrixTypes.TRANSFORM_IS_SCALING: case MatrixTypes.TRANSFORM_IS_SCALING | MatrixTypes.TRANSFORM_IS_TRANSLATION: x *= _m11; y *= _m22; break; default: double xadd = y * _m21; double yadd = x * _m12; x *= _m11; x += xadd; y *= _m22; y += yadd; break; } } /// <summary> /// MultiplyPoint /// </summary> internal void MultiplyPoint(ref double x, ref double y) { switch (_type) { case MatrixTypes.TRANSFORM_IS_IDENTITY: return; case MatrixTypes.TRANSFORM_IS_TRANSLATION: x += _offsetX; y += _offsetY; return; case MatrixTypes.TRANSFORM_IS_SCALING: x *= _m11; y *= _m22; return; case MatrixTypes.TRANSFORM_IS_SCALING | MatrixTypes.TRANSFORM_IS_TRANSLATION: x *= _m11; x += _offsetX; y *= _m22; y += _offsetY; break; default: double xadd = y * _m21 + _offsetX; double yadd = x * _m12 + _offsetY; x *= _m11; x += xadd; y *= _m22; y += yadd; break; } } /// <summary> /// Creates a rotation transformation about the given point /// </summary> /// <param name='angle'>The angle to rotate specified in radians</param> internal static Matrix CreateRotationRadians(double angle) { return CreateRotationRadians(angle, /* centerX = */ 0, /* centerY = */ 0); } /// <summary> /// Creates a rotation transformation about the given point /// </summary> /// <param name='angle'>The angle to rotate specified in radians</param> /// <param name='centerX'>The centerX of rotation</param> /// <param name='centerY'>The centerY of rotation</param> internal static Matrix CreateRotationRadians(double angle, double centerX, double centerY) { Matrix matrix = new Matrix(); double sin = Math.Sin(angle); double cos = Math.Cos(angle); double dx = (centerX * (1.0 - cos)) + (centerY * sin); double dy = (centerY * (1.0 - cos)) - (centerX * sin); matrix.SetMatrix( cos, sin, -sin, cos, dx, dy, MatrixTypes.TRANSFORM_IS_UNKNOWN); return matrix; } /// <summary> /// Creates a scaling transform around the given point /// </summary> /// <param name='scaleX'>The scale factor in the x dimension</param> /// <param name='scaleY'>The scale factor in the y dimension</param> /// <param name='centerX'>The centerX of scaling</param> /// <param name='centerY'>The centerY of scaling</param> internal static Matrix CreateScaling(double scaleX, double scaleY, double centerX, double centerY) { Matrix matrix = new Matrix(); matrix.SetMatrix(scaleX, 0, 0, scaleY, centerX - scaleX*centerX, centerY - scaleY*centerY, MatrixTypes.TRANSFORM_IS_SCALING | MatrixTypes.TRANSFORM_IS_TRANSLATION); return matrix; } /// <summary> /// Creates a scaling transform around the origin /// </summary> /// <param name='scaleX'>The scale factor in the x dimension</param> /// <param name='scaleY'>The scale factor in the y dimension</param> internal static Matrix CreateScaling(double scaleX, double scaleY) { Matrix matrix = new Matrix(); matrix.SetMatrix(scaleX, 0, 0, scaleY, 0, 0, MatrixTypes.TRANSFORM_IS_SCALING); return matrix; } /// <summary> /// Creates a skew transform /// </summary> /// <param name='skewX'>The skew angle in the x dimension in degrees</param> /// <param name='skewY'>The skew angle in the y dimension in degrees</param> internal static Matrix CreateSkewRadians(double skewX, double skewY) { Matrix matrix = new Matrix(); matrix.SetMatrix(1.0, Math.Tan(skewY), Math.Tan(skewX), 1.0, 0.0, 0.0, MatrixTypes.TRANSFORM_IS_UNKNOWN); return matrix; } /// <summary> /// Sets the transformation to the given translation specified by the offset vector. /// </summary> /// <param name='offsetX'>The offset in X</param> /// <param name='offsetY'>The offset in Y</param> internal static Matrix CreateTranslation(double offsetX, double offsetY) { Matrix matrix = new Matrix(); matrix.SetMatrix(1, 0, 0, 1, offsetX, offsetY, MatrixTypes.TRANSFORM_IS_TRANSLATION); return matrix; } #endregion Internal Methods #region Private Methods /// <summary> /// Sets the transformation to the identity. /// </summary> private static Matrix CreateIdentity() { Matrix matrix = new Matrix(); matrix.SetMatrix(1, 0, 0, 1, 0, 0, MatrixTypes.TRANSFORM_IS_IDENTITY); return matrix; } ///<summary> /// Sets the transform to /// / m11, m12, 0 \ /// | m21, m22, 0 | /// \ offsetX, offsetY, 1 / /// where offsetX, offsetY is the translation. ///</summary> private void SetMatrix(double m11, double m12, double m21, double m22, double offsetX, double offsetY, MatrixTypes type) { this._m11 = m11; this._m12 = m12; this._m21 = m21; this._m22 = m22; this._offsetX = offsetX; this._offsetY = offsetY; this._type = type; } /// <summary> /// Set the type of the matrix based on its current contents /// </summary> private void DeriveMatrixType() { _type = 0; // Now classify our matrix. if (!(_m21 == 0 && _m12 == 0)) { _type = MatrixTypes.TRANSFORM_IS_UNKNOWN; return; } if (!(_m11 == 1 && _m22 == 1)) { _type = MatrixTypes.TRANSFORM_IS_SCALING; } if (!(_offsetX == 0 && _offsetY == 0)) { _type |= MatrixTypes.TRANSFORM_IS_TRANSLATION; } if (0 == (_type & (MatrixTypes.TRANSFORM_IS_TRANSLATION | MatrixTypes.TRANSFORM_IS_SCALING))) { // We have an identity matrix. _type = MatrixTypes.TRANSFORM_IS_IDENTITY; } return; } /// <summary> /// Asserts that the matrix tag is one of the valid options and /// that coefficients are correct. /// </summary> [Conditional("DEBUG")] private void Debug_CheckType() { switch(_type) { case MatrixTypes.TRANSFORM_IS_IDENTITY: return; case MatrixTypes.TRANSFORM_IS_UNKNOWN: return; case MatrixTypes.TRANSFORM_IS_SCALING: Debug.Assert(_m21 == 0); Debug.Assert(_m12 == 0); Debug.Assert(_offsetX == 0); Debug.Assert(_offsetY == 0); return; case MatrixTypes.TRANSFORM_IS_TRANSLATION: Debug.Assert(_m21 == 0); Debug.Assert(_m12 == 0); Debug.Assert(_m11 == 1); Debug.Assert(_m22 == 1); return; case MatrixTypes.TRANSFORM_IS_SCALING|MatrixTypes.TRANSFORM_IS_TRANSLATION: Debug.Assert(_m21 == 0); Debug.Assert(_m12 == 0); return; default: Debug.Assert(false); return; } } #endregion Private Methods #region Private Properties and Fields /// <summary> /// Efficient but conservative test for identity. Returns /// true if the the matrix is identity. If it returns false /// the matrix may still be identity. /// </summary> private bool IsDistinguishedIdentity { get { return _type == MatrixTypes.TRANSFORM_IS_IDENTITY; } } // The hash code for a matrix is the xor of its element's hashes. // Since the identity matrix has 2 1's and 4 0's its hash is 0. private const int c_identityHashCode = 0; #endregion Private Properties and Fields internal double _m11; internal double _m12; internal double _m21; internal double _m22; internal double _offsetX; internal double _offsetY; internal MatrixTypes _type; // This field is only used by unmanaged code which isn't detected by the compiler. #pragma warning disable 0414 // Matrix in blt'd to unmanaged code, so this is padding // to align structure. // // Testing note: Validate that this blt will work on 64-bit // internal Int32 _padding; #pragma warning restore 0414 public string ToString(string? format, IFormatProvider? formatProvider) { return ""; } } }
using System; using System.Collections.Generic; using Newtonsoft.Json; /* * AvaTax API Client Library * * (c) 2004-2019 Avalara, Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @author Genevieve Conty * @author Greg Hester * Swagger name: AvaTaxClient */ namespace Avalara.AvaTax.RestClient { /// <summary> /// Represents a tax rule that changes the behavior of Avalara's tax engine for certain products and/or entity use codes /// in certain jurisdictions. /// /// Avalara supports a few different types of tax rules. For information about tax rule types, see /// [TaxRuleTypeId](https://developer.avalara.com/api-reference/avatax/rest/v2/models/enums/TaxRuleTypeId/) /// /// Because different types of tax rules have different behavior, some fields may change their behavior based on /// the type of tax rule selected. Please read the documentation for each field carefully and ensure that /// the value you send is appropriate for the type of tax rule. /// </summary> public class TaxRuleModel { /// <summary> /// The unique ID number of this tax rule. /// </summary> public Int32 id { get; set; } /// <summary> /// The unique ID number of the company that owns this tax rule. /// </summary> public Int32? companyId { get; set; } /// <summary> /// For rules that apply to a specific tax code only, this specifies which tax code is affected by this rule. /// /// You can choose to specify a tax code either by passing its unique ID number in the `taxCodeId` field or /// by passing its alphanumeric code in the `taxCode` field. To search for the appropriate tax code for your /// custom rule, use the `ListTaxCodes` API. /// /// The `RateOverrideRule`, `BaseRule`, and `ExemptEntityRule` rule types can be applied to all tax codes. To /// make a rule that applies to all tax codes, leave both fields blank. /// /// The `ProductTaxabilityRule` rule must be associated with a tax code. If you attempt to create a product taxability rule /// without a tax code, you will get an error message. /// </summary> public Int32? taxCodeId { get; set; } /// <summary> /// For rules that apply to a specific tax code only, this specifies which tax code is affected by this rule. /// /// You can choose to specify a tax code either by passing its unique ID number in the `taxCodeId` field or /// by passing its alphanumeric code in the `taxCode` field. To search for the appropriate tax code for your /// custom rule, use the `ListTaxCodes` API. /// /// The `RateOverrideRule`, `BaseRule`, and `ExemptEntityRule` rule types can be applied to all tax codes. To /// make a rule that applies to all tax codes, leave both fields blank. /// /// The `ProductTaxabilityRule` rule must be associated with a tax code. If you attempt to create a product taxability rule /// without a tax code, you will get an error message. /// </summary> public String taxCode { get; set; } /// <summary> /// For U.S. tax rules, this is the state's Federal Information Processing Standard (FIPS) code. /// /// This field is required for rules that apply to specific jurisdictions in the United States. It is not required /// if you set the `isAllJuris` flag to true. /// </summary> public String stateFIPS { get; set; } /// <summary> /// The name of the jurisdiction to which this tax rule applies. /// /// Custom tax rules can apply to a specific jurisdiction or to all jurisdictions. To select a jurisdiction, use the /// [ListJurisdictions API](https://developer.avalara.com/api-reference/avatax/rest/v2/methods/Definitions/ListJurisdictions/) /// or the [ListJurisdictionsByAddress API](https://developer.avalara.com/api-reference/avatax/rest/v2/methods/Definitions/ListJurisdictionsByAddress/). /// To set a rule that applies to all jurisdictions of a specific type, see `isAllJuris`. /// /// Once you have determined which jurisdiction you wish to assign to the tax rule, you should fill in the `jurisName`, `jurisCode`, and /// `jurisdictionTypeId` fields using the information you retrieved from the API above. /// </summary> public String jurisName { get; set; } /// <summary> /// The code of the jurisdiction to which this tax rule applies. /// /// Custom tax rules can apply to a specific jurisdiction or to all jurisdictions. To select a jurisdiction, use the /// [ListJurisdictions API](https://developer.avalara.com/api-reference/avatax/rest/v2/methods/Definitions/ListJurisdictions/) /// or the [ListJurisdictionsByAddress API](https://developer.avalara.com/api-reference/avatax/rest/v2/methods/Definitions/ListJurisdictionsByAddress/). /// /// Once you have determined which jurisdiction you wish to assign to the tax rule, you should fill in the `jurisName`, `jurisCode`, and /// `jurisdictionTypeId` fields using the information you retrieved from the API above. /// </summary> public String jurisCode { get; set; } /// <summary> /// DEPRECATED - Date: 12/20/2017, Version: 18.1, Message: Please use `jurisdictionTypeId` instead. /// </summary> public JurisTypeId? jurisTypeId { get; set; } /// <summary> /// The type of the jurisdiction to which this tax rule applies. /// /// Custom tax rules can apply to a specific jurisdiction or to all jurisdictions. To select a jurisdiction, use the /// [ListJurisdictions API](https://developer.avalara.com/api-reference/avatax/rest/v2/methods/Definitions/ListJurisdictions/) /// or the [ListJurisdictionsByAddress API](https://developer.avalara.com/api-reference/avatax/rest/v2/methods/Definitions/ListJurisdictionsByAddress/). /// /// Once you have determined which jurisdiction you wish to assign to the tax rule, you should fill in the `jurisName`, `jurisCode`, and /// `jurisdictionTypeId` fields using the information you retrieved from the API above. /// /// To make a custom tax rule for US or Canada that applies to all jurisdictions of a specific type, see the `isAllJuris` /// field for more information. /// </summary> public JurisdictionType? jurisdictionTypeId { get; set; } /// <summary> /// DEPRECATED - Date: 10/16/2017, Version: 17.11, Message: Please use `entityUseCode` instead. /// </summary> public String customerUsageType { get; set; } /// <summary> /// The entity use code to which this rule applies. /// /// You can create custom `entityUseCode` values with specific behavior using this API, or you can change /// the behavior of Avalara's system-defined entity use codes. /// /// For a full list of Avalara-defined entity use codes, see the [ListEntityUseCodes API](https://developer.avalara.com/api-reference/avatax/rest/v2/methods/Definitions/ListEntityUseCodes/). /// </summary> public String entityUseCode { get; set; } /// <summary> /// DEPRECATED - Date: 09/30/2021, Version: 21.9.0, Message: Please use `taxTypeCode` instead. /// Some tax type groups contain multiple different types of tax. To create a rule that affects only one /// type of tax within a tax type group, set this value to the code matching the specific tax type within /// that group. The custom tax rule will then only apply to taxes calculated for that specific type. /// /// For rules that affect all tax types, use the value `A` to match `All` tax types within that group. /// </summary> public MatchingTaxType? taxTypeId { get; set; } /// <summary> /// Indicates the code of the tax type that applies to this rule. Use /api/v2/definitions/taxtypes endpoint to retrieve the list of tax types applicable for your company. /// </summary> public String taxTypeCode { get; set; } /// <summary> /// TaxRule Product Detail indicates the HSCode(s) to which the tax rule applies. /// </summary> public List<TaxRuleProductDetailModel> taxRuleProductDetail { get; set; } /// <summary> /// DEPRECATED - Date: 8/27/2018, Version: 18.9, Message: Please use `rateTypeCode`, `taxTypeGroup` and `subTaxType` instead. /// </summary> public RateType? rateTypeId { get; set; } /// <summary> /// Indicates the code of the rate type that applies to this rule. Use [ListRateTypesByCountry](https://developer.avalara.com/api-reference/avatax/rest/v2/methods/Definitions/ListRateTypesByCountry/) API for a full list of rate type codes. /// /// If you specify a value in the rateTypeCode field, this rule will cause tax lines that are affected by the rule /// to change to a different rate type code. /// </summary> public String rateTypeCode { get; set; } /// <summary> /// This type value determines the behavior of the tax rule. /// /// You can specify that this rule controls the product's taxability or exempt / nontaxable status, the product's rate /// (for example, if you have been granted an official ruling for your product's rate that differs from the official rate), /// or other types of behavior. /// </summary> public TaxRuleTypeId taxRuleTypeId { get; set; } /// <summary> /// Allows you to make tax rules apply to lower jurisdictions. This feature is only available in the United States and Canada. /// /// * In the United States, this value can be used for rules written at the `State` jurisdictional level. If set to `true`, this rule will at the state level, county level, city level, and special jurisdiction level. /// * In Canada, this value can be used for rules written at the `Country` or `State` jurisdictional levels. If set to `true`, this rule will at all lower jurisdictional levels. /// /// For any other use case, this value must be `false`. /// </summary> public Boolean? isAllJuris { get; set; } /// <summary> /// This field has different behavior based on the type of the tax rule. /// /// * For a product taxability rule, this value is either 1 or 0, indicating taxable or non-taxable. /// * For a rate override rule, this value is the corrected rate stored as a decimal, for example, a rate of 5% would be stored as 0.05 decimal. If you use the special value of 1.0, only the cap and threshold values will be applied and the rate will be left alone. /// </summary> public Decimal? value { get; set; } /// <summary> /// The maximum cap for the price of this item according to this rule. Any amount above this cap will not be subject to this rule. /// /// For example, if you must pay 5% of a product's value up to a maximum value of $1000, you would set the `cap` to `1000.00` and the `value` to `0.05`. /// </summary> public Decimal? cap { get; set; } /// <summary> /// The per-unit threshold that must be met before this rule applies. /// /// For example, if your product is nontaxable unless it is above $100 per product, you would set the `threshold` value to `100`. In this case, the rate /// for the rule would apply to the entire amount above $100. /// /// You can also create rules that make the entire product taxable if it exceeds a threshold, but is nontaxable /// if it is below the threshold. To choose this, set the `options` field to the value `TaxAll`. /// </summary> public Decimal? threshold { get; set; } /// <summary> /// Supports custom options for your tax rule. /// /// Supported options include: /// * `TaxAll` - This value indicates that the entire amount of the line becomes taxable when the line amount exceeds the `threshold`. /// </summary> public String options { get; set; } /// <summary> /// The first date at which this rule applies. If `null`, this rule will apply to all dates prior to the end date. /// </summary> public DateTime? effectiveDate { get; set; } /// <summary> /// The last date for which this rule applies. If `null`, this rule will apply to all dates after the effective date. /// </summary> public DateTime? endDate { get; set; } /// <summary> /// A friendly name for this tax rule. /// </summary> public String description { get; set; } /// <summary> /// For U.S. tax rules, this is the county's Federal Information Processing Standard (FIPS) code. /// /// This field is required for rules that apply to specific jurisdictions in the United States. It is not required /// if you set the `isAllJuris` flag to true. /// </summary> public String countyFIPS { get; set; } /// <summary> /// DEPRECATED - Date: 8/27/2018, Version: 18.9, Message: This field is no longer required. /// </summary> public Boolean? isSTPro { get; set; } /// <summary> /// Name or ISO 3166 code identifying the country where this rule will apply. /// /// This field supports many different country identifiers: /// * Two character ISO 3166 codes /// * Three character ISO 3166 codes /// * Fully spelled out names of the country in ISO supported languages /// * Common alternative spellings for many countries /// /// For a full list of all supported codes and names, please see the Definitions API `ListCountries`. /// </summary> public String country { get; set; } /// <summary> /// Name or ISO 3166 code identifying the region where this rule will apply. /// /// This field supports many different region identifiers: /// * Two and three character ISO 3166 region codes /// * Fully spelled out names of the region in ISO supported languages /// * Common alternative spellings for many regions /// /// For a full list of all supported codes and names, please see the Definitions API `ListRegions`. /// NOTE: Region is required for US and not required for non-US countries because the user may be either creating a Country-level or Region-level rule. /// </summary> public String region { get; set; } /// <summary> /// The sourcing types to which this rule applies. /// </summary> public Sourcing? sourcing { get; set; } /// <summary> /// This field has different behavior based on the type of rule. /// /// * For a product taxability rule, if the rule applies to an item, this value will override the tax type group of the original product. /// * For other rules, this value determines what tax type groups will be affected by the rule. /// /// Refer to `ListTaxTypeGroups` for a list of tax type groups supported by AvaTax. /// </summary> public String taxTypeGroup { get; set; } /// <summary> /// This field has different behavior based on the type of rule. /// /// * For a product taxability rule, if the rule applies to an item, this value will override the tax sub type of the original product. /// * For other rules, this value determines what tax sub types will be affected by the rule. /// /// Refer to `ListTaxSubtypes` for a list of tax sub types supported by AvaTax. /// </summary> public String taxSubType { get; set; } /// <summary> /// Reserved for Avalara internal usage. Leave this field null. /// </summary> public String nonPassthroughExpression { get; set; } /// <summary> /// The currency code to use for this rule. /// /// For a list of currencies supported by AvaTax, use the [ListCurrencies API](https://developer.avalara.com/api-reference/avatax/rest/v2/methods/Definitions/ListCurrencies/). /// </summary> public String currencyCode { get; set; } /// <summary> /// Reserved for Avalara internal usage. Leave this field null. /// </summary> public Int32? preferredProgramId { get; set; } /// <summary> /// For tax rules that are calculated using units of measurement, this indicates the unit of measurement type /// used to calculate the amounts for this rule. /// /// For a list of units of measurement, use the [ListUnitsOfMeasurement API](https://developer.avalara.com/api-reference/avatax/rest/v2/methods/Definitions/ListUnitOfMeasurement/). /// </summary> public Int32? uomId { get; set; } /// <summary> /// The date when this record was created. /// </summary> public DateTime? createdDate { get; set; } /// <summary> /// The User ID of the user who created this record. /// </summary> public Int32? createdUserId { get; set; } /// <summary> /// The date/time when this record was last modified. /// </summary> public DateTime? modifiedDate { get; set; } /// <summary> /// The user ID of the user who last modified this record. /// </summary> public Int32? modifiedUserId { get; set; } /// <summary> /// The UnitOfBasis for the TaxRule /// </summary> public String unitOfBasis { get; set; } /// <summary> /// Convert this object to a JSON string of itself /// </summary> /// <returns>A JSON string of this object</returns> public override string ToString() { return JsonConvert.SerializeObject(this, new JsonSerializerSettings() { Formatting = Formatting.Indented }); } } }
using System; using NBitcoin.BouncyCastle.Crypto.Utilities; using NBitcoin.BouncyCastle.Utilities; namespace NBitcoin.BouncyCastle.Crypto.Digests { /** * Base class for SHA-384 and SHA-512. */ internal abstract class LongDigest : IDigest, IMemoable { private int MyByteLength = 128; private byte[] xBuf; private int xBufOff; private long byteCount1; private long byteCount2; internal ulong H1, H2, H3, H4, H5, H6, H7, H8; private ulong[] W = new ulong[80]; private int wOff; /** * Constructor for variable length word */ internal LongDigest() { this.xBuf = new byte[8]; Reset(); } /** * Copy constructor. We are using copy constructors in place * of the object.Clone() interface as this interface is not * supported by J2ME. */ internal LongDigest( LongDigest t) { this.xBuf = new byte[t.xBuf.Length]; CopyIn(t); } protected void CopyIn(LongDigest t) { Array.Copy(t.xBuf, 0, this.xBuf, 0, t.xBuf.Length); this.xBufOff = t.xBufOff; this.byteCount1 = t.byteCount1; this.byteCount2 = t.byteCount2; this.H1 = t.H1; this.H2 = t.H2; this.H3 = t.H3; this.H4 = t.H4; this.H5 = t.H5; this.H6 = t.H6; this.H7 = t.H7; this.H8 = t.H8; Array.Copy(t.W, 0, this.W, 0, t.W.Length); this.wOff = t.wOff; } public void Update( byte input) { this.xBuf[this.xBufOff++] = input; if(this.xBufOff == this.xBuf.Length) { ProcessWord(this.xBuf, 0); this.xBufOff = 0; } this.byteCount1++; } public void BlockUpdate( byte[] input, int inOff, int length) { // // fill the current word // while((this.xBufOff != 0) && (length > 0)) { Update(input[inOff]); inOff++; length--; } // // process whole words. // while(length > this.xBuf.Length) { ProcessWord(input, inOff); inOff += this.xBuf.Length; length -= this.xBuf.Length; this.byteCount1 += this.xBuf.Length; } // // load in the remainder. // while(length > 0) { Update(input[inOff]); inOff++; length--; } } public void Finish() { AdjustByteCounts(); long lowBitLength = this.byteCount1 << 3; long hiBitLength = this.byteCount2; // // add the pad bytes. // Update((byte)128); while(this.xBufOff != 0) { Update((byte)0); } ProcessLength(lowBitLength, hiBitLength); ProcessBlock(); } public virtual void Reset() { this.byteCount1 = 0; this.byteCount2 = 0; this.xBufOff = 0; for(int i = 0; i < this.xBuf.Length; i++) { this.xBuf[i] = 0; } this.wOff = 0; Array.Clear(this.W, 0, this.W.Length); } internal void ProcessWord( byte[] input, int inOff) { this.W[this.wOff] = Pack.BE_To_UInt64(input, inOff); if(++this.wOff == 16) { ProcessBlock(); } } /** * adjust the byte counts so that byteCount2 represents the * upper long (less 3 bits) word of the byte count. */ private void AdjustByteCounts() { if(this.byteCount1 > 0x1fffffffffffffffL) { this.byteCount2 += (long)((ulong) this.byteCount1 >> 61); this.byteCount1 &= 0x1fffffffffffffffL; } } internal void ProcessLength( long lowW, long hiW) { if(this.wOff > 14) { ProcessBlock(); } this.W[14] = (ulong)hiW; this.W[15] = (ulong)lowW; } internal void ProcessBlock() { AdjustByteCounts(); // // expand 16 word block into 80 word blocks. // for(int ti = 16; ti <= 79; ++ti) { this.W[ti] = Sigma1(this.W[ti - 2]) + this.W[ti - 7] + Sigma0(this.W[ti - 15]) + this.W[ti - 16]; } // // set up working variables. // ulong a = this.H1; ulong b = this.H2; ulong c = this.H3; ulong d = this.H4; ulong e = this.H5; ulong f = this.H6; ulong g = this.H7; ulong h = this.H8; int t = 0; for(int i = 0; i < 10; i++) { // t = 8 * i h += Sum1(e) + Ch(e, f, g) + K[t] + this.W[t++]; d += h; h += Sum0(a) + Maj(a, b, c); // t = 8 * i + 1 g += Sum1(d) + Ch(d, e, f) + K[t] + this.W[t++]; c += g; g += Sum0(h) + Maj(h, a, b); // t = 8 * i + 2 f += Sum1(c) + Ch(c, d, e) + K[t] + this.W[t++]; b += f; f += Sum0(g) + Maj(g, h, a); // t = 8 * i + 3 e += Sum1(b) + Ch(b, c, d) + K[t] + this.W[t++]; a += e; e += Sum0(f) + Maj(f, g, h); // t = 8 * i + 4 d += Sum1(a) + Ch(a, b, c) + K[t] + this.W[t++]; h += d; d += Sum0(e) + Maj(e, f, g); // t = 8 * i + 5 c += Sum1(h) + Ch(h, a, b) + K[t] + this.W[t++]; g += c; c += Sum0(d) + Maj(d, e, f); // t = 8 * i + 6 b += Sum1(g) + Ch(g, h, a) + K[t] + this.W[t++]; f += b; b += Sum0(c) + Maj(c, d, e); // t = 8 * i + 7 a += Sum1(f) + Ch(f, g, h) + K[t] + this.W[t++]; e += a; a += Sum0(b) + Maj(b, c, d); } this.H1 += a; this.H2 += b; this.H3 += c; this.H4 += d; this.H5 += e; this.H6 += f; this.H7 += g; this.H8 += h; // // reset the offset and clean out the word buffer. // this.wOff = 0; Array.Clear(this.W, 0, 16); } /* SHA-384 and SHA-512 functions (as for SHA-256 but for longs) */ private static ulong Ch(ulong x, ulong y, ulong z) { return (x & y) ^ (~x & z); } private static ulong Maj(ulong x, ulong y, ulong z) { return (x & y) ^ (x & z) ^ (y & z); } private static ulong Sum0(ulong x) { return ((x << 36) | (x >> 28)) ^ ((x << 30) | (x >> 34)) ^ ((x << 25) | (x >> 39)); } private static ulong Sum1(ulong x) { return ((x << 50) | (x >> 14)) ^ ((x << 46) | (x >> 18)) ^ ((x << 23) | (x >> 41)); } private static ulong Sigma0(ulong x) { return ((x << 63) | (x >> 1)) ^ ((x << 56) | (x >> 8)) ^ (x >> 7); } private static ulong Sigma1(ulong x) { return ((x << 45) | (x >> 19)) ^ ((x << 3) | (x >> 61)) ^ (x >> 6); } /* SHA-384 and SHA-512 Constants * (represent the first 64 bits of the fractional parts of the * cube roots of the first sixty-four prime numbers) */ internal static readonly ulong[] K = { 0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc, 0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118, 0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2, 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694, 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65, 0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5, 0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4, 0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70, 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df, 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b, 0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30, 0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8, 0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8, 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3, 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec, 0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b, 0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, 0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b, 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c, 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817 }; public int GetByteLength() { return this.MyByteLength; } public abstract string AlgorithmName { get; } public abstract int GetDigestSize(); public abstract int DoFinal(byte[] output, int outOff); public abstract IMemoable Copy(); public abstract void Reset(IMemoable t); } }
// 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.Text; using System.Runtime.InteropServices; using System.ComponentModel; using System.Diagnostics; using System; using System.Collections.Generic; using System.Threading; using System.Globalization; using System.Security; namespace System.ServiceProcess { /// This class represents an NT service. It allows you to connect to a running or stopped service /// and manipulate it or get information about it. public class ServiceController : IDisposable { private readonly string _machineName; private readonly ManualResetEvent _waitForStatusSignal = new ManualResetEvent(false); private const string DefaultMachineName = "."; private string _name; private string _eitherName; private string _displayName; private int _commandsAccepted; private bool _statusGenerated; private bool _startTypeInitialized; private int _type; private bool _disposed; private SafeServiceHandle _serviceManagerHandle; private ServiceControllerStatus _status; private ServiceController[] _dependentServices; private ServiceController[] _servicesDependedOn; private ServiceStartMode _startType; private const int SERVICENAMEMAXLENGTH = 80; private const int DISPLAYNAMEBUFFERSIZE = 256; /// Creates a ServiceController object, based on service name. public ServiceController(string name) : this(name, DefaultMachineName) { } /// Creates a ServiceController object, based on machine and service name. public ServiceController(string name, string machineName) { if (!CheckMachineName(machineName)) throw new ArgumentException(SR.Format(SR.BadMachineName, machineName)); if (string.IsNullOrEmpty(name)) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(name), name)); _machineName = machineName; _eitherName = name; _type = Interop.Advapi32.ServiceTypeOptions.SERVICE_TYPE_ALL; } /// Used by the GetServices and GetDevices methods. Avoids duplicating work by the static /// methods and our own GenerateInfo(). private ServiceController(string machineName, Interop.Advapi32.ENUM_SERVICE_STATUS status) { if (!CheckMachineName(machineName)) throw new ArgumentException(SR.Format(SR.BadMachineName, machineName)); _machineName = machineName; _name = status.serviceName; _displayName = status.displayName; _commandsAccepted = status.controlsAccepted; _status = (ServiceControllerStatus)status.currentState; _type = status.serviceType; _statusGenerated = true; } /// Used by the GetServicesInGroup method. private ServiceController(string machineName, Interop.Advapi32.ENUM_SERVICE_STATUS_PROCESS status) { if (!CheckMachineName(machineName)) throw new ArgumentException(SR.Format(SR.BadMachineName, machineName)); _machineName = machineName; _name = status.serviceName; _displayName = status.displayName; _commandsAccepted = status.controlsAccepted; _status = (ServiceControllerStatus)status.currentState; _type = status.serviceType; _statusGenerated = true; } /// Tells if the service referenced by this object can be paused. public bool CanPauseAndContinue { get { GenerateStatus(); return (_commandsAccepted & Interop.Advapi32.AcceptOptions.ACCEPT_PAUSE_CONTINUE) != 0; } } /// Tells if the service is notified when system shutdown occurs. public bool CanShutdown { get { GenerateStatus(); return (_commandsAccepted & Interop.Advapi32.AcceptOptions.ACCEPT_SHUTDOWN) != 0; } } /// Tells if the service referenced by this object can be stopped. public bool CanStop { get { GenerateStatus(); return (_commandsAccepted & Interop.Advapi32.AcceptOptions.ACCEPT_STOP) != 0; } } /// The descriptive name shown for this service in the Service applet. public string DisplayName { get { if (_displayName == null) GenerateNames(); return _displayName; } } /// The set of services that depend on this service. These are the services that will be stopped if /// this service is stopped. public ServiceController[] DependentServices { get { if (_dependentServices == null) { IntPtr serviceHandle = GetServiceHandle(Interop.Advapi32.ServiceOptions.SERVICE_ENUMERATE_DEPENDENTS); try { // figure out how big a buffer we need to get the info int bytesNeeded = 0; int numEnumerated = 0; bool result = Interop.Advapi32.EnumDependentServices(serviceHandle, Interop.Advapi32.ServiceState.SERVICE_STATE_ALL, IntPtr.Zero, 0, ref bytesNeeded, ref numEnumerated); if (result) { _dependentServices = Array.Empty<ServiceController>(); return _dependentServices; } int lastError = Marshal.GetLastWin32Error(); if (lastError != Interop.Errors.ERROR_MORE_DATA) throw new Win32Exception(lastError); // allocate the buffer IntPtr enumBuffer = Marshal.AllocHGlobal((IntPtr)bytesNeeded); try { // get all the info result = Interop.Advapi32.EnumDependentServices(serviceHandle, Interop.Advapi32.ServiceState.SERVICE_STATE_ALL, enumBuffer, bytesNeeded, ref bytesNeeded, ref numEnumerated); if (!result) throw new Win32Exception(); // for each of the entries in the buffer, create a new ServiceController object. _dependentServices = new ServiceController[numEnumerated]; for (int i = 0; i < numEnumerated; i++) { Interop.Advapi32.ENUM_SERVICE_STATUS status = new Interop.Advapi32.ENUM_SERVICE_STATUS(); IntPtr structPtr = (IntPtr)((long)enumBuffer + (i * Marshal.SizeOf<Interop.Advapi32.ENUM_SERVICE_STATUS>())); Marshal.PtrToStructure(structPtr, status); _dependentServices[i] = new ServiceController(_machineName, status); } } finally { Marshal.FreeHGlobal(enumBuffer); } } finally { Interop.Advapi32.CloseServiceHandle(serviceHandle); } } return _dependentServices; } } /// The name of the machine on which this service resides. public string MachineName { get { return _machineName; } } /// Returns the short name of the service referenced by this object. public string ServiceName { get { if (_name == null) GenerateNames(); return _name; } } public unsafe ServiceController[] ServicesDependedOn { get { if (_servicesDependedOn != null) return _servicesDependedOn; IntPtr serviceHandle = GetServiceHandle(Interop.Advapi32.ServiceOptions.SERVICE_QUERY_CONFIG); try { int bytesNeeded = 0; bool success = Interop.Advapi32.QueryServiceConfig(serviceHandle, IntPtr.Zero, 0, out bytesNeeded); if (success) { _servicesDependedOn = Array.Empty<ServiceController>(); return _servicesDependedOn; } int lastError = Marshal.GetLastWin32Error(); if (lastError != Interop.Errors.ERROR_INSUFFICIENT_BUFFER) throw new Win32Exception(lastError); // get the info IntPtr bufPtr = Marshal.AllocHGlobal((IntPtr)bytesNeeded); try { success = Interop.Advapi32.QueryServiceConfig(serviceHandle, bufPtr, bytesNeeded, out bytesNeeded); if (!success) throw new Win32Exception(Marshal.GetLastWin32Error()); Interop.Advapi32.QUERY_SERVICE_CONFIG config = new Interop.Advapi32.QUERY_SERVICE_CONFIG(); Marshal.PtrToStructure(bufPtr, config); Dictionary<string, ServiceController> dependencyHash = null; char* dependencyChar = config.lpDependencies; if (dependencyChar != null) { // lpDependencies points to the start of multiple null-terminated strings. The list is // double-null terminated. int length = 0; dependencyHash = new Dictionary<string, ServiceController>(); while (*(dependencyChar + length) != '\0') { length++; if (*(dependencyChar + length) == '\0') { string dependencyNameStr = new string(dependencyChar, 0, length); dependencyChar = dependencyChar + length + 1; length = 0; if (dependencyNameStr.StartsWith("+", StringComparison.Ordinal)) { // this entry is actually a service load group Interop.Advapi32.ENUM_SERVICE_STATUS_PROCESS[] loadGroup = GetServicesInGroup(_machineName, dependencyNameStr.Substring(1)); foreach (Interop.Advapi32.ENUM_SERVICE_STATUS_PROCESS groupMember in loadGroup) { if (!dependencyHash.ContainsKey(groupMember.serviceName)) dependencyHash.Add(groupMember.serviceName, new ServiceController(MachineName, groupMember)); } } else { if (!dependencyHash.ContainsKey(dependencyNameStr)) dependencyHash.Add(dependencyNameStr, new ServiceController(dependencyNameStr, MachineName)); } } } } if (dependencyHash != null) { _servicesDependedOn = new ServiceController[dependencyHash.Count]; dependencyHash.Values.CopyTo(_servicesDependedOn, 0); } else { _servicesDependedOn = Array.Empty<ServiceController>(); } return _servicesDependedOn; } finally { Marshal.FreeHGlobal(bufPtr); } } finally { Interop.Advapi32.CloseServiceHandle(serviceHandle); } } } public ServiceStartMode StartType { get { if (_startTypeInitialized) return _startType; IntPtr serviceHandle = IntPtr.Zero; try { serviceHandle = GetServiceHandle(Interop.Advapi32.ServiceOptions.SERVICE_QUERY_CONFIG); int bytesNeeded = 0; bool success = Interop.Advapi32.QueryServiceConfig(serviceHandle, IntPtr.Zero, 0, out bytesNeeded); int lastError = Marshal.GetLastWin32Error(); if (lastError != Interop.Errors.ERROR_INSUFFICIENT_BUFFER) throw new Win32Exception(lastError); // get the info IntPtr bufPtr = IntPtr.Zero; try { bufPtr = Marshal.AllocHGlobal((IntPtr)bytesNeeded); success = Interop.Advapi32.QueryServiceConfig(serviceHandle, bufPtr, bytesNeeded, out bytesNeeded); if (!success) throw new Win32Exception(Marshal.GetLastWin32Error()); Interop.Advapi32.QUERY_SERVICE_CONFIG config = new Interop.Advapi32.QUERY_SERVICE_CONFIG(); Marshal.PtrToStructure(bufPtr, config); _startType = (ServiceStartMode)config.dwStartType; _startTypeInitialized = true; } finally { if (bufPtr != IntPtr.Zero) Marshal.FreeHGlobal(bufPtr); } } finally { if (serviceHandle != IntPtr.Zero) Interop.Advapi32.CloseServiceHandle(serviceHandle); } return _startType; } } public SafeHandle ServiceHandle { get { return new SafeServiceHandle(GetServiceHandle(Interop.Advapi32.ServiceOptions.SERVICE_ALL_ACCESS)); } } /// Gets the status of the service referenced by this object, e.g., Running, Stopped, etc. public ServiceControllerStatus Status { get { GenerateStatus(); return _status; } } /// Gets the type of service that this object references. public ServiceType ServiceType { get { GenerateStatus(); return (ServiceType)_type; } } private static bool CheckMachineName(string value) { return !string.IsNullOrWhiteSpace(value) && value.IndexOf('\\') == -1; } private void Close() { } public void Dispose() { Dispose(true); } /// Disconnects this object from the service and frees any allocated resources. protected virtual void Dispose(bool disposing) { if (_serviceManagerHandle != null) { _serviceManagerHandle.Dispose(); _serviceManagerHandle = null; } _statusGenerated = false; _startTypeInitialized = false; _type = Interop.Advapi32.ServiceTypeOptions.SERVICE_TYPE_ALL; _disposed = true; } private unsafe void GenerateStatus() { if (!_statusGenerated) { IntPtr serviceHandle = GetServiceHandle(Interop.Advapi32.ServiceOptions.SERVICE_QUERY_STATUS); try { Interop.Advapi32.SERVICE_STATUS svcStatus = new Interop.Advapi32.SERVICE_STATUS(); bool success = Interop.Advapi32.QueryServiceStatus(serviceHandle, &svcStatus); if (!success) throw new Win32Exception(Marshal.GetLastWin32Error()); _commandsAccepted = svcStatus.controlsAccepted; _status = (ServiceControllerStatus)svcStatus.currentState; _type = svcStatus.serviceType; _statusGenerated = true; } finally { Interop.Advapi32.CloseServiceHandle(serviceHandle); } } } private unsafe void GenerateNames() { if (_machineName.Length == 0) throw new ArgumentException(SR.NoMachineName); IntPtr databaseHandle = IntPtr.Zero; IntPtr memory = IntPtr.Zero; int bytesNeeded; int servicesReturned; int resumeHandle = 0; try { databaseHandle = GetDataBaseHandleWithEnumerateAccess(_machineName); Interop.Advapi32.EnumServicesStatusEx( databaseHandle, Interop.Advapi32.ServiceControllerOptions.SC_ENUM_PROCESS_INFO, Interop.Advapi32.ServiceTypeOptions.SERVICE_TYPE_WIN32 | Interop.Advapi32.ServiceTypeOptions.SERVICE_TYPE_DRIVER, Interop.Advapi32.StatusOptions.STATUS_ALL, IntPtr.Zero, 0, out bytesNeeded, out servicesReturned, ref resumeHandle, null); memory = Marshal.AllocHGlobal(bytesNeeded); Interop.Advapi32.EnumServicesStatusEx( databaseHandle, Interop.Advapi32.ServiceControllerOptions.SC_ENUM_PROCESS_INFO, Interop.Advapi32.ServiceTypeOptions.SERVICE_TYPE_WIN32 | Interop.Advapi32.ServiceTypeOptions.SERVICE_TYPE_DRIVER, Interop.Advapi32.StatusOptions.STATUS_ALL, memory, bytesNeeded, out bytesNeeded, out servicesReturned, ref resumeHandle, null); // Since the service name of one service cannot be equal to the // service or display name of another service, we can safely // loop through all services checking if either the service or // display name matches the user given name. If there is a // match, then we've found the service. for (int i = 0; i < servicesReturned; i++) { IntPtr structPtr = (IntPtr)((long)memory + (i * Marshal.SizeOf<Interop.Advapi32.ENUM_SERVICE_STATUS_PROCESS>())); Interop.Advapi32.ENUM_SERVICE_STATUS_PROCESS status = new Interop.Advapi32.ENUM_SERVICE_STATUS_PROCESS(); Marshal.PtrToStructure(structPtr, status); if (string.Equals(_eitherName, status.serviceName, StringComparison.OrdinalIgnoreCase) || string.Equals(_eitherName, status.displayName, StringComparison.OrdinalIgnoreCase)) { if (_name == null) { _name = status.serviceName; } if (_displayName == null) { _displayName = status.displayName; } _eitherName = string.Empty; return; } } throw new InvalidOperationException(SR.Format(SR.NoService, _eitherName, _machineName)); } finally { Marshal.FreeHGlobal(memory); if (databaseHandle != IntPtr.Zero) { Interop.Advapi32.CloseServiceHandle(databaseHandle); } } } private static IntPtr GetDataBaseHandleWithAccess(string machineName, int serviceControlManagerAccess) { IntPtr databaseHandle = IntPtr.Zero; if (machineName.Equals(DefaultMachineName) || machineName.Length == 0) { databaseHandle = Interop.Advapi32.OpenSCManager(null, null, serviceControlManagerAccess); } else { databaseHandle = Interop.Advapi32.OpenSCManager(machineName, null, serviceControlManagerAccess); } if (databaseHandle == IntPtr.Zero) { Exception inner = new Win32Exception(Marshal.GetLastWin32Error()); throw new InvalidOperationException(SR.Format(SR.OpenSC, machineName), inner); } return databaseHandle; } private void GetDataBaseHandleWithConnectAccess() { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } // get a handle to SCM with connect access and store it in serviceManagerHandle field. if (_serviceManagerHandle == null) { _serviceManagerHandle = new SafeServiceHandle(GetDataBaseHandleWithAccess(_machineName, Interop.Advapi32.ServiceControllerOptions.SC_MANAGER_CONNECT)); } } private static IntPtr GetDataBaseHandleWithEnumerateAccess(string machineName) { return GetDataBaseHandleWithAccess(machineName, Interop.Advapi32.ServiceControllerOptions.SC_MANAGER_ENUMERATE_SERVICE); } /// Gets all the device-driver services on the local machine. public static ServiceController[] GetDevices() { return GetDevices(DefaultMachineName); } /// Gets all the device-driver services in the machine specified. public static ServiceController[] GetDevices(string machineName) { return GetServicesOfType(machineName, Interop.Advapi32.ServiceTypeOptions.SERVICE_TYPE_DRIVER); } /// Opens a handle for the current service. The handle must be closed with /// a call to Interop.CloseServiceHandle(). private IntPtr GetServiceHandle(int desiredAccess) { GetDataBaseHandleWithConnectAccess(); IntPtr serviceHandle = Interop.Advapi32.OpenService(_serviceManagerHandle.DangerousGetHandle(), ServiceName, desiredAccess); if (serviceHandle == IntPtr.Zero) { Exception inner = new Win32Exception(Marshal.GetLastWin32Error()); throw new InvalidOperationException(SR.Format(SR.OpenService, ServiceName, _machineName), inner); } return serviceHandle; } /// Gets the services (not including device-driver services) on the local machine. public static ServiceController[] GetServices() { return GetServices(DefaultMachineName); } /// Gets the services (not including device-driver services) on the machine specified. public static ServiceController[] GetServices(string machineName) { return GetServicesOfType(machineName, Interop.Advapi32.ServiceTypeOptions.SERVICE_TYPE_WIN32); } /// Helper function for ServicesDependedOn. private static Interop.Advapi32.ENUM_SERVICE_STATUS_PROCESS[] GetServicesInGroup(string machineName, string group) { return GetServices<Interop.Advapi32.ENUM_SERVICE_STATUS_PROCESS>(machineName, Interop.Advapi32.ServiceTypeOptions.SERVICE_TYPE_WIN32, group, status => { return status; }); } /// Helper function for GetDevices and GetServices. private static ServiceController[] GetServicesOfType(string machineName, int serviceType) { if (!CheckMachineName(machineName)) throw new ArgumentException(SR.Format(SR.BadMachineName, machineName)); return GetServices<ServiceController>(machineName, serviceType, null, status => { return new ServiceController(machineName, status); }); } /// Helper for GetDevices, GetServices, and ServicesDependedOn private static T[] GetServices<T>(string machineName, int serviceType, string group, Func<Interop.Advapi32.ENUM_SERVICE_STATUS_PROCESS, T> selector) { IntPtr databaseHandle = IntPtr.Zero; IntPtr memory = IntPtr.Zero; int bytesNeeded; int servicesReturned; int resumeHandle = 0; T[] services; try { databaseHandle = GetDataBaseHandleWithEnumerateAccess(machineName); Interop.Advapi32.EnumServicesStatusEx( databaseHandle, Interop.Advapi32.ServiceControllerOptions.SC_ENUM_PROCESS_INFO, serviceType, Interop.Advapi32.StatusOptions.STATUS_ALL, IntPtr.Zero, 0, out bytesNeeded, out servicesReturned, ref resumeHandle, group); memory = Marshal.AllocHGlobal((IntPtr)bytesNeeded); // // Get the set of services // Interop.Advapi32.EnumServicesStatusEx( databaseHandle, Interop.Advapi32.ServiceControllerOptions.SC_ENUM_PROCESS_INFO, serviceType, Interop.Advapi32.StatusOptions.STATUS_ALL, memory, bytesNeeded, out bytesNeeded, out servicesReturned, ref resumeHandle, group); // // Go through the block of memory it returned to us and select the results // services = new T[servicesReturned]; for (int i = 0; i < servicesReturned; i++) { IntPtr structPtr = (IntPtr)((long)memory + (i * Marshal.SizeOf<Interop.Advapi32.ENUM_SERVICE_STATUS_PROCESS>())); Interop.Advapi32.ENUM_SERVICE_STATUS_PROCESS status = new Interop.Advapi32.ENUM_SERVICE_STATUS_PROCESS(); Marshal.PtrToStructure(structPtr, status); services[i] = selector(status); } } finally { Marshal.FreeHGlobal(memory); if (databaseHandle != IntPtr.Zero) { Interop.Advapi32.CloseServiceHandle(databaseHandle); } } return services; } /// Suspends a service's operation. public unsafe void Pause() { IntPtr serviceHandle = GetServiceHandle(Interop.Advapi32.ServiceOptions.SERVICE_PAUSE_CONTINUE); try { Interop.Advapi32.SERVICE_STATUS status = new Interop.Advapi32.SERVICE_STATUS(); bool result = Interop.Advapi32.ControlService(serviceHandle, Interop.Advapi32.ControlOptions.CONTROL_PAUSE, &status); if (!result) { Exception inner = new Win32Exception(Marshal.GetLastWin32Error()); throw new InvalidOperationException(SR.Format(SR.PauseService, ServiceName, _machineName), inner); } } finally { Interop.Advapi32.CloseServiceHandle(serviceHandle); } } /// Continues a service after it has been paused. public unsafe void Continue() { IntPtr serviceHandle = GetServiceHandle(Interop.Advapi32.ServiceOptions.SERVICE_PAUSE_CONTINUE); try { Interop.Advapi32.SERVICE_STATUS status = new Interop.Advapi32.SERVICE_STATUS(); bool result = Interop.Advapi32.ControlService(serviceHandle, Interop.Advapi32.ControlOptions.CONTROL_CONTINUE, &status); if (!result) { Exception inner = new Win32Exception(Marshal.GetLastWin32Error()); throw new InvalidOperationException(SR.Format(SR.ResumeService, ServiceName, _machineName), inner); } } finally { Interop.Advapi32.CloseServiceHandle(serviceHandle); } } /// Refreshes all property values. public void Refresh() { _statusGenerated = false; _startTypeInitialized = false; _dependentServices = null; _servicesDependedOn = null; } /// Starts the service. public void Start() { Start(Array.Empty<string>()); } /// Starts a service in the machine specified. public void Start(string[] args) { if (args == null) throw new ArgumentNullException(nameof(args)); IntPtr serviceHandle = GetServiceHandle(Interop.Advapi32.ServiceOptions.SERVICE_START); try { IntPtr[] argPtrs = new IntPtr[args.Length]; int i = 0; try { for (i = 0; i < args.Length; i++) { if (args[i] == null) throw new ArgumentNullException($"{nameof(args)}[{i}]", SR.ArgsCantBeNull); argPtrs[i] = Marshal.StringToHGlobalUni(args[i]); } } catch { for (int j = 0; j < i; j++) Marshal.FreeHGlobal(argPtrs[i]); throw; } GCHandle argPtrsHandle = new GCHandle(); try { argPtrsHandle = GCHandle.Alloc(argPtrs, GCHandleType.Pinned); bool result = Interop.Advapi32.StartService(serviceHandle, args.Length, (IntPtr)argPtrsHandle.AddrOfPinnedObject()); if (!result) { Exception inner = new Win32Exception(Marshal.GetLastWin32Error()); throw new InvalidOperationException(SR.Format(SR.CannotStart, ServiceName, _machineName), inner); } } finally { for (i = 0; i < args.Length; i++) Marshal.FreeHGlobal(argPtrs[i]); if (argPtrsHandle.IsAllocated) argPtrsHandle.Free(); } } finally { Interop.Advapi32.CloseServiceHandle(serviceHandle); } } /// Stops the service. If any other services depend on this one for operation, /// they will be stopped first. The DependentServices property lists this set /// of services. public unsafe void Stop() { IntPtr serviceHandle = GetServiceHandle(Interop.Advapi32.ServiceOptions.SERVICE_STOP); try { // Before stopping this service, stop all the dependent services that are running. // (It's OK not to cache the result of getting the DependentServices property because it caches on its own.) for (int i = 0; i < DependentServices.Length; i++) { ServiceController currentDependent = DependentServices[i]; currentDependent.Refresh(); if (currentDependent.Status != ServiceControllerStatus.Stopped) { currentDependent.Stop(); currentDependent.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 30)); } } Interop.Advapi32.SERVICE_STATUS status = new Interop.Advapi32.SERVICE_STATUS(); bool result = Interop.Advapi32.ControlService(serviceHandle, Interop.Advapi32.ControlOptions.CONTROL_STOP, &status); if (!result) { Exception inner = new Win32Exception(Marshal.GetLastWin32Error()); throw new InvalidOperationException(SR.Format(SR.StopService, ServiceName, _machineName), inner); } } finally { Interop.Advapi32.CloseServiceHandle(serviceHandle); } } /// Waits infinitely until the service has reached the given status. public void WaitForStatus(ServiceControllerStatus desiredStatus) { WaitForStatus(desiredStatus, TimeSpan.MaxValue); } /// Waits until the service has reached the given status or until the specified time /// has expired public void WaitForStatus(ServiceControllerStatus desiredStatus, TimeSpan timeout) { if (!Enum.IsDefined(typeof(ServiceControllerStatus), desiredStatus)) throw new ArgumentException(SR.Format(SR.InvalidEnumArgument, nameof(desiredStatus), (int)desiredStatus, typeof(ServiceControllerStatus))); DateTime start = DateTime.UtcNow; Refresh(); while (Status != desiredStatus) { if (DateTime.UtcNow - start > timeout) throw new System.ServiceProcess.TimeoutException(SR.Timeout); _waitForStatusSignal.WaitOne(250); Refresh(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Xsl.XsltOld { using System; using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl.Runtime; using MS.Internal.Xml.XPath; using System.Security; internal class Key { private readonly XmlQualifiedName _name; private readonly int _matchKey; private readonly int _useKey; private ArrayList _keyNodes; public Key(XmlQualifiedName name, int matchkey, int usekey) { _name = name; _matchKey = matchkey; _useKey = usekey; _keyNodes = null; } public XmlQualifiedName Name { get { return _name; } } public int MatchKey { get { return _matchKey; } } public int UseKey { get { return _useKey; } } public void AddKey(XPathNavigator root, Hashtable table) { if (_keyNodes == null) { _keyNodes = new ArrayList(); } _keyNodes.Add(new DocumentKeyList(root, table)); } public Hashtable GetKeys(XPathNavigator root) { if (_keyNodes != null) { for (int i = 0; i < _keyNodes.Count; i++) { if (((DocumentKeyList)_keyNodes[i]).RootNav.IsSamePosition(root)) { return ((DocumentKeyList)_keyNodes[i]).KeyTable; } } } return null; } public Key Clone() { return new Key(_name, _matchKey, _useKey); } } internal struct DocumentKeyList { private readonly XPathNavigator _rootNav; private readonly Hashtable _keyTable; public DocumentKeyList(XPathNavigator rootNav, Hashtable keyTable) { _rootNav = rootNav; _keyTable = keyTable; } public XPathNavigator RootNav { get { return _rootNav; } } public Hashtable KeyTable { get { return _keyTable; } } } internal class RootAction : TemplateBaseAction { private const int QueryInitialized = 2; private const int RootProcessed = 3; private readonly Hashtable _attributeSetTable = new Hashtable(); private readonly Hashtable _decimalFormatTable = new Hashtable(); private List<Key> _keyList; private XsltOutput _output; public Stylesheet builtInSheet; internal XsltOutput Output { get { if (_output == null) { _output = new XsltOutput(); } return _output; } } /* * Compile */ internal override void Compile(Compiler compiler) { CompileDocument(compiler, /*inInclude*/ false); } internal void InsertKey(XmlQualifiedName name, int MatchKey, int UseKey) { if (_keyList == null) { _keyList = new List<Key>(); } _keyList.Add(new Key(name, MatchKey, UseKey)); } internal AttributeSetAction GetAttributeSet(XmlQualifiedName name) { AttributeSetAction action = (AttributeSetAction)_attributeSetTable[name]; if (action == null) { throw XsltException.Create(SR.Xslt_NoAttributeSet, name.ToString()); } return action; } public void PorcessAttributeSets(Stylesheet rootStylesheet) { MirgeAttributeSets(rootStylesheet); // As we mentioned we need to invert all lists. foreach (AttributeSetAction attSet in _attributeSetTable.Values) { if (attSet.containedActions != null) { attSet.containedActions.Reverse(); } } // ensures there are no cycles in the attribute-sets use dfs marking method CheckAttributeSets_RecurceInList(new Hashtable(), _attributeSetTable.Keys); } private void MirgeAttributeSets(Stylesheet stylesheet) { // mirge stylesheet.AttributeSetTable to this.AttributeSetTable if (stylesheet.AttributeSetTable != null) { foreach (AttributeSetAction srcAttSet in stylesheet.AttributeSetTable.Values) { ArrayList srcAttList = srcAttSet.containedActions; AttributeSetAction dstAttSet = (AttributeSetAction)_attributeSetTable[srcAttSet.Name]; if (dstAttSet == null) { dstAttSet = new AttributeSetAction(); { dstAttSet.name = srcAttSet.Name; dstAttSet.containedActions = new ArrayList(); } _attributeSetTable[srcAttSet.Name] = dstAttSet; } ArrayList dstAttList = dstAttSet.containedActions; // We adding attributes in reverse order for purpuse. In the mirged list most importent attset shoud go last one // so we'll need to invert dstAttList finaly. if (srcAttList != null) { for (int src = srcAttList.Count - 1; 0 <= src; src--) { // We can ignore duplicate attibutes here. dstAttList.Add(srcAttList[src]); } } } } foreach (Stylesheet importedStylesheet in stylesheet.Imports) { MirgeAttributeSets(importedStylesheet); } } private void CheckAttributeSets_RecurceInList(Hashtable markTable, ICollection setQNames) { const string PROCESSING = "P"; const string DONE = "D"; foreach (XmlQualifiedName qname in setQNames) { object mark = markTable[qname]; if (mark == (object)PROCESSING) { throw XsltException.Create(SR.Xslt_CircularAttributeSet, qname.ToString()); } else if (mark == (object)DONE) { continue; // optimization: we already investigated this attribute-set. } else { Debug.Assert(mark == null); markTable[qname] = (object)PROCESSING; CheckAttributeSets_RecurceInContainer(markTable, GetAttributeSet(qname)); markTable[qname] = (object)DONE; } } } private void CheckAttributeSets_RecurceInContainer(Hashtable markTable, ContainerAction container) { if (container.containedActions == null) { return; } foreach (Action action in container.containedActions) { if (action is UseAttributeSetsAction) { CheckAttributeSets_RecurceInList(markTable, ((UseAttributeSetsAction)action).UsedSets); } else if (action is ContainerAction) { CheckAttributeSets_RecurceInContainer(markTable, (ContainerAction)action); } } } internal void AddDecimalFormat(XmlQualifiedName name, DecimalFormat formatinfo) { DecimalFormat exist = (DecimalFormat)_decimalFormatTable[name]; if (exist != null) { NumberFormatInfo info = exist.info; NumberFormatInfo newinfo = formatinfo.info; if (info.NumberDecimalSeparator != newinfo.NumberDecimalSeparator || info.NumberGroupSeparator != newinfo.NumberGroupSeparator || info.PositiveInfinitySymbol != newinfo.PositiveInfinitySymbol || info.NegativeSign != newinfo.NegativeSign || info.NaNSymbol != newinfo.NaNSymbol || info.PercentSymbol != newinfo.PercentSymbol || info.PerMilleSymbol != newinfo.PerMilleSymbol || exist.zeroDigit != formatinfo.zeroDigit || exist.digit != formatinfo.digit || exist.patternSeparator != formatinfo.patternSeparator ) { throw XsltException.Create(SR.Xslt_DupDecimalFormat, name.ToString()); } } _decimalFormatTable[name] = formatinfo; } internal DecimalFormat GetDecimalFormat(XmlQualifiedName name) { return _decimalFormatTable[name] as DecimalFormat; } internal List<Key> KeyList { get { return _keyList; } } internal override void Execute(Processor processor, ActionFrame frame) { Debug.Assert(processor != null && frame != null); switch (frame.State) { case Initialized: frame.AllocateVariables(variableCount); XPathNavigator root = processor.Document.Clone(); root.MoveToRoot(); frame.InitNodeSet(new XPathSingletonIterator(root)); if (this.containedActions != null && this.containedActions.Count > 0) { processor.PushActionFrame(frame); } frame.State = QueryInitialized; break; case QueryInitialized: Debug.Assert(frame.State == QueryInitialized); frame.NextNode(processor); Debug.Assert(Processor.IsRoot(frame.Node)); if (processor.Debugger != null) { // this is like apply-templates, but we don't have it on stack. // Pop the stack, otherwise last instruction will be on it. processor.PopDebuggerStack(); } processor.PushTemplateLookup(frame.NodeSet, /*mode:*/null, /*importsOf:*/null); frame.State = RootProcessed; break; case RootProcessed: Debug.Assert(frame.State == RootProcessed); frame.Finished(); break; default: Debug.Fail("Invalid RootAction execution state"); break; } } } }
using System; using System.IO; using System.Linq; using System.Reflection; using JetBrains.Diagnostics; using JetBrains.Rider.Model.Unity; using JetBrains.Rider.Unity.Editor.Logger; using UnityEditor; using UnityEngine; namespace JetBrains.Rider.Unity.Editor { public interface IPluginSettings { OperatingSystemFamilyRider OperatingSystemFamilyRider { get; } } public class PluginSettings : IPluginSettings { private static readonly ILog ourLogger = Log.GetLog<PluginSettings>(); public static LoggingLevel SelectedLoggingLevel { get => (LoggingLevel) EditorPrefs.GetInt("Rider_SelectedLoggingLevel", 0); set { EditorPrefs.SetInt("Rider_SelectedLoggingLevel", (int) value); LogInitializer.InitLog(value); } } public static string[] GetInstalledNetFrameworks() { if (SystemInfoRiderPlugin.operatingSystemFamily != OperatingSystemFamilyRider.Windows) throw new InvalidOperationException("GetTargetFrameworkVersionWindowsMono2 is designed for Windows only"); var programFiles86 = Environment.GetEnvironmentVariable("PROGRAMFILES(X86)") ?? Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); if (string.IsNullOrEmpty(programFiles86)) programFiles86 = @"C:\Program Files (x86)"; var referenceAssembliesPaths = new[] { Path.Combine(programFiles86, @"Reference Assemblies\Microsoft\Framework\.NETFramework"), Path.Combine(programFiles86, @"Reference Assemblies\Microsoft\Framework") //RIDER-42873 }.Select(s => new DirectoryInfo(s)).Where(a=>a.Exists).ToArray(); if (!referenceAssembliesPaths.Any()) return new string[0]; var availableVersions = referenceAssembliesPaths .SelectMany(a=>a.GetDirectories("v*")) .Select(a => a.Name.Substring(1)) .Where(v => InvokeIfValidVersion(v, s => { })) .Where(v=>new Version(v) >= new Version("3.5")) .ToArray(); return availableVersions; } private static bool InvokeIfValidVersion(string input, Action<string> action) { try { // ReSharper disable once ObjectCreationAsStatement new Version(input); // mono 2.6 doesn't support Version.TryParse action(input); return true; } catch (ArgumentException) { } // can't put loggin here because ot fire on every symbol catch (FormatException) { } return false; } public static bool OverrideTargetFrameworkVersion { get { return EditorPrefs.GetBool("Rider_OverrideTargetFrameworkVersion", false); } private set { EditorPrefs.SetBool("Rider_OverrideTargetFrameworkVersion", value); } } // Only used for Unity 2018.1 and below public static ScriptCompilationDuringPlay AssemblyReloadSettings { get { if (UnityUtils.UnityVersion >= new Version(2018, 2)) { Debug.Log("Incorrectly accessing old script compilation settings on newer Unity. Use EditorPrefsWrapper.ScriptChangedDuringPlayOptions"); return ScriptCompilationDuringPlay.RecompileAndContinuePlaying; } return UnityUtils.ToScriptCompilationDuringPlay(EditorPrefs.GetInt("Rider_AssemblyReloadSettings", UnityUtils.FromScriptCompilationDuringPlay(ScriptCompilationDuringPlay.RecompileAndContinuePlaying))); } set { EditorPrefs.SetInt("Rider_AssemblyReloadSettings", UnityUtils.FromScriptCompilationDuringPlay(value)); } } public static bool UseLatestRiderFromToolbox { get { return EditorPrefs.GetBool("UseLatestRiderFromToolbox", true); } set { EditorPrefs.SetBool("UseLatestRiderFromToolbox", value); } } private static string TargetFrameworkVersionDefault = "4.6"; public static string TargetFrameworkVersion { get { return EditorPrefs.GetString("Rider_TargetFrameworkVersion", TargetFrameworkVersionDefault); } private set { InvokeIfValidVersion(value, val => { EditorPrefs.SetString("Rider_TargetFrameworkVersion", val); }); } } public static bool OverrideTargetFrameworkVersionOldMono { get { return EditorPrefs.GetBool("Rider_OverrideTargetFrameworkVersionOldMono", false); } private set { EditorPrefs.SetBool("Rider_OverrideTargetFrameworkVersionOldMono", value); } } private static string TargetFrameworkVersionOldMonoDefault = "3.5"; public static string TargetFrameworkVersionOldMono { get { return EditorPrefs.GetString("Rider_TargetFrameworkVersionOldMono", TargetFrameworkVersionOldMonoDefault); } private set { InvokeIfValidVersion(value, val => { EditorPrefs.SetString("Rider_TargetFrameworkVersionOldMono", val); }); } } public static bool OverrideLangVersion { get { return EditorPrefs.GetBool("Rider_OverrideLangVersion", false); } private set { EditorPrefs.SetBool("Rider_OverrideLangVersion", value); } } public static string LangVersion { get { return EditorPrefs.GetString("Rider_LangVersion", "4"); } private set { EditorPrefs.SetString("Rider_LangVersion", value); } } public static bool RiderInitializedOnce { get { return EditorPrefs.GetBool("RiderInitializedOnce", false); } set { EditorPrefs.SetBool("RiderInitializedOnce", value); } } public static bool LogEventsCollectorEnabled { get { return EditorPrefs.GetBool("Rider_LogEventsCollectorEnabled", true); } private set { EditorPrefs.SetBool("Rider_LogEventsCollectorEnabled", value); } } /// <summary> /// Preferences menu layout /// </summary> /// <remarks> /// Contains all 3 toggles: Enable/Disable; Debug On/Off; Writing Launch File On/Off /// </remarks> #if !UNITY_2019_2 // this is not loaded, for Rider package, so remove it to avoid compilation warning [PreferenceItem("Rider")] #endif private static void RiderPreferencesItem() { EditorGUIUtility.labelWidth = 200f; EditorGUILayout.BeginVertical(); var alternatives = RiderPathLocator.GetAllFoundInfos(SystemInfoRiderPlugin.operatingSystemFamily); if (alternatives.Any()) // from known locations { var paths = alternatives.Select(a => a.Path).ToList(); var externalEditor = EditorPrefsWrapper.ExternalScriptEditor; var alts = alternatives.Select(s => s.Presentation).ToList(); if (!paths.Contains(externalEditor)) { paths.Add(externalEditor); alts.Add(externalEditor); } var index = paths.IndexOf(externalEditor); var result = paths[EditorGUILayout.Popup("Rider build:", index == -1 ? 0 : index, alts.ToArray())]; EditorPrefsWrapper.ExternalScriptEditor = result; } if (PluginEntryPoint.IsRiderDefaultEditor() && !RiderPathProvider.RiderPathExist(EditorPrefsWrapper.ExternalScriptEditor, SystemInfoRiderPlugin.operatingSystemFamily)) { EditorGUILayout.HelpBox($"Rider is selected as preferred ExternalEditor, but doesn't exist on disk {EditorPrefsWrapper.ExternalScriptEditor}", MessageType.Warning); } UseLatestRiderFromToolbox = EditorGUILayout.Toggle(new GUIContent("Update Rider to latest version"), UseLatestRiderFromToolbox); GUILayout.BeginVertical(); LogEventsCollectorEnabled = EditorGUILayout.Toggle(new GUIContent("Pass Console to Rider:"), LogEventsCollectorEnabled); if (UnityUtils.ScriptingRuntime > 0) { OverrideTargetFrameworkVersion = EditorGUILayout.Toggle(new GUIContent("Override TargetFrameworkVersion:"), OverrideTargetFrameworkVersion); if (OverrideTargetFrameworkVersion) { var help = @"TargetFramework >= 4.6 is recommended."; TargetFrameworkVersion = EditorGUILayout.TextField( new GUIContent("For Active profile NET 4.6", help), TargetFrameworkVersion); EditorGUILayout.HelpBox(help, MessageType.None); } } else { OverrideTargetFrameworkVersionOldMono = EditorGUILayout.Toggle(new GUIContent("Override TargetFrameworkVersion:"), OverrideTargetFrameworkVersionOldMono); if (OverrideTargetFrameworkVersionOldMono) { var helpOldMono = @"TargetFramework = 3.5 is recommended. - With 4.5 Rider may show ambiguous references in UniRx."; TargetFrameworkVersionOldMono = EditorGUILayout.TextField( new GUIContent("For Active profile NET 3.5:", helpOldMono), TargetFrameworkVersionOldMono); EditorGUILayout.HelpBox(helpOldMono, MessageType.None); } } // Unity 2018.1 doesn't require installed dotnet framework, it references everything from Unity installation if (SystemInfoRiderPlugin.operatingSystemFamily == OperatingSystemFamilyRider.Windows && UnityUtils.UnityVersion < new Version(2018, 1)) { var detectedDotnetText = string.Empty; var installedFrameworks = GetInstalledNetFrameworks(); if (installedFrameworks.Any()) detectedDotnetText = installedFrameworks.OrderBy(v => new Version(v)).Aggregate((a, b) => a+"; "+b); EditorGUILayout.HelpBox($"Installed dotnet versions: {detectedDotnetText}", MessageType.None); } GUILayout.EndVertical(); OverrideLangVersion = EditorGUILayout.Toggle(new GUIContent("Override LangVersion:"), OverrideLangVersion); if (OverrideLangVersion) { var workaroundUrl = "https://gist.github.com/van800/875ce55eaf88d65b105d010d7b38a8d4"; var workaroundText = "Use this <color=#0000FF>workaround</color> if overriding doesn't work."; var helpLangVersion = @"Avoid overriding, unless there is no particular need."; LangVersion = EditorGUILayout.TextField( new GUIContent("LangVersion:", helpLangVersion), LangVersion); LinkButton(caption: workaroundText, url: workaroundUrl); EditorGUILayout.HelpBox(helpLangVersion, MessageType.None); } GUILayout.Label(""); EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Log file:"); var previous = GUI.enabled; GUI.enabled = previous && SelectedLoggingLevel != LoggingLevel.OFF; var button = GUILayout.Button(new GUIContent("Open log")); if (button) { //UnityEditorInternal.InternalEditorUtility.OpenFileAtLineExternal(PluginEntryPoint.LogPath, 0); // works much faster than the commented code, when Rider is already started PluginEntryPoint.OpenAssetHandler.OnOpenedAsset(PluginEntryPoint.LogPath, 0, 0); } GUI.enabled = previous; GUILayout.EndHorizontal(); var loggingMsg = @"Sets the amount of Rider Debug output. If you are about to report an issue, please select Verbose logging level and attach Unity console output to the issue."; SelectedLoggingLevel = (LoggingLevel) EditorGUILayout.EnumPopup(new GUIContent("Logging Level:", loggingMsg), SelectedLoggingLevel); EditorGUILayout.HelpBox(loggingMsg, MessageType.None); // This setting is natively supported in Unity 2018.2+ if (UnityUtils.UnityVersion < new Version(2018, 2)) { EditorGUI.BeginChangeCheck(); AssemblyReloadSettings = (ScriptCompilationDuringPlay) EditorGUILayout.EnumPopup("Script Changes during Playing:", AssemblyReloadSettings); if (EditorGUI.EndChangeCheck()) { if (AssemblyReloadSettings == ScriptCompilationDuringPlay.RecompileAfterFinishedPlaying && EditorApplication.isPlaying) { ourLogger.Info("LockReloadAssemblies"); EditorApplication.LockReloadAssemblies(); } else { ourLogger.Info("UnlockReloadAssemblies"); EditorApplication.UnlockReloadAssemblies(); } } } var githubRepo = "https://github.com/JetBrains/resharper-unity"; var caption = $"<color=#0000FF>{githubRepo}</color>"; LinkButton(caption: caption, url: githubRepo); GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); var version = Assembly.GetExecutingAssembly().GetName().Version; GUILayout.Label("Plugin version: " + version, new GUIStyle() { normal = new GUIStyleState() { textColor = new Color(0, 0, 0, .6f), }, margin = new RectOffset(4, 4, 4, 4), }); GUILayout.EndHorizontal(); // left for testing purposes /* if (GUILayout.Button("reset RiderInitializedOnce = false")) { RiderInitializedOnce = false; }*/ EditorGUILayout.EndVertical(); } private static void LinkButton(string caption, string url) { var style = GUI.skin.label; style.richText = true; var bClicked = GUILayout.Button(caption, style); var rect = GUILayoutUtility.GetLastRect(); rect.width = style.CalcSize(new GUIContent(caption)).x; EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link); if (bClicked) Application.OpenURL(url); } public OperatingSystemFamilyRider OperatingSystemFamilyRider => SystemInfoRiderPlugin.operatingSystemFamily; internal static class SystemInfoRiderPlugin { // This call on Linux is extremely slow, so cache it private static readonly string ourOperatingSystem = SystemInfo.operatingSystem; // Do not rename. Explicitly disabled for consistency/compatibility with future Unity API // ReSharper disable once InconsistentNaming public static OperatingSystemFamilyRider operatingSystemFamily { get { if (ourOperatingSystem.StartsWith("Mac", StringComparison.InvariantCultureIgnoreCase)) { return OperatingSystemFamilyRider.MacOSX; } if (ourOperatingSystem.StartsWith("Win", StringComparison.InvariantCultureIgnoreCase)) { return OperatingSystemFamilyRider.Windows; } if (ourOperatingSystem.StartsWith("Lin", StringComparison.InvariantCultureIgnoreCase)) { return OperatingSystemFamilyRider.Linux; } return OperatingSystemFamilyRider.Other; } } } } }
/* * Farseer Physics Engine: * Copyright (c) 2012 Ian Qvist * * Original source Box2D: * Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using System.Diagnostics; using FarseerPhysics.Common; using Microsoft.Xna.Framework; namespace FarseerPhysics.Dynamics.Joints { // p = attached point, m = mouse point // C = p - m // Cdot = v // = v + cross(w, r) // J = [I r_skew] // Identity used: // w k % (rx i + ry j) = w * (-ry i + rx j) /// <summary> /// A mouse joint is used to make a point on a body track a /// specified world point. This is a soft constraint with a maximum /// force. This allows the constraint to stretch without /// applying huge forces. /// NOTE: this joint is not documented in the manual because it was /// developed to be used in the testbed. If you want to learn how to /// use the mouse joint, look at the testbed. /// </summary> public class FixedMouseJoint : Joint { #region Properties/Fields /// <summary> /// The local anchor point on BodyA /// </summary> public Vector2 localAnchorA; public override Vector2 worldAnchorA { get { return bodyA.getWorldPoint( localAnchorA ); } set { localAnchorA = bodyA.getLocalPoint( value ); } } public override Vector2 worldAnchorB { get { return _worldAnchor; } set { wakeBodies(); _worldAnchor = value; } } /// <summary> /// The maximum constraint force that can be exerted to move the candidate body. Usually you will express /// as some multiple of the weight (multiplier * mass * gravity). /// </summary> public float maxForce { get { return _maxForce; } set { Debug.Assert( MathUtils.isValid( value ) && value >= 0.0f ); _maxForce = value; } } /// <summary> /// The response speed. /// </summary> public float frequency { get { return _frequency; } set { Debug.Assert( MathUtils.isValid( value ) && value >= 0.0f ); _frequency = value; } } /// <summary> /// The damping ratio. 0 = no damping, 1 = critical damping. /// </summary> public float dampingRatio { get { return _dampingRatio; } set { Debug.Assert( MathUtils.isValid( value ) && value >= 0.0f ); _dampingRatio = value; } } Vector2 _worldAnchor; float _frequency; float _dampingRatio; float _beta; // Solver shared Vector2 _impulse; float _maxForce; float _gamma; // Solver temp int _indexA; Vector2 _rA; Vector2 _localCenterA; float _invMassA; float _invIA; Mat22 _mass; Vector2 _C; #endregion /// <summary> /// This requires a world target point, /// tuning parameters, and the time step. /// </summary> /// <param name="body">The body.</param> /// <param name="worldAnchor">The target.</param> public FixedMouseJoint( Body body, Vector2 worldAnchor ) : base( body ) { jointType = JointType.FixedMouse; frequency = 5.0f; dampingRatio = 0.7f; maxForce = 1000 * body.mass; Debug.Assert( worldAnchor.isValid() ); _worldAnchor = worldAnchor; localAnchorA = MathUtils.mulT( bodyA._xf, worldAnchor ); } public override Vector2 getReactionForce( float invDt ) { return invDt * _impulse; } public override float getReactionTorque( float invDt ) { return invDt * 0.0f; } internal override void initVelocityConstraints( ref SolverData data ) { _indexA = bodyA.islandIndex; _localCenterA = bodyA._sweep.localCenter; _invMassA = bodyA._invMass; _invIA = bodyA._invI; var cA = data.positions[_indexA].c; var aA = data.positions[_indexA].a; var vA = data.velocities[_indexA].v; var wA = data.velocities[_indexA].w; var qA = new Rot( aA ); float mass = bodyA.mass; // Frequency float omega = 2.0f * Settings.pi * frequency; // Damping coefficient float d = 2.0f * mass * dampingRatio * omega; // Spring stiffness float k = mass * ( omega * omega ); // magic formulas // gamma has units of inverse mass. // beta has units of inverse time. float h = data.step.dt; Debug.Assert( d + h * k > Settings.epsilon, "damping is less than Epsilon. Does the body have mass?" ); _gamma = h * ( d + h * k ); if( _gamma != 0.0f ) _gamma = 1.0f / _gamma; _beta = h * k * _gamma; // Compute the effective mass matrix. _rA = MathUtils.mul( qA, localAnchorA - _localCenterA ); // K = [(1/m1 + 1/m2) * eye(2) - skew(r1) * invI1 * skew(r1) - skew(r2) * invI2 * skew(r2)] // = [1/m1+1/m2 0 ] + invI1 * [r1.Y*r1.Y -r1.X*r1.Y] + invI2 * [r1.Y*r1.Y -r1.X*r1.Y] // [ 0 1/m1+1/m2] [-r1.X*r1.Y r1.X*r1.X] [-r1.X*r1.Y r1.X*r1.X] var K = new Mat22(); K.ex.X = _invMassA + _invIA * _rA.Y * _rA.Y + _gamma; K.ex.Y = -_invIA * _rA.X * _rA.Y; K.ey.X = K.ex.Y; K.ey.Y = _invMassA + _invIA * _rA.X * _rA.X + _gamma; _mass = K.Inverse; _C = cA + _rA - _worldAnchor; _C *= _beta; // Cheat with some damping wA *= 0.98f; if( Settings.enableWarmstarting ) { _impulse *= data.step.dtRatio; vA += _invMassA * _impulse; wA += _invIA * MathUtils.cross( _rA, _impulse ); } else { _impulse = Vector2.Zero; } data.velocities[_indexA].v = vA; data.velocities[_indexA].w = wA; } internal override void solveVelocityConstraints( ref SolverData data ) { var vA = data.velocities[_indexA].v; var wA = data.velocities[_indexA].w; // Cdot = v + cross(w, r) var Cdot = vA + MathUtils.cross( wA, _rA ); var impulse = MathUtils.mul( ref _mass, -( Cdot + _C + _gamma * _impulse ) ); var oldImpulse = _impulse; _impulse += impulse; float maxImpulse = data.step.dt * maxForce; if( _impulse.LengthSquared() > maxImpulse * maxImpulse ) { _impulse *= maxImpulse / _impulse.Length(); } impulse = _impulse - oldImpulse; vA += _invMassA * impulse; wA += _invIA * MathUtils.cross( _rA, impulse ); data.velocities[_indexA].v = vA; data.velocities[_indexA].w = wA; } internal override bool solvePositionConstraints( ref SolverData data ) { return true; } } }
// 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.Diagnostics; using System.Diagnostics.Contracts; using System.Text; using System.Threading; using System.Security; namespace System.Text { // DBCSCodePageEncoding // internal class DBCSCodePageEncoding : BaseCodePageEncoding { // Pointers to our memory section parts [SecurityCritical] protected unsafe char* mapBytesToUnicode = null; // char 65536 [SecurityCritical] protected unsafe ushort* mapUnicodeToBytes = null; // byte 65536 protected const char UNKNOWN_CHAR_FLAG = (char)0x0; protected const char UNICODE_REPLACEMENT_CHAR = (char)0xFFFD; protected const char LEAD_BYTE_CHAR = (char)0xFFFE; // For lead bytes // Note that even though we provide bytesUnknown and byteCountUnknown, // They aren't actually used because of the fallback mechanism. (char is though) private ushort _bytesUnknown; private int _byteCountUnknown; protected char charUnknown = (char)0; [System.Security.SecurityCritical] // auto-generated public DBCSCodePageEncoding(int codePage) : this(codePage, codePage) { } [System.Security.SecurityCritical] // auto-generated internal DBCSCodePageEncoding(int codePage, int dataCodePage) : base(codePage, dataCodePage) { } [System.Security.SecurityCritical] // auto-generated internal DBCSCodePageEncoding(int codePage, int dataCodePage, EncoderFallback enc, DecoderFallback dec) : base(codePage, dataCodePage, enc, dec) { } // MBCS data section: // // We treat each multibyte pattern as 2 bytes in our table. If it's a single byte, then the high byte // for that position will be 0. When the table is loaded, leading bytes are flagged with 0xFFFE, so // when reading the table look up with each byte. If the result is 0xFFFE, then use 2 bytes to read // further data. FFFF is a special value indicating that the Unicode code is the same as the // character code (this helps us support code points < 0x20). FFFD is used as replacement character. // // Normal table: // WCHAR* - Starting with MB code point 0. // FFFF indicates we are to use the multibyte value for our code point. // FFFE is the lead byte mark. (This should only appear in positions < 0x100) // FFFD is the replacement (unknown character) mark. // 2-20 means to advance the pointer 2-0x20 characters. // 1 means to advance to the multibyte position contained in the next char. // 0 has no specific meaning (May not be possible.) // // Table ends when multibyte position has advanced to 0xFFFF. // // Bytes->Unicode Best Fit table: // WCHAR* - Same as normal table, except first wchar is byte position to start at. // // Unicode->Bytes Best Fit Table: // WCHAR* - Same as normal table, except first wchar is char position to start at and // we loop through unicode code points and the table has the byte points that // correspond to those unicode code points. // We have a managed code page entry, so load our tables // [System.Security.SecurityCritical] // auto-generated protected override unsafe void LoadManagedCodePage() { fixed (byte* pBytes = m_codePageHeader) { CodePageHeader* pCodePage = (CodePageHeader*)pBytes; // Should be loading OUR code page Debug.Assert(pCodePage->CodePage == dataTableCodePage, "[DBCSCodePageEncoding.LoadManagedCodePage]Expected to load data table code page"); // Make sure we're really a 1-byte code page if (pCodePage->ByteCount != 2) throw new NotSupportedException(SR.Format(SR.NotSupported_NoCodepageData, CodePage)); // Remember our unknown bytes & chars _bytesUnknown = pCodePage->ByteReplace; charUnknown = pCodePage->UnicodeReplace; // Need to make sure the fallback buffer's fallback char is correct if (DecoderFallback is InternalDecoderBestFitFallback) { ((InternalDecoderBestFitFallback)(DecoderFallback)).cReplacement = charUnknown; } // Is our replacement bytesUnknown a single or double byte character? _byteCountUnknown = 1; if (_bytesUnknown > 0xff) _byteCountUnknown++; // We use fallback encoder, which uses ?, which so far all of our tables do as well Debug.Assert(_bytesUnknown == 0x3f, "[DBCSCodePageEncoding.LoadManagedCodePage]Expected 0x3f (?) as unknown byte character"); // Get our mapped section (bytes to allocate = 2 bytes per 65536 Unicode chars + 2 bytes per 65536 DBCS chars) // Plus 4 byte to remember CP # when done loading it. (Don't want to get IA64 or anything out of alignment) byte* pNativeMemory = GetNativeMemory(65536 * 2 * 2 + 4 + iExtraBytes); mapBytesToUnicode = (char*)pNativeMemory; mapUnicodeToBytes = (ushort*)(pNativeMemory + 65536 * 2); // Need to read our data file and fill in our section. // WARNING: Multiple code pieces could do this at once (so we don't have to lock machine-wide) // so be careful here. Only stick legal values in here, don't stick temporary values. // Move to the beginning of the data section byte[] buffer = new byte[m_dataSize]; lock (s_streamLock) { s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset, SeekOrigin.Begin); s_codePagesEncodingDataStream.Read(buffer, 0, m_dataSize); } fixed (byte* pBuffer = buffer) { char* pData = (char*)pBuffer; // We start at bytes position 0 int bytePosition = 0; int useBytes = 0; while (bytePosition < 0x10000) { // Get the next byte char input = *pData; pData++; // build our table: if (input == 1) { // Use next data as our byte position bytePosition = (int)(*pData); pData++; continue; } else if (input < 0x20 && input > 0) { // Advance input characters bytePosition += input; continue; } else if (input == 0xFFFF) { // Same as our bytePosition useBytes = bytePosition; input = unchecked((char)bytePosition); } else if (input == LEAD_BYTE_CHAR) // 0xfffe { // Lead byte mark Debug.Assert(bytePosition < 0x100, "[DBCSCodePageEncoding.LoadManagedCodePage]expected lead byte to be < 0x100"); useBytes = bytePosition; // input stays 0xFFFE } else if (input == UNICODE_REPLACEMENT_CHAR) { // Replacement char is already done bytePosition++; continue; } else { // Use this character useBytes = bytePosition; // input == input; } // We may need to clean up the selected character & position if (CleanUpBytes(ref useBytes)) { // Use this selected character at the selected position, don't do this if not supposed to. if (input != LEAD_BYTE_CHAR) { // Don't do this for lead byte marks. mapUnicodeToBytes[input] = unchecked((ushort)useBytes); } mapBytesToUnicode[useBytes] = input; } bytePosition++; } } // See if we have any clean up to do CleanUpEndBytes(mapBytesToUnicode); } } // Any special processing for this code page protected virtual bool CleanUpBytes(ref int bytes) { return true; } // Any special processing for this code page [System.Security.SecurityCritical] // auto-generated protected virtual unsafe void CleanUpEndBytes(char* chars) { } // Private object for locking instead of locking on a public type for SQL reliability work. private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if (s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } } // Read in our best fit table [System.Security.SecurityCritical] // auto-generated protected unsafe override void ReadBestFitTable() { // Lock so we don't confuse ourselves. lock (InternalSyncObject) { // If we got a best fit array already then don't do this if (arrayUnicodeBestFit == null) { // // Read in Best Fit table. // // First we have to advance past original character mapping table // Move to the beginning of the data section byte[] buffer = new byte[m_dataSize]; lock (s_streamLock) { s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset, SeekOrigin.Begin); s_codePagesEncodingDataStream.Read(buffer, 0, m_dataSize); } fixed (byte* pBuffer = buffer) { char* pData = (char*)pBuffer; // We start at bytes position 0 int bytesPosition = 0; while (bytesPosition < 0x10000) { // Get the next byte char input = *pData; pData++; // build our table: if (input == 1) { // Use next data as our byte position bytesPosition = (int)(*pData); pData++; } else if (input < 0x20 && input > 0) { // Advance input characters bytesPosition += input; } else { // All other cases add 1 to bytes position bytesPosition++; } } // Now bytesPosition is at start of bytes->unicode best fit table char* pBytes2Unicode = pData; // Now pData should be pointing to first word of bytes -> unicode best fit table // (which we're also not using at the moment) int iBestFitCount = 0; bytesPosition = *pData; pData++; while (bytesPosition < 0x10000) { // Get the next byte char input = *pData; pData++; // build our table: if (input == 1) { // Use next data as our byte position bytesPosition = (int)(*pData); pData++; } else if (input < 0x20 && input > 0) { // Advance input characters bytesPosition += input; } else { // Use this character (unless it's unknown, unk just skips 1) if (input != UNICODE_REPLACEMENT_CHAR) { int correctedChar = bytesPosition; if (CleanUpBytes(ref correctedChar)) { // Sometimes correction makes them the same as no best fit, skip those. if (mapBytesToUnicode[correctedChar] != input) { iBestFitCount++; } } } // Position gets incremented in any case. bytesPosition++; } } // Now we know how big the best fit table has to be char[] arrayTemp = new char[iBestFitCount * 2]; // Now we know how many best fits we have, so go back & read them in iBestFitCount = 0; pData = pBytes2Unicode; bytesPosition = *pData; pData++; bool bOutOfOrder = false; // Read it all in again while (bytesPosition < 0x10000) { // Get the next byte char input = *pData; pData++; // build our table: if (input == 1) { // Use next data as our byte position bytesPosition = (int)(*pData); pData++; } else if (input < 0x20 && input > 0) { // Advance input characters bytesPosition += input; } else { // Use this character (unless its unknown, unk just skips 1) if (input != UNICODE_REPLACEMENT_CHAR) { int correctedChar = bytesPosition; if (CleanUpBytes(ref correctedChar)) { // Sometimes correction makes them same as no best fit, skip those. if (mapBytesToUnicode[correctedChar] != input) { if (correctedChar != bytesPosition) bOutOfOrder = true; arrayTemp[iBestFitCount++] = unchecked((char)correctedChar); arrayTemp[iBestFitCount++] = input; } } } // Position gets incremented in any case. bytesPosition++; } } // If they're out of order we need to sort them. if (bOutOfOrder) { Debug.Assert((arrayTemp.Length / 2) < 20, "[DBCSCodePageEncoding.ReadBestFitTable]Expected small best fit table < 20 for code page " + CodePage + ", not " + arrayTemp.Length / 2); for (int i = 0; i < arrayTemp.Length - 2; i += 2) { int iSmallest = i; char cSmallest = arrayTemp[i]; for (int j = i + 2; j < arrayTemp.Length; j += 2) { // Find smallest one for front if (cSmallest > arrayTemp[j]) { cSmallest = arrayTemp[j]; iSmallest = j; } } // If smallest one is something else, switch them if (iSmallest != i) { char temp = arrayTemp[iSmallest]; arrayTemp[iSmallest] = arrayTemp[i]; arrayTemp[i] = temp; temp = arrayTemp[iSmallest + 1]; arrayTemp[iSmallest + 1] = arrayTemp[i + 1]; arrayTemp[i + 1] = temp; } } } // Remember our array arrayBytesBestFit = arrayTemp; // Now were at beginning of Unicode -> Bytes best fit table, need to count them char* pUnicode2Bytes = pData; int unicodePosition = *(pData++); iBestFitCount = 0; while (unicodePosition < 0x10000) { // Get the next byte char input = *pData; pData++; // build our table: if (input == 1) { // Use next data as our byte position unicodePosition = (int)*pData; pData++; } else if (input < 0x20 && input > 0) { // Advance input characters unicodePosition += input; } else { // Same as our unicodePosition or use this character if (input > 0) iBestFitCount++; unicodePosition++; } } // Allocate our table arrayTemp = new char[iBestFitCount * 2]; // Now do it again to fill the array with real values pData = pUnicode2Bytes; unicodePosition = *(pData++); iBestFitCount = 0; while (unicodePosition < 0x10000) { // Get the next byte char input = *pData; pData++; // build our table: if (input == 1) { // Use next data as our byte position unicodePosition = (int)*pData; pData++; } else if (input < 0x20 && input > 0) { // Advance input characters unicodePosition += input; } else { if (input > 0) { // Use this character, may need to clean it up int correctedChar = (int)input; if (CleanUpBytes(ref correctedChar)) { arrayTemp[iBestFitCount++] = unchecked((char)unicodePosition); // Have to map it to Unicode because best fit will need Unicode value of best fit char. arrayTemp[iBestFitCount++] = mapBytesToUnicode[correctedChar]; } } unicodePosition++; } } // Remember our array arrayUnicodeBestFit = arrayTemp; } } } } // GetByteCount // Note: We start by assuming that the output will be the same as count. Having // an encoder or fallback may change that assumption [System.Security.SecurityCritical] // auto-generated public override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(count >= 0, "[DBCSCodePageEncoding.GetByteCount]count is negative"); Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetByteCount]chars is null"); // Assert because we shouldn't be able to have a null encoder. Debug.Assert(EncoderFallback != null, "[DBCSCodePageEncoding.GetByteCount]Attempting to use null fallback"); CheckMemorySection(); // Get any left over characters char charLeftOver = (char)0; if (encoder != null) { charLeftOver = encoder.charLeftOver; // Only count if encoder.m_throwOnOverflow if (encoder.InternalHasFallbackBuffer && encoder.FallbackBuffer.Remaining > 0) throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, EncodingName, encoder.Fallback.GetType())); } // prepare our end int byteCount = 0; char* charEnd = chars + count; // For fallback we will need a fallback buffer EncoderFallbackBuffer fallbackBuffer = null; EncoderFallbackBufferHelper fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer); // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[DBCSCodePageEncoding.GetByteCount]leftover character should be high surrogate"); Debug.Assert(encoder != null, "[DBCSCodePageEncoding.GetByteCount]Expect to have encoder if we have a charLeftOver"); // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback fallbackBuffer = encoder.FallbackBuffer; fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(chars, charEnd, encoder, false); // This will fallback a pair if *chars is a low surrogate fallbackHelper.InternalFallback(charLeftOver, ref chars); } // Now we may have fallback char[] already (from the encoder) // We have to use fallback method. char ch; while ((ch = (fallbackBuffer == null) ? '\0' : fallbackHelper.InternalGetNextChar()) != 0 || chars < charEnd) { // First unwind any fallback if (ch == 0) { // No fallback, just get next char ch = *chars; chars++; } // get byte for this char ushort sTemp = mapUnicodeToBytes[ch]; // Check for fallback, this'll catch surrogate pairs too. if (sTemp == 0 && ch != (char)0) { if (fallbackBuffer == null) { // Initialize the buffer if (encoder == null) fallbackBuffer = EncoderFallback.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(charEnd - count, charEnd, encoder, false); } // Get Fallback fallbackHelper.InternalFallback(ch, ref chars); continue; } // We'll use this one byteCount++; if (sTemp >= 0x100) byteCount++; } return (int)byteCount; } [System.Security.SecurityCritical] // auto-generated public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetBytes]bytes is null"); Debug.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetBytes]byteCount is negative"); Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetBytes]chars is null"); Debug.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetBytes]charCount is negative"); // Assert because we shouldn't be able to have a null encoder. Debug.Assert(EncoderFallback != null, "[DBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback"); CheckMemorySection(); // For fallback we will need a fallback buffer EncoderFallbackBuffer fallbackBuffer = null; // prepare our end char* charEnd = chars + charCount; char* charStart = chars; byte* byteStart = bytes; byte* byteEnd = bytes + byteCount; EncoderFallbackBufferHelper fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer); // Get any left over characters char charLeftOver = (char)0; if (encoder != null) { charLeftOver = encoder.charLeftOver; Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), "[DBCSCodePageEncoding.GetBytes]leftover character should be high surrogate"); // Go ahead and get the fallback buffer (need leftover fallback if converting) fallbackBuffer = encoder.FallbackBuffer; fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(chars, charEnd, encoder, true); // If we're not converting we must not have a fallback buffer if (encoder.m_throwOnOverflow && fallbackBuffer.Remaining > 0) throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, EncodingName, encoder.Fallback.GetType())); // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { Debug.Assert(encoder != null, "[DBCSCodePageEncoding.GetBytes]Expect to have encoder if we have a charLeftOver"); // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback fallbackHelper.InternalFallback(charLeftOver, ref chars); } } // Now we may have fallback char[] already from the encoder // Go ahead and do it, including the fallback. char ch; while ((ch = (fallbackBuffer == null) ? '\0' : fallbackHelper.InternalGetNextChar()) != 0 || chars < charEnd) { // First unwind any fallback if (ch == 0) { // No fallback, just get next char ch = *chars; chars++; } // get byte for this char ushort sTemp = mapUnicodeToBytes[ch]; // Check for fallback, this'll catch surrogate pairs too. if (sTemp == 0 && ch != (char)0) { if (fallbackBuffer == null) { // Initialize the buffer Debug.Assert(encoder == null, "[DBCSCodePageEncoding.GetBytes]Expected delayed create fallback only if no encoder."); fallbackBuffer = EncoderFallback.CreateFallbackBuffer(); fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(charEnd - charCount, charEnd, encoder, true); } // Get Fallback fallbackHelper.InternalFallback(ch, ref chars); continue; } // We'll use this one (or two) // Bounds check // Go ahead and add it, lead byte 1st if necessary if (sTemp >= 0x100) { if (bytes + 1 >= byteEnd) { // didn't use this char, we'll throw or use buffer if (fallbackBuffer == null || fallbackHelper.bFallingBack == false) { Debug.Assert(chars > charStart, "[DBCSCodePageEncoding.GetBytes]Expected chars to have advanced (double byte case)"); chars--; // don't use last char } else fallbackBuffer.MovePrevious(); // don't use last fallback ThrowBytesOverflow(encoder, chars == charStart); // throw ? break; // don't throw, stop } *bytes = unchecked((byte)(sTemp >> 8)); bytes++; } // Single byte else if (bytes >= byteEnd) { // didn't use this char, we'll throw or use buffer if (fallbackBuffer == null || fallbackHelper.bFallingBack == false) { Debug.Assert(chars > charStart, "[DBCSCodePageEncoding.GetBytes]Expected chars to have advanced (single byte case)"); chars--; // don't use last char } else fallbackBuffer.MovePrevious(); // don't use last fallback ThrowBytesOverflow(encoder, chars == charStart); // throw ? break; // don't throw, stop } *bytes = unchecked((byte)(sTemp & 0xff)); bytes++; } // encoder stuff if we have one if (encoder != null) { // Fallback stuck it in encoder if necessary, but we have to clear MustFlush cases if (fallbackBuffer != null && !fallbackHelper.bUsedEncoder) // Clear it in case of MustFlush encoder.charLeftOver = (char)0; // Set our chars used count encoder.m_charsUsed = (int)(chars - charStart); } return (int)(bytes - byteStart); } // This is internal and called by something else, [System.Security.SecurityCritical] // auto-generated public override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) { // Just assert, we're called internally so these should be safe, checked already Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetCharCount]bytes is null"); Debug.Assert(count >= 0, "[DBCSCodePageEncoding.GetCharCount]byteCount is negative"); CheckMemorySection(); // Fix our decoder DBCSDecoder decoder = (DBCSDecoder)baseDecoder; // Get our fallback DecoderFallbackBuffer fallbackBuffer = null; // We'll need to know where the end is byte* byteEnd = bytes + count; int charCount = count; // Assume 1 char / byte // Shouldn't have anything in fallback buffer for GetCharCount // (don't have to check m_throwOnOverflow for count) Debug.Assert(decoder == null || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer at start"); DecoderFallbackBufferHelper fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer); // If we have a left over byte, use it if (decoder != null && decoder.bLeftOver > 0) { // We have a left over byte? if (count == 0) { // No input though if (!decoder.MustFlush) { // Don't have to flush return 0; } Debug.Assert(fallbackBuffer == null, "[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer"); fallbackBuffer = decoder.FallbackBuffer; fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(bytes, null); byte[] byteBuffer = new byte[] { unchecked((byte)decoder.bLeftOver) }; return fallbackHelper.InternalFallback(byteBuffer, bytes); } // Get our full info int iBytes = decoder.bLeftOver << 8; iBytes |= (*bytes); bytes++; // This is either 1 known char or fallback // Already counted 1 char // Look up our bytes char cDecoder = mapBytesToUnicode[iBytes]; if (cDecoder == 0 && iBytes != 0) { // Deallocate preallocated one charCount--; // We'll need a fallback Debug.Assert(fallbackBuffer == null, "[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer for unknown pair"); fallbackBuffer = decoder.FallbackBuffer; fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(byteEnd - count, null); // Do fallback, we know there're 2 bytes byte[] byteBuffer = new byte[] { unchecked((byte)(iBytes >> 8)), unchecked((byte)iBytes) }; charCount += fallbackHelper.InternalFallback(byteBuffer, bytes); } // else we already reserved space for this one. } // Loop, watch out for fallbacks while (bytes < byteEnd) { // Faster if don't use *bytes++; int iBytes = *bytes; bytes++; char c = mapBytesToUnicode[iBytes]; // See if it was a double byte character if (c == LEAD_BYTE_CHAR) { // It's a lead byte charCount--; // deallocate preallocated lead byte if (bytes < byteEnd) { // Have another to use, so use it iBytes <<= 8; iBytes |= *bytes; bytes++; c = mapBytesToUnicode[iBytes]; } else { // No input left if (decoder == null || decoder.MustFlush) { // have to flush anyway, set to unknown so we use fallback charCount++; // reallocate deallocated lead byte c = UNKNOWN_CHAR_FLAG; } else { // We'll stick it in decoder break; } } } // See if it was unknown. // Unknown and known chars already allocated, but fallbacks aren't if (c == UNKNOWN_CHAR_FLAG && iBytes != 0) { if (fallbackBuffer == null) { if (decoder == null) fallbackBuffer = DecoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(byteEnd - count, null); } // Do fallback charCount--; // Get rid of preallocated extra char byte[] byteBuffer = null; if (iBytes < 0x100) byteBuffer = new byte[] { unchecked((byte)iBytes) }; else byteBuffer = new byte[] { unchecked((byte)(iBytes >> 8)), unchecked((byte)iBytes) }; charCount += fallbackHelper.InternalFallback(byteBuffer, bytes); } } // Shouldn't have anything in fallback buffer for GetChars Debug.Assert(decoder == null || !decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer at end"); // Return our count return charCount; } [System.Security.SecurityCritical] // auto-generated public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS baseDecoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetChars]bytes is null"); Debug.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetChars]byteCount is negative"); Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetChars]chars is null"); Debug.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetChars]charCount is negative"); CheckMemorySection(); // Fix our decoder DBCSDecoder decoder = (DBCSDecoder)baseDecoder; // We'll need to know where the end is byte* byteStart = bytes; byte* byteEnd = bytes + byteCount; char* charStart = chars; char* charEnd = chars + charCount; bool bUsedDecoder = false; // Get our fallback DecoderFallbackBuffer fallbackBuffer = null; // Shouldn't have anything in fallback buffer for GetChars Debug.Assert(decoder == null || !decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[DBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start"); DecoderFallbackBufferHelper fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer); // If we have a left over byte, use it if (decoder != null && decoder.bLeftOver > 0) { // We have a left over byte? if (byteCount == 0) { // No input though if (!decoder.MustFlush) { // Don't have to flush return 0; } // Well, we're flushing, so use '?' or fallback // fallback leftover byte Debug.Assert(fallbackBuffer == null, "[DBCSCodePageEncoding.GetChars]Expected empty fallback"); fallbackBuffer = decoder.FallbackBuffer; fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(bytes, charEnd); // If no room, it's hopeless, this was 1st fallback byte[] byteBuffer = new byte[] { unchecked((byte)decoder.bLeftOver) }; if (!fallbackHelper.InternalFallback(byteBuffer, bytes, ref chars)) ThrowCharsOverflow(decoder, true); decoder.bLeftOver = 0; // Done, return it return (int)(chars - charStart); } // Get our full info int iBytes = decoder.bLeftOver << 8; iBytes |= (*bytes); bytes++; // Look up our bytes char cDecoder = mapBytesToUnicode[iBytes]; if (cDecoder == UNKNOWN_CHAR_FLAG && iBytes != 0) { Debug.Assert(fallbackBuffer == null, "[DBCSCodePageEncoding.GetChars]Expected empty fallback for two bytes"); fallbackBuffer = decoder.FallbackBuffer; fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(byteEnd - byteCount, charEnd); byte[] byteBuffer = new byte[] { unchecked((byte)(iBytes >> 8)), unchecked((byte)iBytes) }; if (!fallbackHelper.InternalFallback(byteBuffer, bytes, ref chars)) ThrowCharsOverflow(decoder, true); } else { // Do we have output room?, hopeless if not, this is first char if (chars >= charEnd) ThrowCharsOverflow(decoder, true); *(chars++) = cDecoder; } } // Loop, paying attention to our fallbacks. while (bytes < byteEnd) { // Faster if don't use *bytes++; int iBytes = *bytes; bytes++; char c = mapBytesToUnicode[iBytes]; // See if it was a double byte character if (c == LEAD_BYTE_CHAR) { // Its a lead byte if (bytes < byteEnd) { // Have another to use, so use it iBytes <<= 8; iBytes |= *bytes; bytes++; c = mapBytesToUnicode[iBytes]; } else { // No input left if (decoder == null || decoder.MustFlush) { // have to flush anyway, set to unknown so we use fallback c = UNKNOWN_CHAR_FLAG; } else { // Stick it in decoder bUsedDecoder = true; decoder.bLeftOver = (byte)iBytes; break; } } } // See if it was unknown if (c == UNKNOWN_CHAR_FLAG && iBytes != 0) { if (fallbackBuffer == null) { if (decoder == null) fallbackBuffer = DecoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(byteEnd - byteCount, charEnd); } // Do fallback byte[] byteBuffer = null; if (iBytes < 0x100) byteBuffer = new byte[] { unchecked((byte)iBytes) }; else byteBuffer = new byte[] { unchecked((byte)(iBytes >> 8)), unchecked((byte)iBytes) }; if (!fallbackHelper.InternalFallback(byteBuffer, bytes, ref chars)) { // May or may not throw, but we didn't get these byte(s) Debug.Assert(bytes >= byteStart + byteBuffer.Length, "[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for fallback"); bytes -= byteBuffer.Length; // didn't use these byte(s) fallbackHelper.InternalReset(); // Didn't fall this back ThrowCharsOverflow(decoder, bytes == byteStart); // throw? break; // don't throw, but stop loop } } else { // Do we have buffer room? if (chars >= charEnd) { // May or may not throw, but we didn't get these byte(s) Debug.Assert(bytes > byteStart, "[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for lead byte"); bytes--; // unused byte if (iBytes >= 0x100) { Debug.Assert(bytes > byteStart, "[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for trail byte"); bytes--; // 2nd unused byte } ThrowCharsOverflow(decoder, bytes == byteStart); // throw? break; // don't throw, but stop loop } *(chars++) = c; } } // We already stuck it in encoder if necessary, but we have to clear cases where nothing new got into decoder if (decoder != null) { // Clear it in case of MustFlush if (bUsedDecoder == false) { decoder.bLeftOver = 0; } // Remember our count decoder.m_bytesUsed = (int)(bytes - byteStart); } // Shouldn't have anything in fallback buffer for GetChars Debug.Assert(decoder == null || !decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[DBCSCodePageEncoding.GetChars]Expected empty fallback buffer at end"); // Return length of our output return (int)(chars - charStart); } public override int GetMaxByteCount(int charCount) { if (charCount < 0) throw new ArgumentOutOfRangeException("charCount", SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // Characters would be # of characters + 1 in case high surrogate is ? * max fallback long byteCount = (long)charCount + 1; if (EncoderFallback.MaxCharCount > 1) byteCount *= EncoderFallback.MaxCharCount; // 2 to 1 is worst case. Already considered surrogate fallback byteCount *= 2; if (byteCount > 0x7fffffff) throw new ArgumentOutOfRangeException("charCount", SR.ArgumentOutOfRange_GetByteCountOverflow); return (int)byteCount; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) throw new ArgumentOutOfRangeException("byteCount", SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // DBCS is pretty much the same, but could have hanging high byte making extra ? and fallback for unknown long charCount = ((long)byteCount + 1); // 1 to 1 for most characters. Only surrogates with fallbacks have less, unknown fallbacks could be longer. if (DecoderFallback.MaxCharCount > 1) charCount *= DecoderFallback.MaxCharCount; if (charCount > 0x7fffffff) throw new ArgumentOutOfRangeException("byteCount", SR.ArgumentOutOfRange_GetCharCountOverflow); return (int)charCount; } public override Decoder GetDecoder() { return new DBCSDecoder(this); } internal class DBCSDecoder : DecoderNLS { // Need a place for the last left over byte internal byte bLeftOver = 0; public DBCSDecoder(DBCSCodePageEncoding encoding) : base(encoding) { // Base calls reset } public override void Reset() { bLeftOver = 0; if (m_fallbackBuffer != null) m_fallbackBuffer.Reset(); } // Anything left in our decoder? internal override bool HasState { get { return (bLeftOver != 0); } } } } }
#if NETFX_CORE using MarkerMetro.Unity.WinLegacy.Security.Cryptography; using System.Threading.Tasks; using System.Globalization; #endif using Facebook; using System; using System.Collections.Generic; using MarkerMetro.Unity.WinIntegration; #if NETFX_CORE using Windows.Storage; using MarkerMetro.Unity.WinIntegration.Storage; #endif namespace MarkerMetro.Unity.WinIntegration.Facebook { public delegate void FacebookDelegate(FBResult result); public delegate void InitDelegate(); public delegate void HideUnityDelegate(bool hideUnity); public enum HttpMethod { GET, POST, DELETE } public class FBResult { public string Error { get; set; } public string Text { get; set; } public JsonObject Json { get; set; } } public class MissingPlatformException : Exception { public MissingPlatformException() : base("Platform components have not been set") { } } public static class FB { #if NETFX_CORE private static FacebookClient _client; private static IWebInterface _web; private static HideUnityDelegate _onHideUnity; private static string _redirectUrl = "http://www.facebook.com/connect/login_success.html"; private const string TOKEN_KEY = "ATK"; private const string EXPIRY_DATE = "EXP"; private const string EXPIRY_DATE_BIN = "EXPB"; private const string FBID_KEY = "FBID"; private const string FBNAME_KEY = "FBNAME"; #endif public static string UserId { get; private set; } public static string UserName { get; set; } public static bool IsLoggedIn { get { return !string.IsNullOrEmpty(AccessToken); } } public static string AppId { get; private set; } public static string AccessToken { get; private set; } public static DateTime Expires { get; private set; } // check whether facebook is initialized public static bool IsInitialized { get { #if NETFX_CORE return _client != null; #else throw new PlatformNotSupportedException(""); #endif } } public static void Logout() { #if NETFX_CORE if (_web == null) throw new MissingPlatformException(); if (_web.IsActive || !IsLoggedIn) return; var uri = _client.GetLogoutUrl(new { access_token = AccessToken, next = _redirectUrl, display = "popup" }); _web.ClearCookies(); InvalidateData(); _web.Navigate(uri, false, (url, state) => { _web.Finish(); }, (url, error, state) => _web.Finish()); #else throw new PlatformNotSupportedException(""); #endif } public static void Login(string permissions, FacebookDelegate callback) { #if NETFX_CORE if (_web == null) throw new MissingPlatformException(); if (_web.IsActive || IsLoggedIn) { // Already in use if (callback != null) { callback(new FBResult() { Error = "Already in use" }); } return; } var uri = _client.GetLoginUrl(new { redirect_uri = _redirectUrl, scope = permissions, display = "popup", response_type = "token" }); _web.ClearCookies(); _web.Navigate(uri, true, onError: LoginNavigationError, state: callback, startedCallback: LoginNavigationStarted); if (_onHideUnity != null) { _onHideUnity(true); } #else throw new PlatformNotSupportedException(""); #endif } #if NETFX_CORE private static void LoginNavigationError(Uri url, int error, object state) { //Debug.LogError("Nav error: " + error); if (state is FacebookDelegate) ((FacebookDelegate)state)(new FBResult() { Error = error.ToString() }); _web.Finish(); if (_onHideUnity != null) _onHideUnity(false); } private static void LoginNavigationStarted(Uri url, object state) { FacebookOAuthResult result; // Check if we're waiting for user input or if login is complete if (_client.TryParseOAuthCallbackUrl(url, out result)) { // Login complete if (result.IsSuccess) { AccessToken = result.AccessToken; Expires = result.Expires; _client.AccessToken = AccessToken; Settings.Set(TOKEN_KEY, EncryptionProvider.Encrypt(AccessToken, AppId)); Settings.Set(EXPIRY_DATE_BIN, Expires.ToBinary()); } _web.Finish(); if (_onHideUnity != null) { _onHideUnity(false); } API("/me?fields=id,name", HttpMethod.GET, fbResult => { if (IsLoggedIn) { UserId = fbResult.Json["id"] as string; UserName = fbResult.Json["name"] as string; Settings.Set(FBID_KEY, UserId); Settings.Set(FBNAME_KEY, UserName); } if (state is FacebookDelegate) { JsonObject jResult = new JsonObject(); jResult.Add(new KeyValuePair<string, object>("authToken", AccessToken)); jResult.Add(new KeyValuePair<string, object>("authTokenExpiry", Expires.ToString())); ((FacebookDelegate)state)(new FBResult() { Json = jResult, Text = jResult.ToString() }); } }); } } #endif public static void Init( InitDelegate onInitComplete, string appId, HideUnityDelegate onHideUnity, string redirectUrl = null) { #if NETFX_CORE if (_client != null) { if (onInitComplete != null) onInitComplete(); return; } if (_web == null) throw new MissingPlatformException(); if (string.IsNullOrEmpty(appId)) throw new ArgumentException("Invalid Facebook App ID"); if (!string.IsNullOrEmpty(redirectUrl)) _redirectUrl = redirectUrl; _client = new FacebookClient(); _client.GetCompleted += HandleGetCompleted; AppId = _client.AppId = appId; _onHideUnity = onHideUnity; if (Settings.HasKey(TOKEN_KEY)) { AccessToken = EncryptionProvider.Decrypt(Settings.GetString(TOKEN_KEY), AppId); if (Settings.HasKey(EXPIRY_DATE)) { string expDate = EncryptionProvider.Decrypt(Settings.GetString(EXPIRY_DATE), AppId); Expires = DateTime.Parse(expDate, CultureInfo.InvariantCulture); } else { long expDate = Settings.GetLong(EXPIRY_DATE_BIN); Expires = DateTime.FromBinary(expDate); } _client.AccessToken = AccessToken; UserId = Settings.GetString(FBID_KEY); UserName = Settings.GetString(FBNAME_KEY); // verifies if the token has expired: if (DateTime.Compare(DateTime.UtcNow, Expires) > 0) InvalidateData(); //var task = TestAccessToken(); //task.Wait(); } if (onInitComplete != null) onInitComplete(); #else throw new PlatformNotSupportedException(""); #endif } public static void ChangeRedirect(string redirectUrl) { #if NETFX_CORE if (!string.IsNullOrEmpty(redirectUrl) && !_web.IsActive) _redirectUrl = redirectUrl; #endif } #if NETFX_CORE /// <summary> /// Test if the access token is still valid by making a simple API call /// </summary> /// <returns>The async task</returns> private static async Task TestAccessToken() { try { await _client.GetTaskAsync("/me?fields=id,name"); } catch (FacebookApiException) { // If any exception then auto login has been an issue. Set everything to null so the game // thinks the user is logged out and they can restart the login procedure InvalidateData(); } } private static void InvalidateData() { AccessToken = null; Expires = default(DateTime); UserId = null; UserName = null; _client.AccessToken = null; Settings.DeleteKey(TOKEN_KEY); Settings.DeleteKey(FBID_KEY); Settings.DeleteKey(FBNAME_KEY); Settings.DeleteKey(EXPIRY_DATE); Settings.DeleteKey(EXPIRY_DATE_BIN); } private static void HandleGetCompleted(object sender, FacebookApiEventArgs e) { var callback = e.UserState as FacebookDelegate; if (callback != null) { var result = new FBResult(); if (e.Cancelled) result.Error = "Cancelled"; else if (e.Error != null) result.Error = e.Error.Message; else { var obj = e.GetResultData(); result.Text = obj.ToString(); result.Json = obj as JsonObject; } Dispatcher.InvokeOnAppThread(() => { callback(result); }); } } #endif public static void API( string endpoint, HttpMethod method, FacebookDelegate callback, object parameters = null) { #if NETFX_CORE if (_web == null) throw new MissingPlatformException(); if (!IsLoggedIn) { // Already in use if (callback != null) callback(new FBResult() { Error = "Not logged in" }); return; } Task.Run(async () => { FBResult fbResult = null; try { object apiCall; if (method == HttpMethod.GET) { apiCall = await _client.GetTaskAsync(endpoint, parameters); } else if (method == HttpMethod.POST) { apiCall = await _client.PostTaskAsync(endpoint, parameters); } else { apiCall = await _client.DeleteTaskAsync(endpoint); } if (apiCall != null) { fbResult = new FBResult(); fbResult.Text = apiCall.ToString(); fbResult.Json = apiCall as JsonObject; } } catch (Exception ex) { fbResult = new FBResult(); fbResult.Error = ex.Message; } if (callback != null) { Dispatcher.InvokeOnAppThread(() => { callback(fbResult); }); } }); #else throw new PlatformNotSupportedException(""); #endif } public static void SetPlatformInterface(IWebInterface web) { #if NETFX_CORE _web = web; #else throw new PlatformNotSupportedException(""); #endif } /// <summary> /// Show Request Dialog. /// to, title, data, filters, excludeIds and maxRecipients are not currently supported at this time. /// </summary> public static void AppRequest( string message, string[] to = null, string filters = "", string[] excludeIds = null, int? maxRecipients = null, string data = "", string title = "", FacebookDelegate callback = null ) { #if NETFX_CORE /// /// @note: [vaughan.sanders 15.8.14] We are overriding the Unity FB.AppRequest here to send a more /// general web style request as WP8 does not support the actual request functionality. /// Currently we ignore all but the message and callback params /// if (_web == null) throw new MissingPlatformException(); if (_web.IsActive || !IsLoggedIn) { // Already in use if (callback != null) callback(new FBResult() { Error = "Already in use / Not Logged In" }); return; } if (_onHideUnity != null) _onHideUnity(true); Uri uri = new Uri("https://www.facebook.com/dialog/apprequests?app_id=" + AppId + "&message=" + message + "&display=popup&redirect_uri=" + _redirectUrl, UriKind.RelativeOrAbsolute); _web.Navigate(uri, true, finishedCallback: (url, state) => { if (url.ToString().StartsWith(_redirectUrl)) { // parsing query string to get request id and facebook ids of the people the request has been sent to // or error code and error messages FBResult fbResult = new FBResult(); fbResult.Json = new JsonObject(); string[] queries = url.Query.Split('&'); if (queries.Length > 0) { string request = string.Empty; List<string> toList = new List<string>(); foreach (string query in queries) { string[] keyValue = query.Split('='); if (keyValue.Length == 2) { if (keyValue[0].Contains("request")) request = keyValue[1]; else if (keyValue[0].Contains("to")) toList.Add(keyValue[1]); else if (keyValue[0].Contains("error_code")) fbResult.Error = keyValue[1]; else if (keyValue[0].Contains("error_message")) fbResult.Text = keyValue[1].Replace('+', ' '); } } if (!string.IsNullOrWhiteSpace(request)) { fbResult.Json.Add(new KeyValuePair<string, object>("request", request)); fbResult.Json.Add(new KeyValuePair<string, object>("to", toList)); } } // If there's no error, assign the success text if (string.IsNullOrWhiteSpace(fbResult.Text)) fbResult.Text = "Success"; _web.Finish(); if (_onHideUnity != null) _onHideUnity(false); if (callback != null) callback(fbResult); } }, onError: LoginNavigationError, state: callback); // throw not supported exception when user passed in parameters not supported currently if (!string.IsNullOrWhiteSpace(filters) || excludeIds != null || maxRecipients != null || to != null || !string.IsNullOrWhiteSpace(data) || !string.IsNullOrWhiteSpace(title)) throw new NotSupportedException("to, title, data, filters, excludeIds and maxRecipients are not currently supported at this time."); #else throw new PlatformNotSupportedException(""); #endif } /// <summary> /// Show the Feed Dialog. /// mediaSource, actionName, actionLink, reference and properties are not currently supported at this time. /// </summary> public static void Feed( string toId = "", string link = "", string linkName = "", string linkCaption = "", string linkDescription = "", string picture = "", string mediaSource = "", string actionName = "", string actionLink = "", string reference = "", Dictionary<string, string[]> properties = null, FacebookDelegate callback = null) { #if NETFX_CORE if (_web == null) throw new MissingPlatformException(); if (_web.IsActive || !IsLoggedIn) { // Already in use if (callback != null) callback(new FBResult() { Error = "Already in use / Not Logged In" }); return; } if (_onHideUnity != null) _onHideUnity(true); Uri uri = new Uri("https://www.facebook.com/dialog/feed?app_id=" + AppId + "&to=" + toId + "&link=" + link + "&name=" + linkName + "&caption=" + linkCaption + "&description=" + linkDescription + "&picture=" + picture + "&display=popup&redirect_uri=" + _redirectUrl, UriKind.RelativeOrAbsolute); _web.Navigate(uri, true, finishedCallback: (url, state) => { if (url.ToString().StartsWith(_redirectUrl)) { // parsing query string to get request id and facebook ids of the people the request has been sent to // or error code and error messages FBResult fbResult = new FBResult(); fbResult.Json = new JsonObject(); string[] queries = url.Query.Split('&'); if (queries.Length > 0) { string postId = string.Empty; List<string> toList = new List<string>(); foreach (string query in queries) { string[] keyValue = query.Split('='); if (keyValue.Length == 2) { if (keyValue[0].Contains("post_id")) postId = keyValue[1]; else if (keyValue[0].Contains("error_code")) fbResult.Error = keyValue[1]; else if (keyValue[0].Contains("error_msg")) fbResult.Text = keyValue[1].Replace('+', ' '); } } if (!string.IsNullOrWhiteSpace(postId)) { fbResult.Json.Add(new KeyValuePair<string, object>("post_id", postId)); } } // If there's no error, assign the success text if (string.IsNullOrWhiteSpace(fbResult.Text)) fbResult.Text = "Success"; _web.Finish(); if (_onHideUnity != null) _onHideUnity(false); if (callback != null) callback(fbResult); } }, onError: LoginNavigationError, state: callback); // throw not supported exception when user passed in parameters not supported currently if (!string.IsNullOrWhiteSpace(mediaSource) || !string.IsNullOrWhiteSpace(actionName) || !string.IsNullOrWhiteSpace(actionLink) || !string.IsNullOrWhiteSpace(reference) || properties != null) throw new NotSupportedException("mediaSource, actionName, actionLink, reference and properties are not currently supported at this time."); #else throw new PlatformNotSupportedException(""); #endif } } }
# CS_ARCH_SYSZ, 0, None 0xec,0x00,0x80,0x00,0x00,0xd9 = aghik %r0, %r0, -32768 0xec,0x00,0xff,0xff,0x00,0xd9 = aghik %r0, %r0, -1 0xec,0x00,0x00,0x00,0x00,0xd9 = aghik %r0, %r0, 0 0xec,0x00,0x00,0x01,0x00,0xd9 = aghik %r0, %r0, 1 0xec,0x00,0x7f,0xff,0x00,0xd9 = aghik %r0, %r0, 32767 0xec,0x0f,0x00,0x00,0x00,0xd9 = aghik %r0, %r15, 0 0xec,0xf0,0x00,0x00,0x00,0xd9 = aghik %r15, %r0, 0 0xec,0x78,0xff,0xf0,0x00,0xd9 = aghik %r7, %r8, -16 0xb9,0xe8,0x00,0x00 = agrk %r0, %r0, %r0 0xb9,0xe8,0xf0,0x00 = agrk %r0, %r0, %r15 0xb9,0xe8,0x00,0x0f = agrk %r0, %r15, %r0 0xb9,0xe8,0x00,0xf0 = agrk %r15, %r0, %r0 0xb9,0xe8,0x90,0x78 = agrk %r7, %r8, %r9 0xec,0x00,0x80,0x00,0x00,0xd8 = ahik %r0, %r0, -32768 0xec,0x00,0xff,0xff,0x00,0xd8 = ahik %r0, %r0, -1 0xec,0x00,0x00,0x00,0x00,0xd8 = ahik %r0, %r0, 0 0xec,0x00,0x00,0x01,0x00,0xd8 = ahik %r0, %r0, 1 0xec,0x00,0x7f,0xff,0x00,0xd8 = ahik %r0, %r0, 32767 0xec,0x0f,0x00,0x00,0x00,0xd8 = ahik %r0, %r15, 0 0xec,0xf0,0x00,0x00,0x00,0xd8 = ahik %r15, %r0, 0 0xec,0x78,0xff,0xf0,0x00,0xd8 = ahik %r7, %r8, -16 0xcc,0x08,0x80,0x00,0x00,0x00 = aih %r0, -2147483648 0xcc,0x08,0xff,0xff,0xff,0xff = aih %r0, -1 0xcc,0x08,0x00,0x00,0x00,0x00 = aih %r0, 0 0xcc,0x08,0x00,0x00,0x00,0x01 = aih %r0, 1 0xcc,0x08,0x7f,0xff,0xff,0xff = aih %r0, 2147483647 0xcc,0xf8,0x00,0x00,0x00,0x00 = aih %r15, 0 0xec,0x00,0x80,0x00,0x00,0xdb = alghsik %r0, %r0, -32768 0xec,0x00,0xff,0xff,0x00,0xdb = alghsik %r0, %r0, -1 0xec,0x00,0x00,0x00,0x00,0xdb = alghsik %r0, %r0, 0 0xec,0x00,0x00,0x01,0x00,0xdb = alghsik %r0, %r0, 1 0xec,0x00,0x7f,0xff,0x00,0xdb = alghsik %r0, %r0, 32767 0xec,0x0f,0x00,0x00,0x00,0xdb = alghsik %r0, %r15, 0 0xec,0xf0,0x00,0x00,0x00,0xdb = alghsik %r15, %r0, 0 0xec,0x78,0xff,0xf0,0x00,0xdb = alghsik %r7, %r8, -16 0xb9,0xea,0x00,0x00 = algrk %r0, %r0, %r0 0xb9,0xea,0xf0,0x00 = algrk %r0, %r0, %r15 0xb9,0xea,0x00,0x0f = algrk %r0, %r15, %r0 0xb9,0xea,0x00,0xf0 = algrk %r15, %r0, %r0 0xb9,0xea,0x90,0x78 = algrk %r7, %r8, %r9 0xec,0x00,0x80,0x00,0x00,0xda = alhsik %r0, %r0, -32768 0xec,0x00,0xff,0xff,0x00,0xda = alhsik %r0, %r0, -1 0xec,0x00,0x00,0x00,0x00,0xda = alhsik %r0, %r0, 0 0xec,0x00,0x00,0x01,0x00,0xda = alhsik %r0, %r0, 1 0xec,0x00,0x7f,0xff,0x00,0xda = alhsik %r0, %r0, 32767 0xec,0x0f,0x00,0x00,0x00,0xda = alhsik %r0, %r15, 0 0xec,0xf0,0x00,0x00,0x00,0xda = alhsik %r15, %r0, 0 0xec,0x78,0xff,0xf0,0x00,0xda = alhsik %r7, %r8, -16 0xb9,0xfa,0x00,0x00 = alrk %r0, %r0, %r0 0xb9,0xfa,0xf0,0x00 = alrk %r0, %r0, %r15 0xb9,0xfa,0x00,0x0f = alrk %r0, %r15, %r0 0xb9,0xfa,0x00,0xf0 = alrk %r15, %r0, %r0 0xb9,0xfa,0x90,0x78 = alrk %r7, %r8, %r9 0xb9,0xf8,0x00,0x00 = ark %r0, %r0, %r0 0xb9,0xf8,0xf0,0x00 = ark %r0, %r0, %r15 0xb9,0xf8,0x00,0x0f = ark %r0, %r15, %r0 0xb9,0xf8,0x00,0xf0 = ark %r15, %r0, %r0 0xb9,0xf8,0x90,0x78 = ark %r7, %r8, %r9 0xb3,0x91,0x00,0x00 = cdlfbr %f0, 0, %r0, 0 0xb3,0x91,0x0f,0x00 = cdlfbr %f0, 0, %r0, 15 0xb3,0x91,0x00,0x0f = cdlfbr %f0, 0, %r15, 0 0xb3,0x91,0xf0,0x00 = cdlfbr %f0, 15, %r0, 0 0xb3,0x91,0x57,0x46 = cdlfbr %f4, 5, %r6, 7 0xb3,0x91,0x00,0xf0 = cdlfbr %f15, 0, %r0, 0 0xb3,0xa1,0x00,0x00 = cdlgbr %f0, 0, %r0, 0 0xb3,0xa1,0x0f,0x00 = cdlgbr %f0, 0, %r0, 15 0xb3,0xa1,0x00,0x0f = cdlgbr %f0, 0, %r15, 0 0xb3,0xa1,0xf0,0x00 = cdlgbr %f0, 15, %r0, 0 0xb3,0xa1,0x57,0x46 = cdlgbr %f4, 5, %r6, 7 0xb3,0xa1,0x00,0xf0 = cdlgbr %f15, 0, %r0, 0 0xb3,0x90,0x00,0x00 = celfbr %f0, 0, %r0, 0 0xb3,0x90,0x0f,0x00 = celfbr %f0, 0, %r0, 15 0xb3,0x90,0x00,0x0f = celfbr %f0, 0, %r15, 0 0xb3,0x90,0xf0,0x00 = celfbr %f0, 15, %r0, 0 0xb3,0x90,0x57,0x46 = celfbr %f4, 5, %r6, 7 0xb3,0x90,0x00,0xf0 = celfbr %f15, 0, %r0, 0 0xb3,0xa0,0x00,0x00 = celgbr %f0, 0, %r0, 0 0xb3,0xa0,0x0f,0x00 = celgbr %f0, 0, %r0, 15 0xb3,0xa0,0x00,0x0f = celgbr %f0, 0, %r15, 0 0xb3,0xa0,0xf0,0x00 = celgbr %f0, 15, %r0, 0 0xb3,0xa0,0x57,0x46 = celgbr %f4, 5, %r6, 7 0xb3,0xa0,0x00,0xf0 = celgbr %f15, 0, %r0, 0 0xe3,0x00,0x00,0x00,0x80,0xcd = chf %r0, -524288 0xe3,0x00,0x0f,0xff,0xff,0xcd = chf %r0, -1 0xe3,0x00,0x00,0x00,0x00,0xcd = chf %r0, 0 0xe3,0x00,0x00,0x01,0x00,0xcd = chf %r0, 1 0xe3,0x00,0x0f,0xff,0x7f,0xcd = chf %r0, 524287 0xe3,0x00,0x10,0x00,0x00,0xcd = chf %r0, 0(%r1) 0xe3,0x00,0xf0,0x00,0x00,0xcd = chf %r0, 0(%r15) 0xe3,0x01,0xff,0xff,0x7f,0xcd = chf %r0, 524287(%r1, %r15) 0xe3,0x0f,0x1f,0xff,0x7f,0xcd = chf %r0, 524287(%r15, %r1) 0xe3,0xf0,0x00,0x00,0x00,0xcd = chf %r15, 0 0xcc,0x0d,0x80,0x00,0x00,0x00 = cih %r0, -2147483648 0xcc,0x0d,0xff,0xff,0xff,0xff = cih %r0, -1 0xcc,0x0d,0x00,0x00,0x00,0x00 = cih %r0, 0 0xcc,0x0d,0x00,0x00,0x00,0x01 = cih %r0, 1 0xcc,0x0d,0x7f,0xff,0xff,0xff = cih %r0, 2147483647 0xcc,0xfd,0x00,0x00,0x00,0x00 = cih %r15, 0 0xb3,0x9d,0x00,0x00 = clfdbr %r0, 0, %f0, 0 0xb3,0x9d,0x0f,0x00 = clfdbr %r0, 0, %f0, 15 0xb3,0x9d,0x00,0x0f = clfdbr %r0, 0, %f15, 0 0xb3,0x9d,0xf0,0x00 = clfdbr %r0, 15, %f0, 0 0xb3,0x9d,0x57,0x46 = clfdbr %r4, 5, %f6, 7 0xb3,0x9d,0x00,0xf0 = clfdbr %r15, 0, %f0, 0 0xb3,0x9c,0x00,0x00 = clfebr %r0, 0, %f0, 0 0xb3,0x9c,0x0f,0x00 = clfebr %r0, 0, %f0, 15 0xb3,0x9c,0x00,0x0f = clfebr %r0, 0, %f15, 0 0xb3,0x9c,0xf0,0x00 = clfebr %r0, 15, %f0, 0 0xb3,0x9c,0x57,0x46 = clfebr %r4, 5, %f6, 7 0xb3,0x9c,0x00,0xf0 = clfebr %r15, 0, %f0, 0 0xb3,0x9e,0x00,0x00 = clfxbr %r0, 0, %f0, 0 0xb3,0x9e,0x0f,0x00 = clfxbr %r0, 0, %f0, 15 0xb3,0x9e,0x00,0x0d = clfxbr %r0, 0, %f13, 0 0xb3,0x9e,0xf0,0x00 = clfxbr %r0, 15, %f0, 0 0xb3,0x9e,0x59,0x78 = clfxbr %r7, 5, %f8, 9 0xb3,0x9e,0x00,0xf0 = clfxbr %r15, 0, %f0, 0 0xb3,0xad,0x00,0x00 = clgdbr %r0, 0, %f0, 0 0xb3,0xad,0x0f,0x00 = clgdbr %r0, 0, %f0, 15 0xb3,0xad,0x00,0x0f = clgdbr %r0, 0, %f15, 0 0xb3,0xad,0xf0,0x00 = clgdbr %r0, 15, %f0, 0 0xb3,0xad,0x57,0x46 = clgdbr %r4, 5, %f6, 7 0xb3,0xad,0x00,0xf0 = clgdbr %r15, 0, %f0, 0 0xb3,0xac,0x00,0x00 = clgebr %r0, 0, %f0, 0 0xb3,0xac,0x0f,0x00 = clgebr %r0, 0, %f0, 15 0xb3,0xac,0x00,0x0f = clgebr %r0, 0, %f15, 0 0xb3,0xac,0xf0,0x00 = clgebr %r0, 15, %f0, 0 0xb3,0xac,0x57,0x46 = clgebr %r4, 5, %f6, 7 0xb3,0xac,0x00,0xf0 = clgebr %r15, 0, %f0, 0 0xb3,0xae,0x00,0x00 = clgxbr %r0, 0, %f0, 0 0xb3,0xae,0x0f,0x00 = clgxbr %r0, 0, %f0, 15 0xb3,0xae,0x00,0x0d = clgxbr %r0, 0, %f13, 0 0xb3,0xae,0xf0,0x00 = clgxbr %r0, 15, %f0, 0 0xb3,0xae,0x59,0x78 = clgxbr %r7, 5, %f8, 9 0xb3,0xae,0x00,0xf0 = clgxbr %r15, 0, %f0, 0 0xe3,0x00,0x00,0x00,0x80,0xcf = clhf %r0, -524288 0xe3,0x00,0x0f,0xff,0xff,0xcf = clhf %r0, -1 0xe3,0x00,0x00,0x00,0x00,0xcf = clhf %r0, 0 0xe3,0x00,0x00,0x01,0x00,0xcf = clhf %r0, 1 0xe3,0x00,0x0f,0xff,0x7f,0xcf = clhf %r0, 524287 0xe3,0x00,0x10,0x00,0x00,0xcf = clhf %r0, 0(%r1) 0xe3,0x00,0xf0,0x00,0x00,0xcf = clhf %r0, 0(%r15) 0xe3,0x01,0xff,0xff,0x7f,0xcf = clhf %r0, 524287(%r1, %r15) 0xe3,0x0f,0x1f,0xff,0x7f,0xcf = clhf %r0, 524287(%r15, %r1) 0xe3,0xf0,0x00,0x00,0x00,0xcf = clhf %r15, 0 0xcc,0x0f,0x00,0x00,0x00,0x00 = clih %r0, 0 0xcc,0x0f,0x00,0x00,0x00,0x01 = clih %r0, 1 0xcc,0x0f,0xff,0xff,0xff,0xff = clih %r0, 4294967295 0xcc,0xff,0x00,0x00,0x00,0x00 = clih %r15, 0 0xb3,0x92,0x00,0x00 = cxlfbr %f0, 0, %r0, 0 0xb3,0x92,0x0f,0x00 = cxlfbr %f0, 0, %r0, 15 0xb3,0x92,0x00,0x0f = cxlfbr %f0, 0, %r15, 0 0xb3,0x92,0xf0,0x00 = cxlfbr %f0, 15, %r0, 0 0xb3,0x92,0x5a,0x49 = cxlfbr %f4, 5, %r9, 10 0xb3,0x92,0x00,0xd0 = cxlfbr %f13, 0, %r0, 0 0xb3,0xa2,0x00,0x00 = cxlgbr %f0, 0, %r0, 0 0xb3,0xa2,0x0f,0x00 = cxlgbr %f0, 0, %r0, 15 0xb3,0xa2,0x00,0x0f = cxlgbr %f0, 0, %r15, 0 0xb3,0xa2,0xf0,0x00 = cxlgbr %f0, 15, %r0, 0 0xb3,0xa2,0x5a,0x49 = cxlgbr %f4, 5, %r9, 10 0xb3,0xa2,0x00,0xd0 = cxlgbr %f13, 0, %r0, 0 // 0xb3,0x5f,0x00,0x00 = fidbra %f0, 0, %f0, 0 0xb3,0x5f,0x0f,0x00 = fidbra %f0, 0, %f0, 15 // 0xb3,0x5f,0x00,0x0f = fidbra %f0, 0, %f15, 0 // 0xb3,0x5f,0xf0,0x00 = fidbra %f0, 15, %f0, 0 0xb3,0x5f,0x57,0x46 = fidbra %f4, 5, %f6, 7 // 0xb3,0x5f,0x00,0xf0 = fidbra %f15, 0, %f0, 0 // 0xb3,0x57,0x00,0x00 = fiebra %f0, 0, %f0, 0 0xb3,0x57,0x0f,0x00 = fiebra %f0, 0, %f0, 15 // 0xb3,0x57,0x00,0x0f = fiebra %f0, 0, %f15, 0 // 0xb3,0x57,0xf0,0x00 = fiebra %f0, 15, %f0, 0 0xb3,0x57,0x57,0x46 = fiebra %f4, 5, %f6, 7 // 0xb3,0x57,0x00,0xf0 = fiebra %f15, 0, %f0, 0 // 0xb3,0x47,0x00,0x00 = fixbra %f0, 0, %f0, 0 0xb3,0x47,0x0f,0x00 = fixbra %f0, 0, %f0, 15 // 0xb3,0x47,0x00,0x0d = fixbra %f0, 0, %f13, 0 // 0xb3,0x47,0xf0,0x00 = fixbra %f0, 15, %f0, 0 0xb3,0x47,0x59,0x48 = fixbra %f4, 5, %f8, 9 // 0xb3,0x47,0x00,0xd0 = fixbra %f13, 0, %f0, 0 0xeb,0x00,0x00,0x00,0x80,0xf8 = laa %r0, %r0, -524288 0xeb,0x00,0x0f,0xff,0xff,0xf8 = laa %r0, %r0, -1 0xeb,0x00,0x00,0x00,0x00,0xf8 = laa %r0, %r0, 0 0xeb,0x00,0x00,0x01,0x00,0xf8 = laa %r0, %r0, 1 0xeb,0x00,0x0f,0xff,0x7f,0xf8 = laa %r0, %r0, 524287 0xeb,0x00,0x10,0x00,0x00,0xf8 = laa %r0, %r0, 0(%r1) 0xeb,0x00,0xf0,0x00,0x00,0xf8 = laa %r0, %r0, 0(%r15) 0xeb,0x00,0x1f,0xff,0x7f,0xf8 = laa %r0, %r0, 524287(%r1) 0xeb,0x00,0xff,0xff,0x7f,0xf8 = laa %r0, %r0, 524287(%r15) 0xeb,0x0f,0x00,0x00,0x00,0xf8 = laa %r0, %r15, 0 0xeb,0xf0,0x00,0x00,0x00,0xf8 = laa %r15, %r0, 0 0xeb,0x00,0x00,0x00,0x80,0xe8 = laag %r0, %r0, -524288 0xeb,0x00,0x0f,0xff,0xff,0xe8 = laag %r0, %r0, -1 0xeb,0x00,0x00,0x00,0x00,0xe8 = laag %r0, %r0, 0 0xeb,0x00,0x00,0x01,0x00,0xe8 = laag %r0, %r0, 1 0xeb,0x00,0x0f,0xff,0x7f,0xe8 = laag %r0, %r0, 524287 0xeb,0x00,0x10,0x00,0x00,0xe8 = laag %r0, %r0, 0(%r1) 0xeb,0x00,0xf0,0x00,0x00,0xe8 = laag %r0, %r0, 0(%r15) 0xeb,0x00,0x1f,0xff,0x7f,0xe8 = laag %r0, %r0, 524287(%r1) 0xeb,0x00,0xff,0xff,0x7f,0xe8 = laag %r0, %r0, 524287(%r15) 0xeb,0x0f,0x00,0x00,0x00,0xe8 = laag %r0, %r15, 0 0xeb,0xf0,0x00,0x00,0x00,0xe8 = laag %r15, %r0, 0 0xeb,0x00,0x00,0x00,0x80,0xfa = laal %r0, %r0, -524288 0xeb,0x00,0x0f,0xff,0xff,0xfa = laal %r0, %r0, -1 0xeb,0x00,0x00,0x00,0x00,0xfa = laal %r0, %r0, 0 0xeb,0x00,0x00,0x01,0x00,0xfa = laal %r0, %r0, 1 0xeb,0x00,0x0f,0xff,0x7f,0xfa = laal %r0, %r0, 524287 0xeb,0x00,0x10,0x00,0x00,0xfa = laal %r0, %r0, 0(%r1) 0xeb,0x00,0xf0,0x00,0x00,0xfa = laal %r0, %r0, 0(%r15) 0xeb,0x00,0x1f,0xff,0x7f,0xfa = laal %r0, %r0, 524287(%r1) 0xeb,0x00,0xff,0xff,0x7f,0xfa = laal %r0, %r0, 524287(%r15) 0xeb,0x0f,0x00,0x00,0x00,0xfa = laal %r0, %r15, 0 0xeb,0xf0,0x00,0x00,0x00,0xfa = laal %r15, %r0, 0 0xeb,0x00,0x00,0x00,0x80,0xea = laalg %r0, %r0, -524288 0xeb,0x00,0x0f,0xff,0xff,0xea = laalg %r0, %r0, -1 0xeb,0x00,0x00,0x00,0x00,0xea = laalg %r0, %r0, 0 0xeb,0x00,0x00,0x01,0x00,0xea = laalg %r0, %r0, 1 0xeb,0x00,0x0f,0xff,0x7f,0xea = laalg %r0, %r0, 524287 0xeb,0x00,0x10,0x00,0x00,0xea = laalg %r0, %r0, 0(%r1) 0xeb,0x00,0xf0,0x00,0x00,0xea = laalg %r0, %r0, 0(%r15) 0xeb,0x00,0x1f,0xff,0x7f,0xea = laalg %r0, %r0, 524287(%r1) 0xeb,0x00,0xff,0xff,0x7f,0xea = laalg %r0, %r0, 524287(%r15) 0xeb,0x0f,0x00,0x00,0x00,0xea = laalg %r0, %r15, 0 0xeb,0xf0,0x00,0x00,0x00,0xea = laalg %r15, %r0, 0 0xeb,0x00,0x00,0x00,0x80,0xf4 = lan %r0, %r0, -524288 0xeb,0x00,0x0f,0xff,0xff,0xf4 = lan %r0, %r0, -1 0xeb,0x00,0x00,0x00,0x00,0xf4 = lan %r0, %r0, 0 0xeb,0x00,0x00,0x01,0x00,0xf4 = lan %r0, %r0, 1 0xeb,0x00,0x0f,0xff,0x7f,0xf4 = lan %r0, %r0, 524287 0xeb,0x00,0x10,0x00,0x00,0xf4 = lan %r0, %r0, 0(%r1) 0xeb,0x00,0xf0,0x00,0x00,0xf4 = lan %r0, %r0, 0(%r15) 0xeb,0x00,0x1f,0xff,0x7f,0xf4 = lan %r0, %r0, 524287(%r1) 0xeb,0x00,0xff,0xff,0x7f,0xf4 = lan %r0, %r0, 524287(%r15) 0xeb,0x0f,0x00,0x00,0x00,0xf4 = lan %r0, %r15, 0 0xeb,0xf0,0x00,0x00,0x00,0xf4 = lan %r15, %r0, 0 0xeb,0x00,0x00,0x00,0x80,0xe4 = lang %r0, %r0, -524288 0xeb,0x00,0x0f,0xff,0xff,0xe4 = lang %r0, %r0, -1 0xeb,0x00,0x00,0x00,0x00,0xe4 = lang %r0, %r0, 0 0xeb,0x00,0x00,0x01,0x00,0xe4 = lang %r0, %r0, 1 0xeb,0x00,0x0f,0xff,0x7f,0xe4 = lang %r0, %r0, 524287 0xeb,0x00,0x10,0x00,0x00,0xe4 = lang %r0, %r0, 0(%r1) 0xeb,0x00,0xf0,0x00,0x00,0xe4 = lang %r0, %r0, 0(%r15) 0xeb,0x00,0x1f,0xff,0x7f,0xe4 = lang %r0, %r0, 524287(%r1) 0xeb,0x00,0xff,0xff,0x7f,0xe4 = lang %r0, %r0, 524287(%r15) 0xeb,0x0f,0x00,0x00,0x00,0xe4 = lang %r0, %r15, 0 0xeb,0xf0,0x00,0x00,0x00,0xe4 = lang %r15, %r0, 0 0xeb,0x00,0x00,0x00,0x80,0xf6 = lao %r0, %r0, -524288 0xeb,0x00,0x0f,0xff,0xff,0xf6 = lao %r0, %r0, -1 0xeb,0x00,0x00,0x00,0x00,0xf6 = lao %r0, %r0, 0 0xeb,0x00,0x00,0x01,0x00,0xf6 = lao %r0, %r0, 1 0xeb,0x00,0x0f,0xff,0x7f,0xf6 = lao %r0, %r0, 524287 0xeb,0x00,0x10,0x00,0x00,0xf6 = lao %r0, %r0, 0(%r1) 0xeb,0x00,0xf0,0x00,0x00,0xf6 = lao %r0, %r0, 0(%r15) 0xeb,0x00,0x1f,0xff,0x7f,0xf6 = lao %r0, %r0, 524287(%r1) 0xeb,0x00,0xff,0xff,0x7f,0xf6 = lao %r0, %r0, 524287(%r15) 0xeb,0x0f,0x00,0x00,0x00,0xf6 = lao %r0, %r15, 0 0xeb,0xf0,0x00,0x00,0x00,0xf6 = lao %r15, %r0, 0 0xeb,0x00,0x00,0x00,0x80,0xe6 = laog %r0, %r0, -524288 0xeb,0x00,0x0f,0xff,0xff,0xe6 = laog %r0, %r0, -1 0xeb,0x00,0x00,0x00,0x00,0xe6 = laog %r0, %r0, 0 0xeb,0x00,0x00,0x01,0x00,0xe6 = laog %r0, %r0, 1 0xeb,0x00,0x0f,0xff,0x7f,0xe6 = laog %r0, %r0, 524287 0xeb,0x00,0x10,0x00,0x00,0xe6 = laog %r0, %r0, 0(%r1) 0xeb,0x00,0xf0,0x00,0x00,0xe6 = laog %r0, %r0, 0(%r15) 0xeb,0x00,0x1f,0xff,0x7f,0xe6 = laog %r0, %r0, 524287(%r1) 0xeb,0x00,0xff,0xff,0x7f,0xe6 = laog %r0, %r0, 524287(%r15) 0xeb,0x0f,0x00,0x00,0x00,0xe6 = laog %r0, %r15, 0 0xeb,0xf0,0x00,0x00,0x00,0xe6 = laog %r15, %r0, 0 0xeb,0x00,0x00,0x00,0x80,0xf7 = lax %r0, %r0, -524288 0xeb,0x00,0x0f,0xff,0xff,0xf7 = lax %r0, %r0, -1 0xeb,0x00,0x00,0x00,0x00,0xf7 = lax %r0, %r0, 0 0xeb,0x00,0x00,0x01,0x00,0xf7 = lax %r0, %r0, 1 0xeb,0x00,0x0f,0xff,0x7f,0xf7 = lax %r0, %r0, 524287 0xeb,0x00,0x10,0x00,0x00,0xf7 = lax %r0, %r0, 0(%r1) 0xeb,0x00,0xf0,0x00,0x00,0xf7 = lax %r0, %r0, 0(%r15) 0xeb,0x00,0x1f,0xff,0x7f,0xf7 = lax %r0, %r0, 524287(%r1) 0xeb,0x00,0xff,0xff,0x7f,0xf7 = lax %r0, %r0, 524287(%r15) 0xeb,0x0f,0x00,0x00,0x00,0xf7 = lax %r0, %r15, 0 0xeb,0xf0,0x00,0x00,0x00,0xf7 = lax %r15, %r0, 0 0xeb,0x00,0x00,0x00,0x80,0xe7 = laxg %r0, %r0, -524288 0xeb,0x00,0x0f,0xff,0xff,0xe7 = laxg %r0, %r0, -1 0xeb,0x00,0x00,0x00,0x00,0xe7 = laxg %r0, %r0, 0 0xeb,0x00,0x00,0x01,0x00,0xe7 = laxg %r0, %r0, 1 0xeb,0x00,0x0f,0xff,0x7f,0xe7 = laxg %r0, %r0, 524287 0xeb,0x00,0x10,0x00,0x00,0xe7 = laxg %r0, %r0, 0(%r1) 0xeb,0x00,0xf0,0x00,0x00,0xe7 = laxg %r0, %r0, 0(%r15) 0xeb,0x00,0x1f,0xff,0x7f,0xe7 = laxg %r0, %r0, 524287(%r1) 0xeb,0x00,0xff,0xff,0x7f,0xe7 = laxg %r0, %r0, 524287(%r15) 0xeb,0x0f,0x00,0x00,0x00,0xe7 = laxg %r0, %r15, 0 0xeb,0xf0,0x00,0x00,0x00,0xe7 = laxg %r15, %r0, 0 0xe3,0x00,0x00,0x00,0x80,0xc0 = lbh %r0, -524288 0xe3,0x00,0x0f,0xff,0xff,0xc0 = lbh %r0, -1 0xe3,0x00,0x00,0x00,0x00,0xc0 = lbh %r0, 0 0xe3,0x00,0x00,0x01,0x00,0xc0 = lbh %r0, 1 0xe3,0x00,0x0f,0xff,0x7f,0xc0 = lbh %r0, 524287 0xe3,0x00,0x10,0x00,0x00,0xc0 = lbh %r0, 0(%r1) 0xe3,0x00,0xf0,0x00,0x00,0xc0 = lbh %r0, 0(%r15) 0xe3,0x01,0xff,0xff,0x7f,0xc0 = lbh %r0, 524287(%r1, %r15) 0xe3,0x0f,0x1f,0xff,0x7f,0xc0 = lbh %r0, 524287(%r15, %r1) 0xe3,0xf0,0x00,0x00,0x00,0xc0 = lbh %r15, 0 0xe3,0x00,0x00,0x00,0x80,0xca = lfh %r0, -524288 0xe3,0x00,0x0f,0xff,0xff,0xca = lfh %r0, -1 0xe3,0x00,0x00,0x00,0x00,0xca = lfh %r0, 0 0xe3,0x00,0x00,0x01,0x00,0xca = lfh %r0, 1 0xe3,0x00,0x0f,0xff,0x7f,0xca = lfh %r0, 524287 0xe3,0x00,0x10,0x00,0x00,0xca = lfh %r0, 0(%r1) 0xe3,0x00,0xf0,0x00,0x00,0xca = lfh %r0, 0(%r15) 0xe3,0x01,0xff,0xff,0x7f,0xca = lfh %r0, 524287(%r1, %r15) 0xe3,0x0f,0x1f,0xff,0x7f,0xca = lfh %r0, 524287(%r15, %r1) 0xe3,0xf0,0x00,0x00,0x00,0xca = lfh %r15, 0 0xe3,0x00,0x00,0x00,0x80,0xc4 = lhh %r0, -524288 0xe3,0x00,0x0f,0xff,0xff,0xc4 = lhh %r0, -1 0xe3,0x00,0x00,0x00,0x00,0xc4 = lhh %r0, 0 0xe3,0x00,0x00,0x01,0x00,0xc4 = lhh %r0, 1 0xe3,0x00,0x0f,0xff,0x7f,0xc4 = lhh %r0, 524287 0xe3,0x00,0x10,0x00,0x00,0xc4 = lhh %r0, 0(%r1) 0xe3,0x00,0xf0,0x00,0x00,0xc4 = lhh %r0, 0(%r15) 0xe3,0x01,0xff,0xff,0x7f,0xc4 = lhh %r0, 524287(%r1, %r15) 0xe3,0x0f,0x1f,0xff,0x7f,0xc4 = lhh %r0, 524287(%r15, %r1) 0xe3,0xf0,0x00,0x00,0x00,0xc4 = lhh %r15, 0 0xe3,0x00,0x00,0x00,0x80,0xc2 = llch %r0, -524288 0xe3,0x00,0x0f,0xff,0xff,0xc2 = llch %r0, -1 0xe3,0x00,0x00,0x00,0x00,0xc2 = llch %r0, 0 0xe3,0x00,0x00,0x01,0x00,0xc2 = llch %r0, 1 0xe3,0x00,0x0f,0xff,0x7f,0xc2 = llch %r0, 524287 0xe3,0x00,0x10,0x00,0x00,0xc2 = llch %r0, 0(%r1) 0xe3,0x00,0xf0,0x00,0x00,0xc2 = llch %r0, 0(%r15) 0xe3,0x01,0xff,0xff,0x7f,0xc2 = llch %r0, 524287(%r1, %r15) 0xe3,0x0f,0x1f,0xff,0x7f,0xc2 = llch %r0, 524287(%r15, %r1) 0xe3,0xf0,0x00,0x00,0x00,0xc2 = llch %r15, 0 0xe3,0x00,0x00,0x00,0x80,0xc6 = llhh %r0, -524288 0xe3,0x00,0x0f,0xff,0xff,0xc6 = llhh %r0, -1 0xe3,0x00,0x00,0x00,0x00,0xc6 = llhh %r0, 0 0xe3,0x00,0x00,0x01,0x00,0xc6 = llhh %r0, 1 0xe3,0x00,0x0f,0xff,0x7f,0xc6 = llhh %r0, 524287 0xe3,0x00,0x10,0x00,0x00,0xc6 = llhh %r0, 0(%r1) 0xe3,0x00,0xf0,0x00,0x00,0xc6 = llhh %r0, 0(%r15) 0xe3,0x01,0xff,0xff,0x7f,0xc6 = llhh %r0, 524287(%r1, %r15) 0xe3,0x0f,0x1f,0xff,0x7f,0xc6 = llhh %r0, 524287(%r15, %r1) 0xe3,0xf0,0x00,0x00,0x00,0xc6 = llhh %r15, 0 0xeb,0x00,0x00,0x00,0x00,0xf2 = loc %r0, 0, 0 0xeb,0x0f,0x00,0x00,0x00,0xf2 = loc %r0, 0, 15 0xeb,0x00,0x00,0x00,0x80,0xf2 = loc %r0, -524288, 0 0xeb,0x00,0x0f,0xff,0x7f,0xf2 = loc %r0, 524287, 0 0xeb,0x00,0x10,0x00,0x00,0xf2 = loc %r0, 0(%r1), 0 0xeb,0x00,0xf0,0x00,0x00,0xf2 = loc %r0, 0(%r15), 0 0xeb,0xf0,0x00,0x00,0x00,0xf2 = loc %r15, 0, 0 // 0xeb,0x13,0x2f,0xff,0x00,0xf2 = loc %r1, 4095(%r2), 3 0xeb,0x11,0x30,0x02,0x00,0xf2 = loco %r1, 2(%r3) 0xeb,0x12,0x30,0x02,0x00,0xf2 = loch %r1, 2(%r3) 0xeb,0x13,0x30,0x02,0x00,0xf2 = locnle %r1, 2(%r3) 0xeb,0x14,0x30,0x02,0x00,0xf2 = locl %r1, 2(%r3) 0xeb,0x15,0x30,0x02,0x00,0xf2 = locnhe %r1, 2(%r3) 0xeb,0x16,0x30,0x02,0x00,0xf2 = loclh %r1, 2(%r3) 0xeb,0x17,0x30,0x02,0x00,0xf2 = locne %r1, 2(%r3) 0xeb,0x18,0x30,0x02,0x00,0xf2 = loce %r1, 2(%r3) 0xeb,0x19,0x30,0x02,0x00,0xf2 = locnlh %r1, 2(%r3) 0xeb,0x1a,0x30,0x02,0x00,0xf2 = loche %r1, 2(%r3) 0xeb,0x1b,0x30,0x02,0x00,0xf2 = locnl %r1, 2(%r3) 0xeb,0x1c,0x30,0x02,0x00,0xf2 = locle %r1, 2(%r3) 0xeb,0x1d,0x30,0x02,0x00,0xf2 = locnh %r1, 2(%r3) 0xeb,0x1e,0x30,0x02,0x00,0xf2 = locno %r1, 2(%r3) 0xeb,0x00,0x00,0x00,0x00,0xe2 = locg %r0, 0, 0 0xeb,0x0f,0x00,0x00,0x00,0xe2 = locg %r0, 0, 15 0xeb,0x00,0x00,0x00,0x80,0xe2 = locg %r0, -524288, 0 0xeb,0x00,0x0f,0xff,0x7f,0xe2 = locg %r0, 524287, 0 0xeb,0x00,0x10,0x00,0x00,0xe2 = locg %r0, 0(%r1), 0 0xeb,0x00,0xf0,0x00,0x00,0xe2 = locg %r0, 0(%r15), 0 0xeb,0xf0,0x00,0x00,0x00,0xe2 = locg %r15, 0, 0 // 0xeb,0x13,0x2f,0xff,0x00,0xe2 = locg %r1, 4095(%r2), 3 0xeb,0x11,0x30,0x02,0x00,0xe2 = locgo %r1, 2(%r3) 0xeb,0x12,0x30,0x02,0x00,0xe2 = locgh %r1, 2(%r3) 0xeb,0x13,0x30,0x02,0x00,0xe2 = locgnle %r1, 2(%r3) 0xeb,0x14,0x30,0x02,0x00,0xe2 = locgl %r1, 2(%r3) 0xeb,0x15,0x30,0x02,0x00,0xe2 = locgnhe %r1, 2(%r3) 0xeb,0x16,0x30,0x02,0x00,0xe2 = locglh %r1, 2(%r3) 0xeb,0x17,0x30,0x02,0x00,0xe2 = locgne %r1, 2(%r3) 0xeb,0x18,0x30,0x02,0x00,0xe2 = locge %r1, 2(%r3) 0xeb,0x19,0x30,0x02,0x00,0xe2 = locgnlh %r1, 2(%r3) 0xeb,0x1a,0x30,0x02,0x00,0xe2 = locghe %r1, 2(%r3) 0xeb,0x1b,0x30,0x02,0x00,0xe2 = locgnl %r1, 2(%r3) 0xeb,0x1c,0x30,0x02,0x00,0xe2 = locgle %r1, 2(%r3) 0xeb,0x1d,0x30,0x02,0x00,0xe2 = locgnh %r1, 2(%r3) 0xeb,0x1e,0x30,0x02,0x00,0xe2 = locgno %r1, 2(%r3) 0xb9,0xe2,0x00,0x12 = locgr %r1, %r2, 0 0xb9,0xe2,0xf0,0x12 = locgr %r1, %r2, 15 0xb9,0xe2,0x10,0x13 = locgro %r1, %r3 0xb9,0xe2,0x20,0x13 = locgrh %r1, %r3 0xb9,0xe2,0x30,0x13 = locgrnle %r1, %r3 0xb9,0xe2,0x40,0x13 = locgrl %r1, %r3 0xb9,0xe2,0x50,0x13 = locgrnhe %r1, %r3 0xb9,0xe2,0x60,0x13 = locgrlh %r1, %r3 0xb9,0xe2,0x70,0x13 = locgrne %r1, %r3 0xb9,0xe2,0x80,0x13 = locgre %r1, %r3 0xb9,0xe2,0x90,0x13 = locgrnlh %r1, %r3 0xb9,0xe2,0xa0,0x13 = locgrhe %r1, %r3 0xb9,0xe2,0xb0,0x13 = locgrnl %r1, %r3 0xb9,0xe2,0xc0,0x13 = locgrle %r1, %r3 0xb9,0xe2,0xd0,0x13 = locgrnh %r1, %r3 0xb9,0xe2,0xe0,0x13 = locgrno %r1, %r3 0xb9,0xf2,0x00,0x12 = locr %r1, %r2, 0 0xb9,0xf2,0xf0,0x12 = locr %r1, %r2, 15 0xb9,0xf2,0x10,0x13 = locro %r1, %r3 0xb9,0xf2,0x20,0x13 = locrh %r1, %r3 0xb9,0xf2,0x30,0x13 = locrnle %r1, %r3 0xb9,0xf2,0x40,0x13 = locrl %r1, %r3 0xb9,0xf2,0x50,0x13 = locrnhe %r1, %r3 0xb9,0xf2,0x60,0x13 = locrlh %r1, %r3 0xb9,0xf2,0x70,0x13 = locrne %r1, %r3 0xb9,0xf2,0x80,0x13 = locre %r1, %r3 0xb9,0xf2,0x90,0x13 = locrnlh %r1, %r3 0xb9,0xf2,0xa0,0x13 = locrhe %r1, %r3 0xb9,0xf2,0xb0,0x13 = locrnl %r1, %r3 0xb9,0xf2,0xc0,0x13 = locrle %r1, %r3 0xb9,0xf2,0xd0,0x13 = locrnh %r1, %r3 0xb9,0xf2,0xe0,0x13 = locrno %r1, %r3 0xb9,0xe4,0x00,0x00 = ngrk %r0, %r0, %r0 0xb9,0xe4,0xf0,0x00 = ngrk %r0, %r0, %r15 0xb9,0xe4,0x00,0x0f = ngrk %r0, %r15, %r0 0xb9,0xe4,0x00,0xf0 = ngrk %r15, %r0, %r0 0xb9,0xe4,0x90,0x78 = ngrk %r7, %r8, %r9 0xb9,0xf4,0x00,0x00 = nrk %r0, %r0, %r0 0xb9,0xf4,0xf0,0x00 = nrk %r0, %r0, %r15 0xb9,0xf4,0x00,0x0f = nrk %r0, %r15, %r0 0xb9,0xf4,0x00,0xf0 = nrk %r15, %r0, %r0 0xb9,0xf4,0x90,0x78 = nrk %r7, %r8, %r9 0xb9,0xe6,0x00,0x00 = ogrk %r0, %r0, %r0 0xb9,0xe6,0xf0,0x00 = ogrk %r0, %r0, %r15 0xb9,0xe6,0x00,0x0f = ogrk %r0, %r15, %r0 0xb9,0xe6,0x00,0xf0 = ogrk %r15, %r0, %r0 0xb9,0xe6,0x90,0x78 = ogrk %r7, %r8, %r9 0xb9,0xf6,0x00,0x00 = ork %r0, %r0, %r0 0xb9,0xf6,0xf0,0x00 = ork %r0, %r0, %r15 0xb9,0xf6,0x00,0x0f = ork %r0, %r15, %r0 0xb9,0xf6,0x00,0xf0 = ork %r15, %r0, %r0 0xb9,0xf6,0x90,0x78 = ork %r7, %r8, %r9 0xec,0x00,0x00,0x00,0x00,0x5d = risbhg %r0, %r0, 0, 0, 0 0xec,0x00,0x00,0x00,0x3f,0x5d = risbhg %r0, %r0, 0, 0, 63 0xec,0x00,0x00,0xff,0x00,0x5d = risbhg %r0, %r0, 0, 255, 0 0xec,0x00,0xff,0x00,0x00,0x5d = risbhg %r0, %r0, 255, 0, 0 0xec,0x0f,0x00,0x00,0x00,0x5d = risbhg %r0, %r15, 0, 0, 0 0xec,0xf0,0x00,0x00,0x00,0x5d = risbhg %r15, %r0, 0, 0, 0 0xec,0x45,0x06,0x07,0x08,0x5d = risbhg %r4, %r5, 6, 7, 8 0xec,0x00,0x00,0x00,0x00,0x51 = risblg %r0, %r0, 0, 0, 0 0xec,0x00,0x00,0x00,0x3f,0x51 = risblg %r0, %r0, 0, 0, 63 0xec,0x00,0x00,0xff,0x00,0x51 = risblg %r0, %r0, 0, 255, 0 0xec,0x00,0xff,0x00,0x00,0x51 = risblg %r0, %r0, 255, 0, 0 0xec,0x0f,0x00,0x00,0x00,0x51 = risblg %r0, %r15, 0, 0, 0 0xec,0xf0,0x00,0x00,0x00,0x51 = risblg %r15, %r0, 0, 0, 0 0xec,0x45,0x06,0x07,0x08,0x51 = risblg %r4, %r5, 6, 7, 8 0xb9,0xe9,0x00,0x00 = sgrk %r0, %r0, %r0 0xb9,0xe9,0xf0,0x00 = sgrk %r0, %r0, %r15 0xb9,0xe9,0x00,0x0f = sgrk %r0, %r15, %r0 0xb9,0xe9,0x00,0xf0 = sgrk %r15, %r0, %r0 0xb9,0xe9,0x90,0x78 = sgrk %r7, %r8, %r9 0xb9,0xeb,0x00,0x00 = slgrk %r0, %r0, %r0 0xb9,0xeb,0xf0,0x00 = slgrk %r0, %r0, %r15 0xb9,0xeb,0x00,0x0f = slgrk %r0, %r15, %r0 0xb9,0xeb,0x00,0xf0 = slgrk %r15, %r0, %r0 0xb9,0xeb,0x90,0x78 = slgrk %r7, %r8, %r9 0xb9,0xfb,0x00,0x00 = slrk %r0, %r0, %r0 0xb9,0xfb,0xf0,0x00 = slrk %r0, %r0, %r15 0xb9,0xfb,0x00,0x0f = slrk %r0, %r15, %r0 0xb9,0xfb,0x00,0xf0 = slrk %r15, %r0, %r0 0xb9,0xfb,0x90,0x78 = slrk %r7, %r8, %r9 0xeb,0x00,0x00,0x00,0x00,0xdf = sllk %r0, %r0, 0 0xeb,0xf1,0x00,0x00,0x00,0xdf = sllk %r15, %r1, 0 0xeb,0x1f,0x00,0x00,0x00,0xdf = sllk %r1, %r15, 0 0xeb,0xff,0x00,0x00,0x00,0xdf = sllk %r15, %r15, 0 0xeb,0x00,0x00,0x00,0x80,0xdf = sllk %r0, %r0, -524288 0xeb,0x00,0x0f,0xff,0xff,0xdf = sllk %r0, %r0, -1 0xeb,0x00,0x00,0x01,0x00,0xdf = sllk %r0, %r0, 1 0xeb,0x00,0x0f,0xff,0x7f,0xdf = sllk %r0, %r0, 524287 0xeb,0x00,0x10,0x00,0x00,0xdf = sllk %r0, %r0, 0(%r1) 0xeb,0x00,0xf0,0x00,0x00,0xdf = sllk %r0, %r0, 0(%r15) 0xeb,0x00,0x1f,0xff,0x7f,0xdf = sllk %r0, %r0, 524287(%r1) 0xeb,0x00,0xff,0xff,0x7f,0xdf = sllk %r0, %r0, 524287(%r15) 0xeb,0x00,0x00,0x00,0x00,0xdc = srak %r0, %r0, 0 0xeb,0xf1,0x00,0x00,0x00,0xdc = srak %r15, %r1, 0 0xeb,0x1f,0x00,0x00,0x00,0xdc = srak %r1, %r15, 0 0xeb,0xff,0x00,0x00,0x00,0xdc = srak %r15, %r15, 0 0xeb,0x00,0x00,0x00,0x80,0xdc = srak %r0, %r0, -524288 0xeb,0x00,0x0f,0xff,0xff,0xdc = srak %r0, %r0, -1 0xeb,0x00,0x00,0x01,0x00,0xdc = srak %r0, %r0, 1 0xeb,0x00,0x0f,0xff,0x7f,0xdc = srak %r0, %r0, 524287 0xeb,0x00,0x10,0x00,0x00,0xdc = srak %r0, %r0, 0(%r1) 0xeb,0x00,0xf0,0x00,0x00,0xdc = srak %r0, %r0, 0(%r15) 0xeb,0x00,0x1f,0xff,0x7f,0xdc = srak %r0, %r0, 524287(%r1) 0xeb,0x00,0xff,0xff,0x7f,0xdc = srak %r0, %r0, 524287(%r15) 0xb9,0xf9,0x00,0x00 = srk %r0, %r0, %r0 0xb9,0xf9,0xf0,0x00 = srk %r0, %r0, %r15 0xb9,0xf9,0x00,0x0f = srk %r0, %r15, %r0 0xb9,0xf9,0x00,0xf0 = srk %r15, %r0, %r0 0xb9,0xf9,0x90,0x78 = srk %r7, %r8, %r9 0xeb,0x00,0x00,0x00,0x00,0xde = srlk %r0, %r0, 0 0xeb,0xf1,0x00,0x00,0x00,0xde = srlk %r15, %r1, 0 0xeb,0x1f,0x00,0x00,0x00,0xde = srlk %r1, %r15, 0 0xeb,0xff,0x00,0x00,0x00,0xde = srlk %r15, %r15, 0 0xeb,0x00,0x00,0x00,0x80,0xde = srlk %r0, %r0, -524288 0xeb,0x00,0x0f,0xff,0xff,0xde = srlk %r0, %r0, -1 0xeb,0x00,0x00,0x01,0x00,0xde = srlk %r0, %r0, 1 0xeb,0x00,0x0f,0xff,0x7f,0xde = srlk %r0, %r0, 524287 0xeb,0x00,0x10,0x00,0x00,0xde = srlk %r0, %r0, 0(%r1) 0xeb,0x00,0xf0,0x00,0x00,0xde = srlk %r0, %r0, 0(%r15) 0xeb,0x00,0x1f,0xff,0x7f,0xde = srlk %r0, %r0, 524287(%r1) 0xeb,0x00,0xff,0xff,0x7f,0xde = srlk %r0, %r0, 524287(%r15) 0xe3,0x00,0x00,0x00,0x80,0xc3 = stch %r0, -524288 0xe3,0x00,0x0f,0xff,0xff,0xc3 = stch %r0, -1 0xe3,0x00,0x00,0x00,0x00,0xc3 = stch %r0, 0 0xe3,0x00,0x00,0x01,0x00,0xc3 = stch %r0, 1 0xe3,0x00,0x0f,0xff,0x7f,0xc3 = stch %r0, 524287 0xe3,0x00,0x10,0x00,0x00,0xc3 = stch %r0, 0(%r1) 0xe3,0x00,0xf0,0x00,0x00,0xc3 = stch %r0, 0(%r15) 0xe3,0x01,0xff,0xff,0x7f,0xc3 = stch %r0, 524287(%r1, %r15) 0xe3,0x0f,0x1f,0xff,0x7f,0xc3 = stch %r0, 524287(%r15, %r1) 0xe3,0xf0,0x00,0x00,0x00,0xc3 = stch %r15, 0 0xe3,0x00,0x00,0x00,0x80,0xc7 = sthh %r0, -524288 0xe3,0x00,0x0f,0xff,0xff,0xc7 = sthh %r0, -1 0xe3,0x00,0x00,0x00,0x00,0xc7 = sthh %r0, 0 0xe3,0x00,0x00,0x01,0x00,0xc7 = sthh %r0, 1 0xe3,0x00,0x0f,0xff,0x7f,0xc7 = sthh %r0, 524287 0xe3,0x00,0x10,0x00,0x00,0xc7 = sthh %r0, 0(%r1) 0xe3,0x00,0xf0,0x00,0x00,0xc7 = sthh %r0, 0(%r15) 0xe3,0x01,0xff,0xff,0x7f,0xc7 = sthh %r0, 524287(%r1, %r15) 0xe3,0x0f,0x1f,0xff,0x7f,0xc7 = sthh %r0, 524287(%r15, %r1) 0xe3,0xf0,0x00,0x00,0x00,0xc7 = sthh %r15, 0 0xe3,0x00,0x00,0x00,0x80,0xcb = stfh %r0, -524288 0xe3,0x00,0x0f,0xff,0xff,0xcb = stfh %r0, -1 0xe3,0x00,0x00,0x00,0x00,0xcb = stfh %r0, 0 0xe3,0x00,0x00,0x01,0x00,0xcb = stfh %r0, 1 0xe3,0x00,0x0f,0xff,0x7f,0xcb = stfh %r0, 524287 0xe3,0x00,0x10,0x00,0x00,0xcb = stfh %r0, 0(%r1) 0xe3,0x00,0xf0,0x00,0x00,0xcb = stfh %r0, 0(%r15) 0xe3,0x01,0xff,0xff,0x7f,0xcb = stfh %r0, 524287(%r1, %r15) 0xe3,0x0f,0x1f,0xff,0x7f,0xcb = stfh %r0, 524287(%r15, %r1) 0xe3,0xf0,0x00,0x00,0x00,0xcb = stfh %r15, 0 0xeb,0x00,0x00,0x00,0x00,0xf3 = stoc %r0, 0, 0 0xeb,0x0f,0x00,0x00,0x00,0xf3 = stoc %r0, 0, 15 0xeb,0x00,0x00,0x00,0x80,0xf3 = stoc %r0, -524288, 0 0xeb,0x00,0x0f,0xff,0x7f,0xf3 = stoc %r0, 524287, 0 0xeb,0x00,0x10,0x00,0x00,0xf3 = stoc %r0, 0(%r1), 0 0xeb,0x00,0xf0,0x00,0x00,0xf3 = stoc %r0, 0(%r15), 0 0xeb,0xf0,0x00,0x00,0x00,0xf3 = stoc %r15, 0, 0 // 0xeb,0x13,0x2f,0xff,0x00,0xf3 = stoc %r1, 4095(%r2), 3 0xeb,0x11,0x30,0x02,0x00,0xf3 = stoco %r1, 2(%r3) 0xeb,0x12,0x30,0x02,0x00,0xf3 = stoch %r1, 2(%r3) 0xeb,0x13,0x30,0x02,0x00,0xf3 = stocnle %r1, 2(%r3) 0xeb,0x14,0x30,0x02,0x00,0xf3 = stocl %r1, 2(%r3) 0xeb,0x15,0x30,0x02,0x00,0xf3 = stocnhe %r1, 2(%r3) 0xeb,0x16,0x30,0x02,0x00,0xf3 = stoclh %r1, 2(%r3) 0xeb,0x17,0x30,0x02,0x00,0xf3 = stocne %r1, 2(%r3) 0xeb,0x18,0x30,0x02,0x00,0xf3 = stoce %r1, 2(%r3) 0xeb,0x19,0x30,0x02,0x00,0xf3 = stocnlh %r1, 2(%r3) 0xeb,0x1a,0x30,0x02,0x00,0xf3 = stoche %r1, 2(%r3) 0xeb,0x1b,0x30,0x02,0x00,0xf3 = stocnl %r1, 2(%r3) 0xeb,0x1c,0x30,0x02,0x00,0xf3 = stocle %r1, 2(%r3) 0xeb,0x1d,0x30,0x02,0x00,0xf3 = stocnh %r1, 2(%r3) 0xeb,0x1e,0x30,0x02,0x00,0xf3 = stocno %r1, 2(%r3) 0xeb,0x00,0x00,0x00,0x00,0xe3 = stocg %r0, 0, 0 0xeb,0x0f,0x00,0x00,0x00,0xe3 = stocg %r0, 0, 15 0xeb,0x00,0x00,0x00,0x80,0xe3 = stocg %r0, -524288, 0 0xeb,0x00,0x0f,0xff,0x7f,0xe3 = stocg %r0, 524287, 0 0xeb,0x00,0x10,0x00,0x00,0xe3 = stocg %r0, 0(%r1), 0 0xeb,0x00,0xf0,0x00,0x00,0xe3 = stocg %r0, 0(%r15), 0 0xeb,0xf0,0x00,0x00,0x00,0xe3 = stocg %r15, 0, 0 // 0xeb,0x13,0x2f,0xff,0x00,0xe3 = stocg %r1, 4095(%r2), 3 0xeb,0x11,0x30,0x02,0x00,0xe3 = stocgo %r1, 2(%r3) 0xeb,0x12,0x30,0x02,0x00,0xe3 = stocgh %r1, 2(%r3) 0xeb,0x13,0x30,0x02,0x00,0xe3 = stocgnle %r1, 2(%r3) 0xeb,0x14,0x30,0x02,0x00,0xe3 = stocgl %r1, 2(%r3) 0xeb,0x15,0x30,0x02,0x00,0xe3 = stocgnhe %r1, 2(%r3) 0xeb,0x16,0x30,0x02,0x00,0xe3 = stocglh %r1, 2(%r3) 0xeb,0x17,0x30,0x02,0x00,0xe3 = stocgne %r1, 2(%r3) 0xeb,0x18,0x30,0x02,0x00,0xe3 = stocge %r1, 2(%r3) 0xeb,0x19,0x30,0x02,0x00,0xe3 = stocgnlh %r1, 2(%r3) 0xeb,0x1a,0x30,0x02,0x00,0xe3 = stocghe %r1, 2(%r3) 0xeb,0x1b,0x30,0x02,0x00,0xe3 = stocgnl %r1, 2(%r3) 0xeb,0x1c,0x30,0x02,0x00,0xe3 = stocgle %r1, 2(%r3) 0xeb,0x1d,0x30,0x02,0x00,0xe3 = stocgnh %r1, 2(%r3) 0xeb,0x1e,0x30,0x02,0x00,0xe3 = stocgno %r1, 2(%r3) 0xb9,0xe7,0x00,0x00 = xgrk %r0, %r0, %r0 0xb9,0xe7,0xf0,0x00 = xgrk %r0, %r0, %r15 0xb9,0xe7,0x00,0x0f = xgrk %r0, %r15, %r0 0xb9,0xe7,0x00,0xf0 = xgrk %r15, %r0, %r0 0xb9,0xe7,0x90,0x78 = xgrk %r7, %r8, %r9 0xb9,0xf7,0x00,0x00 = xrk %r0, %r0, %r0 0xb9,0xf7,0xf0,0x00 = xrk %r0, %r0, %r15 0xb9,0xf7,0x00,0x0f = xrk %r0, %r15, %r0 0xb9,0xf7,0x00,0xf0 = xrk %r15, %r0, %r0 0xb9,0xf7,0x90,0x78 = xrk %r7, %r8, %r9