context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Runtime.Serialization; namespace HTLib2 { using LinearAlgebra = global::dnAnalytics.LinearAlgebra; using _daMatrix = global::dnAnalytics.LinearAlgebra.Matrix; using _daVector = global::dnAnalytics.LinearAlgebra.Vector; using _daSparseMatrix = global::dnAnalytics.LinearAlgebra.SparseMatrix; using _daDenseMatrix = global::dnAnalytics.LinearAlgebra.DenseMatrix; [Serializable] public class daMatrix { public readonly _daMatrix val; public daMatrix(_daMatrix source) { this.val = source; } public static explicit operator _daMatrix(daMatrix mat) { return mat.val; } public _daMatrix ToDaMatrix() { return this.val; } public static daMatrix operator -( daMatrix rightSide) { return new daMatrix( - rightSide.val); } public static daMatrix operator -( daMatrix leftSide, daMatrix rightSide) { return new daMatrix(leftSide.val + -1*rightSide.val); } public static daMatrix operator -( daMatrix leftSide, _daMatrix rightSide) { return new daMatrix(leftSide.val - rightSide ); } public static daMatrix operator -(_daMatrix leftSide, daMatrix rightSide) { return new daMatrix(leftSide - rightSide.val); } public static daMatrix operator *(double leftSide, daMatrix rightSide) { return new daMatrix(leftSide * rightSide.val); } public static daMatrix operator *( daMatrix leftSide, double rightSide) { return new daMatrix(leftSide.val * rightSide ); } public static daMatrix operator *( daMatrix leftSide, daMatrix rightSide) { return new daMatrix(leftSide.val * rightSide.val); } public static daMatrix operator *( daMatrix leftSide, _daMatrix rightSide) { return new daMatrix(leftSide.val * rightSide ); } public static daMatrix operator *(_daMatrix leftSide, daMatrix rightSide) { return new daMatrix(leftSide * rightSide.val); } public static daVector operator *( daMatrix leftSide, daVector rightSide) { return new daVector(leftSide.val * rightSide.val); } public static daVector operator *( daMatrix leftSide, _daVector rightSide) { return new daVector(leftSide.val * rightSide ); } public static daVector operator *( daVector leftSide, daMatrix rightSide) { return new daVector(leftSide.val * rightSide.val); } public static daVector operator *(_daVector leftSide, daMatrix rightSide) { return new daVector(leftSide * rightSide.val); } public static daMatrix operator /( daMatrix leftSide, double rightSide) { return new daMatrix(leftSide.val / rightSide ); } public static daMatrix operator +( daMatrix rightSide) { return new daMatrix( + rightSide.val); } public static daMatrix operator +( daMatrix leftSide, daMatrix rightSide) { return new daMatrix(leftSide.val + rightSide.val); } public static daMatrix operator +( daMatrix leftSide, _daMatrix rightSide) { return new daMatrix(leftSide.val + rightSide ); } public static daMatrix operator +(_daMatrix leftSide, daMatrix rightSide) { return new daMatrix(leftSide + rightSide.val); } public int Columns { get{ return val.Columns; } } public int Rows { get{ return val.Rows; } } public double this[int row, int column] { get{ return val[row, column]; } set{ val[row, column] = value; } } public void Add(double scalar) { val.Add(scalar); } public void Add(_daMatrix other) { val.Add(other); } public void Add(double scalar, _daMatrix result) { val.Add(scalar, result); } public void Add(_daMatrix other, _daMatrix result) { val.Add(other, result); } public daMatrix Append(_daMatrix right) { return new daMatrix(val.Append(right)); } public void Append(_daMatrix right, _daMatrix result) { val.Append(right, result); } public void Clear() { val.Clear(); } public daMatrix Clone() { return new daMatrix(val.Clone()); } public double ConditionNumber() { return val.ConditionNumber(); } public void CopyTo(_daMatrix target) { val.CopyTo(target); } public double Determinant() { return val.Determinant(); } public daMatrix DiagonalStack(_daMatrix lower) { return new daMatrix(val.DiagonalStack(lower)); } public void DiagonalStack(_daMatrix lower, _daMatrix result) { val.DiagonalStack(lower, result); } public void Divide(double scalar) { val.Divide(scalar); } public void Divide(double scalar, _daMatrix result) { val.Divide(scalar, result); } public bool Equals(_daMatrix other) { return val.Equals(other); } public override bool Equals(object obj) { return val.Equals(obj); } public double FrobeniusNorm() { return val.FrobeniusNorm(); } public void Gemm(double alpha, double beta, bool transposeA, bool transposeB, _daMatrix a, _daMatrix b) { val.Gemm(alpha, beta, transposeA, transposeB, a, b); } public daVector GetColumn(int index) { return new daVector(val.GetColumn(index)); } public void GetColumn(int index, _daVector result) { val.GetColumn(index, result); } public daVector GetColumn(int columnIndex, int rowIndex, int length) { return new daVector(val.GetColumn(columnIndex, rowIndex, length)); } public void GetColumn(int columnIndex, int rowIndex, int length, _daVector result) { val.GetColumn(columnIndex, rowIndex, length, result); } public IEnumerable<KeyValuePair<int, daVector>> GetColumnEnumerator() { HDebug.Assert(false); return null; } public IEnumerable<KeyValuePair<int, daVector>> GetColumnEnumerator(int index, int length) { HDebug.Assert(false); return null; } public daVector GetDiagonal() { return new daVector(val.GetDiagonal()); } public override int GetHashCode() { return val.GetHashCode(); } public daMatrix GetLowerTriangle() { return new daMatrix(val.GetLowerTriangle()); } public void GetLowerTriangle(_daMatrix result) { val.GetLowerTriangle(result); } public daVector GetRow(int index) { return new daVector(val.GetRow(index)); } public void GetRow(int index, _daVector result) { val.GetRow(index, result); } public daVector GetRow(int rowIndex, int columnIndex, int length) { return new daVector(val.GetRow(rowIndex, columnIndex, length)); } public void GetRow(int rowIndex, int columnIndex, int length, _daVector result) { val.GetRow(rowIndex, columnIndex, length, result); } public IEnumerable<KeyValuePair<int, daVector>> GetRowEnumerator() { HDebug.Assert(false); return null; } public IEnumerable<KeyValuePair<int, daVector>> GetRowEnumerator(int index, int length) { HDebug.Assert(false); return null; } public daMatrix GetStrictlyLowerTriangle() { return new daMatrix(val.GetStrictlyLowerTriangle()); } public void GetStrictlyLowerTriangle(_daMatrix result) { val.GetStrictlyLowerTriangle(result); } public daMatrix GetStrictlyUpperTriangle() { return new daMatrix(val.GetStrictlyUpperTriangle()); } public void GetStrictlyUpperTriangle(_daMatrix result) { val.GetStrictlyUpperTriangle(result); } public daMatrix GetSubdaMatrix(int rowIndex, int rowLength, int columnIndex, int columnLength) { return new daMatrix(val.GetSubMatrix(rowIndex, rowLength, columnIndex, columnLength)); } public daMatrix GetUpperTriangle() { return new daMatrix(val.GetUpperTriangle()); } public void GetUpperTriangle(_daMatrix result) { val.GetUpperTriangle(result); } public double InfinityNorm() { return val.InfinityNorm(); } public daMatrix InsertColumn(int columnIndex, _daVector column) { return new daMatrix(val.InsertColumn(columnIndex, column)); } public daMatrix InsertRow(int rowIndex, _daVector row) { return new daMatrix(val.InsertRow(rowIndex, row)); } //public daMatrix Inverse() { return new daMatrix(val.Inverse()); } public daMatrix KroneckerProduct(_daMatrix other) { return new daMatrix(val.KroneckerProduct(other)); } public void KroneckerProduct(_daMatrix other, _daMatrix result) { val.KroneckerProduct(other, result); } public double L1Norm() { return val.L1Norm(); } public double L2Norm() { return val.L2Norm(); } public daVector LeftMultiply(_daVector leftSide) { return new daVector(val.LeftMultiply(leftSide)); } public void LeftMultiply(_daVector leftSide, _daVector result) { val.LeftMultiply(leftSide, result); } public void Multiply(double scalar) { val.Multiply(scalar); } public daMatrix Multiply(_daMatrix other) { return new daMatrix(val.Multiply(other)); } public daVector Multiply(_daVector rightSide) { return new daVector(val.Multiply(rightSide)); } public void Multiply(double scalar, _daMatrix result) { val.Multiply(scalar, result); } public void Multiply(_daMatrix other, _daMatrix result) { val.Multiply(other, result); } public void Multiply(_daVector rightSide, _daVector result) { val.Multiply(rightSide, result); } public void Negate() { val.Negate(); } public void Negate(_daMatrix result) { val.Negate(result); } public daMatrix NormalizeColumns(int pValue) { return new daMatrix(val.NormalizeColumns(pValue)); } public daMatrix NormalizeRows(int pValue) { return new daMatrix(val.NormalizeRows(pValue)); } public daMatrix Plus() { return new daMatrix(val.Plus()); } public daMatrix PointwiseMultiply(_daMatrix other) { return new daMatrix(val.PointwiseMultiply(other)); } public void PointwiseMultiply(_daMatrix other, _daMatrix result) { val.PointwiseMultiply(other, result); } public void SetColumn(int index, double[] source) { val.SetColumn(index, source); } public void SetColumn(int index, _daVector source) { val.SetColumn(index, source); } public void SetDiagonal(double[] source) { val.SetDiagonal(source); } public void SetDiagonal(_daVector source) { val.SetDiagonal(source); } public void SetRow(int index, double[] source) { val.SetRow(index, source); } public void SetRow(int index, _daVector source) { val.SetRow(index, source); } public void SetSubdaMatrix(int rowIndex, int rowLength, int columnIndex, int columnLength, _daMatrix subMatrix) { val.SetSubMatrix(rowIndex, rowLength, columnIndex, columnLength, subMatrix); } public daMatrix Stack(_daMatrix lower) { return new daMatrix(val.Stack(lower)); } public void Stack(_daMatrix lower, _daMatrix result) { val.Stack(lower, result); } public void Subtract(double scalar) { val.Subtract(scalar); } public void Subtract(_daMatrix other) { val.Subtract(other); } public void Subtract(double scalar, _daMatrix result) { val.Subtract(scalar, result); } public void Subtract(_daMatrix other, _daMatrix result) { val.Subtract(other, result); } public double[,] ToArray() { return val.ToArray(); } public double[] ToColumnWiseArray() { return val.ToColumnWiseArray(); } public double[] ToRowWiseArray() { return val.ToRowWiseArray(); } public override string ToString() { return val.ToString(); } public string ToString(IFormatProvider formatProvider) { return val.ToString(formatProvider); } public string ToString(string format) { return val.ToString(format); } public string ToString(string format, IFormatProvider formatProvider) { return val.ToString(format, formatProvider); } public double Trace() { return val.Trace(); } public daMatrix Transpose() { return new daMatrix(val.Transpose()); } //public Pair<Matrix, Matrix> Eigensystem() //{ // Matrix mat = this.ToArray(); // Pair<Matrix, Matrix> val_vec = mat.Eigensystem(); // if(false) // { // Matrix val = val_vec.first; // Matrix vec = val_vec.second; // Matrix mat2 = vec * val * vec.Inverse(); // Matrix diff = mat - mat2; // } // return val_vec; //} // //public daMatrix Inverse() //{ // return Inverse("svd"); //} //public daMatrix Inverse(string option) //{ // return daMatrix.Inverse(this.val, option); //} //static Triple<double[,], string, _daMatrix> Inverse_buffer; //public static _daMatrix InverseBuffered(double[,] mat, string option) //{ // if(Inverse_buffer == null) return null; // if(option != Inverse_buffer.second) return null; // if(mat.GetLength(0) != Inverse_buffer.first.GetLength(0)) return null; // if(mat.GetLength(1) != Inverse_buffer.first.GetLength(1)) return null; // for(int i=0; i<mat.GetLength(0); i++) // for(int j=0; j<mat.GetLength(1); j++) // if(mat[i, j] != Inverse_buffer.first[i, j]) // { // return null; // } // return Inverse_buffer.third; //} //public static daMatrix Inverse(_daMatrix mat, string option) //{ // double[,] _mat = mat.ToArray(); // _daMatrix buffered = InverseBuffered(_mat, option); // if(buffered != null) // return new daMatrix(buffered); // // _daMatrix imat; // switch(option.ToLower()) // { // case "svd": // { // Debug.Assert(mat.Rows == mat.Columns); // int n = mat.Rows; // global::dnAnalytics.LinearAlgebra.Decomposition.Svd svd = (new global::dnAnalytics.LinearAlgebra.Decomposition.Svd(mat, true)); // _daMatrix U = svd.U(); // _daMatrix W = svd.W(); // _daMatrix VT = svd.VT(); // _daSparseMatrix iW = new _daSparseMatrix(n, n); // for(int i=0; i<n; i++) // if(W[i, i] >= 0.000000001) // iW[i, i] = 1 / W[i, i]; // else iW[i, i] = 0; // imat = VT.Transpose() * iW * U.Transpose(); // } // break; // case "default": // { // imat = mat.Inverse(); // } // break; // default: // goto case "svd"; // } // // Inverse_buffer = new Triple<double[,], string, _daMatrix>(_mat, option, imat); // return new daMatrix(imat); //} } }
using System; using System.Linq; using System.Reflection; using System.Threading; using ColossalFramework; using ColossalFramework.Math; using JetBrains.Annotations; using UnityEngine; // ReSharper disable InconsistentNaming namespace TrafficManager { public class CustomPathManager : PathManager { CustomPathFind[] _replacementPathFinds; public static CustomPathFind PathFindInstance; //On waking up, replace the stock pathfinders with the custom one [UsedImplicitly] public new virtual void Awake() { Log.Message("Waking up CustomPathManager."); var stockPathFinds = GetComponents<PathFind>(); var numOfStockPathFinds = stockPathFinds.Length; Log.Message("Creating " + numOfStockPathFinds + " custom PathFind objects."); _replacementPathFinds = new CustomPathFind[numOfStockPathFinds]; for (var i = 0; i < numOfStockPathFinds; i++) { _replacementPathFinds[i] = gameObject.AddComponent<CustomPathFind>(); Destroy(stockPathFinds[i]); } Log.Message("Setting _replacementPathFinds"); var fieldInfo = typeof(PathManager).GetField("m_pathfinds", BindingFlags.NonPublic | BindingFlags.Instance); Log.Message("Setting m_pathfinds to custom collection"); fieldInfo?.SetValue(this, _replacementPathFinds); } public void UpdateWithPathManagerValues(PathManager stockPathManager) { // Needed fields come from joaofarias' csl-traffic // https://github.com/joaofarias/csl-traffic m_simulationProfiler = stockPathManager.m_simulationProfiler; m_drawCallData = stockPathManager.m_drawCallData; m_properties = stockPathManager.m_properties; m_pathUnitCount = stockPathManager.m_pathUnitCount; m_renderPathGizmo = stockPathManager.m_renderPathGizmo; m_pathUnits = stockPathManager.m_pathUnits; m_bufferLock = stockPathManager.m_bufferLock; } // // BEGIN STOCK CODE // public new bool CreatePath(out uint unit, ref Randomizer randomizer, uint buildIndex, PathUnit.Position startPos, PathUnit.Position endPos, NetInfo.LaneType laneTypes, VehicleInfo.VehicleType vehicleTypes, float maxLength) { PathUnit.Position position = default(PathUnit.Position); return CreatePath(out unit, ref randomizer, buildIndex, startPos, position, endPos, position, position, laneTypes, vehicleTypes, maxLength, false, false, false, false); } public new bool CreatePath(out uint unit, ref Randomizer randomizer, uint buildIndex, PathUnit.Position startPosA, PathUnit.Position startPosB, PathUnit.Position endPosA, PathUnit.Position endPosB, NetInfo.LaneType laneTypes, VehicleInfo.VehicleType vehicleTypes, float maxLength) { return CreatePath(out unit, ref randomizer, buildIndex, startPosA, startPosB, endPosA, endPosB, default(PathUnit.Position), laneTypes, vehicleTypes, maxLength, false, false, false, false); } public new bool CreatePath(out uint unit, ref Randomizer randomizer, uint buildIndex, PathUnit.Position startPosA, PathUnit.Position startPosB, PathUnit.Position endPosA, PathUnit.Position endPosB, NetInfo.LaneType laneTypes, VehicleInfo.VehicleType vehicleTypes, float maxLength, bool isHeavyVehicle, bool ignoreBlocked, bool stablePath, bool skipQueue) { return CreatePath(out unit, ref randomizer, buildIndex, startPosA, startPosB, endPosA, endPosB, default(PathUnit.Position), laneTypes, vehicleTypes, maxLength, isHeavyVehicle, ignoreBlocked, stablePath, skipQueue); } public new bool CreatePath(out uint unit, ref Randomizer randomizer, uint buildIndex, PathUnit.Position startPosA, PathUnit.Position startPosB, PathUnit.Position endPosA, PathUnit.Position endPosB, PathUnit.Position vehiclePosition, NetInfo.LaneType laneTypes, VehicleInfo.VehicleType vehicleTypes, float maxLength, bool isHeavyVehicle, bool ignoreBlocked, bool stablePath, bool skipQueue) { return CreatePath(out unit, ref randomizer, buildIndex, startPosA, startPosB, endPosA, endPosB, default(PathUnit.Position), laneTypes, vehicleTypes, maxLength, isHeavyVehicle, ignoreBlocked, stablePath, skipQueue, ItemClass.Service.None); } public bool CreatePath(out uint unit, ref Randomizer randomizer, uint buildIndex, PathUnit.Position startPosA, PathUnit.Position startPosB, PathUnit.Position endPosA, PathUnit.Position endPosB, NetInfo.LaneType laneTypes, VehicleInfo.VehicleType vehicleTypes, float maxLength, bool isHeavyVehicle, bool ignoreBlocked, bool stablePath, bool skipQueue, ItemClass.Service vehicleService) { return CreatePath(out unit, ref randomizer, buildIndex, startPosA, startPosB, endPosA, endPosB, default(PathUnit.Position), laneTypes, vehicleTypes, maxLength, isHeavyVehicle, ignoreBlocked, stablePath, skipQueue, vehicleService); } public bool CreatePath(out uint unit, ref Randomizer randomizer, uint buildIndex, PathUnit.Position startPosA, PathUnit.Position startPosB, PathUnit.Position endPosA, PathUnit.Position endPosB, PathUnit.Position vehiclePosition, NetInfo.LaneType laneTypes, VehicleInfo.VehicleType vehicleTypes, float maxLength, bool isHeavyVehicle, bool ignoreBlocked, bool stablePath, bool skipQueue, ItemClass.Service vehicleService) { while (!Monitor.TryEnter(m_bufferLock, SimulationManager.SYNCHRONIZE_TIMEOUT)) { } uint num; try { if (!m_pathUnits.CreateItem(out num, ref randomizer)) { unit = 0u; return false; } m_pathUnitCount = (int)(m_pathUnits.ItemCount() - 1u); } finally { Monitor.Exit(m_bufferLock); } unit = num; byte simulationFlags = createSimulationFlag(isHeavyVehicle, ignoreBlocked, stablePath, vehicleService); assignPathProperties(unit, buildIndex, startPosA, startPosB, endPosA, endPosB, vehiclePosition, laneTypes, vehicleTypes, maxLength, simulationFlags); return findShortestPath(unit, skipQueue); } public new static uint GetLaneID(PathUnit.Position pathPos) { var netManager = Singleton<NetManager>.instance; var num = netManager.m_segments.m_buffer[pathPos.m_segment].m_lanes; var num2 = 0; while (num2 < pathPos.m_lane && num != 0u) { num = netManager.m_lanes.m_buffer[(int)((UIntPtr)num)].m_nextLane; num2++; } return num; } private void assignPathProperties(uint unit, uint buildIndex, PathUnit.Position startPosA, PathUnit.Position startPosB, PathUnit.Position endPosA, PathUnit.Position endPosB, PathUnit.Position vehiclePosition, NetInfo.LaneType laneTypes, VehicleInfo.VehicleType vehicleTypes, float maxLength, byte simulationFlags) { m_pathUnits.m_buffer[(int)((UIntPtr)unit)].m_simulationFlags = simulationFlags; m_pathUnits.m_buffer[(int)((UIntPtr)unit)].m_pathFindFlags = 0; m_pathUnits.m_buffer[(int)((UIntPtr)unit)].m_buildIndex = buildIndex; m_pathUnits.m_buffer[(int)((UIntPtr)unit)].m_position00 = startPosA; m_pathUnits.m_buffer[(int)((UIntPtr)unit)].m_position01 = endPosA; m_pathUnits.m_buffer[(int)((UIntPtr)unit)].m_position02 = startPosB; m_pathUnits.m_buffer[(int)((UIntPtr)unit)].m_position03 = endPosB; m_pathUnits.m_buffer[(int)((UIntPtr)unit)].m_position11 = vehiclePosition; m_pathUnits.m_buffer[(int)((UIntPtr)unit)].m_nextPathUnit = 0u; m_pathUnits.m_buffer[(int)((UIntPtr)unit)].m_laneTypes = (byte)laneTypes; m_pathUnits.m_buffer[(int)((UIntPtr)unit)].m_vehicleTypes = (byte)vehicleTypes; m_pathUnits.m_buffer[(int)((UIntPtr)unit)].m_length = maxLength; m_pathUnits.m_buffer[(int)((UIntPtr)unit)].m_positionCount = 20; m_pathUnits.m_buffer[(int)((UIntPtr)unit)].m_referenceCount = 1; } private bool findShortestPath(uint unit, bool skipQueue) { int[] maxPathLength = {10000000}; CustomPathFind pathFind = null; foreach (var pathFind2 in _replacementPathFinds.Where(pathFind2 => pathFind2.IsAvailable && pathFind2.m_queuedPathFindCount < maxPathLength[0])) { maxPathLength[0] = pathFind2.m_queuedPathFindCount; pathFind = pathFind2; } if (pathFind != null && pathFind.CalculatePath(unit, skipQueue)) { return true; } ReleasePath(unit); return false; } private static byte createSimulationFlag(bool isHeavyVehicle, bool ignoreBlocked, bool stablePath, ItemClass.Service vehicleService) { byte simulationFlags = 1; if (isHeavyVehicle) { simulationFlags |= 16; } if (ignoreBlocked) { simulationFlags |= 32; } if (stablePath) { simulationFlags |= 64; } byte vehicleFlag = 0; if (vehicleService == ItemClass.Service.None) return simulationFlags; //No VehicleFlag needed. if (vehicleService == ItemClass.Service.Commercial) vehicleFlag |= 128; else if (vehicleService == ItemClass.Service.FireDepartment) vehicleFlag |= 130; else if (vehicleService == ItemClass.Service.Garbage) vehicleFlag |= 132; else if (vehicleService == ItemClass.Service.HealthCare) vehicleFlag |= 134; else if (vehicleService == ItemClass.Service.Industrial) vehicleFlag |= 136; else if (vehicleService == ItemClass.Service.PoliceDepartment) vehicleFlag |= 138; else if (vehicleService == ItemClass.Service.PublicTransport) vehicleFlag |= 140; simulationFlags |= vehicleFlag; return simulationFlags; } } }
// // Copyright (c) 2004-2006 Jaroslaw Kowalski <[email protected]> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of 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; using System.IO; using System.Globalization; using System.Collections; using System.Runtime.InteropServices; using System.Text; using System.Xml; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; namespace Tools { [TaskName("sync-vs-project-items")] public class SyncVSProjectItems : Task { private FileSet _sourceFiles; private FileSet _projectFiles; private FileSet _resourceFiles; [BuildElement("source-files")] public FileSet SourceFiles { get { return _sourceFiles; } set { _sourceFiles = value; } } [BuildElement("project-files")] public FileSet ProjectFiles { get { return _projectFiles; } set { _projectFiles = value; } } [BuildElement("resource-files")] public FileSet ResourceFiles { get { return _resourceFiles; } set { _resourceFiles = value; } } private Hashtable _relativeSourceFiles = new Hashtable(); private Hashtable _relativeResourceFiles = new Hashtable(); private int _added = 0; private int _removed = 0; private static string RelativePath(string baseDir, string rootedName) { if (rootedName.ToLower().StartsWith(baseDir.ToLower())) { string s = rootedName.Substring(baseDir.Length); return s; } throw new Exception("Path " + rootedName + " is not within " + baseDir); } protected override void ExecuteTask() { string baseDir = SourceFiles.BaseDirectory.FullName; if (!baseDir.EndsWith("\\")) baseDir = baseDir + "\\"; if (SourceFiles != null) { foreach (string s in SourceFiles.FileNames) { _relativeSourceFiles[RelativePath(baseDir, s)] = s; } } if (ResourceFiles != null) { foreach (string s in ResourceFiles.FileNames) { _relativeResourceFiles[RelativePath(baseDir, s)] = s; } } foreach (string projectFile in ProjectFiles.FileNames) { XmlDocument doc = new XmlDocument(); doc.Load(projectFile); _added = 0; _removed = 0; if (doc.SelectSingleNode("//Files/Include") != null) { Log(Level.Verbose, "Visual Studio 2002/2003-style project."); ProcessOldProject(doc); } else { Log(Level.Verbose, "MSBuild-style project."); ProcessMSBuildProject(doc); } if (_added + _removed > 0) { Log(Level.Info, "Project: {0} Added: {1} Removed: {2}", projectFile, _added, _removed); using (FileStream fs = File.Create(projectFile)) { XmlTextWriter xtw = new XmlTextWriter(fs, Encoding.UTF8); xtw.QuoteChar = '\''; xtw.Formatting = Formatting.Indented; doc.Save(xtw); } } } } private void ProcessOldProject(XmlDocument doc) { SyncOldProjectItem(doc, "Compile", "Code", _relativeSourceFiles); SyncOldProjectItem(doc, "EmbeddedResource", null, _relativeResourceFiles); } private void SyncOldProjectItem(XmlDocument doc, string buildAction, string subType, Hashtable directoryFiles) { Hashtable projectSourceFiles = new Hashtable(); foreach (XmlElement el in doc.SelectNodes("//File[@BuildAction='" + buildAction + "']")) { string name = el.GetAttribute("RelPath"); projectSourceFiles[name] = el; } XmlElement filesInclude = (XmlElement)doc.SelectSingleNode("//Files/Include"); foreach (string s in projectSourceFiles.Keys) { if (!directoryFiles.Contains(s)) { XmlElement el = (XmlElement)projectSourceFiles[s]; Log(Level.Verbose, "File {0} not found in directory. Removing.", s); el.ParentNode.RemoveChild(el); _removed++; } } foreach (string s in directoryFiles.Keys) { if (!projectSourceFiles.Contains(s)) { Log(Level.Verbose, "File {0} not found in project. Adding.", s); XmlElement el = doc.CreateElement("File"); el.SetAttribute("RelPath", s); if (subType != null) el.SetAttribute("SubType", subType); el.SetAttribute("BuildAction", buildAction); filesInclude.AppendChild(el); _added++; } } } private void ProcessMSBuildProject(XmlDocument doc) { SyncProjectItem(doc, "Compile", "Code", _relativeSourceFiles); SyncProjectItem(doc, "EmbeddedResource", null, _relativeResourceFiles); } private void SyncProjectItem(XmlDocument doc, string type, string subType, Hashtable directoryFiles) { string msbuildNamespace = "http://schemas.microsoft.com/developer/msbuild/2003"; Hashtable projectSourceFiles = new Hashtable(); XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable); mgr.AddNamespace("msb", msbuildNamespace); XmlElement itemGroup = null; foreach (XmlElement el in doc.SelectNodes("//msb:" + type, mgr)) { string name = el.GetAttribute("Include"); projectSourceFiles[name] = el; if (itemGroup == null) itemGroup = (XmlElement)el.ParentNode; } if (itemGroup == null) { XmlNode importNode = doc.SelectSingleNode("//msb:Import", mgr); if (importNode == null) throw new Exception("No <Import> node in project."); itemGroup = doc.CreateElement("ItemGroup", msbuildNamespace); doc.DocumentElement.InsertBefore(itemGroup, importNode); } foreach (string s in projectSourceFiles.Keys) { if (!directoryFiles.Contains(s)) { XmlElement el = (XmlElement)projectSourceFiles[s]; Log(Level.Verbose, "File {0} not found in directory. Removing.", s); el.ParentNode.RemoveChild(el); _removed++; } } foreach (string s in directoryFiles.Keys) { if (!projectSourceFiles.Contains(s)) { Log(Level.Verbose, "File {0} not found in project. Adding.", s); XmlElement el = doc.CreateElement(type, msbuildNamespace); el.SetAttribute("Include", s); itemGroup.AppendChild(el); _added++; } } } } }
// // Copyright (C) 2013 Sixense Entertainment Inc. // All Rights Reserved // // Sixense Driver Unity Plugin // Version 1.0 // using UnityEngine; using System.Collections; using System.Runtime.InteropServices; /// <summary> /// Hand controller is bound to. /// </summary> public enum SixenseHands { UNKNOWN = 0, LEFT = 1, RIGHT = 2, } /// <summary> /// Controller button mask. /// </summary> /// <remarks> /// The TRIGGER button is set when the Trigger value is greater than the TriggerButtonThreshold. /// </remarks> public enum SixenseButtons { START = 1, ONE = 32, TWO = 64, THREE = 8, FOUR = 16, BUMPER = 128, JOYSTICK = 256, TRIGGER = 512, } /// <summary> /// SixenseInput provides an interface for accessing Sixense controllers. /// </summary> /// <remarks> /// This script should be bound to a GameObject in the scene so that its Start(), Update() and OnApplicationQuit() methods are called. This can be done by adding the SixenseInput prefab to a scene. The public static interface to the Controller objects provides a user friendly way to integrate Sixense controllers into your application. /// </remarks> public class SixenseInput : MonoBehaviour { /// <summary> /// Controller objects provide access to Sixense controllers data. /// </summary> public class Controller { /// <summary> /// The controller enabled state. /// </summary> public bool Enabled { get { return m_Enabled; } } /// <summary> /// The controller docked state. /// </summary> public bool Docked { get { return m_Docked; } } /// <summary> /// Hand the controller bound to, which could be UNKNOWN. /// </summary> public SixenseHands Hand { get { return ( ( m_Hand == SixenseHands.UNKNOWN ) ? m_HandBind : m_Hand ); } } /// <summary> /// Value of trigger from released (0.0) to pressed (1.0). /// </summary> public float Trigger { get { return m_Trigger; } } /// <summary> /// Value of joystick X axis from left (-1.0) to right (1.0). /// </summary> public float JoystickX { get { return m_JoystickX; } } /// <summary> /// Value of joystick Y axis from bottom (-1.0) to top (1.0). /// </summary> public float JoystickY { get { return m_JoystickY; } } /// <summary> /// The controller position in Unity coordinates. /// </summary> public Vector3 Position { get { return new Vector3( m_Position.x, m_Position.y, -m_Position.z ); } } /// <summary> /// The raw controller position value. /// </summary> public Vector3 PositionRaw { get { return m_Position; } } /// <summary> /// The controller rotation in Unity coordinates. /// </summary> public Quaternion Rotation { get { return new Quaternion( -m_Rotation.x, -m_Rotation.y, m_Rotation.z, m_Rotation.w ); } } /// <summary> /// The raw controller rotation value. /// </summary> public Quaternion RotationRaw { get { return m_Rotation; } } /// <summary> /// The value which the Trigger value must pass to register a TRIGGER button press. This value can be set. /// </summary> public float TriggerButtonThreshold { get { return m_TriggerButtonThreshold; } set { m_TriggerButtonThreshold = value; } } /// <summary> /// Returns true if the button parameter is being pressed. /// </summary> public bool GetButton( SixenseButtons button ) { return ( ( button & m_Buttons ) != 0 ); } /// <summary> /// Returns true if the button parameter was pressed this frame. /// </summary> public bool GetButtonDown( SixenseButtons button ) { return ( ( button & m_Buttons ) != 0 ) && ( ( button & m_ButtonsPrevious ) == 0 ); } /// <summary> /// Returns true if the button parameter was released this frame. /// </summary> public bool GetButtonUp( SixenseButtons button ) { return ( ( button & m_Buttons ) == 0 ) && ( ( button & m_ButtonsPrevious ) != 0 ); } /// <summary> /// The default trigger button threshold constant. /// </summary> public const float DefaultTriggerButtonThreshold = 0.9f; internal Controller() { m_Enabled = false; m_Docked = false; m_Hand = SixenseHands.UNKNOWN; m_HandBind = SixenseHands.UNKNOWN; m_Buttons = 0; m_ButtonsPrevious = 0; m_Trigger = 0.0f; m_JoystickX = 0.0f; m_JoystickY = 0.0f; m_Position.Set( 0.0f, 0.0f, 0.0f ); m_Rotation.Set( 0.0f, 0.0f, 0.0f, 1.0f ); } internal void SetEnabled( bool enabled ) { m_Enabled = enabled; } internal void Update( ref SixensePlugin.sixenseControllerData cd ) { m_Docked = ( cd.is_docked != 0 ); m_Hand = ( SixenseHands )cd.which_hand; m_ButtonsPrevious = m_Buttons; m_Buttons = ( SixenseButtons )cd.buttons; m_Trigger = cd.trigger; m_JoystickX = cd.joystick_x; m_JoystickY = cd.joystick_y; m_Position.Set( cd.pos[0], cd.pos[1], cd.pos[2] ); m_Rotation.Set( cd.rot_quat[0], cd.rot_quat[1], cd.rot_quat[2], cd.rot_quat[3] ); if ( m_Trigger > TriggerButtonThreshold ) { m_Buttons |= SixenseButtons.TRIGGER; } } internal SixenseHands HandBind { get { return m_HandBind; } set { m_HandBind = value; } } private bool m_Enabled; private bool m_Docked; private SixenseHands m_Hand; private SixenseHands m_HandBind; private SixenseButtons m_Buttons; private SixenseButtons m_ButtonsPrevious; private float m_Trigger; private float m_TriggerButtonThreshold = DefaultTriggerButtonThreshold; private float m_JoystickX; private float m_JoystickY; private Vector3 m_Position; private Quaternion m_Rotation; } /// <summary> /// Max number of controllers allowed by driver. /// </summary> public const uint MAX_CONTROLLERS = 4; /// <summary> /// Access to Controller objects. /// </summary> public static Controller[] Controllers { get { return m_Controllers; } } /// <summary> /// Gets the Controller object bound to the specified hand. /// </summary> public static Controller GetController( SixenseHands hand ) { for ( int i = 0; i < MAX_CONTROLLERS; i++ ) { if ( ( m_Controllers[i] != null ) && ( m_Controllers[i].Hand == hand ) ) { return m_Controllers[i]; } } return null; } /// <summary> /// Returns true if the base for zero-based index i is connected. /// </summary> public static bool IsBaseConnected( int i ) { return ( SixensePlugin.sixenseIsBaseConnected( i ) != 0 ); } /// <summary> /// Enable or disable the controller manager. /// </summary> public static bool ControllerManagerEnabled = true; private enum ControllerManagerState { NONE, BIND_CONTROLLER_ONE, BIND_CONTROLLER_TWO, } private static Controller[] m_Controllers = new Controller[MAX_CONTROLLERS]; private ControllerManagerState m_ControllerManagerState = ControllerManagerState.NONE; /// <summary> /// Initialize the sixense driver and allocate the controllers. /// </summary> void Start() { SixensePlugin.sixenseInit(); for ( int i = 0; i < MAX_CONTROLLERS; i++ ) { m_Controllers[i] = new Controller(); } } /// <summary> /// Update the static controller data once per frame. /// </summary> void Update() { // update controller data uint numControllersBound = 0; uint numControllersEnabled = 0; SixensePlugin.sixenseControllerData cd = new SixensePlugin.sixenseControllerData(); for ( int i = 0; i < MAX_CONTROLLERS; i++ ) { if ( m_Controllers[i] != null ) { if ( SixensePlugin.sixenseIsControllerEnabled( i ) == 1 ) { SixensePlugin.sixenseGetNewestData( i, ref cd ); m_Controllers[i].Update( ref cd ); m_Controllers[i].SetEnabled( true ); numControllersEnabled++; if ( ControllerManagerEnabled && ( SixenseInput.Controllers[i].Hand != SixenseHands.UNKNOWN ) ) { numControllersBound++; } } else { m_Controllers[i].SetEnabled( false ); } } } // update controller manager if ( ControllerManagerEnabled ) { if ( numControllersEnabled < 2 ) { m_ControllerManagerState = ControllerManagerState.NONE; } switch( m_ControllerManagerState ) { case ControllerManagerState.NONE: { if ( IsBaseConnected( 0 ) && ( numControllersEnabled > 1 ) ) { if ( numControllersBound == 0 ) { m_ControllerManagerState = ControllerManagerState.BIND_CONTROLLER_ONE; } else if ( numControllersBound == 1 ) { m_ControllerManagerState = ControllerManagerState.BIND_CONTROLLER_TWO; } } } break; case ControllerManagerState.BIND_CONTROLLER_ONE: { if ( numControllersBound > 0 ) { m_ControllerManagerState = ControllerManagerState.BIND_CONTROLLER_TWO; } else { for ( int i = 0; i < MAX_CONTROLLERS; i++ ) { if ( ( m_Controllers[i] != null ) && Controllers[i].GetButtonDown( SixenseButtons.TRIGGER ) && ( Controllers[i].Hand == SixenseHands.UNKNOWN ) ) { Controllers[i].HandBind = SixenseHands.LEFT; SixensePlugin.sixenseAutoEnableHemisphereTracking( i ); m_ControllerManagerState = ControllerManagerState.BIND_CONTROLLER_TWO; break; } } } } break; case ControllerManagerState.BIND_CONTROLLER_TWO: { if ( numControllersBound > 1 ) { m_ControllerManagerState = ControllerManagerState.NONE; } else { for ( int i = 0; i < MAX_CONTROLLERS; i++ ) { if ( ( m_Controllers[i] != null ) && Controllers[i].GetButtonDown( SixenseButtons.TRIGGER ) && ( Controllers[i].Hand == SixenseHands.UNKNOWN ) ) { Controllers[i].HandBind = SixenseHands.RIGHT; SixensePlugin.sixenseAutoEnableHemisphereTracking( i ); m_ControllerManagerState = ControllerManagerState.NONE; break; } } } } break; default: break; } } } /// <summary> /// Updates the controller manager GUI. /// </summary> void OnGUI() { if ( ControllerManagerEnabled && ( m_ControllerManagerState != ControllerManagerState.NONE ) ) { uint boxWidth = 300; uint boxHeight = 24; string boxText = ( m_ControllerManagerState == ControllerManagerState.BIND_CONTROLLER_ONE ) ? "Point left controller at base and pull trigger." : "Point right controller at base and pull trigger."; GUI.Box( new Rect( ( ( Screen.width / 2 ) - ( boxWidth / 2 ) ), ( ( Screen.height / 2 ) - ( boxHeight / 2 ) ), boxWidth, boxHeight ), boxText ); } } /// <summary> /// Exit sixense when the application quits. /// </summary> void OnApplicationQuit() { SixensePlugin.sixenseExit(); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ApiManagement { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; using Models; using 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> /// ApiOperations operations. /// </summary> internal partial class ApiOperations : IServiceOperations<ApiManagementClient>, IApiOperations { /// <summary> /// Initializes a new instance of the ApiOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ApiOperations(ApiManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the ApiManagementClient /// </summary> public ApiManagementClient Client { get; private set; } /// <summary> /// Lists all APIs of the API Management service instance. /// <see href="https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-create-apis" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ApiContract>>> ListByServiceWithHttpMessagesAsync(string resourceGroupName, string serviceName, ODataQuery<ApiContract> odataQuery = default(ODataQuery<ApiContract>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serviceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serviceName"); } if (serviceName != null) { if (serviceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50); } if (serviceName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "serviceName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$")) { throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByService", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/apis").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ApiContract>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<ApiContract>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the details of the API specified by its identifier. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ApiContract,ApiGetHeaders>> GetWithHttpMessagesAsync(string resourceGroupName, string serviceName, string apiId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serviceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serviceName"); } if (serviceName != null) { if (serviceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50); } if (serviceName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "serviceName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$")) { throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"); } } if (apiId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "apiId"); } if (apiId != null) { if (apiId.Length > 256) { throw new ValidationException(ValidationRules.MaxLength, "apiId", 256); } if (apiId.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "apiId", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(apiId, "^[^*#&+:<>?]+$")) { throw new ValidationException(ValidationRules.Pattern, "apiId", "^[^*#&+:<>?]+$"); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("serviceName", serviceName); tracingParameters.Add("apiId", apiId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/apis/{apiId}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName)); _url = _url.Replace("{apiId}", System.Uri.EscapeDataString(apiId)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ApiContract,ApiGetHeaders>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ApiContract>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<ApiGetHeaders>(JsonSerializer.Create(Client.DeserializationSettings)); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates new or updates existing specified API of the API Management service /// instance. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='parameters'> /// Create or update parameters. /// </param> /// <param name='ifMatch'> /// ETag of the Api Entity. For Create Api Etag should not be specified. For /// Update Etag should match the existing Entity or it can be * for /// unconditional update. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ApiContract,ApiCreateOrUpdateHeaders>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, string apiId, ApiCreateOrUpdateParameter parameters, string ifMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serviceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serviceName"); } if (serviceName != null) { if (serviceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50); } if (serviceName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "serviceName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$")) { throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"); } } if (apiId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "apiId"); } if (apiId != null) { if (apiId.Length > 256) { throw new ValidationException(ValidationRules.MaxLength, "apiId", 256); } if (apiId.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "apiId", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(apiId, "^[^*#&+:<>?]+$")) { throw new ValidationException(ValidationRules.Pattern, "apiId", "^[^*#&+:<>?]+$"); } } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("serviceName", serviceName); tracingParameters.Add("apiId", apiId); tracingParameters.Add("parameters", parameters); tracingParameters.Add("ifMatch", ifMatch); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/apis/{apiId}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName)); _url = _url.Replace("{apiId}", System.Uri.EscapeDataString(apiId)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (ifMatch != null) { if (_httpRequest.Headers.Contains("If-Match")) { _httpRequest.Headers.Remove("If-Match"); } _httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201 && (int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ApiContract,ApiCreateOrUpdateHeaders>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ApiContract>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ApiContract>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<ApiCreateOrUpdateHeaders>(JsonSerializer.Create(Client.DeserializationSettings)); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Updates the specified API of the API Management service instance. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='parameters'> /// API Update Contract parameters. /// </param> /// <param name='ifMatch'> /// ETag of the API entity. ETag should match the current entity state in the /// header response of the GET request or it should be * for unconditional /// update. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> UpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, string apiId, ApiUpdateContract parameters, string ifMatch, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serviceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serviceName"); } if (serviceName != null) { if (serviceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50); } if (serviceName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "serviceName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$")) { throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"); } } if (apiId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "apiId"); } if (apiId != null) { if (apiId.Length > 256) { throw new ValidationException(ValidationRules.MaxLength, "apiId", 256); } if (apiId.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "apiId", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(apiId, "^[^*#&+:<>?]+$")) { throw new ValidationException(ValidationRules.Pattern, "apiId", "^[^*#&+:<>?]+$"); } } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (ifMatch == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ifMatch"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("serviceName", serviceName); tracingParameters.Add("apiId", apiId); tracingParameters.Add("parameters", parameters); tracingParameters.Add("ifMatch", ifMatch); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/apis/{apiId}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName)); _url = _url.Replace("{apiId}", System.Uri.EscapeDataString(apiId)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.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("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (ifMatch != null) { if (_httpRequest.Headers.Contains("If-Match")) { _httpRequest.Headers.Remove("If-Match"); } _httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified API of the API Management service instance. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='ifMatch'> /// ETag of the API Entity. ETag should match the current entity state from the /// header response of the GET request or it should be * for unconditional /// update. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string serviceName, string apiId, string ifMatch, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serviceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serviceName"); } if (serviceName != null) { if (serviceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50); } if (serviceName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "serviceName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$")) { throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"); } } if (apiId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "apiId"); } if (apiId != null) { if (apiId.Length > 256) { throw new ValidationException(ValidationRules.MaxLength, "apiId", 256); } if (apiId.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "apiId", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(apiId, "^[^*#&+:<>?]+$")) { throw new ValidationException(ValidationRules.Pattern, "apiId", "^[^*#&+:<>?]+$"); } } if (ifMatch == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ifMatch"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("serviceName", serviceName); tracingParameters.Add("apiId", apiId); tracingParameters.Add("ifMatch", ifMatch); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/apis/{apiId}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName)); _url = _url.Replace("{apiId}", System.Uri.EscapeDataString(apiId)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (ifMatch != null) { if (_httpRequest.Headers.Contains("If-Match")) { _httpRequest.Headers.Remove("If-Match"); } _httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists all APIs of the API Management service instance. /// <see href="https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-create-apis" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ApiContract>>> ListByServiceNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByServiceNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ApiContract>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<ApiContract>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Input; using osu.Framework.Input.Bindings; using osu.Framework.Input.Events; using osu.Framework.Input.StateChanges.Events; using osu.Framework.Input.States; using osu.Game.Configuration; using osu.Game.Input; using osu.Game.Input.Bindings; using osu.Game.Input.Handlers; using osu.Game.Screens.Play; using static osu.Game.Input.Handlers.ReplayInputHandler; namespace osu.Game.Rulesets.UI { public abstract class RulesetInputManager<T> : PassThroughInputManager, ICanAttachKeyCounter, IHasReplayHandler, IHasRecordingHandler where T : struct { private ReplayRecorder recorder; public ReplayRecorder Recorder { set { if (value != null && recorder != null) throw new InvalidOperationException("Cannot attach more than one recorder"); recorder?.Expire(); recorder = value; if (recorder != null) KeyBindingContainer.Add(recorder); } } protected override InputState CreateInitialState() => new RulesetInputManagerInputState<T>(base.CreateInitialState()); protected readonly KeyBindingContainer<T> KeyBindingContainer; protected override Container<Drawable> Content => content; private readonly Container content; protected RulesetInputManager(RulesetInfo ruleset, int variant, SimultaneousBindingMode unique) { InternalChild = KeyBindingContainer = CreateKeyBindingContainer(ruleset, variant, unique) .WithChild(content = new Container { RelativeSizeAxes = Axes.Both }); } [BackgroundDependencyLoader(true)] private void load(OsuConfigManager config) { mouseDisabled = config.GetBindable<bool>(OsuSetting.MouseDisableButtons); } #region Action mapping (for replays) public override void HandleInputStateChange(InputStateChangeEvent inputStateChange) { if (inputStateChange is ReplayStateChangeEvent<T> replayStateChanged) { foreach (var action in replayStateChanged.ReleasedActions) KeyBindingContainer.TriggerReleased(action); foreach (var action in replayStateChanged.PressedActions) KeyBindingContainer.TriggerPressed(action); } else { base.HandleInputStateChange(inputStateChange); } } #endregion #region IHasReplayHandler private ReplayInputHandler replayInputHandler; public ReplayInputHandler ReplayInputHandler { get => replayInputHandler; set { if (replayInputHandler != null) RemoveHandler(replayInputHandler); replayInputHandler = value; UseParentInput = replayInputHandler == null; if (replayInputHandler != null) AddHandler(replayInputHandler); } } #endregion #region Setting application (disables etc.) private Bindable<bool> mouseDisabled; protected override bool Handle(UIEvent e) { switch (e) { case MouseDownEvent _: if (mouseDisabled.Value) return true; // importantly, block upwards propagation so global bindings also don't fire. break; case MouseUpEvent mouseUp: if (!CurrentState.Mouse.IsPressed(mouseUp.Button)) return false; break; } return base.Handle(e); } #endregion #region Key Counter Attachment public void Attach(KeyCounterDisplay keyCounter) { var receptor = new ActionReceptor(keyCounter); KeyBindingContainer.Add(receptor); keyCounter.SetReceptor(receptor); keyCounter.AddRange(KeyBindingContainer.DefaultKeyBindings .Select(b => b.GetAction<T>()) .Distinct() .OrderBy(action => action) .Select(action => new KeyCounterAction<T>(action))); } public class ActionReceptor : KeyCounterDisplay.Receptor, IKeyBindingHandler<T> { public ActionReceptor(KeyCounterDisplay target) : base(target) { } public bool OnPressed(T action) => Target.Children.OfType<KeyCounterAction<T>>().Any(c => c.OnPressed(action, Clock.Rate >= 0)); public void OnReleased(T action) { foreach (var c in Target.Children.OfType<KeyCounterAction<T>>()) c.OnReleased(action, Clock.Rate >= 0); } } #endregion protected virtual KeyBindingContainer<T> CreateKeyBindingContainer(RulesetInfo ruleset, int variant, SimultaneousBindingMode unique) => new RulesetKeyBindingContainer(ruleset, variant, unique); public class RulesetKeyBindingContainer : DatabasedKeyBindingContainer<T> { public RulesetKeyBindingContainer(RulesetInfo ruleset, int variant, SimultaneousBindingMode unique) : base(ruleset, variant, unique) { } protected override void ReloadMappings() { base.ReloadMappings(); KeyBindings = KeyBindings.Where(b => RealmKeyBindingStore.CheckValidForGameplay(b.KeyCombination)).ToList(); } } } /// <summary> /// Expose the <see cref="ReplayInputHandler"/> in a capable <see cref="InputManager"/>. /// </summary> public interface IHasReplayHandler { ReplayInputHandler ReplayInputHandler { get; set; } } public interface IHasRecordingHandler { public ReplayRecorder Recorder { set; } } /// <summary> /// Supports attaching a <see cref="KeyCounterDisplay"/>. /// Keys will be populated automatically and a receptor will be injected inside. /// </summary> public interface ICanAttachKeyCounter { void Attach(KeyCounterDisplay keyCounter); } public class RulesetInputManagerInputState<T> : InputState where T : struct { public ReplayState<T> LastReplayState; public RulesetInputManagerInputState(InputState state = null) : base(state) { } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Security.Claims; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Umbraco.Extensions; namespace Umbraco.Cms.Core.Security { public abstract class UmbracoUserStore<TUser, TRole> : UserStoreBase<TUser, TRole, string, IdentityUserClaim<string>, IdentityUserRole<string>, IdentityUserLogin<string>, IdentityUserToken<string>, IdentityRoleClaim<string>> where TUser : UmbracoIdentityUser where TRole : IdentityRole<string> { protected UmbracoUserStore(IdentityErrorDescriber describer) : base(describer) { } /// <summary> /// Not supported in Umbraco /// </summary> /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] public override IQueryable<TUser> Users => throw new NotImplementedException(); protected static int UserIdToInt(string userId) { if(int.TryParse(userId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { return result; } throw new InvalidOperationException($"Unable to convert user ID ({userId})to int using InvariantCulture"); } protected static string UserIdToString(int userId) => string.Intern(userId.ToString(CultureInfo.InvariantCulture)); /// <summary> /// Not supported in Umbraco /// </summary> /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] public override Task AddClaimsAsync(TUser user, IEnumerable<Claim> claims, CancellationToken cancellationToken = default) => throw new NotImplementedException(); /// <summary> /// Adds a user to a role (user group) /// </summary> public override Task AddToRoleAsync(TUser user, string normalizedRoleName, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } if (normalizedRoleName == null) { throw new ArgumentNullException(nameof(normalizedRoleName)); } if (string.IsNullOrWhiteSpace(normalizedRoleName)) { throw new ArgumentException("Value can't be empty or consist only of white-space characters.", nameof(normalizedRoleName)); } IdentityUserRole<string> userRole = user.Roles.SingleOrDefault(r => r.RoleId == normalizedRoleName); if (userRole == null) { user.AddRole(normalizedRoleName); } return Task.CompletedTask; } /// <inheritdoc /> public override Task<TUser> FindByIdAsync(string userId, CancellationToken cancellationToken = default) => FindUserAsync(userId, cancellationToken); /// <summary> /// Not supported in Umbraco /// </summary> /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] public override Task<IList<Claim>> GetClaimsAsync(TUser user, CancellationToken cancellationToken = default) => throw new NotImplementedException(); /// <inheritdoc /> public override Task<string> GetNormalizedEmailAsync(TUser user, CancellationToken cancellationToken) => GetEmailAsync(user, cancellationToken); /// <inheritdoc /> public override Task<string> GetNormalizedUserNameAsync(TUser user, CancellationToken cancellationToken = default) => GetUserNameAsync(user, cancellationToken); /// <summary> /// Gets a list of role names the specified user belongs to. /// </summary> public override Task<IList<string>> GetRolesAsync(TUser user, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } return Task.FromResult((IList<string>)user.Roles.Select(x => x.RoleId).ToList()); } /// <inheritdoc /> public override Task<string> GetSecurityStampAsync(TUser user, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } // the stamp cannot be null, so if it is currently null then we'll just return a hash of the password return Task.FromResult(user.SecurityStamp.IsNullOrWhiteSpace() ? user.PasswordHash.GenerateHash() : user.SecurityStamp); } /// <summary> /// Not supported in Umbraco /// </summary> /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] public override Task<IList<TUser>> GetUsersForClaimAsync(Claim claim, CancellationToken cancellationToken = default) => throw new NotImplementedException(); /// <inheritdoc /> public override async Task<bool> HasPasswordAsync(TUser user, CancellationToken cancellationToken = default) { // This checks if it's null bool result = await base.HasPasswordAsync(user, cancellationToken); if (result) { // we also want to check empty return string.IsNullOrEmpty(user.PasswordHash) == false; } return false; } /// <summary> /// Returns true if a user is in the role /// </summary> public override Task<bool> IsInRoleAsync(TUser user, string normalizedRoleName, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } return Task.FromResult(user.Roles.Select(x => x.RoleId).InvariantContains(normalizedRoleName)); } /// <summary> /// Not supported in Umbraco /// </summary> /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] public override Task RemoveClaimsAsync(TUser user, IEnumerable<Claim> claims, CancellationToken cancellationToken = default) => throw new NotImplementedException(); /// <summary> /// Removes the role (user group) for the user /// </summary> public override Task RemoveFromRoleAsync(TUser user, string normalizedRoleName, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) { throw new ArgumentNullException(nameof(user)); } if (normalizedRoleName == null) { throw new ArgumentNullException(nameof(normalizedRoleName)); } if (string.IsNullOrWhiteSpace(normalizedRoleName)) { throw new ArgumentException("Value can't be empty or consist only of white-space characters.", nameof(normalizedRoleName)); } IdentityUserRole<string> userRole = user.Roles.SingleOrDefault(r => r.RoleId == normalizedRoleName); if (userRole != null) { user.Roles.Remove(userRole); } return Task.CompletedTask; } /// <summary> /// Not supported in Umbraco /// </summary> /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] public override Task ReplaceClaimAsync(TUser user, Claim claim, Claim newClaim, CancellationToken cancellationToken = default) => throw new NotImplementedException(); /// <inheritdoc /> public override Task SetNormalizedEmailAsync(TUser user, string normalizedEmail, CancellationToken cancellationToken) => SetEmailAsync(user, normalizedEmail, cancellationToken); /// <inheritdoc /> public override Task SetNormalizedUserNameAsync(TUser user, string normalizedName, CancellationToken cancellationToken = default) => SetUserNameAsync(user, normalizedName, cancellationToken); /// <inheritdoc /> public override async Task SetPasswordHashAsync(TUser user, string passwordHash, CancellationToken cancellationToken = default) { await base.SetPasswordHashAsync(user, passwordHash, cancellationToken); user.LastPasswordChangeDateUtc = DateTime.UtcNow; } /// <summary> /// Not supported in Umbraco, see comments above on GetTokenAsync, RemoveTokenAsync, SetTokenAsync /// </summary> /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] protected override Task AddUserTokenAsync(IdentityUserToken<string> token) => throw new NotImplementedException(); /// <summary> /// Not supported in Umbraco, see comments above on GetTokenAsync, RemoveTokenAsync, SetTokenAsync /// </summary> /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] protected override Task<IdentityUserToken<string>> FindTokenAsync(TUser user, string loginProvider, string name, CancellationToken cancellationToken) => throw new NotImplementedException(); /// <summary> /// Not supported in Umbraco, see comments above on GetTokenAsync, RemoveTokenAsync, SetTokenAsync /// </summary> /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] protected override Task RemoveUserTokenAsync(IdentityUserToken<string> token) => throw new NotImplementedException(); } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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 Google.Protobuf.Collections; using System; using System.Collections.Generic; using System.IO; namespace Google.Protobuf { /// <summary> /// Reads and decodes protocol message fields. /// </summary> /// <remarks> /// <para> /// This class is generally used by generated code to read appropriate /// primitives from the stream. It effectively encapsulates the lowest /// levels of protocol buffer format. /// </para> /// <para> /// Repeated fields and map fields are not handled by this class; use <see cref="RepeatedField{T}"/> /// and <see cref="MapField{TKey, TValue}"/> to serialize such fields. /// </para> /// </remarks> public sealed class CodedInputStream { /// <summary> /// Buffer of data read from the stream or provided at construction time. /// </summary> private readonly byte[] buffer; /// <summary> /// The index of the buffer at which we need to refill from the stream (if there is one). /// </summary> private int bufferSize; private int bufferSizeAfterLimit = 0; /// <summary> /// The position within the current buffer (i.e. the next byte to read) /// </summary> private int bufferPos = 0; /// <summary> /// The stream to read further input from, or null if the byte array buffer was provided /// directly on construction, with no further data available. /// </summary> private readonly Stream input; /// <summary> /// The last tag we read. 0 indicates we've read to the end of the stream /// (or haven't read anything yet). /// </summary> private uint lastTag = 0; /// <summary> /// The next tag, used to store the value read by PeekTag. /// </summary> private uint nextTag = 0; private bool hasNextTag = false; internal const int DefaultRecursionLimit = 64; internal const int DefaultSizeLimit = 64 << 20; // 64MB internal const int BufferSize = 4096; /// <summary> /// The total number of bytes read before the current buffer. The /// total bytes read up to the current position can be computed as /// totalBytesRetired + bufferPos. /// </summary> private int totalBytesRetired = 0; /// <summary> /// The absolute position of the end of the current message. /// </summary> private int currentLimit = int.MaxValue; private int recursionDepth = 0; private readonly int recursionLimit; private readonly int sizeLimit; #region Construction // Note that the checks are performed such that we don't end up checking obviously-valid things // like non-null references for arrays we've just created. /// <summary> /// Creates a new CodedInputStream reading data from the given byte array. /// </summary> public CodedInputStream(byte[] buffer) : this(null, ProtoPreconditions.CheckNotNull(buffer, "buffer"), 0, buffer.Length) { } /// <summary> /// Creates a new CodedInputStream that reads from the given byte array slice. /// </summary> public CodedInputStream(byte[] buffer, int offset, int length) : this(null, ProtoPreconditions.CheckNotNull(buffer, "buffer"), offset, offset + length) { if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset", "Offset must be within the buffer"); } if (length < 0 || offset + length > buffer.Length) { throw new ArgumentOutOfRangeException("length", "Length must be non-negative and within the buffer"); } } /// <summary> /// Creates a new CodedInputStream reading data from the given stream. /// </summary> public CodedInputStream(Stream input) : this(input, new byte[BufferSize], 0, 0) { ProtoPreconditions.CheckNotNull(input, "input"); } /// <summary> /// Creates a new CodedInputStream reading data from the given /// stream and buffer, using the default limits. /// </summary> internal CodedInputStream(Stream input, byte[] buffer, int bufferPos, int bufferSize) { this.input = input; this.buffer = buffer; this.bufferPos = bufferPos; this.bufferSize = bufferSize; this.sizeLimit = DefaultSizeLimit; this.recursionLimit = DefaultRecursionLimit; } /// <summary> /// Creates a new CodedInputStream reading data from the given /// stream and buffer, using the specified limits. /// </summary> /// <remarks> /// This chains to the version with the default limits instead of vice versa to avoid /// having to check that the default values are valid every time. /// </remarks> internal CodedInputStream(Stream input, byte[] buffer, int bufferPos, int bufferSize, int sizeLimit, int recursionLimit) : this(input, buffer, bufferPos, bufferSize) { if (sizeLimit <= 0) { throw new ArgumentOutOfRangeException("sizeLimit", "Size limit must be positive"); } if (recursionLimit <= 0) { throw new ArgumentOutOfRangeException("recursionLimit!", "Recursion limit must be positive"); } this.sizeLimit = sizeLimit; this.recursionLimit = recursionLimit; } #endregion /// <summary> /// Creates a <see cref="CodedInputStream"/> with the specified size and recursion limits, reading /// from an input stream. /// </summary> /// <remarks> /// This method exists separately from the constructor to reduce the number of constructor overloads. /// It is likely to be used considerably less frequently than the constructors, as the default limits /// are suitable for most use cases. /// </remarks> /// <param name="input">The input stream to read from</param> /// <param name="sizeLimit">The total limit of data to read from the stream.</param> /// <param name="recursionLimit">The maximum recursion depth to allow while reading.</param> /// <returns>A <c>CodedInputStream</c> reading from <paramref name="input"/> with the specified size /// and recursion limits.</returns> public static CodedInputStream CreateWithLimits(Stream input, int sizeLimit, int recursionLimit) { return new CodedInputStream(input, new byte[BufferSize], 0, 0, sizeLimit, recursionLimit); } /// <summary> /// Returns the current position in the input stream, or the position in the input buffer /// </summary> public long Position { get { if (input != null) { return input.Position - ((bufferSize + bufferSizeAfterLimit) - bufferPos); } return bufferPos; } } /// <summary> /// Returns the last tag read, or 0 if no tags have been read or we've read beyond /// the end of the stream. /// </summary> internal uint LastTag { get { return lastTag; } } /// <summary> /// Returns the size limit for this stream. /// </summary> /// <remarks> /// This limit is applied when reading from the underlying stream, as a sanity check. It is /// not applied when reading from a byte array data source without an underlying stream. /// The default value is 64MB. /// </remarks> /// <value> /// The size limit. /// </value> public int SizeLimit { get { return sizeLimit; } } /// <summary> /// Returns the recursion limit for this stream. This limit is applied whilst reading messages, /// to avoid maliciously-recursive data. /// </summary> /// <remarks> /// The default limit is 64. /// </remarks> /// <value> /// The recursion limit for this stream. /// </value> public int RecursionLimit { get { return recursionLimit; } } #region Validation /// <summary> /// Verifies that the last call to ReadTag() returned tag 0 - in other words, /// we've reached the end of the stream when we expected to. /// </summary> /// <exception cref="InvalidProtocolBufferException">The /// tag read was not the one specified</exception> internal void CheckReadEndOfStreamTag() { if (lastTag != 0) { throw InvalidProtocolBufferException.MoreDataAvailable(); } } #endregion #region Reading of tags etc /// <summary> /// Peeks at the next field tag. This is like calling <see cref="ReadTag"/>, but the /// tag is not consumed. (So a subsequent call to <see cref="ReadTag"/> will return the /// same value.) /// </summary> public uint PeekTag() { if (hasNextTag) { return nextTag; } uint savedLast = lastTag; nextTag = ReadTag(); hasNextTag = true; lastTag = savedLast; // Undo the side effect of ReadTag return nextTag; } /// <summary> /// Reads a field tag, returning the tag of 0 for "end of stream". /// </summary> /// <remarks> /// If this method returns 0, it doesn't necessarily mean the end of all /// the data in this CodedInputStream; it may be the end of the logical stream /// for an embedded message, for example. /// </remarks> /// <returns>The next field tag, or 0 for end of stream. (0 is never a valid tag.)</returns> public uint ReadTag() { if (hasNextTag) { lastTag = nextTag; hasNextTag = false; return lastTag; } // Optimize for the incredibly common case of having at least two bytes left in the buffer, // and those two bytes being enough to get the tag. This will be true for fields up to 4095. if (bufferPos + 2 <= bufferSize) { int tmp = buffer[bufferPos++]; if (tmp < 128) { lastTag = (uint)tmp; } else { int result = tmp & 0x7f; if ((tmp = buffer[bufferPos++]) < 128) { result |= tmp << 7; lastTag = (uint) result; } else { // Nope, rewind and go the potentially slow route. bufferPos -= 2; lastTag = ReadRawVarint32(); } } } else { if (IsAtEnd) { lastTag = 0; return 0; // This is the only case in which we return 0. } lastTag = ReadRawVarint32(); } if (lastTag == 0) { // If we actually read zero, that's not a valid tag. throw InvalidProtocolBufferException.InvalidTag(); } return lastTag; } /// <summary> /// Skips the data for the field with the tag we've just read. /// This should be called directly after <see cref="ReadTag"/>, when /// the caller wishes to skip an unknown field. /// </summary> /// <remarks> /// This method throws <see cref="InvalidProtocolBufferException"/> if the last-read tag was an end-group tag. /// If a caller wishes to skip a group, they should skip the whole group, by calling this method after reading the /// start-group tag. This behavior allows callers to call this method on any field they don't understand, correctly /// resulting in an error if an end-group tag has not been paired with an earlier start-group tag. /// </remarks> /// <exception cref="InvalidProtocolBufferException">The last tag was an end-group tag</exception> /// <exception cref="InvalidOperationException">The last read operation read to the end of the logical stream</exception> public void SkipLastField() { if (lastTag == 0) { throw new InvalidOperationException("SkipLastField cannot be called at the end of a stream"); } switch (WireFormat.GetTagWireType(lastTag)) { case WireFormat.WireType.StartGroup: SkipGroup(lastTag); break; case WireFormat.WireType.EndGroup: throw new InvalidProtocolBufferException( "SkipLastField called on an end-group tag, indicating that the corresponding start-group was missing"); case WireFormat.WireType.Fixed32: ReadFixed32(); break; case WireFormat.WireType.Fixed64: ReadFixed64(); break; case WireFormat.WireType.LengthDelimited: var length = ReadLength(); SkipRawBytes(length); break; case WireFormat.WireType.Varint: ReadRawVarint32(); break; } } private void SkipGroup(uint startGroupTag) { // Note: Currently we expect this to be the way that groups are read. We could put the recursion // depth changes into the ReadTag method instead, potentially... recursionDepth++; if (recursionDepth >= recursionLimit) { throw InvalidProtocolBufferException.RecursionLimitExceeded(); } uint tag; while (true) { tag = ReadTag(); if (tag == 0) { throw InvalidProtocolBufferException.TruncatedMessage(); } // Can't call SkipLastField for this case- that would throw. if (WireFormat.GetTagWireType(tag) == WireFormat.WireType.EndGroup) { break; } // This recursion will allow us to handle nested groups. SkipLastField(); } int startField = WireFormat.GetTagFieldNumber(startGroupTag); int endField = WireFormat.GetTagFieldNumber(tag); if (startField != endField) { throw new InvalidProtocolBufferException( $"Mismatched end-group tag. Started with field {startField}; ended with field {endField}"); } recursionDepth--; } /// <summary> /// Reads a double field from the stream. /// </summary> public double ReadDouble() { return BitConverter.Int64BitsToDouble((long) ReadRawLittleEndian64()); } /// <summary> /// Reads a float field from the stream. /// </summary> public float ReadFloat() { if (BitConverter.IsLittleEndian && 4 <= bufferSize - bufferPos) { float ret = BitConverter.ToSingle(buffer, bufferPos); bufferPos += 4; return ret; } else { byte[] rawBytes = ReadRawBytes(4); if (!BitConverter.IsLittleEndian) { ByteArray.Reverse(rawBytes); } return BitConverter.ToSingle(rawBytes, 0); } } /// <summary> /// Reads a uint64 field from the stream. /// </summary> public ulong ReadUInt64() { return ReadRawVarint64(); } /// <summary> /// Reads an int64 field from the stream. /// </summary> public long ReadInt64() { return (long) ReadRawVarint64(); } /// <summary> /// Reads an int32 field from the stream. /// </summary> public int ReadInt32() { return (int) ReadRawVarint32(); } /// <summary> /// Reads a fixed64 field from the stream. /// </summary> public ulong ReadFixed64() { return ReadRawLittleEndian64(); } /// <summary> /// Reads a fixed32 field from the stream. /// </summary> public uint ReadFixed32() { return ReadRawLittleEndian32(); } /// <summary> /// Reads a bool field from the stream. /// </summary> public bool ReadBool() { return ReadRawVarint32() != 0; } /// <summary> /// Reads a string field from the stream. /// </summary> public string ReadString() { int length = ReadLength(); // No need to read any data for an empty string. if (length == 0) { return ""; } if (length <= bufferSize - bufferPos) { // Fast path: We already have the bytes in a contiguous buffer, so // just copy directly from it. String result = CodedOutputStream.Utf8Encoding.GetString(buffer, bufferPos, length); bufferPos += length; return result; } // Slow path: Build a byte array first then copy it. return CodedOutputStream.Utf8Encoding.GetString(ReadRawBytes(length), 0, length); } /// <summary> /// Reads an embedded message field value from the stream. /// </summary> public void ReadMessage(IMessage builder) { int length = ReadLength(); if (recursionDepth >= recursionLimit) { throw InvalidProtocolBufferException.RecursionLimitExceeded(); } int oldLimit = PushLimit(length); ++recursionDepth; builder.MergeFrom(this); CheckReadEndOfStreamTag(); // Check that we've read exactly as much data as expected. if (!ReachedLimit) { throw InvalidProtocolBufferException.TruncatedMessage(); } --recursionDepth; PopLimit(oldLimit); } /// <summary> /// Reads a bytes field value from the stream. /// </summary> public ByteString ReadBytes() { int length = ReadLength(); if (length <= bufferSize - bufferPos && length > 0) { // Fast path: We already have the bytes in a contiguous buffer, so // just copy directly from it. ByteString result = ByteString.CopyFrom(buffer, bufferPos, length); bufferPos += length; return result; } else { // Slow path: Build a byte array and attach it to a new ByteString. return ByteString.AttachBytes(ReadRawBytes(length)); } } /// <summary> /// Reads a uint32 field value from the stream. /// </summary> public uint ReadUInt32() { return ReadRawVarint32(); } /// <summary> /// Reads an enum field value from the stream. If the enum is valid for type T, /// then the ref value is set and it returns true. Otherwise the unknown output /// value is set and this method returns false. /// </summary> public int ReadEnum() { // Currently just a pass-through, but it's nice to separate it logically from WriteInt32. return (int) ReadRawVarint32(); } /// <summary> /// Reads an sfixed32 field value from the stream. /// </summary> public int ReadSFixed32() { return (int) ReadRawLittleEndian32(); } /// <summary> /// Reads an sfixed64 field value from the stream. /// </summary> public long ReadSFixed64() { return (long) ReadRawLittleEndian64(); } /// <summary> /// Reads an sint32 field value from the stream. /// </summary> public int ReadSInt32() { return DecodeZigZag32(ReadRawVarint32()); } /// <summary> /// Reads an sint64 field value from the stream. /// </summary> public long ReadSInt64() { return DecodeZigZag64(ReadRawVarint64()); } /// <summary> /// Reads a length for length-delimited data. /// </summary> /// <remarks> /// This is internally just reading a varint, but this method exists /// to make the calling code clearer. /// </remarks> public int ReadLength() { return (int) ReadRawVarint32(); } /// <summary> /// Peeks at the next tag in the stream. If it matches <paramref name="tag"/>, /// the tag is consumed and the method returns <c>true</c>; otherwise, the /// stream is left in the original position and the method returns <c>false</c>. /// </summary> public bool MaybeConsumeTag(uint tag) { if (PeekTag() == tag) { hasNextTag = false; return true; } return false; } #endregion #region Underlying reading primitives /// <summary> /// Same code as ReadRawVarint32, but read each byte individually, checking for /// buffer overflow. /// </summary> private uint SlowReadRawVarint32() { int tmp = ReadRawByte(); if (tmp < 128) { return (uint) tmp; } int result = tmp & 0x7f; if ((tmp = ReadRawByte()) < 128) { result |= tmp << 7; } else { result |= (tmp & 0x7f) << 7; if ((tmp = ReadRawByte()) < 128) { result |= tmp << 14; } else { result |= (tmp & 0x7f) << 14; if ((tmp = ReadRawByte()) < 128) { result |= tmp << 21; } else { result |= (tmp & 0x7f) << 21; result |= (tmp = ReadRawByte()) << 28; if (tmp >= 128) { // Discard upper 32 bits. for (int i = 0; i < 5; i++) { if (ReadRawByte() < 128) { return (uint) result; } } throw InvalidProtocolBufferException.MalformedVarint(); } } } } return (uint) result; } /// <summary> /// Reads a raw Varint from the stream. If larger than 32 bits, discard the upper bits. /// This method is optimised for the case where we've got lots of data in the buffer. /// That means we can check the size just once, then just read directly from the buffer /// without constant rechecking of the buffer length. /// </summary> internal uint ReadRawVarint32() { if (bufferPos + 5 > bufferSize) { return SlowReadRawVarint32(); } int tmp = buffer[bufferPos++]; if (tmp < 128) { return (uint) tmp; } int result = tmp & 0x7f; if ((tmp = buffer[bufferPos++]) < 128) { result |= tmp << 7; } else { result |= (tmp & 0x7f) << 7; if ((tmp = buffer[bufferPos++]) < 128) { result |= tmp << 14; } else { result |= (tmp & 0x7f) << 14; if ((tmp = buffer[bufferPos++]) < 128) { result |= tmp << 21; } else { result |= (tmp & 0x7f) << 21; result |= (tmp = buffer[bufferPos++]) << 28; if (tmp >= 128) { // Discard upper 32 bits. // Note that this has to use ReadRawByte() as we only ensure we've // got at least 5 bytes at the start of the method. This lets us // use the fast path in more cases, and we rarely hit this section of code. for (int i = 0; i < 5; i++) { if (ReadRawByte() < 128) { return (uint) result; } } throw InvalidProtocolBufferException.MalformedVarint(); } } } } return (uint) result; } /// <summary> /// Reads a varint from the input one byte at a time, so that it does not /// read any bytes after the end of the varint. If you simply wrapped the /// stream in a CodedInputStream and used ReadRawVarint32(Stream) /// then you would probably end up reading past the end of the varint since /// CodedInputStream buffers its input. /// </summary> /// <param name="input"></param> /// <returns></returns> internal static uint ReadRawVarint32(Stream input) { int result = 0; int offset = 0; for (; offset < 32; offset += 7) { int b = input.ReadByte(); if (b == -1) { throw InvalidProtocolBufferException.TruncatedMessage(); } result |= (b & 0x7f) << offset; if ((b & 0x80) == 0) { return (uint) result; } } // Keep reading up to 64 bits. for (; offset < 64; offset += 7) { int b = input.ReadByte(); if (b == -1) { throw InvalidProtocolBufferException.TruncatedMessage(); } if ((b & 0x80) == 0) { return (uint) result; } } throw InvalidProtocolBufferException.MalformedVarint(); } /// <summary> /// Reads a raw varint from the stream. /// </summary> internal ulong ReadRawVarint64() { int shift = 0; ulong result = 0; while (shift < 64) { byte b = ReadRawByte(); result |= (ulong) (b & 0x7F) << shift; if ((b & 0x80) == 0) { return result; } shift += 7; } throw InvalidProtocolBufferException.MalformedVarint(); } /// <summary> /// Reads a 32-bit little-endian integer from the stream. /// </summary> internal uint ReadRawLittleEndian32() { uint b1 = ReadRawByte(); uint b2 = ReadRawByte(); uint b3 = ReadRawByte(); uint b4 = ReadRawByte(); return b1 | (b2 << 8) | (b3 << 16) | (b4 << 24); } /// <summary> /// Reads a 64-bit little-endian integer from the stream. /// </summary> internal ulong ReadRawLittleEndian64() { ulong b1 = ReadRawByte(); ulong b2 = ReadRawByte(); ulong b3 = ReadRawByte(); ulong b4 = ReadRawByte(); ulong b5 = ReadRawByte(); ulong b6 = ReadRawByte(); ulong b7 = ReadRawByte(); ulong b8 = ReadRawByte(); return b1 | (b2 << 8) | (b3 << 16) | (b4 << 24) | (b5 << 32) | (b6 << 40) | (b7 << 48) | (b8 << 56); } /// <summary> /// Decode a 32-bit value with ZigZag encoding. /// </summary> /// <remarks> /// ZigZag encodes signed integers into values that can be efficiently /// encoded with varint. (Otherwise, negative values must be /// sign-extended to 64 bits to be varint encoded, thus always taking /// 10 bytes on the wire.) /// </remarks> internal static int DecodeZigZag32(uint n) { return (int)(n >> 1) ^ -(int)(n & 1); } /// <summary> /// Decode a 32-bit value with ZigZag encoding. /// </summary> /// <remarks> /// ZigZag encodes signed integers into values that can be efficiently /// encoded with varint. (Otherwise, negative values must be /// sign-extended to 64 bits to be varint encoded, thus always taking /// 10 bytes on the wire.) /// </remarks> internal static long DecodeZigZag64(ulong n) { return (long)(n >> 1) ^ -(long)(n & 1); } #endregion #region Internal reading and buffer management /// <summary> /// Sets currentLimit to (current position) + byteLimit. This is called /// when descending into a length-delimited embedded message. The previous /// limit is returned. /// </summary> /// <returns>The old limit.</returns> internal int PushLimit(int byteLimit) { if (byteLimit < 0) { throw InvalidProtocolBufferException.NegativeSize(); } byteLimit += totalBytesRetired + bufferPos; int oldLimit = currentLimit; if (byteLimit > oldLimit) { throw InvalidProtocolBufferException.TruncatedMessage(); } currentLimit = byteLimit; RecomputeBufferSizeAfterLimit(); return oldLimit; } private void RecomputeBufferSizeAfterLimit() { bufferSize += bufferSizeAfterLimit; int bufferEnd = totalBytesRetired + bufferSize; if (bufferEnd > currentLimit) { // Limit is in current buffer. bufferSizeAfterLimit = bufferEnd - currentLimit; bufferSize -= bufferSizeAfterLimit; } else { bufferSizeAfterLimit = 0; } } /// <summary> /// Discards the current limit, returning the previous limit. /// </summary> internal void PopLimit(int oldLimit) { currentLimit = oldLimit; RecomputeBufferSizeAfterLimit(); } /// <summary> /// Returns whether or not all the data before the limit has been read. /// </summary> /// <returns></returns> internal bool ReachedLimit { get { if (currentLimit == int.MaxValue) { return false; } int currentAbsolutePosition = totalBytesRetired + bufferPos; return currentAbsolutePosition >= currentLimit; } } /// <summary> /// Returns true if the stream has reached the end of the input. This is the /// case if either the end of the underlying input source has been reached or /// the stream has reached a limit created using PushLimit. /// </summary> public bool IsAtEnd { get { return bufferPos == bufferSize && !RefillBuffer(false); } } /// <summary> /// Called when buffer is empty to read more bytes from the /// input. If <paramref name="mustSucceed"/> is true, RefillBuffer() gurantees that /// either there will be at least one byte in the buffer when it returns /// or it will throw an exception. If <paramref name="mustSucceed"/> is false, /// RefillBuffer() returns false if no more bytes were available. /// </summary> /// <param name="mustSucceed"></param> /// <returns></returns> private bool RefillBuffer(bool mustSucceed) { if (bufferPos < bufferSize) { throw new InvalidOperationException("RefillBuffer() called when buffer wasn't empty."); } if (totalBytesRetired + bufferSize == currentLimit) { // Oops, we hit a limit. if (mustSucceed) { throw InvalidProtocolBufferException.TruncatedMessage(); } else { return false; } } totalBytesRetired += bufferSize; bufferPos = 0; bufferSize = (input == null) ? 0 : input.Read(buffer, 0, buffer.Length); if (bufferSize < 0) { throw new InvalidOperationException("Stream.Read returned a negative count"); } if (bufferSize == 0) { if (mustSucceed) { throw InvalidProtocolBufferException.TruncatedMessage(); } else { return false; } } else { RecomputeBufferSizeAfterLimit(); int totalBytesRead = totalBytesRetired + bufferSize + bufferSizeAfterLimit; if (totalBytesRead > sizeLimit || totalBytesRead < 0) { throw InvalidProtocolBufferException.SizeLimitExceeded(); } return true; } } /// <summary> /// Read one byte from the input. /// </summary> /// <exception cref="InvalidProtocolBufferException"> /// the end of the stream or the current limit was reached /// </exception> internal byte ReadRawByte() { if (bufferPos == bufferSize) { RefillBuffer(true); } return buffer[bufferPos++]; } /// <summary> /// Reads a fixed size of bytes from the input. /// </summary> /// <exception cref="InvalidProtocolBufferException"> /// the end of the stream or the current limit was reached /// </exception> internal byte[] ReadRawBytes(int size) { if (size < 0) { throw InvalidProtocolBufferException.NegativeSize(); } if (totalBytesRetired + bufferPos + size > currentLimit) { // Read to the end of the stream (up to the current limit) anyway. SkipRawBytes(currentLimit - totalBytesRetired - bufferPos); // Then fail. throw InvalidProtocolBufferException.TruncatedMessage(); } if (size <= bufferSize - bufferPos) { // We have all the bytes we need already. byte[] bytes = new byte[size]; ByteArray.Copy(buffer, bufferPos, bytes, 0, size); bufferPos += size; return bytes; } else if (size < buffer.Length) { // Reading more bytes than are in the buffer, but not an excessive number // of bytes. We can safely allocate the resulting array ahead of time. // First copy what we have. byte[] bytes = new byte[size]; int pos = bufferSize - bufferPos; ByteArray.Copy(buffer, bufferPos, bytes, 0, pos); bufferPos = bufferSize; // We want to use RefillBuffer() and then copy from the buffer into our // byte array rather than reading directly into our byte array because // the input may be unbuffered. RefillBuffer(true); while (size - pos > bufferSize) { Buffer.BlockCopy(buffer, 0, bytes, pos, bufferSize); pos += bufferSize; bufferPos = bufferSize; RefillBuffer(true); } ByteArray.Copy(buffer, 0, bytes, pos, size - pos); bufferPos = size - pos; return bytes; } else { // The size is very large. For security reasons, we can't allocate the // entire byte array yet. The size comes directly from the input, so a // maliciously-crafted message could provide a bogus very large size in // order to trick the app into allocating a lot of memory. We avoid this // by allocating and reading only a small chunk at a time, so that the // malicious message must actually *be* extremely large to cause // problems. Meanwhile, we limit the allowed size of a message elsewhere. // Remember the buffer markers since we'll have to copy the bytes out of // it later. int originalBufferPos = bufferPos; int originalBufferSize = bufferSize; // Mark the current buffer consumed. totalBytesRetired += bufferSize; bufferPos = 0; bufferSize = 0; // Read all the rest of the bytes we need. int sizeLeft = size - (originalBufferSize - originalBufferPos); List<byte[]> chunks = new List<byte[]>(); while (sizeLeft > 0) { byte[] chunk = new byte[Math.Min(sizeLeft, buffer.Length)]; int pos = 0; while (pos < chunk.Length) { int n = (input == null) ? -1 : input.Read(chunk, pos, chunk.Length - pos); if (n <= 0) { throw InvalidProtocolBufferException.TruncatedMessage(); } totalBytesRetired += n; pos += n; } sizeLeft -= chunk.Length; chunks.Add(chunk); } // OK, got everything. Now concatenate it all into one buffer. byte[] bytes = new byte[size]; // Start by copying the leftover bytes from this.buffer. int newPos = originalBufferSize - originalBufferPos; ByteArray.Copy(buffer, originalBufferPos, bytes, 0, newPos); // And now all the chunks. foreach (byte[] chunk in chunks) { Buffer.BlockCopy(chunk, 0, bytes, newPos, chunk.Length); newPos += chunk.Length; } // Done. return bytes; } } /// <summary> /// Reads and discards <paramref name="size"/> bytes. /// </summary> /// <exception cref="InvalidProtocolBufferException">the end of the stream /// or the current limit was reached</exception> private void SkipRawBytes(int size) { if (size < 0) { throw InvalidProtocolBufferException.NegativeSize(); } if (totalBytesRetired + bufferPos + size > currentLimit) { // Read to the end of the stream anyway. SkipRawBytes(currentLimit - totalBytesRetired - bufferPos); // Then fail. throw InvalidProtocolBufferException.TruncatedMessage(); } if (size <= bufferSize - bufferPos) { // We have all the bytes we need already. bufferPos += size; } else { // Skipping more bytes than are in the buffer. First skip what we have. int pos = bufferSize - bufferPos; // ROK 5/7/2013 Issue #54: should retire all bytes in buffer (bufferSize) // totalBytesRetired += pos; totalBytesRetired += bufferSize; bufferPos = 0; bufferSize = 0; // Then skip directly from the InputStream for the rest. if (pos < size) { if (input == null) { throw InvalidProtocolBufferException.TruncatedMessage(); } SkipImpl(size - pos); totalBytesRetired += size - pos; } } } /// <summary> /// Abstraction of skipping to cope with streams which can't really skip. /// </summary> private void SkipImpl(int amountToSkip) { if (input.CanSeek) { long previousPosition = input.Position; input.Position += amountToSkip; if (input.Position != previousPosition + amountToSkip) { throw InvalidProtocolBufferException.TruncatedMessage(); } } else { byte[] skipBuffer = new byte[Math.Min(1024, amountToSkip)]; while (amountToSkip > 0) { int bytesRead = input.Read(skipBuffer, 0, Math.Min(skipBuffer.Length, amountToSkip)); if (bytesRead <= 0) { throw InvalidProtocolBufferException.TruncatedMessage(); } amountToSkip -= bytesRead; } } } #endregion } }
using System.Collections.Generic; using System.Text; using Box2D.Collision; using Box2D.Common; using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace CocosSharp { internal static class b2VecHelper { public static CCVector2 ToCCVector2(this b2Vec2 vec) { return new CCVector2(vec.x, vec.y); } internal static Color ToColor(this b2Color color) { return new Color(color.r, color.g, color.b); } internal static CCColor4B ToCCColor4B(this b2Color color) { return new CCColor4B (color.r, color.g, color.b, 255); } } public class CCBox2dDraw : b2Draw { #if WINDOWS_PHONE || OUYA public const int CircleSegments = 16; #else public const int CircleSegments = 32; #endif internal Color TextColor = Color.White; CCPrimitiveBatch primitiveBatch; SpriteFont spriteFont; List<StringData> stringData; StringBuilder stringBuilder; #region Structs struct StringData { public object[] Args; public Color Color; public string S; public int X, Y; public StringData(int x, int y, string s, object[] args, Color color) { X = x; Y = y; S = s; Args = args; Color = color; } } #endregion Structs #region Constructors public CCBox2dDraw(string spriteFontName) { primitiveBatch = new CCPrimitiveBatch(5000); spriteFont = CCContentManager.SharedContentManager.Load<SpriteFont>(spriteFontName); stringData = new List<StringData>(); stringBuilder = new StringBuilder(); } #endregion Constructors public override void DrawPolygon(b2Vec2[] vertices, int vertexCount, b2Color color) { if (!primitiveBatch.IsReady()) { throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything."); } for (int i = 0; i < vertexCount - 1; i++) { primitiveBatch.AddVertex(vertices[i].ToCCVector2(), color.ToCCColor4B(), PrimitiveType.LineList); primitiveBatch.AddVertex(vertices[i + 1].ToCCVector2(), color.ToCCColor4B(), PrimitiveType.LineList); } primitiveBatch.AddVertex(vertices[vertexCount - 1].ToCCVector2(), color.ToCCColor4B(), PrimitiveType.LineList); primitiveBatch.AddVertex(vertices[0].ToCCVector2(), color.ToCCColor4B(), PrimitiveType.LineList); } public override void DrawSolidPolygon(b2Vec2[] vertices, int vertexCount, b2Color color) { if (!primitiveBatch.IsReady()) { throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything."); } if (vertexCount == 2) { DrawPolygon(vertices, vertexCount, color); return; } var colorFill = color.ToCCColor4B() * 0.5f; for (int i = 1; i < vertexCount - 1; i++) { primitiveBatch.AddVertex(vertices[0].ToCCVector2(), colorFill, PrimitiveType.TriangleList); primitiveBatch.AddVertex(vertices[i].ToCCVector2(), colorFill, PrimitiveType.TriangleList); primitiveBatch.AddVertex(vertices[i + 1].ToCCVector2(), colorFill, PrimitiveType.TriangleList); } DrawPolygon(vertices, vertexCount, color); } public override void DrawCircle(b2Vec2 center, float radius, b2Color color) { if (!primitiveBatch.IsReady()) { throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything."); } const double increment = Math.PI * 2.0 / CircleSegments; double theta = 0.0; var col = color.ToCCColor4B(); CCVector2 centr = center.ToCCVector2(); for (int i = 0, count = CircleSegments; i < count; i++) { CCVector2 v1 = centr + radius * new CCVector2((float) Math.Cos(theta), (float) Math.Sin(theta)); CCVector2 v2 = centr + radius * new CCVector2((float) Math.Cos(theta + increment), (float) Math.Sin(theta + increment)); primitiveBatch.AddVertex(ref v1, col, PrimitiveType.LineList); primitiveBatch.AddVertex(ref v2, col, PrimitiveType.LineList); theta += increment; } } public override void DrawSolidCircle(b2Vec2 center, float radius, b2Vec2 axis, b2Color color) { if (!primitiveBatch.IsReady()) { throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything."); } const double increment = Math.PI * 2.0 / CircleSegments; double theta = 0.0; var colorFill = color.ToCCColor4B() * 0.5f; var centr = center.ToCCVector2(); CCVector2 v0 = center.ToCCVector2() + radius * new CCVector2((float) Math.Cos(theta), (float) Math.Sin(theta)); theta += increment; for (int i = 1; i < CircleSegments - 1; i++) { var v1 = centr + radius * new CCVector2((float) Math.Cos(theta), (float) Math.Sin(theta)); var v2 = centr + radius * new CCVector2((float) Math.Cos(theta + increment), (float) Math.Sin(theta + increment)); primitiveBatch.AddVertex(ref v0, colorFill, PrimitiveType.TriangleList); primitiveBatch.AddVertex(ref v1, colorFill, PrimitiveType.TriangleList); primitiveBatch.AddVertex(ref v2, colorFill, PrimitiveType.TriangleList); theta += increment; } DrawCircle(center, radius, color); DrawSegment(center, center + axis * radius, color); } public override void DrawSegment(b2Vec2 p1, b2Vec2 p2, b2Color color) { if (!primitiveBatch.IsReady()) { throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything."); } primitiveBatch.AddVertex(p1.ToCCVector2(), color.ToCCColor4B(), PrimitiveType.LineList); primitiveBatch.AddVertex(p2.ToCCVector2(), color.ToCCColor4B(), PrimitiveType.LineList); } public override void DrawTransform(b2Transform xf) { const float axisScale = 0.4f; b2Vec2 p1 = xf.p; b2Vec2 p2 = p1 + axisScale * xf.q.GetXAxis(); DrawSegment(p1, p2, new b2Color(1, 0, 0)); p2 = p1 + axisScale * xf.q.GetYAxis(); DrawSegment(p1, p2, new b2Color(0, 1, 0)); } public void DrawString(int x, int y, string format, params object[] objects) { stringData.Add(new StringData(x, y, format, objects, Color.White)); } public void DrawPoint(b2Vec2 p, float size, b2Color color) { b2Vec2[] verts = new b2Vec2[4]; float hs = size / 2.0f; verts[0] = p + new b2Vec2(-hs, -hs); verts[1] = p + new b2Vec2(hs, -hs); verts[2] = p + new b2Vec2(hs, hs); verts[3] = p + new b2Vec2(-hs, hs); DrawSolidPolygon(verts, 4, color); } public void DrawAABB(b2AABB aabb, b2Color p1) { b2Vec2[] verts = new b2Vec2[4]; verts[0] = new b2Vec2(aabb.LowerBound.x, aabb.LowerBound.y); verts[1] = new b2Vec2(aabb.UpperBound.x, aabb.LowerBound.y); verts[2] = new b2Vec2(aabb.UpperBound.x, aabb.UpperBound.y); verts[3] = new b2Vec2(aabb.LowerBound.x, aabb.UpperBound.y); DrawPolygon(verts, 4, p1); } public void Begin() { primitiveBatch.Begin(); } public void End() { primitiveBatch.End(); // var _batch = CCDrawManager.SharedDrawManager.SpriteBatch; // // _batch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend); // // for (int i = 0; i < stringData.Count; i++) // { // stringBuilder.Length = 0; // stringBuilder.AppendFormat(stringData[i].S, stringData[i].Args); // _batch.DrawString(spriteFont, stringBuilder, new Vector2(stringData[i].X, stringData[i].Y), // stringData[i].Color); // } // // _batch.End(); stringData.Clear(); } } }
using System; using UIKit; using Eto.Forms; using Eto.iOS.Forms.Controls; using Eto.Drawing; using Eto.Mac.Forms; using sd = System.Drawing; using Eto.iOS.Forms.Toolbar; namespace Eto.iOS.Forms { public abstract class IosWindow<TControl, TWidget, TCallback> : MacPanel<TControl, TWidget, TCallback>, Window.IHandler where TControl: UIView where TWidget: Window where TCallback: Window.ICallback { public override UIView ContainerControl { get { return Control; } } public bool DisableNavigationToolbar { get; set; } public new Point Location { get { return Control.Frame.Location.ToEtoPoint(); } set { var frame = this.Control.Frame; frame.Location = value.ToNS(); this.Control.Frame = frame; } } public double Opacity { get { return Control.Alpha; } set { Control.Alpha = (float)value; } } public override void AttachEvent(string handler) { switch (handler) { case Window.ClosedEvent: case Window.ClosingEvent: // TODO break; default: base.AttachEvent(handler); break; } } protected override void Initialize() { base.Initialize(); Control.BackgroundColor = UIColor.White; } public virtual void Close() { } ToolBar toolBar; public ToolBar ToolBar { get { return toolBar; } set { toolBar = value; if (toolBar != null) { var toolbarHandler = toolBar.Handler as ToolBarHandler; if (toolbarHandler != null) { toolbarHandler.UpdateContentSize = () => LayoutAllChildren(); } } SetToolbar(); } } public override void OnLoad(EventArgs e) { SetToolbar(true); base.OnLoad(e); } NavigationHandler GetTopNavigation() { var content = Widget.Content; while (content is Panel) { content = ((Panel)content).Content; } return content == null ? null : content.Handler as NavigationHandler; } protected override CoreGraphics.CGRect AdjustContent(CoreGraphics.CGRect rect) { rect = base.AdjustContent(rect); if (ToolBar != null) { var toolbarHandler = toolBar.Handler as ToolBarHandler; if (toolbarHandler != null) { var tbheight = toolbarHandler.Control.Frame.Height; rect.Height -= tbheight; if (ToolBar.Dock == ToolBarDock.Top) rect.Y += tbheight; } } return rect; } protected bool UseTopToolBar { get { return toolBar != null && toolBar.Dock == ToolBarDock.Top; } } void SetToolbar(bool force = false) { if (toolBar == null) return; var control = ToolBarHandler.GetControl(toolBar); var topNav = GetTopNavigation(); if (!DisableNavigationToolbar && topNav != null && toolBar.Dock == ToolBarDock.Bottom) { topNav.MainToolBar = control.Items; } else if (Widget.Loaded || force) { control.SizeToFit(); var height = control.Frame.Height; CoreGraphics.CGSize screenSize; if (Platform.IsIos7) screenSize = UIScreen.MainScreen.Bounds.Size; else screenSize = UIScreen.MainScreen.ApplicationFrame.Size; var bottom = toolBar.Dock == ToolBarDock.Bottom; var frame = new CoreGraphics.CGRect(0, 0, screenSize.Width, height); var mask = UIViewAutoresizing.FlexibleWidth; if (bottom) { frame.Y = screenSize.Height - height; mask |= UIViewAutoresizing.FlexibleTopMargin; } else frame.Y = ApplicationHandler.Instance.StatusBarAdjustment; control.Frame = frame; control.AutoresizingMask = mask; this.AddChild(toolBar); if (Widget.Loaded) LayoutChildren(); } } public abstract string Title { get; set; } public Screen Screen { get { return Screen.PrimaryScreen; } } public MenuBar Menu { get { return null; } set { } } public Icon Icon { get { return null; } set { } } public bool Resizable { get { return false; } set { } } public bool Maximizable { get { return false; } set { } } public bool Minimizable { get { return false; } set { } } public bool ShowInTaskbar { get { return false; } set { } } public bool Topmost { get { return false; } set { } } public WindowState WindowState { get; set; } public Rectangle RestoreBounds { get { return Widget.Bounds; } } public WindowStyle WindowStyle { get { return WindowStyle.Default; } set { } } public virtual void BringToFront() { } public virtual void SendToBack() { } public override ContextMenu ContextMenu { get { return null; } set { } } public virtual void SetOwner(Window owner) { } } }
using System; using System.Linq; using System.Text; using System.Collections.Generic; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; namespace HETSAPI.Models { /// <summary> /// User Database Model /// </summary> [MetaData (Description = "An identified user in the HETS Application that has a defined authorization level.")] public partial class User : AuditableEntity, IEquatable<User> { /// <summary> /// User Database Model Constructor (required by entity framework) /// </summary> public User() { Id = 0; } /// <summary> /// Initializes a new instance of the <see cref="User" /> class. /// </summary> /// <param name="id">A system-generated unique identifier for a User (required).</param> /// <param name="givenName">Given name of the user. (required).</param> /// <param name="surname">Surname of the user. (required).</param> /// <param name="active">A flag indicating the User is active in the system. Set false to remove access to the system for the user. (required).</param> /// <param name="initials">Initials of the user, to be presented where screen space is at a premium..</param> /// <param name="email">The email address of the user in the system..</param> /// <param name="smUserId">Security Manager User ID.</param> /// <param name="guid">The GUID unique to the user as provided by the authentication system. In this case, authentication is done by Siteminder and the GUID uniquely identifies the user within the user directories managed by Siteminder - e.g. IDIR and BCeID. The GUID is equivalent to the IDIR Id, but is guaranteed unique to a person, while the IDIR ID is not - IDIR IDs can be recycled..</param> /// <param name="smAuthorizationDirectory">The user directory service used by Siteminder to authenticate the user - usually IDIR or BCeID..</param> /// <param name="userRoles">UserRoles</param> /// <param name="district">The District that the User belongs to.</param> /// <param name="userDistricts">UserDistricts</param> public User(int id, string givenName, string surname, bool active, string initials = null, string email = null, string smUserId = null, string guid = null, string smAuthorizationDirectory = null, List<UserRole> userRoles = null, District district = null, List<UserDistrict> userDistricts = null) { Id = id; GivenName = givenName; Surname = surname; Active = active; Initials = initials; Email = email; SmUserId = smUserId; Guid = guid; SmAuthorizationDirectory = smAuthorizationDirectory; UserRoles = userRoles; District = district; UserDistricts = userDistricts; } /// <summary> /// A system-generated unique identifier for a User /// </summary> /// <value>A system-generated unique identifier for a User</value> [MetaData (Description = "A system-generated unique identifier for a User")] public int Id { get; set; } /// <summary> /// Given name of the user. /// </summary> /// <value>Given name of the user.</value> [MetaData (Description = "Given name of the user.")] [MaxLength(50)] public string GivenName { get; set; } /// <summary> /// Surname of the user. /// </summary> /// <value>Surname of the user.</value> [MetaData (Description = "Surname of the user.")] [MaxLength(50)] public string Surname { get; set; } /// <summary> /// A flag indicating the User is active in the system. Set false to remove access to the system for the user. /// </summary> /// <value>A flag indicating the User is active in the system. Set false to remove access to the system for the user.</value> [MetaData (Description = "A flag indicating the User is active in the system. Set false to remove access to the system for the user.")] public bool Active { get; set; } /// <summary> /// Initials of the user, to be presented where screen space is at a premium. /// </summary> /// <value>Initials of the user, to be presented where screen space is at a premium.</value> [MetaData (Description = "Initials of the user, to be presented where screen space is at a premium.")] [MaxLength(10)] public string Initials { get; set; } /// <summary> /// The email address of the user in the system. /// </summary> /// <value>The email address of the user in the system.</value> [MetaData (Description = "The email address of the user in the system.")] [MaxLength(255)] public string Email { get; set; } /// <summary> /// Security Manager User ID /// </summary> /// <value>Security Manager User ID</value> [MetaData (Description = "Security Manager User ID")] [MaxLength(255)] public string SmUserId { get; set; } /// <summary> /// The GUID unique to the user as provided by the authentication system. In this case, authentication is done by Siteminder and the GUID uniquely identifies the user within the user directories managed by Siteminder - e.g. IDIR and BCeID. The GUID is equivalent to the IDIR Id, but is guaranteed unique to a person, while the IDIR ID is not - IDIR IDs can be recycled. /// </summary> /// <value>The GUID unique to the user as provided by the authentication system. In this case, authentication is done by Siteminder and the GUID uniquely identifies the user within the user directories managed by Siteminder - e.g. IDIR and BCeID. The GUID is equivalent to the IDIR Id, but is guaranteed unique to a person, while the IDIR ID is not - IDIR IDs can be recycled.</value> [MetaData (Description = "The GUID unique to the user as provided by the authentication system. In this case, authentication is done by Siteminder and the GUID uniquely identifies the user within the user directories managed by Siteminder - e.g. IDIR and BCeID. The GUID is equivalent to the IDIR Id, but is guaranteed unique to a person, while the IDIR ID is not - IDIR IDs can be recycled.")] [MaxLength(255)] public string Guid { get; set; } /// <summary> /// The user directory service used by Siteminder to authenticate the user - usually IDIR or BCeID. /// </summary> /// <value>The user directory service used by Siteminder to authenticate the user - usually IDIR or BCeID.</value> [MetaData (Description = "The user directory service used by Siteminder to authenticate the user - usually IDIR or BCeID.")] [MaxLength(255)] public string SmAuthorizationDirectory { get; set; } /// <summary> /// Gets or Sets UserRoles /// </summary> public List<UserRole> UserRoles { get; set; } /// <summary> /// The District that the User belongs to /// </summary> /// <value>The District that the User belongs to</value> [MetaData (Description = "The District that the User belongs to")] public District District { get; set; } /// <summary> /// Foreign key for District /// </summary> [ForeignKey("District")] [JsonIgnore] [MetaData (Description = "The District that the User belongs to")] public int? DistrictId { get; set; } /// <summary> /// Gets or Sets UserDistricts /// </summary> public List<UserDistrict> UserDistricts { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class User {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" GivenName: ").Append(GivenName).Append("\n"); sb.Append(" Surname: ").Append(Surname).Append("\n"); sb.Append(" Active: ").Append(Active).Append("\n"); sb.Append(" Initials: ").Append(Initials).Append("\n"); sb.Append(" Email: ").Append(Email).Append("\n"); sb.Append(" SmUserId: ").Append(SmUserId).Append("\n"); sb.Append(" Guid: ").Append(Guid).Append("\n"); sb.Append(" SmAuthorizationDirectory: ").Append(SmAuthorizationDirectory).Append("\n"); sb.Append(" UserRoles: ").Append(UserRoles).Append("\n"); sb.Append(" District: ").Append(District).Append("\n"); sb.Append(" UserDistricts: ").Append(UserDistricts).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { if (obj is null) { return false; } if (ReferenceEquals(this, obj)) { return true; } return obj.GetType() == GetType() && Equals((User)obj); } /// <summary> /// Returns true if User instances are equal /// </summary> /// <param name="other">Instance of User to be compared</param> /// <returns>Boolean</returns> public bool Equals(User other) { if (other is null) { return false; } if (ReferenceEquals(this, other)) { return true; } return ( Id == other.Id || Id.Equals(other.Id) ) && ( GivenName == other.GivenName || GivenName != null && GivenName.Equals(other.GivenName) ) && ( Surname == other.Surname || Surname != null && Surname.Equals(other.Surname) ) && ( Active == other.Active || Active.Equals(other.Active) ) && ( Initials == other.Initials || Initials != null && Initials.Equals(other.Initials) ) && ( Email == other.Email || Email != null && Email.Equals(other.Email) ) && ( SmUserId == other.SmUserId || SmUserId != null && SmUserId.Equals(other.SmUserId) ) && ( Guid == other.Guid || Guid != null && Guid.Equals(other.Guid) ) && ( SmAuthorizationDirectory == other.SmAuthorizationDirectory || SmAuthorizationDirectory != null && SmAuthorizationDirectory.Equals(other.SmAuthorizationDirectory) ) && ( UserRoles == other.UserRoles || UserRoles != null && UserRoles.SequenceEqual(other.UserRoles) ) && ( District == other.District || District != null && District.Equals(other.District) ) && ( UserDistricts == other.UserDistricts || UserDistricts != null && UserDistricts.SequenceEqual(other.UserDistricts) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks hash = hash * 59 + Id.GetHashCode(); if (GivenName != null) { hash = hash * 59 + GivenName.GetHashCode(); } if (Surname != null) { hash = hash * 59 + Surname.GetHashCode(); } hash = hash * 59 + Active.GetHashCode(); if (Initials != null) { hash = hash * 59 + Initials.GetHashCode(); } if (Email != null) { hash = hash * 59 + Email.GetHashCode(); } if (SmUserId != null) { hash = hash * 59 + SmUserId.GetHashCode(); } if (Guid != null) { hash = hash * 59 + Guid.GetHashCode(); } if (SmAuthorizationDirectory != null) { hash = hash * 59 + SmAuthorizationDirectory.GetHashCode(); } if (UserRoles != null) { hash = hash * 59 + UserRoles.GetHashCode(); } if (District != null) { hash = hash * 59 + District.GetHashCode(); } if (UserDistricts != null) { hash = hash * 59 + UserDistricts.GetHashCode(); } return hash; } } #region Operators /// <summary> /// Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator ==(User left, User right) { return Equals(left, right); } /// <summary> /// Not Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator !=(User left, User right) { return !Equals(left, right); } #endregion Operators } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using DBlog.TransitData; using System.Text; using DBlog.Tools.Web; using DBlog.Data.Hibernate; using DBlog.TransitData.References; public partial class ShowPost : BlogPage { private TransitPost mPost = null; private bool mPreferredOnly = false; public bool PreferredOnly { get { return DBlog.Tools.Web.ViewState<bool>.GetViewStateValue( ViewState, string.Format("{0}:Preferred", ID), mPreferredOnly); } set { DBlog.Tools.Web.ViewState<bool>.SetViewStateValue( EnableViewState, ViewState, string.Format("{0}:Preferred", ID), value, ref mPreferredOnly); } } public bool PreferredOnlyFromQueryString { get { object p = Request["PreferredOnly"]; if (p == null) return false; bool pb = false; bool.TryParse(p.ToString(), out pb); return pb; } } public TransitPost Post { get { if (mPost == null) { if (!string.IsNullOrEmpty(Request["slug"])) { mPost = SessionManager.GetCachedObject<TransitPost>( "GetPostBySlug", SessionManager.PostTicket, Request["slug"]); } else if (RequestId > 0) { mPost = SessionManager.GetCachedObject<TransitPost>( "GetPostById", SessionManager.PostTicket, RequestId); } else { mPost = new TransitPost(); } } return mPost; } } public bool HasAccess { get { string key = string.Format("{0}:{1}:PostAccess", SessionManager.PostTicket, Post.Id); object result = Cache[key]; if (result == null) { result = SessionManager.BlogService.HasAccessToPost( SessionManager.PostTicket, Post.Id); Cache.Insert(key, result, null, DateTime.Now.AddHours(1), TimeSpan.Zero); } return (bool)result; } } public void comments_ItemCommand(object sender, DataGridCommandEventArgs e) { try { switch (e.CommandName) { case "Delete": SessionManager.BlogService.DeleteComment(SessionManager.Ticket, int.Parse(e.CommandArgument.ToString())); SessionManager.Invalidate<TransitPostComment>(); SessionManager.Invalidate<TransitComment>(); GetCommentsData(sender, e); break; } } catch (Exception ex) { ReportException(ex); } } protected void Page_Load(object sender, EventArgs e) { try { images.OnGetDataSource += new EventHandler(images_OnGetDataSource); comments.OnGetDataSource += new EventHandler(comments_OnGetDataSource); if (!IsPostBack) { PreferredOnly = PreferredOnlyFromQueryString; if (!HasAccess) { Response.Redirect(string.Format("./Login.aspx?r={0}&cookie={1}&access=denied", Renderer.UrlEncode(UrlPathAndQuery), SessionManager.sDBlogPostCookieName)); } if (SessionManager.CountersEnabled) { CounterCache.IncrementPostCounter(Post.Id, Cache, SessionManager); } GetData(sender, e); spanAdmin.Visible = SessionManager.IsAdministrator; linkEdit.NavigateUrl = string.Format("EditPost.aspx?id={0}", Post.Id); } } catch (Exception ex) { ReportException(ex); } } public void comments_OnGetDataSource(object sender, EventArgs e) { comments.DataSource = SessionManager.GetCachedCollection<TransitPostComment>( "GetPostComments", SessionManager.PostTicket, new TransitPostCommentQueryOptions( Post.Id, comments.AllowPaging ? comments.PageSize : 0, comments.AllowPaging ? comments.CurrentPageIndex : 0)); } public void GetData(object sender, EventArgs e) { TransitPost post = Post; // linkComment.NavigateUrl = string.Format("EditPostComment.aspx?sid={0}", post.Id); Title = posttitle.Text = Renderer.Render(post.Title); postbody.Text = RenderEx(post.Body, post.Id); posttopics.Text = GetTopics(post.Topics); postcreated.Text = post.Created.ToString("d"); if (SessionManager.CountersEnabled) { postcounter.Text = string.Format("{0} Click{1}", post.Counter.Count, post.Counter.Count != 1 ? "s" : string.Empty); } else { postcounter.Visible = false; } panelPicture.Visible = (post.ImageId != 0 && post.ImagesCount <= 1); postimage.ImageUrl = string.Format("./ShowPicture.aspx?id={0}", post.ImageId); linkimage.HRef = string.Format("./ShowImage.aspx?id={0}&pid={1}", post.ImageId, post.Id); twitterShare.Url = string.Format("{0}{1}", SessionManager.WebsiteUrl, post.LinkUri); twitterShare.Text = post.Title; disqusComments.DisqusId = string.Format("Post_{0}", post.Id); disqusComments.DisqusUrl = string.Format("{0}{1}", SessionManager.WebsiteUrl, post.LinkUri); GetImagesData(sender, e); GetCommentsData(sender, e); } public string GetTopics(TransitTopic[] topics) { StringBuilder sb = new StringBuilder(); foreach (TransitTopic topic in topics) { if (sb.Length != 0) sb.Append(", "); sb.Append(Renderer.Render(topic.Name)); } return sb.ToString(); } void GetCommentsData(object sender, EventArgs e) { TransitPost post = Post; comments.Visible = (post.CommentsCount > 0); comments.CurrentPageIndex = 0; comments.VirtualItemCount = SessionManager.GetCachedCollectionCount<TransitPostComment>( "GetPostCommentsCount", SessionManager.PostTicket, new TransitPostCommentQueryOptions(Post.Id)); comments_OnGetDataSource(sender, e); comments.DataBind(); } void GetImagesData(object sender, EventArgs e) { TransitPost post = Post; TransitPostImageQueryOptions imagesoptions = new TransitPostImageQueryOptions(Post.Id); imagesoptions.PreferredOnly = PreferredOnly; images.Visible = (post.ImagesCount > 1); images.CurrentPageIndex = 0; images.VirtualItemCount = SessionManager.GetCachedCollectionCount<TransitPostImage>( "GetPostImagesCountEx", SessionManager.PostTicket, imagesoptions); images_OnGetDataSource(sender, e); images.DataBind(); } void images_OnGetDataSource(object sender, EventArgs e) { string sortexpression = Request.Params["SortExpression"]; string sortdirection = Request.Params["SortDirection"]; TransitPostImageQueryOptions options = new TransitPostImageQueryOptions( Post.Id, images.PageSize, images.CurrentPageIndex); options.SortDirection = string.IsNullOrEmpty(sortdirection) ? WebServiceQuerySortDirection.Ascending : (WebServiceQuerySortDirection)Enum.Parse(typeof(WebServiceQuerySortDirection), sortdirection); options.SortExpression = string.IsNullOrEmpty(sortexpression) ? "Image.Image_Id" : sortexpression; options.PreferredOnly = PreferredOnly; images.DataSource = SessionManager.GetCachedCollection<TransitPostImage>( "GetPostImagesEx", SessionManager.PostTicket, options); } public string GetComments(TransitImage image) { if (image == null) return string.Empty; if (image.CommentsCount == 0) return string.Empty; return string.Format("{0} Comment{1}", image.CommentsCount, image.CommentsCount != 1 ? "s" : string.Empty); } public string GetCounter(TransitImage image) { if (!SessionManager.CountersEnabled) return string.Empty; if (image == null) return String.Empty; if (image.Counter.Count == 0) return string.Empty; return string.Format("[{0}]", image.Counter.Count); } public void linkPreferred_Click(object sender, EventArgs e) { try { PreferredOnly = ! PreferredOnly; GetImagesData(sender, e); } catch (Exception ex) { ReportException(ex); } } protected override void OnPreRender(EventArgs e) { linkPreferred.Text = PreferredOnly ? "Show All" : "Favorites"; base.OnPreRender(e); } public void images_OnItemCommand(object sender, DataListCommandEventArgs e) { try { switch (e.CommandName) { case "TogglePreferred": TransitImage image = SessionManager.GetCachedObject<TransitImage>( "GetImageById", SessionManager.Ticket, int.Parse(e.CommandArgument.ToString())); image.Preferred = !image.Preferred; SessionManager.BlogService.CreateOrUpdateImageAttributes(SessionManager.Ticket, image); SessionManager.Invalidate<TransitImage>(); images_OnGetDataSource(sender, e); ((LinkButton)e.CommandSource).Text = image.Preferred ? "P" : "p"; break; } } catch (Exception ex) { ReportException(ex); } } public string GetImageUri(TransitPostImage ti) { StringBuilder result = new StringBuilder(); result.AppendFormat("ShowImage.aspx?id={0}&pid={1}&index={2}", ti.Image.Id, ti.Post.Id, ti.Index); if (PreferredOnly) result.Append("&PreferredOnly=true"); if (!string.IsNullOrEmpty(Request.Params["SortExpression"])) result.AppendFormat("&SortExpression={0}", Request.Params["SortExpression"]); if (!string.IsNullOrEmpty(Request.Params["SortDirection"])) result.AppendFormat("&SortDirection={0}", Request.Params["SortDirection"]); return result.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.Xml; using System.Xml.Schema; using System.Xml.Serialization; using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Diagnostics; namespace System.Runtime.Serialization { internal static class Globals { /// <SecurityNote> /// Review - changes to const could affect code generation logic; any changes should be reviewed. /// </SecurityNote> internal const BindingFlags ScanAllMembers = BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; private static XmlQualifiedName s_idQualifiedName; internal static XmlQualifiedName IdQualifiedName { get { if (s_idQualifiedName == null) s_idQualifiedName = new XmlQualifiedName(Globals.IdLocalName, Globals.SerializationNamespace); return s_idQualifiedName; } } private static XmlQualifiedName s_refQualifiedName; internal static XmlQualifiedName RefQualifiedName { get { if (s_refQualifiedName == null) s_refQualifiedName = new XmlQualifiedName(Globals.RefLocalName, Globals.SerializationNamespace); return s_refQualifiedName; } } private static Type s_typeOfObject; internal static Type TypeOfObject { get { if (s_typeOfObject == null) s_typeOfObject = typeof(object); return s_typeOfObject; } } private static Type s_typeOfValueType; internal static Type TypeOfValueType { get { if (s_typeOfValueType == null) s_typeOfValueType = typeof(ValueType); return s_typeOfValueType; } } private static Type s_typeOfArray; internal static Type TypeOfArray { get { if (s_typeOfArray == null) s_typeOfArray = typeof(Array); return s_typeOfArray; } } private static Type s_typeOfException; internal static Type TypeOfException { get { if (s_typeOfException == null) s_typeOfException = typeof(Exception); return s_typeOfException; } } private static Type s_typeOfString; internal static Type TypeOfString { get { if (s_typeOfString == null) s_typeOfString = typeof(string); return s_typeOfString; } } private static Type s_typeOfInt; internal static Type TypeOfInt { get { if (s_typeOfInt == null) s_typeOfInt = typeof(int); return s_typeOfInt; } } private static Type s_typeOfULong; internal static Type TypeOfULong { get { if (s_typeOfULong == null) s_typeOfULong = typeof(ulong); return s_typeOfULong; } } private static Type s_typeOfVoid; internal static Type TypeOfVoid { get { if (s_typeOfVoid == null) s_typeOfVoid = typeof(void); return s_typeOfVoid; } } private static Type s_typeOfByteArray; internal static Type TypeOfByteArray { get { if (s_typeOfByteArray == null) s_typeOfByteArray = typeof(byte[]); return s_typeOfByteArray; } } private static Type s_typeOfTimeSpan; internal static Type TypeOfTimeSpan { get { if (s_typeOfTimeSpan == null) s_typeOfTimeSpan = typeof(TimeSpan); return s_typeOfTimeSpan; } } private static Type s_typeOfGuid; internal static Type TypeOfGuid { get { if (s_typeOfGuid == null) s_typeOfGuid = typeof(Guid); return s_typeOfGuid; } } private static Type s_typeOfDateTimeOffset; internal static Type TypeOfDateTimeOffset { get { if (s_typeOfDateTimeOffset == null) s_typeOfDateTimeOffset = typeof(DateTimeOffset); return s_typeOfDateTimeOffset; } } private static Type s_typeOfDateTimeOffsetAdapter; internal static Type TypeOfDateTimeOffsetAdapter { get { if (s_typeOfDateTimeOffsetAdapter == null) s_typeOfDateTimeOffsetAdapter = typeof(DateTimeOffsetAdapter); return s_typeOfDateTimeOffsetAdapter; } } private static Type s_typeOfUri; internal static Type TypeOfUri { get { if (s_typeOfUri == null) s_typeOfUri = typeof(Uri); return s_typeOfUri; } } private static Type s_typeOfTypeEnumerable; internal static Type TypeOfTypeEnumerable { get { if (s_typeOfTypeEnumerable == null) s_typeOfTypeEnumerable = typeof(IEnumerable<Type>); return s_typeOfTypeEnumerable; } } private static Type s_typeOfStreamingContext; internal static Type TypeOfStreamingContext { get { if (s_typeOfStreamingContext == null) s_typeOfStreamingContext = typeof(StreamingContext); return s_typeOfStreamingContext; } } private static Type s_typeOfISerializable; internal static Type TypeOfISerializable { get { if (s_typeOfISerializable == null) s_typeOfISerializable = typeof(ISerializable); return s_typeOfISerializable; } } private static Type s_typeOfIDeserializationCallback; internal static Type TypeOfIDeserializationCallback { get { if (s_typeOfIDeserializationCallback == null) s_typeOfIDeserializationCallback = typeof(IDeserializationCallback); return s_typeOfIDeserializationCallback; } } private static Type s_typeOfIObjectReference; internal static Type TypeOfIObjectReference { get { if (s_typeOfIObjectReference == null) s_typeOfIObjectReference = typeof(IObjectReference); return s_typeOfIObjectReference; } } private static Type s_typeOfXmlFormatClassWriterDelegate; internal static Type TypeOfXmlFormatClassWriterDelegate { get { if (s_typeOfXmlFormatClassWriterDelegate == null) s_typeOfXmlFormatClassWriterDelegate = typeof(XmlFormatClassWriterDelegate); return s_typeOfXmlFormatClassWriterDelegate; } } private static Type s_typeOfXmlFormatCollectionWriterDelegate; internal static Type TypeOfXmlFormatCollectionWriterDelegate { get { if (s_typeOfXmlFormatCollectionWriterDelegate == null) s_typeOfXmlFormatCollectionWriterDelegate = typeof(XmlFormatCollectionWriterDelegate); return s_typeOfXmlFormatCollectionWriterDelegate; } } private static Type s_typeOfXmlFormatClassReaderDelegate; internal static Type TypeOfXmlFormatClassReaderDelegate { get { if (s_typeOfXmlFormatClassReaderDelegate == null) s_typeOfXmlFormatClassReaderDelegate = typeof(XmlFormatClassReaderDelegate); return s_typeOfXmlFormatClassReaderDelegate; } } private static Type s_typeOfXmlFormatCollectionReaderDelegate; internal static Type TypeOfXmlFormatCollectionReaderDelegate { get { if (s_typeOfXmlFormatCollectionReaderDelegate == null) s_typeOfXmlFormatCollectionReaderDelegate = typeof(XmlFormatCollectionReaderDelegate); return s_typeOfXmlFormatCollectionReaderDelegate; } } private static Type s_typeOfXmlFormatGetOnlyCollectionReaderDelegate; internal static Type TypeOfXmlFormatGetOnlyCollectionReaderDelegate { get { if (s_typeOfXmlFormatGetOnlyCollectionReaderDelegate == null) s_typeOfXmlFormatGetOnlyCollectionReaderDelegate = typeof(XmlFormatGetOnlyCollectionReaderDelegate); return s_typeOfXmlFormatGetOnlyCollectionReaderDelegate; } } private static Type s_typeOfKnownTypeAttribute; internal static Type TypeOfKnownTypeAttribute { get { if (s_typeOfKnownTypeAttribute == null) s_typeOfKnownTypeAttribute = typeof(KnownTypeAttribute); return s_typeOfKnownTypeAttribute; } } private static Type s_typeOfDataContractAttribute; internal static Type TypeOfDataContractAttribute { get { if (s_typeOfDataContractAttribute == null) s_typeOfDataContractAttribute = typeof(DataContractAttribute); return s_typeOfDataContractAttribute; } } private static Type s_typeOfDataMemberAttribute; internal static Type TypeOfDataMemberAttribute { get { if (s_typeOfDataMemberAttribute == null) s_typeOfDataMemberAttribute = typeof(DataMemberAttribute); return s_typeOfDataMemberAttribute; } } private static Type s_typeOfEnumMemberAttribute; internal static Type TypeOfEnumMemberAttribute { get { if (s_typeOfEnumMemberAttribute == null) s_typeOfEnumMemberAttribute = typeof(EnumMemberAttribute); return s_typeOfEnumMemberAttribute; } } private static Type s_typeOfCollectionDataContractAttribute; internal static Type TypeOfCollectionDataContractAttribute { get { if (s_typeOfCollectionDataContractAttribute == null) s_typeOfCollectionDataContractAttribute = typeof(CollectionDataContractAttribute); return s_typeOfCollectionDataContractAttribute; } } private static Type s_typeOfOptionalFieldAttribute; internal static Type TypeOfOptionalFieldAttribute { get { if (s_typeOfOptionalFieldAttribute == null) { s_typeOfOptionalFieldAttribute = typeof(OptionalFieldAttribute); } return s_typeOfOptionalFieldAttribute; } } private static Type s_typeOfObjectArray; internal static Type TypeOfObjectArray { get { if (s_typeOfObjectArray == null) s_typeOfObjectArray = typeof(object[]); return s_typeOfObjectArray; } } private static Type s_typeOfOnSerializingAttribute; internal static Type TypeOfOnSerializingAttribute { get { if (s_typeOfOnSerializingAttribute == null) s_typeOfOnSerializingAttribute = typeof(OnSerializingAttribute); return s_typeOfOnSerializingAttribute; } } private static Type s_typeOfOnSerializedAttribute; internal static Type TypeOfOnSerializedAttribute { get { if (s_typeOfOnSerializedAttribute == null) s_typeOfOnSerializedAttribute = typeof(OnSerializedAttribute); return s_typeOfOnSerializedAttribute; } } private static Type s_typeOfOnDeserializingAttribute; internal static Type TypeOfOnDeserializingAttribute { get { if (s_typeOfOnDeserializingAttribute == null) s_typeOfOnDeserializingAttribute = typeof(OnDeserializingAttribute); return s_typeOfOnDeserializingAttribute; } } private static Type s_typeOfOnDeserializedAttribute; internal static Type TypeOfOnDeserializedAttribute { get { if (s_typeOfOnDeserializedAttribute == null) s_typeOfOnDeserializedAttribute = typeof(OnDeserializedAttribute); return s_typeOfOnDeserializedAttribute; } } private static Type s_typeOfFlagsAttribute; internal static Type TypeOfFlagsAttribute { get { if (s_typeOfFlagsAttribute == null) s_typeOfFlagsAttribute = typeof(FlagsAttribute); return s_typeOfFlagsAttribute; } } private static Type s_typeOfIXmlSerializable; internal static Type TypeOfIXmlSerializable { get { if (s_typeOfIXmlSerializable == null) s_typeOfIXmlSerializable = typeof(IXmlSerializable); return s_typeOfIXmlSerializable; } } private static Type s_typeOfXmlSchemaProviderAttribute; internal static Type TypeOfXmlSchemaProviderAttribute { get { if (s_typeOfXmlSchemaProviderAttribute == null) s_typeOfXmlSchemaProviderAttribute = typeof(XmlSchemaProviderAttribute); return s_typeOfXmlSchemaProviderAttribute; } } private static Type s_typeOfXmlRootAttribute; internal static Type TypeOfXmlRootAttribute { get { if (s_typeOfXmlRootAttribute == null) s_typeOfXmlRootAttribute = typeof(XmlRootAttribute); return s_typeOfXmlRootAttribute; } } private static Type s_typeOfXmlQualifiedName; internal static Type TypeOfXmlQualifiedName { get { if (s_typeOfXmlQualifiedName == null) s_typeOfXmlQualifiedName = typeof(XmlQualifiedName); return s_typeOfXmlQualifiedName; } } private static Type s_typeOfXmlSchemaType; internal static Type TypeOfXmlSchemaType { get { if (s_typeOfXmlSchemaType == null) { s_typeOfXmlSchemaType = typeof(XmlSchemaType); } return s_typeOfXmlSchemaType; } } private static Type s_typeOfIExtensibleDataObject; internal static Type TypeOfIExtensibleDataObject => s_typeOfIExtensibleDataObject ?? (s_typeOfIExtensibleDataObject = typeof(IExtensibleDataObject)); private static Type s_typeOfExtensionDataObject; internal static Type TypeOfExtensionDataObject => s_typeOfExtensionDataObject ?? (s_typeOfExtensionDataObject = typeof(ExtensionDataObject)); private static Type s_typeOfISerializableDataNode; internal static Type TypeOfISerializableDataNode { get { if (s_typeOfISerializableDataNode == null) s_typeOfISerializableDataNode = typeof(ISerializableDataNode); return s_typeOfISerializableDataNode; } } private static Type s_typeOfClassDataNode; internal static Type TypeOfClassDataNode { get { if (s_typeOfClassDataNode == null) s_typeOfClassDataNode = typeof(ClassDataNode); return s_typeOfClassDataNode; } } private static Type s_typeOfCollectionDataNode; internal static Type TypeOfCollectionDataNode { get { if (s_typeOfCollectionDataNode == null) s_typeOfCollectionDataNode = typeof(CollectionDataNode); return s_typeOfCollectionDataNode; } } private static Type s_typeOfXmlDataNode; internal static Type TypeOfXmlDataNode => s_typeOfXmlDataNode ?? (s_typeOfXmlDataNode = typeof(XmlDataNode)); #if uapaot private static Type s_typeOfSafeSerializationManager; private static bool s_typeOfSafeSerializationManagerSet; internal static Type TypeOfSafeSerializationManager { get { if (!s_typeOfSafeSerializationManagerSet) { s_typeOfSafeSerializationManager = TypeOfInt.Assembly.GetType("System.Runtime.Serialization.SafeSerializationManager"); s_typeOfSafeSerializationManagerSet = true; } return s_typeOfSafeSerializationManager; } } #endif private static Type s_typeOfNullable; internal static Type TypeOfNullable { get { if (s_typeOfNullable == null) s_typeOfNullable = typeof(Nullable<>); return s_typeOfNullable; } } private static Type s_typeOfIDictionaryGeneric; internal static Type TypeOfIDictionaryGeneric { get { if (s_typeOfIDictionaryGeneric == null) s_typeOfIDictionaryGeneric = typeof(IDictionary<,>); return s_typeOfIDictionaryGeneric; } } private static Type s_typeOfIDictionary; internal static Type TypeOfIDictionary { get { if (s_typeOfIDictionary == null) s_typeOfIDictionary = typeof(IDictionary); return s_typeOfIDictionary; } } private static Type s_typeOfIListGeneric; internal static Type TypeOfIListGeneric { get { if (s_typeOfIListGeneric == null) s_typeOfIListGeneric = typeof(IList<>); return s_typeOfIListGeneric; } } private static Type s_typeOfIList; internal static Type TypeOfIList { get { if (s_typeOfIList == null) s_typeOfIList = typeof(IList); return s_typeOfIList; } } private static Type s_typeOfICollectionGeneric; internal static Type TypeOfICollectionGeneric { get { if (s_typeOfICollectionGeneric == null) s_typeOfICollectionGeneric = typeof(ICollection<>); return s_typeOfICollectionGeneric; } } private static Type s_typeOfICollection; internal static Type TypeOfICollection { get { if (s_typeOfICollection == null) s_typeOfICollection = typeof(ICollection); return s_typeOfICollection; } } private static Type s_typeOfIEnumerableGeneric; internal static Type TypeOfIEnumerableGeneric { get { if (s_typeOfIEnumerableGeneric == null) s_typeOfIEnumerableGeneric = typeof(IEnumerable<>); return s_typeOfIEnumerableGeneric; } } private static Type s_typeOfIEnumerable; internal static Type TypeOfIEnumerable { get { if (s_typeOfIEnumerable == null) s_typeOfIEnumerable = typeof(IEnumerable); return s_typeOfIEnumerable; } } private static Type s_typeOfIEnumeratorGeneric; internal static Type TypeOfIEnumeratorGeneric { get { if (s_typeOfIEnumeratorGeneric == null) s_typeOfIEnumeratorGeneric = typeof(IEnumerator<>); return s_typeOfIEnumeratorGeneric; } } private static Type s_typeOfIEnumerator; internal static Type TypeOfIEnumerator { get { if (s_typeOfIEnumerator == null) s_typeOfIEnumerator = typeof(IEnumerator); return s_typeOfIEnumerator; } } private static Type s_typeOfKeyValuePair; internal static Type TypeOfKeyValuePair { get { if (s_typeOfKeyValuePair == null) s_typeOfKeyValuePair = typeof(KeyValuePair<,>); return s_typeOfKeyValuePair; } } private static Type s_typeOfKeyValuePairAdapter; internal static Type TypeOfKeyValuePairAdapter { get { if (s_typeOfKeyValuePairAdapter == null) s_typeOfKeyValuePairAdapter = typeof(KeyValuePairAdapter<,>); return s_typeOfKeyValuePairAdapter; } } private static Type s_typeOfKeyValue; internal static Type TypeOfKeyValue { get { if (s_typeOfKeyValue == null) s_typeOfKeyValue = typeof(KeyValue<,>); return s_typeOfKeyValue; } } private static Type s_typeOfIDictionaryEnumerator; internal static Type TypeOfIDictionaryEnumerator { get { if (s_typeOfIDictionaryEnumerator == null) s_typeOfIDictionaryEnumerator = typeof(IDictionaryEnumerator); return s_typeOfIDictionaryEnumerator; } } private static Type s_typeOfDictionaryEnumerator; internal static Type TypeOfDictionaryEnumerator { get { if (s_typeOfDictionaryEnumerator == null) s_typeOfDictionaryEnumerator = typeof(CollectionDataContract.DictionaryEnumerator); return s_typeOfDictionaryEnumerator; } } private static Type s_typeOfGenericDictionaryEnumerator; internal static Type TypeOfGenericDictionaryEnumerator { get { if (s_typeOfGenericDictionaryEnumerator == null) s_typeOfGenericDictionaryEnumerator = typeof(CollectionDataContract.GenericDictionaryEnumerator<,>); return s_typeOfGenericDictionaryEnumerator; } } private static Type s_typeOfDictionaryGeneric; internal static Type TypeOfDictionaryGeneric { get { if (s_typeOfDictionaryGeneric == null) s_typeOfDictionaryGeneric = typeof(Dictionary<,>); return s_typeOfDictionaryGeneric; } } private static Type s_typeOfHashtable; internal static Type TypeOfHashtable { get { if (s_typeOfHashtable == null) s_typeOfHashtable = TypeOfDictionaryGeneric.MakeGenericType(TypeOfObject, TypeOfObject); return s_typeOfHashtable; } } private static Type s_typeOfListGeneric; internal static Type TypeOfListGeneric { get { if (s_typeOfListGeneric == null) s_typeOfListGeneric = typeof(List<>); return s_typeOfListGeneric; } } private static Type s_typeOfXmlElement; internal static Type TypeOfXmlElement { get { if (s_typeOfXmlElement == null) s_typeOfXmlElement = typeof(XmlElement); return s_typeOfXmlElement; } } private static Type s_typeOfXmlNodeArray; internal static Type TypeOfXmlNodeArray { get { if (s_typeOfXmlNodeArray == null) s_typeOfXmlNodeArray = typeof(XmlNode[]); return s_typeOfXmlNodeArray; } } private static Type s_typeOfDBNull; internal static Type TypeOfDBNull { get { if (s_typeOfDBNull == null) s_typeOfDBNull = typeof(DBNull); return s_typeOfDBNull; } } private static Uri s_dataContractXsdBaseNamespaceUri; internal static Uri DataContractXsdBaseNamespaceUri { get { if (s_dataContractXsdBaseNamespaceUri == null) s_dataContractXsdBaseNamespaceUri = new Uri(DataContractXsdBaseNamespace); return s_dataContractXsdBaseNamespaceUri; } } #region Contract compliance for System.Type private static bool TypeSequenceEqual(Type[] seq1, Type[] seq2) { if (seq1 == null || seq2 == null || seq1.Length != seq2.Length) return false; for (int i = 0; i < seq1.Length; i++) { if (!seq1[i].Equals(seq2[i]) && !seq1[i].IsAssignableFrom(seq2[i])) return false; } return true; } private static MethodBase FilterMethodBases(MethodBase[] methodBases, Type[] parameterTypes, string methodName) { if (methodBases == null || string.IsNullOrEmpty(methodName)) return null; var matchedMethods = methodBases.Where(method => method.Name.Equals(methodName)); matchedMethods = matchedMethods.Where(method => TypeSequenceEqual(method.GetParameters().Select(param => param.ParameterType).ToArray(), parameterTypes)); return matchedMethods.FirstOrDefault(); } internal static ConstructorInfo GetConstructor(this Type type, BindingFlags bindingFlags, Type[] parameterTypes) { var constructorInfos = type.GetConstructors(bindingFlags); var constructorInfo = FilterMethodBases(constructorInfos.Cast<MethodBase>().ToArray(), parameterTypes, ".ctor"); return constructorInfo != null ? (ConstructorInfo)constructorInfo : null; } internal static MethodInfo GetMethod(this Type type, string methodName, BindingFlags bindingFlags, Type[] parameterTypes) { var methodInfos = type.GetMethods(bindingFlags); var methodInfo = FilterMethodBases(methodInfos.Cast<MethodBase>().ToArray(), parameterTypes, methodName); return methodInfo != null ? (MethodInfo)methodInfo : null; } #endregion private static Type s_typeOfScriptObject; private static Func<object, string> s_serializeFunc; private static Func<string, object> s_deserializeFunc; internal static ClassDataContract CreateScriptObjectClassDataContract() { Debug.Assert(s_typeOfScriptObject != null); return new ClassDataContract(s_typeOfScriptObject); } internal static bool TypeOfScriptObject_IsAssignableFrom(Type type) { return s_typeOfScriptObject != null && s_typeOfScriptObject.IsAssignableFrom(type); } internal static void SetScriptObjectJsonSerializer(Type typeOfScriptObject, Func<object, string> serializeFunc, Func<string, object> deserializeFunc) { Globals.s_typeOfScriptObject = typeOfScriptObject; Globals.s_serializeFunc = serializeFunc; Globals.s_deserializeFunc = deserializeFunc; } internal static string ScriptObjectJsonSerialize(object obj) { Debug.Assert(s_serializeFunc != null); return Globals.s_serializeFunc(obj); } internal static object ScriptObjectJsonDeserialize(string json) { Debug.Assert(s_deserializeFunc != null); return Globals.s_deserializeFunc(json); } public const bool DefaultIsRequired = false; public const bool DefaultEmitDefaultValue = true; public const int DefaultOrder = 0; public const bool DefaultIsReference = false; // The value string.Empty aids comparisons (can do simple length checks // instead of string comparison method calls in IL.) public static readonly string NewObjectId = string.Empty; public const string NullObjectId = null; public const string SimpleSRSInternalsVisiblePattern = @"^[\s]*System\.Runtime\.Serialization[\s]*$"; public const string FullSRSInternalsVisiblePattern = @"^[\s]*System\.Runtime\.Serialization[\s]*,[\s]*PublicKey[\s]*=[\s]*(?i:00240000048000009400000006020000002400005253413100040000010001008d56c76f9e8649383049f383c44be0ec204181822a6c31cf5eb7ef486944d032188ea1d3920763712ccb12d75fb77e9811149e6148e5d32fbaab37611c1878ddc19e20ef135d0cb2cff2bfec3d115810c3d9069638fe4be215dbf795861920e5ab6f7db2e2ceef136ac23d5dd2bf031700aec232f6c6b1c785b4305c123b37ab)[\s]*$"; public const string Space = " "; public const string XsiPrefix = "i"; public const string XsdPrefix = "x"; public const string SerPrefix = "z"; public const string SerPrefixForSchema = "ser"; public const string ElementPrefix = "q"; public const string DataContractXsdBaseNamespace = "http://schemas.datacontract.org/2004/07/"; public const string DataContractXmlNamespace = DataContractXsdBaseNamespace + "System.Xml"; public const string SchemaInstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance"; public const string SchemaNamespace = "http://www.w3.org/2001/XMLSchema"; public const string XsiNilLocalName = "nil"; public const string XsiTypeLocalName = "type"; public const string TnsPrefix = "tns"; public const string OccursUnbounded = "unbounded"; public const string AnyTypeLocalName = "anyType"; public const string StringLocalName = "string"; public const string IntLocalName = "int"; public const string True = "true"; public const string False = "false"; public const string ArrayPrefix = "ArrayOf"; public const string XmlnsNamespace = "http://www.w3.org/2000/xmlns/"; public const string XmlnsPrefix = "xmlns"; public const string SchemaLocalName = "schema"; public const string CollectionsNamespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays"; public const string DefaultClrNamespace = "GeneratedNamespace"; public const string DefaultTypeName = "GeneratedType"; public const string DefaultGeneratedMember = "GeneratedMember"; public const string DefaultFieldSuffix = "Field"; public const string DefaultPropertySuffix = "Property"; public const string DefaultMemberSuffix = "Member"; public const string NameProperty = "Name"; public const string NamespaceProperty = "Namespace"; public const string OrderProperty = "Order"; public const string IsReferenceProperty = "IsReference"; public const string IsRequiredProperty = "IsRequired"; public const string EmitDefaultValueProperty = "EmitDefaultValue"; public const string ClrNamespaceProperty = "ClrNamespace"; public const string ItemNameProperty = "ItemName"; public const string KeyNameProperty = "KeyName"; public const string ValueNameProperty = "ValueName"; public const string SerializationInfoPropertyName = "SerializationInfo"; public const string SerializationInfoFieldName = "info"; public const string NodeArrayPropertyName = "Nodes"; public const string NodeArrayFieldName = "nodesField"; public const string ExportSchemaMethod = "ExportSchema"; public const string IsAnyProperty = "IsAny"; public const string ContextFieldName = "context"; public const string GetObjectDataMethodName = "GetObjectData"; public const string GetEnumeratorMethodName = "GetEnumerator"; public const string MoveNextMethodName = "MoveNext"; public const string AddValueMethodName = "AddValue"; public const string CurrentPropertyName = "Current"; public const string ValueProperty = "Value"; public const string EnumeratorFieldName = "enumerator"; public const string SerializationEntryFieldName = "entry"; public const string ExtensionDataSetMethod = "set_ExtensionData"; public const string ExtensionDataSetExplicitMethod = "System.Runtime.Serialization.IExtensibleDataObject.set_ExtensionData"; public const string ExtensionDataObjectPropertyName = "ExtensionData"; public const string ExtensionDataObjectFieldName = "extensionDataField"; public const string AddMethodName = "Add"; public const string GetCurrentMethodName = "get_Current"; // NOTE: These values are used in schema below. If you modify any value, please make the same change in the schema. public const string SerializationNamespace = "http://schemas.microsoft.com/2003/10/Serialization/"; public const string ClrTypeLocalName = "Type"; public const string ClrAssemblyLocalName = "Assembly"; public const string IsValueTypeLocalName = "IsValueType"; public const string EnumerationValueLocalName = "EnumerationValue"; public const string SurrogateDataLocalName = "Surrogate"; public const string GenericTypeLocalName = "GenericType"; public const string GenericParameterLocalName = "GenericParameter"; public const string GenericNameAttribute = "Name"; public const string GenericNamespaceAttribute = "Namespace"; public const string GenericParameterNestedLevelAttribute = "NestedLevel"; public const string IsDictionaryLocalName = "IsDictionary"; public const string ActualTypeLocalName = "ActualType"; public const string ActualTypeNameAttribute = "Name"; public const string ActualTypeNamespaceAttribute = "Namespace"; public const string DefaultValueLocalName = "DefaultValue"; public const string EmitDefaultValueAttribute = "EmitDefaultValue"; public const string IdLocalName = "Id"; public const string RefLocalName = "Ref"; public const string ArraySizeLocalName = "Size"; public const string KeyLocalName = "Key"; public const string ValueLocalName = "Value"; public const string MscorlibAssemblyName = "0"; public const string ParseMethodName = "Parse"; public const string SafeSerializationManagerName = "SafeSerializationManager"; public const string SafeSerializationManagerNamespace = "http://schemas.datacontract.org/2004/07/System.Runtime.Serialization"; public const string ISerializableFactoryTypeLocalName = "FactoryType"; public const string SerializationSchema = @"<?xml version='1.0' encoding='utf-8'?> <xs:schema elementFormDefault='qualified' attributeFormDefault='qualified' xmlns:tns='http://schemas.microsoft.com/2003/10/Serialization/' targetNamespace='http://schemas.microsoft.com/2003/10/Serialization/' xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='anyType' nillable='true' type='xs:anyType' /> <xs:element name='anyURI' nillable='true' type='xs:anyURI' /> <xs:element name='base64Binary' nillable='true' type='xs:base64Binary' /> <xs:element name='boolean' nillable='true' type='xs:boolean' /> <xs:element name='byte' nillable='true' type='xs:byte' /> <xs:element name='dateTime' nillable='true' type='xs:dateTime' /> <xs:element name='decimal' nillable='true' type='xs:decimal' /> <xs:element name='double' nillable='true' type='xs:double' /> <xs:element name='float' nillable='true' type='xs:float' /> <xs:element name='int' nillable='true' type='xs:int' /> <xs:element name='long' nillable='true' type='xs:long' /> <xs:element name='QName' nillable='true' type='xs:QName' /> <xs:element name='short' nillable='true' type='xs:short' /> <xs:element name='string' nillable='true' type='xs:string' /> <xs:element name='unsignedByte' nillable='true' type='xs:unsignedByte' /> <xs:element name='unsignedInt' nillable='true' type='xs:unsignedInt' /> <xs:element name='unsignedLong' nillable='true' type='xs:unsignedLong' /> <xs:element name='unsignedShort' nillable='true' type='xs:unsignedShort' /> <xs:element name='char' nillable='true' type='tns:char' /> <xs:simpleType name='char'> <xs:restriction base='xs:int'/> </xs:simpleType> <xs:element name='duration' nillable='true' type='tns:duration' /> <xs:simpleType name='duration'> <xs:restriction base='xs:duration'> <xs:pattern value='\-?P(\d*D)?(T(\d*H)?(\d*M)?(\d*(\.\d*)?S)?)?' /> <xs:minInclusive value='-P10675199DT2H48M5.4775808S' /> <xs:maxInclusive value='P10675199DT2H48M5.4775807S' /> </xs:restriction> </xs:simpleType> <xs:element name='guid' nillable='true' type='tns:guid' /> <xs:simpleType name='guid'> <xs:restriction base='xs:string'> <xs:pattern value='[\da-fA-F]{8}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{12}' /> </xs:restriction> </xs:simpleType> <xs:attribute name='FactoryType' type='xs:QName' /> <xs:attribute name='Id' type='xs:ID' /> <xs:attribute name='Ref' type='xs:IDREF' /> </xs:schema> "; } }
using System; using System.Diagnostics.CodeAnalysis; using System.Reactive.Concurrency; using System.Threading; using FakeItEasy; using Xunit; using Xunit.Extensions; namespace Burden.Tests { public abstract class AutoJobExecutionQueueTest<TJobInput, TJobOutput> : JobExecutionQueueTest<AutoJobExecutionQueue<TJobInput, TJobOutput>, TJobInput, TJobOutput> { private Func<IScheduler, int, int, AutoJobExecutionQueue<TJobInput, TJobOutput>> _maxConcurrentJobQueueFactory; private Func<int, int, AutoJobExecutionQueue<TJobInput, TJobOutput>> _publicMaxConcurrentJobQueueFactory; [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Nested generics, while advanced, are perfectly acceptable within Funcs")] protected AutoJobExecutionQueueTest(Func<IScheduler, int, int, AutoJobExecutionQueue<TJobInput, TJobOutput>> maxConcurrentJobQueueFactory, Func<int, int, AutoJobExecutionQueue<TJobInput, TJobOutput>> publicMaxConcurrentJobQueueFactory) // : base(s => maxConcurrentJobQueueFactory(s, AutoJobExecutionQueue<TJobInput, TJobOutput>.DefaultConcurrent, 0)) { this._maxConcurrentJobQueueFactory = maxConcurrentJobQueueFactory; this._publicMaxConcurrentJobQueueFactory = publicMaxConcurrentJobQueueFactory; } [Fact] public void Constructor_ThrowsOnLessThanOneConcurrentJob() { Assert.Throws<ArgumentOutOfRangeException>(() => _publicMaxConcurrentJobQueueFactory(0, 0)); } [Fact] public void Add_ToJobQueueInterface_AutomaticallyStartsJob() { var queue = _maxConcurrentJobQueueFactory(Scheduler.Immediate, 10, 10) as IJobExecutionQueue<TJobInput, TJobOutput>; var jobExecuted = new ManualResetEventSlim(false); queue.Add(A.Dummy<TJobInput>(), jobInput => { jobExecuted.Set(); return A.Dummy<TJobOutput>(); }); Assert.True(jobExecuted.Wait(TimeSpan.FromSeconds(2))); } class JobExecutionStatus { public int RemainingJobs { get; set; } public bool ExpectedNumberOfJobsFiredUp { get; set; } public ManualResetEventSlim PrimaryJobPauser { get; set; } public ManualResetEventSlim SecondaryJobPauser { get; set; } public ManualResetEventSlim AllJobsForIterationLaunched { get; set; } public IJobExecutionQueue<TJobInput, TJobOutput> Queue { get; set; } } private JobExecutionStatus WaitForMaxConcurrentJobsToStart(int jobsToAdd, int toStart, int iterations, bool jobShouldThrow) { var status = new JobExecutionStatus() { Queue = _maxConcurrentJobQueueFactory(Scheduler.Immediate, AutoJobExecutionQueue<TJobInput, TJobOutput>.DefaultConcurrent, toStart) as IJobExecutionQueue<TJobInput, TJobOutput>, AllJobsForIterationLaunched = new ManualResetEventSlim(false), PrimaryJobPauser = new ManualResetEventSlim(false), SecondaryJobPauser = new ManualResetEventSlim(false), RemainingJobs = jobsToAdd }; using (var firstGateCrossedByAllJobs = new ManualResetEventSlim(false)) using (var secondGateCrossedByAllJobs = new ManualResetEventSlim(false)) { int jobCounter = 0, firstGateCounter = 0, secondGateCounter = 0; for (int i = 0; i < jobsToAdd; i++) { status.Queue.Add(A.Dummy<TJobInput>(), jobInput => { int expectedCounterValue = Math.Min(status.Queue.MaxConcurrent, Math.Min(toStart, status.RemainingJobs)); if (Interlocked.Increment(ref jobCounter) == expectedCounterValue) status.AllJobsForIterationLaunched.Set(); //we have to get a bit complex here by controlling automatic job execution with 2 locks status.PrimaryJobPauser.Wait(); if (Interlocked.Increment(ref firstGateCounter) == expectedCounterValue) firstGateCrossedByAllJobs.Set(); status.SecondaryJobPauser.Wait(); if (Interlocked.Increment(ref secondGateCounter) == expectedCounterValue) secondGateCrossedByAllJobs.Set(); if (!jobShouldThrow) return A.Dummy<TJobOutput>(); throw new ArgumentException(); }); } for (int j = 0; j < iterations; j++) { //wait for all jobs to start, then reset counter, allow them to complete, and reset allJobsLaunched status.AllJobsForIterationLaunched.Wait(TimeSpan.FromSeconds(5)); //throw new ApplicationException(); Interlocked.Exchange(ref jobCounter, 0); status.AllJobsForIterationLaunched.Reset(); status.RemainingJobs = status.Queue.QueuedCount; //let the next set begin to flow through, by unlocking the first gate status.PrimaryJobPauser.Set(); //wait until all the jobs have received it before resetting the pauser, which will hold the next set of jobs as they're pumped in firstGateCrossedByAllJobs.Wait(TimeSpan.FromSeconds(5)); firstGateCrossedByAllJobs.Reset(); status.PrimaryJobPauser.Reset(); //reset the gate counter... Interlocked.Exchange(ref firstGateCounter, 0); //if it's our last iteration, leaved the jobs paused if (j != iterations - 1) { status.SecondaryJobPauser.Set(); //wait again, this time for the second gate secondGateCrossedByAllJobs.Wait(TimeSpan.FromSeconds(5)); secondGateCrossedByAllJobs.Reset(); Interlocked.Exchange(ref secondGateCounter, 0); } status.SecondaryJobPauser.Reset(); } return status; } } [Theory] [InlineData(25, 5, 1, false)] [InlineData(1, 1, 1, false)] [InlineData(1, 3, 1, false)] [InlineData(25, 5, 2, false)] [InlineData(7, 2, 3, false)] [InlineData(25, 5, 1, true)] [InlineData(1, 1, 1, true)] [InlineData(1, 3, 1, true)] [InlineData(25, 5, 2, true)] [InlineData(7, 2, 3, true)] public void Add_ToJobQueueInterface_AutomaticallyStartsOnlyUpToDefinedNumberOfJob(int jobsToAdd, int startInitially, int iterations, bool jobShouldThrow) { var status = WaitForMaxConcurrentJobsToStart(jobsToAdd, startInitially, iterations, jobShouldThrow); Assert.Equal(Math.Max(jobsToAdd - (startInitially * iterations), 0), status.Queue.QueuedCount); CancelAndWaitOnPausedJobs(status.Queue, status.PrimaryJobPauser, status.SecondaryJobPauser); status.Queue.Dispose(); } [Theory] [InlineData(25, 5, 1)] [InlineData(8, 4, 2)] public void MaxConcurrent_OnJobQueueInterface_RestrictsNewJobsCountToGivenValue(int jobsToAdd, int startInitially, int thenStart) { using (var manualResetEvent = new ManualResetEventSlim(false)) { var status = WaitForMaxConcurrentJobsToStart(jobsToAdd, startInitially, 1, false); status.Queue.MaxConcurrent = thenStart; int i = 0; using (var subscription = status.Queue.WhenJobCompletes.Subscribe(result => { if (Interlocked.Increment(ref i) == startInitially) manualResetEvent.Set(); })) { //release the jobs, and now only the new count should be running status.PrimaryJobPauser.Set(); status.SecondaryJobPauser.Set(); status.PrimaryJobPauser.Reset(); //wait on jobs to complete manualResetEvent.Wait(TimeSpan.FromSeconds(3)); //then to launch status.AllJobsForIterationLaunched.Wait(TimeSpan.FromSeconds(2)); Assert.Equal(thenStart, status.Queue.RunningCount); CancelAndWaitOnPausedJobs(status.Queue, status.PrimaryJobPauser, status.SecondaryJobPauser); } status.Queue.Dispose(); } } } public class AutoJobQueueValueTypeTest : AutoJobExecutionQueueTest<int, int> { public AutoJobQueueValueTypeTest() : base((scheduler, max, toAutostart) => new AutoJobExecutionQueue<int, int>(scheduler, max, toAutostart), (max, toAutostart) => new AutoJobExecutionQueue<int, int>(max)) { } } public class AutoJobQueueReferenceTypeTest : AutoJobExecutionQueueTest<object, object> { public AutoJobQueueReferenceTypeTest() : base((scheduler, max, toAutostart) => new AutoJobExecutionQueue<object, object>(scheduler, max, toAutostart), (max, toAutostart) => new AutoJobExecutionQueue<object, object>(max)) { } } }
/* * This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson, * the work of Kim Sheffield and the fyiReporting project. * * Prior Copyrights: * _________________________________________________________ * |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others| * | (http://reportfu.org) | * ========================================================= * _________________________________________________________ * |Copyright (C) 2004-2008 fyiReporting Software, LLC | * |For additional information, email [email protected] | * |or visit the website www.fyiReporting.com. | * ========================================================= * * License: * * 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.Xml; using System.Xml.XPath; using System.Data; using System.Collections; using System.Collections.Specialized; namespace Reporting.Data { /// <summary> /// Summary description for XmlDataReader. /// </summary> public class XmlDataReader : IDataReader { XmlConnection _xconn; XmlCommand _xcmd; System.Data.CommandBehavior _behavior; // xpath XPathDocument _xpd; // the document XPathNavigator _xpn; // the navigator XPathNodeIterator _xpni; // the main iterator XmlNamespaceManager _nsmgr; // name space manager ListDictionary _NameSpaces; // names spaces used in xml document // column information object[] _Data; // data values of the columns ArrayList _Names; // names of the columns ArrayList _Types; // types of the columns public XmlDataReader(System.Data.CommandBehavior behavior, XmlConnection conn, XmlCommand cmd) { _xconn = conn; _xcmd = cmd; _behavior = behavior; // create an iterator to the selected rows _xpd = new XPathDocument (_xcmd.Url); _xpn = _xpd.CreateNavigator(); _xpni = _xpn.Select(_xcmd.RowsXPath); // select the rows _NameSpaces = new ListDictionary(); _Names = new ArrayList(); _Types = new ArrayList(); // Now determine the actual structure of the row depending on the command if (_xcmd.ColumnsXPath != null) ColumnsSpecifiedInit(); // xpaths to all columns specified else { _xcmd.ColumnsXPath = new ArrayList(); // xpath of all columns will simply be the name switch (_xcmd.Type) { case "both": ColumnsAttributes(); ColumnsElements(); break; case "attributes": ColumnsAttributes(); break; case "elements": ColumnsElements(); break; } } _Data = new object[_Names.Count]; // allocate enough room for data if (_NameSpaces.Count > 0) { _nsmgr = new XmlNamespaceManager(new NameTable()); foreach (string nsprefix in _NameSpaces.Keys) { _nsmgr.AddNamespace(nsprefix, _NameSpaces[nsprefix] as string); // setup namespaces } } else _nsmgr = null; } void ColumnsAttributes() { //go to the first row to get info XPathNodeIterator temp_xpni = _xpni.Clone(); // temporary iterator for determining columns temp_xpni.MoveNext(); XPathNodeIterator ni = temp_xpni.Current.Select("@*"); // select for attributes while (ni.MoveNext()) { _Types.Add(ni.Current.Value.GetType()); AddName(ni.Current.Name); _xcmd.ColumnsXPath.Add("@" + ni.Current.Name); } } void ColumnsElements() { //go to the first row to get info XPathNodeIterator temp_xpni = _xpni.Clone(); // temporary iterator for determining columns temp_xpni.MoveNext(); XPathNodeIterator ni = temp_xpni.Current.Select("*"); while (ni.MoveNext()) { _Types.Add(ni.Current.Value.GetType()); AddName(ni.Current.Name); _xcmd.ColumnsXPath.Add(ni.Current.Name); if (ni.Current.NamespaceURI != String.Empty && ni.Current.Prefix != String.Empty && _NameSpaces[ni.Current.Prefix] == null) { _NameSpaces.Add(ni.Current.Prefix, ni.Current.NamespaceURI); } } } void ColumnsSpecifiedInit() { XPathNodeIterator temp_xpni = _xpni.Clone(); // temporary iterator for determining columns temp_xpni.MoveNext (); foreach (string colxpath in _xcmd.ColumnsXPath ) { XPathNodeIterator ni = temp_xpni.Current.Select(colxpath); ni.MoveNext (); if (ni.Count < 1) { // didn't get anything in the first row; this is ok because // the element might not exist in the first row. _Types.Add("".GetType()); // assume string AddName(colxpath); // just use the name of the path } else { _Types.Add(ni.Current.Value.GetType()); AddName(ni.Current.Name); } } } // adds name to array; ensure name is unique in the table void AddName(string name) { int ci=0; string wname = name; while (_Names.IndexOf(wname) >= 0) { wname = name + "_" + (++ci).ToString(); } _Names.Add(wname); } #region IDataReader Members public int RecordsAffected { get { return 0; } } public bool IsClosed { get { return _xconn.IsOpen; } } public bool NextResult() { return false; } public void Close() { _xpd = null; _xpn = null; _xpni = null; _Data = null; _Names = null; _Types = null; } public bool Read() { if (!_xpni.MoveNext()) return false; // obtain the data from each column int ci=0; foreach (string colxpath in _xcmd.ColumnsXPath ) { XPathNodeIterator ni; if (_nsmgr == null) ni = _xpni.Current.Select(colxpath); else { XPathExpression xp = _xpni.Current.Compile(colxpath); xp.SetContext(_nsmgr); ni = _xpni.Current.Select(xp); } ni.MoveNext (); _Data[ci++] = ni.Count == 0? null: ni.Current.Value; } return true; } public int Depth { get { // TODO: Add XmlDataReader.Depth getter implementation return 0; } } public DataTable GetSchemaTable() { // TODO: Add XmlDataReader.GetSchemaTable implementation return null; } #endregion #region IDisposable Members public void Dispose() { this.Close(); } #endregion #region IDataRecord Members public int GetInt32(int i) { return Convert.ToInt32(_Data[i]); } public object this[string name] { get { int ci = this.GetOrdinal(name); return _Data[ci]; } } object System.Data.IDataRecord.this[int i] { get { return _Data[i]; } } public object GetValue(int i) { return _Data[i]; } public bool IsDBNull(int i) { return _Data[i] == null; } public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length) { throw new NotImplementedException("GetBytes not implemented."); } public byte GetByte(int i) { return Convert.ToByte(_Data[i]); } public Type GetFieldType(int i) { return this._Types[i] as Type; } public decimal GetDecimal(int i) { return Convert.ToDecimal(_Data[i]); } public int GetValues(object[] values) { int i; for (i=0; i < values.Length; i++) { values[i] = i >= _Data.Length? System.DBNull.Value: _Data[i]; } return Math.Min(values.Length, _Data.Length); } public string GetName(int i) { return _Names[i] as string; } public int FieldCount { get { return _Data.Length; } } public long GetInt64(int i) { return Convert.ToInt64(_Data[i]); } public double GetDouble(int i) { return Convert.ToDouble(_Data[i]); } public bool GetBoolean(int i) { return Convert.ToBoolean(_Data[i]); } public Guid GetGuid(int i) { throw new NotImplementedException("GetGuid not implemented."); } public DateTime GetDateTime(int i) { return Convert.ToDateTime(_Data[i]); } public int GetOrdinal(string name) { int ci=0; // do case sensitive lookup foreach (string cname in _Names) { if (cname == name) return ci; ci++; } // do case insensitive lookup ci=0; name = name.ToLower(); foreach (string cname in _Names) { if (cname.ToLower() == name) return ci; ci++; } throw new ArgumentException(string.Format("Column '{0}' not known.", name)); } public string GetDataTypeName(int i) { Type t = _Types[i] as Type; return t.ToString(); } public float GetFloat(int i) { return Convert.ToSingle(_Data[i]); } public IDataReader GetData(int i) { throw new NotImplementedException("GetData not implemented."); } public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length) { throw new NotImplementedException("GetChars not implemented."); } public string GetString(int i) { return Convert.ToString(_Data[i]); } public char GetChar(int i) { return Convert.ToChar(_Data[i]); } public short GetInt16(int i) { return Convert.ToInt16(_Data[i]); } #endregion } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.Serialization; using Microsoft.Xrm.Sdk; namespace PowerShellLibrary.Crm.CmdletProviders { [DataContract] [Microsoft.Xrm.Sdk.Client.EntityLogicalName("uii_workflow_workflowstep_mapping")] [GeneratedCode("CrmSvcUtil", "7.1.0001.3108")] public class UII_workflow_workflowstep_mapping : Entity, INotifyPropertyChanging, INotifyPropertyChanged { public const string EntityLogicalName = "uii_workflow_workflowstep_mapping"; public const int EntityTypeCode = 10016; [AttributeLogicalName("createdby")] public EntityReference CreatedBy { get { return this.GetAttributeValue<EntityReference>("createdby"); } } [AttributeLogicalName("createdon")] public DateTime? CreatedOn { get { return this.GetAttributeValue<DateTime?>("createdon"); } } [AttributeLogicalName("createdonbehalfby")] public EntityReference CreatedOnBehalfBy { get { return this.GetAttributeValue<EntityReference>("createdonbehalfby"); } } [AttributeLogicalName("importsequencenumber")] public int? ImportSequenceNumber { get { return this.GetAttributeValue<int?>("importsequencenumber"); } set { this.OnPropertyChanging("ImportSequenceNumber"); this.SetAttributeValue("importsequencenumber", (object) value); this.OnPropertyChanged("ImportSequenceNumber"); } } [AttributeLogicalName("modifiedby")] public EntityReference ModifiedBy { get { return this.GetAttributeValue<EntityReference>("modifiedby"); } } [AttributeLogicalName("modifiedon")] public DateTime? ModifiedOn { get { return this.GetAttributeValue<DateTime?>("modifiedon"); } } [AttributeLogicalName("modifiedonbehalfby")] public EntityReference ModifiedOnBehalfBy { get { return this.GetAttributeValue<EntityReference>("modifiedonbehalfby"); } } [AttributeLogicalName("overriddencreatedon")] public DateTime? OverriddenCreatedOn { get { return this.GetAttributeValue<DateTime?>("overriddencreatedon"); } set { this.OnPropertyChanging("OverriddenCreatedOn"); this.SetAttributeValue("overriddencreatedon", (object) value); this.OnPropertyChanged("OverriddenCreatedOn"); } } [AttributeLogicalName("ownerid")] public EntityReference OwnerId { get { return this.GetAttributeValue<EntityReference>("ownerid"); } set { this.OnPropertyChanging("OwnerId"); this.SetAttributeValue("ownerid", (object) value); this.OnPropertyChanged("OwnerId"); } } [AttributeLogicalName("owningbusinessunit")] public EntityReference OwningBusinessUnit { get { return this.GetAttributeValue<EntityReference>("owningbusinessunit"); } } [AttributeLogicalName("owningteam")] public EntityReference OwningTeam { get { return this.GetAttributeValue<EntityReference>("owningteam"); } } [AttributeLogicalName("owninguser")] public EntityReference OwningUser { get { return this.GetAttributeValue<EntityReference>("owninguser"); } } [AttributeLogicalName("statecode")] public UII_workflow_workflowstep_mappingState? statecode { get { OptionSetValue attributeValue = this.GetAttributeValue<OptionSetValue>("statecode"); if (attributeValue != null) return new UII_workflow_workflowstep_mappingState?((UII_workflow_workflowstep_mappingState) Enum.ToObject(typeof (UII_workflow_workflowstep_mappingState), attributeValue.Value)); return new UII_workflow_workflowstep_mappingState?(); } set { this.OnPropertyChanging("statecode"); if (!value.HasValue) this.SetAttributeValue("statecode", (object) null); else this.SetAttributeValue("statecode", (object) new OptionSetValue((int) value.Value)); this.OnPropertyChanged("statecode"); } } [AttributeLogicalName("statuscode")] public OptionSetValue statuscode { get { return this.GetAttributeValue<OptionSetValue>("statuscode"); } set { this.OnPropertyChanging("statuscode"); this.SetAttributeValue("statuscode", (object) value); this.OnPropertyChanged("statuscode"); } } [AttributeLogicalName("timezoneruleversionnumber")] public int? TimeZoneRuleVersionNumber { get { return this.GetAttributeValue<int?>("timezoneruleversionnumber"); } set { this.OnPropertyChanging("TimeZoneRuleVersionNumber"); this.SetAttributeValue("timezoneruleversionnumber", (object) value); this.OnPropertyChanged("TimeZoneRuleVersionNumber"); } } [AttributeLogicalName("uii_sequence")] public string UII_sequence { get { return this.GetAttributeValue<string>("uii_sequence"); } set { this.OnPropertyChanging("UII_sequence"); this.SetAttributeValue("uii_sequence", (object) value); this.OnPropertyChanged("UII_sequence"); } } [AttributeLogicalName("uii_workflow_mappingid")] public EntityReference uii_workflow_mappingid { get { return this.GetAttributeValue<EntityReference>("uii_workflow_mappingid"); } set { this.OnPropertyChanging("uii_workflow_mappingid"); this.SetAttributeValue("uii_workflow_mappingid", (object) value); this.OnPropertyChanged("uii_workflow_mappingid"); } } [AttributeLogicalName("uii_workflow_workflowstep_mappingid")] public Guid? UII_workflow_workflowstep_mappingId { get { return this.GetAttributeValue<Guid?>("uii_workflow_workflowstep_mappingid"); } set { this.OnPropertyChanging("UII_workflow_workflowstep_mappingId"); this.SetAttributeValue("uii_workflow_workflowstep_mappingid", (object) value); if (value.HasValue) base.Id = value.Value; else base.Id = Guid.Empty; this.OnPropertyChanged("UII_workflow_workflowstep_mappingId"); } } [AttributeLogicalName("uii_workflow_workflowstep_mappingid")] public override Guid Id { get { return base.Id; } set { this.UII_workflow_workflowstep_mappingId = new Guid?(value); } } [AttributeLogicalName("uii_workflowstep_mappingid")] public EntityReference uii_workflowstep_mappingid { get { return this.GetAttributeValue<EntityReference>("uii_workflowstep_mappingid"); } set { this.OnPropertyChanging("uii_workflowstep_mappingid"); this.SetAttributeValue("uii_workflowstep_mappingid", (object) value); this.OnPropertyChanged("uii_workflowstep_mappingid"); } } [AttributeLogicalName("utcconversiontimezonecode")] public int? UTCConversionTimeZoneCode { get { return this.GetAttributeValue<int?>("utcconversiontimezonecode"); } set { this.OnPropertyChanging("UTCConversionTimeZoneCode"); this.SetAttributeValue("utcconversiontimezonecode", (object) value); this.OnPropertyChanged("UTCConversionTimeZoneCode"); } } [AttributeLogicalName("versionnumber")] public long? VersionNumber { get { return this.GetAttributeValue<long?>("versionnumber"); } } [RelationshipSchemaName("uii_workflow_workflowstep_mapping_AsyncOperations")] public IEnumerable<AsyncOperation> uii_workflow_workflowstep_mapping_AsyncOperations { get { return this.GetRelatedEntities<AsyncOperation>("uii_workflow_workflowstep_mapping_AsyncOperations", new EntityRole?()); } set { this.OnPropertyChanging("uii_workflow_workflowstep_mapping_AsyncOperations"); this.SetRelatedEntities<AsyncOperation>("uii_workflow_workflowstep_mapping_AsyncOperations", new EntityRole?(), value); this.OnPropertyChanged("uii_workflow_workflowstep_mapping_AsyncOperations"); } } [AttributeLogicalName("owningbusinessunit")] [RelationshipSchemaName("business_unit_uii_workflow_workflowstep_mapping")] public BusinessUnit business_unit_uii_workflow_workflowstep_mapping { get { return this.GetRelatedEntity<BusinessUnit>("business_unit_uii_workflow_workflowstep_mapping", new EntityRole?()); } } [AttributeLogicalName("createdby")] [RelationshipSchemaName("lk_uii_workflow_workflowstep_mapping_createdby")] public SystemUser lk_uii_workflow_workflowstep_mapping_createdby { get { return this.GetRelatedEntity<SystemUser>("lk_uii_workflow_workflowstep_mapping_createdby", new EntityRole?()); } } [AttributeLogicalName("createdonbehalfby")] [RelationshipSchemaName("lk_uii_workflow_workflowstep_mapping_createdonbehalfby")] public SystemUser lk_uii_workflow_workflowstep_mapping_createdonbehalfby { get { return this.GetRelatedEntity<SystemUser>("lk_uii_workflow_workflowstep_mapping_createdonbehalfby", new EntityRole?()); } } [AttributeLogicalName("modifiedby")] [RelationshipSchemaName("lk_uii_workflow_workflowstep_mapping_modifiedby")] public SystemUser lk_uii_workflow_workflowstep_mapping_modifiedby { get { return this.GetRelatedEntity<SystemUser>("lk_uii_workflow_workflowstep_mapping_modifiedby", new EntityRole?()); } } [RelationshipSchemaName("lk_uii_workflow_workflowstep_mapping_modifiedonbehalfby")] [AttributeLogicalName("modifiedonbehalfby")] public SystemUser lk_uii_workflow_workflowstep_mapping_modifiedonbehalfby { get { return this.GetRelatedEntity<SystemUser>("lk_uii_workflow_workflowstep_mapping_modifiedonbehalfby", new EntityRole?()); } } [AttributeLogicalName("uii_workflow_mappingid")] [RelationshipSchemaName("uii_workflows_mapping")] public UII_workflow uii_workflows_mapping { get { return this.GetRelatedEntity<UII_workflow>("uii_workflows_mapping", new EntityRole?()); } set { this.OnPropertyChanging("uii_workflows_mapping"); this.SetRelatedEntity<UII_workflow>("uii_workflows_mapping", new EntityRole?(), value); this.OnPropertyChanged("uii_workflows_mapping"); } } [AttributeLogicalName("uii_workflowstep_mappingid")] [RelationshipSchemaName("uii_workflowstep_mapping")] public UII_workflowstep uii_workflowstep_mapping { get { return this.GetRelatedEntity<UII_workflowstep>("uii_workflowstep_mapping", new EntityRole?()); } set { this.OnPropertyChanging("uii_workflowstep_mapping"); this.SetRelatedEntity<UII_workflowstep>("uii_workflowstep_mapping", new EntityRole?(), value); this.OnPropertyChanged("uii_workflowstep_mapping"); } } [RelationshipSchemaName("user_uii_workflow_workflowstep_mapping")] [AttributeLogicalName("owninguser")] public SystemUser user_uii_workflow_workflowstep_mapping { get { return this.GetRelatedEntity<SystemUser>("user_uii_workflow_workflowstep_mapping", new EntityRole?()); } } public event PropertyChangedEventHandler PropertyChanged; public event PropertyChangingEventHandler PropertyChanging; public UII_workflow_workflowstep_mapping() : base("uii_workflow_workflowstep_mapping") { } private void OnPropertyChanged(string propertyName) { if (this.PropertyChanged == null) return; this.PropertyChanged((object) this, new PropertyChangedEventArgs(propertyName)); } private void OnPropertyChanging(string propertyName) { if (this.PropertyChanging == null) return; this.PropertyChanging((object) this, new PropertyChangingEventArgs(propertyName)); } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Provider; using Dbg = System.Management.Automation; namespace Microsoft.PowerShell.Commands { /// <summary> /// The base class for the */content commands. /// </summary> public class ContentCommandBase : CoreCommandWithCredentialsBase, IDisposable { #region Parameters /// <summary> /// Gets or sets the path parameter to the command. /// </summary> [Parameter(Position = 0, ParameterSetName = "Path", Mandatory = true, ValueFromPipelineByPropertyName = true)] public string[] Path { get; set; } /// <summary> /// Gets or sets the literal path parameter to the command. /// </summary> [Parameter(ParameterSetName = "LiteralPath", Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] [Alias("PSPath", "LP")] public string[] LiteralPath { get { return Path; } set { base.SuppressWildcardExpansion = true; Path = value; } } /// <summary> /// Gets or sets the filter property. /// </summary> [Parameter] public override string Filter { get { return base.Filter; } set { base.Filter = value; } } /// <summary> /// Gets or sets the include property. /// </summary> [Parameter] public override string[] Include { get { return base.Include; } set { base.Include = value; } } /// <summary> /// Gets or sets the exclude property. /// </summary> [Parameter] public override string[] Exclude { get { return base.Exclude; } set { base.Exclude = value; } } /// <summary> /// Gets or sets the force property. /// </summary> /// <remarks> /// Gives the provider guidance on how vigorous it should be about performing /// the operation. If true, the provider should do everything possible to perform /// the operation. If false, the provider should attempt the operation but allow /// even simple errors to terminate the operation. /// For example, if the user tries to copy a file to a path that already exists and /// the destination is read-only, if force is true, the provider should copy over /// the existing read-only file. If force is false, the provider should write an error. /// </remarks> [Parameter] public override SwitchParameter Force { get { return base.Force; } set { base.Force = value; } } #endregion Parameters #region parameter data #endregion parameter data #region protected members /// <summary> /// An array of content holder objects that contain the path information /// and content readers/writers for the item represented by the path information. /// </summary> internal List<ContentHolder> contentStreams = new(); /// <summary> /// Wraps the content into a PSObject and adds context information as notes. /// </summary> /// <param name="content"> /// The content being written out. /// </param> /// <param name="readCount"> /// The number of blocks that have been read so far. /// </param> /// <param name="pathInfo"> /// The context the content was retrieved from. /// </param> /// <param name="context"> /// The context the command is being run under. /// </param> internal void WriteContentObject(object content, long readCount, PathInfo pathInfo, CmdletProviderContext context) { Dbg.Diagnostics.Assert( content != null, "The caller should verify the content."); Dbg.Diagnostics.Assert( pathInfo != null, "The caller should verify the pathInfo."); Dbg.Diagnostics.Assert( context != null, "The caller should verify the context."); PSObject result = PSObject.AsPSObject(content); Dbg.Diagnostics.Assert( result != null, "A PSObject should always be constructed."); // Use the cached notes if the cache exists and the path is still the same PSNoteProperty note; if (_currentContentItem != null && ((_currentContentItem.PathInfo == pathInfo) || string.Equals( pathInfo.Path, _currentContentItem.PathInfo.Path, StringComparison.OrdinalIgnoreCase))) { result = _currentContentItem.AttachNotes(result); } else { // Generate a new cache item and cache the notes _currentContentItem = new ContentPathsCache(pathInfo); // Construct a provider qualified path as the Path note string psPath = pathInfo.Path; note = new PSNoteProperty("PSPath", psPath); result.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSPath", psPath); _currentContentItem.PSPath = psPath; try { // Now get the parent path and child name string parentPath = null; if (pathInfo.Drive != null) { parentPath = SessionState.Path.ParseParent(pathInfo.Path, pathInfo.Drive.Root, context); } else { parentPath = SessionState.Path.ParseParent(pathInfo.Path, string.Empty, context); } note = new PSNoteProperty("PSParentPath", parentPath); result.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSParentPath", parentPath); _currentContentItem.ParentPath = parentPath; // Get the child name string childName = SessionState.Path.ParseChildName(pathInfo.Path, context); note = new PSNoteProperty("PSChildName", childName); result.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSChildName", childName); _currentContentItem.ChildName = childName; } catch (NotSupportedException) { // Ignore. The object just won't have ParentPath or ChildName set. } // PSDriveInfo if (pathInfo.Drive != null) { PSDriveInfo drive = pathInfo.Drive; note = new PSNoteProperty("PSDrive", drive); result.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSDrive", drive); _currentContentItem.Drive = drive; } // ProviderInfo ProviderInfo provider = pathInfo.Provider; note = new PSNoteProperty("PSProvider", provider); result.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSProvider", provider); _currentContentItem.Provider = provider; } // Add the ReadCount note note = new PSNoteProperty("ReadCount", readCount); result.Properties.Add(note, true); WriteObject(result); } /// <summary> /// A cache of the notes that get added to the content items as they are written /// to the pipeline. /// </summary> private ContentPathsCache _currentContentItem; /// <summary> /// A class that stores a cache of the notes that get attached to content items /// as they get written to the pipeline. An instance of this cache class is /// only valid for a single path. /// </summary> internal class ContentPathsCache { /// <summary> /// Constructs a content cache item. /// </summary> /// <param name="pathInfo"> /// The path information for which the cache will be bound. /// </param> public ContentPathsCache(PathInfo pathInfo) { PathInfo = pathInfo; } /// <summary> /// The path information for the cached item. /// </summary> public PathInfo PathInfo { get; } /// <summary> /// The cached PSPath of the item. /// </summary> public string PSPath { get; set; } /// <summary> /// The cached parent path of the item. /// </summary> public string ParentPath { get; set; } /// <summary> /// The cached drive for the item. /// </summary> public PSDriveInfo Drive { get; set; } /// <summary> /// The cached provider of the item. /// </summary> public ProviderInfo Provider { get; set; } /// <summary> /// The cached child name of the item. /// </summary> public string ChildName { get; set; } /// <summary> /// Attaches the cached notes to the specified PSObject. /// </summary> /// <param name="content"> /// The PSObject to attached the cached notes to. /// </param> /// <returns> /// The PSObject that was passed in with the cached notes added. /// </returns> public PSObject AttachNotes(PSObject content) { // Construct a provider qualified path as the Path note PSNoteProperty note = new("PSPath", PSPath); content.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSPath", PSPath); // Now attach the parent path and child name note = new PSNoteProperty("PSParentPath", ParentPath); content.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSParentPath", ParentPath); // Attach the child name note = new PSNoteProperty("PSChildName", ChildName); content.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSChildName", ChildName); // PSDriveInfo if (PathInfo.Drive != null) { note = new PSNoteProperty("PSDrive", Drive); content.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSDrive", Drive); } // ProviderInfo note = new PSNoteProperty("PSProvider", Provider); content.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSProvider", Provider); return content; } } /// <summary> /// A struct to hold the path information and the content readers/writers /// for an item. /// </summary> internal readonly struct ContentHolder { internal ContentHolder( PathInfo pathInfo, IContentReader reader, IContentWriter writer) { if (pathInfo == null) { throw PSTraceSource.NewArgumentNullException(nameof(pathInfo)); } PathInfo = pathInfo; Reader = reader; Writer = writer; } internal PathInfo PathInfo { get; } internal IContentReader Reader { get; } internal IContentWriter Writer { get; } } /// <summary> /// Closes the content readers and writers in the content holder array. /// </summary> internal void CloseContent(List<ContentHolder> contentHolders, bool disposing) { if (contentHolders == null) { throw PSTraceSource.NewArgumentNullException(nameof(contentHolders)); } foreach (ContentHolder holder in contentHolders) { try { if (holder.Writer != null) { holder.Writer.Close(); } } catch (Exception e) // Catch-all OK. 3rd party callout { // Catch all the exceptions caused by closing the writer // and write out an error. ProviderInvocationException providerException = new( "ProviderContentCloseError", SessionStateStrings.ProviderContentCloseError, holder.PathInfo.Provider, holder.PathInfo.Path, e); // Log a provider health event MshLog.LogProviderHealthEvent( this.Context, holder.PathInfo.Provider.Name, providerException, Severity.Warning); if (!disposing) { WriteError( new ErrorRecord( providerException.ErrorRecord, providerException)); } } try { if (holder.Reader != null) { holder.Reader.Close(); } } catch (Exception e) // Catch-all OK. 3rd party callout { // Catch all the exceptions caused by closing the writer // and write out an error. ProviderInvocationException providerException = new( "ProviderContentCloseError", SessionStateStrings.ProviderContentCloseError, holder.PathInfo.Provider, holder.PathInfo.Path, e); // Log a provider health event MshLog.LogProviderHealthEvent( this.Context, holder.PathInfo.Provider.Name, providerException, Severity.Warning); if (!disposing) { WriteError( new ErrorRecord( providerException.ErrorRecord, providerException)); } } } } /// <summary> /// Overridden by derived classes to support ShouldProcess with /// the appropriate information. /// </summary> /// <param name="path"> /// The path to the item from which the content writer will be /// retrieved. /// </param> /// <returns> /// True if the action should continue or false otherwise. /// </returns> internal virtual bool CallShouldProcess(string path) { return true; } /// <summary> /// Gets the IContentReaders for the current path(s) /// </summary> /// <returns> /// An array of IContentReaders for the current path(s) /// </returns> internal List<ContentHolder> GetContentReaders( string[] readerPaths, CmdletProviderContext currentCommandContext) { // Resolve all the paths into PathInfo objects Collection<PathInfo> pathInfos = ResolvePaths(readerPaths, false, true, currentCommandContext); // Create the results array List<ContentHolder> results = new(); foreach (PathInfo pathInfo in pathInfos) { // For each path, get the content writer Collection<IContentReader> readers = null; try { string pathToProcess = WildcardPattern.Escape(pathInfo.Path); if (currentCommandContext.SuppressWildcardExpansion) { pathToProcess = pathInfo.Path; } readers = InvokeProvider.Content.GetReader(pathToProcess, currentCommandContext); } catch (PSNotSupportedException notSupported) { WriteError( new ErrorRecord( notSupported.ErrorRecord, notSupported)); continue; } catch (DriveNotFoundException driveNotFound) { WriteError( new ErrorRecord( driveNotFound.ErrorRecord, driveNotFound)); continue; } catch (ProviderNotFoundException providerNotFound) { WriteError( new ErrorRecord( providerNotFound.ErrorRecord, providerNotFound)); continue; } catch (ItemNotFoundException pathNotFound) { WriteError( new ErrorRecord( pathNotFound.ErrorRecord, pathNotFound)); continue; } if (readers != null && readers.Count > 0) { if (readers.Count == 1 && readers[0] != null) { ContentHolder holder = new(pathInfo, readers[0], null); results.Add(holder); } } } return results; } /// <summary> /// Resolves the specified paths to PathInfo objects. /// </summary> /// <param name="pathsToResolve"> /// The paths to be resolved. Each path may contain glob characters. /// </param> /// <param name="allowNonexistingPaths"> /// If true, resolves the path even if it doesn't exist. /// </param> /// <param name="allowEmptyResult"> /// If true, allows a wildcard that returns no results. /// </param> /// <param name="currentCommandContext"> /// The context under which the command is running. /// </param> /// <returns> /// An array of PathInfo objects that are the resolved paths for the /// <paramref name="pathsToResolve"/> parameter. /// </returns> internal Collection<PathInfo> ResolvePaths( string[] pathsToResolve, bool allowNonexistingPaths, bool allowEmptyResult, CmdletProviderContext currentCommandContext) { Collection<PathInfo> results = new(); foreach (string path in pathsToResolve) { bool pathNotFound = false; bool filtersHidPath = false; ErrorRecord pathNotFoundErrorRecord = null; try { // First resolve each of the paths Collection<PathInfo> pathInfos = SessionState.Path.GetResolvedPSPathFromPSPath( path, currentCommandContext); if (pathInfos.Count == 0) { pathNotFound = true; // If the item simply did not exist, // we would have got an ItemNotFoundException. // If we get here, it's because the filters // excluded the file. if (!currentCommandContext.SuppressWildcardExpansion) { filtersHidPath = true; } } foreach (PathInfo pathInfo in pathInfos) { results.Add(pathInfo); } } catch (PSNotSupportedException notSupported) { WriteError( new ErrorRecord( notSupported.ErrorRecord, notSupported)); } catch (DriveNotFoundException driveNotFound) { WriteError( new ErrorRecord( driveNotFound.ErrorRecord, driveNotFound)); } catch (ProviderNotFoundException providerNotFound) { WriteError( new ErrorRecord( providerNotFound.ErrorRecord, providerNotFound)); } catch (ItemNotFoundException pathNotFoundException) { pathNotFound = true; pathNotFoundErrorRecord = new ErrorRecord(pathNotFoundException.ErrorRecord, pathNotFoundException); } if (pathNotFound) { if (allowNonexistingPaths && (!filtersHidPath) && (currentCommandContext.SuppressWildcardExpansion || (!WildcardPattern.ContainsWildcardCharacters(path)))) { ProviderInfo provider = null; PSDriveInfo drive = null; string unresolvedPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath( path, currentCommandContext, out provider, out drive); PathInfo pathInfo = new( drive, provider, unresolvedPath, SessionState); results.Add(pathInfo); } else { if (pathNotFoundErrorRecord == null) { // Detect if the path resolution failed to resolve to a file. string error = StringUtil.Format(NavigationResources.ItemNotFound, Path); Exception e = new(error); pathNotFoundErrorRecord = new ErrorRecord( e, "ItemNotFound", ErrorCategory.ObjectNotFound, Path); } WriteError(pathNotFoundErrorRecord); } } } return results; } #endregion protected members #region IDisposable internal void Dispose(bool isDisposing) { if (isDisposing) { CloseContent(contentStreams, true); contentStreams = new List<ContentHolder>(); } } /// <summary> /// Dispose method in IDisposable. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion IDisposable } }
using System.Linq; using Content.Server.Hands.Components; using Content.Server.Traitor.Uplink.Account; using Content.Server.Traitor.Uplink.Components; using Content.Server.UserInterface; using Content.Shared.ActionBlocker; using Content.Shared.Hands.Components; using Content.Shared.Interaction; using Content.Shared.Inventory; using Content.Shared.Item; using Content.Shared.PDA; using Content.Shared.Traitor.Uplink; using Robust.Server.GameObjects; using Robust.Server.Player; using Robust.Shared.Audio; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Player; namespace Content.Server.Traitor.Uplink { public sealed class UplinkSystem : EntitySystem { [Dependency] private readonly UplinkAccountsSystem _accounts = default!; [Dependency] private readonly UplinkListingSytem _listing = default!; [Dependency] private readonly InventorySystem _inventorySystem = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<UplinkComponent, ComponentInit>(OnInit); SubscribeLocalEvent<UplinkComponent, ComponentRemove>(OnRemove); SubscribeLocalEvent<UplinkComponent, ActivateInWorldEvent>(OnActivate); // UI events SubscribeLocalEvent<UplinkComponent, UplinkBuyListingMessage>(OnBuy); SubscribeLocalEvent<UplinkComponent, UplinkRequestUpdateInterfaceMessage>(OnRequestUpdateUI); SubscribeLocalEvent<UplinkComponent, UplinkTryWithdrawTC>(OnWithdrawTC); SubscribeLocalEvent<UplinkAccountBalanceChanged>(OnBalanceChangedBroadcast); } public void SetAccount(UplinkComponent component, UplinkAccount account) { if (component.UplinkAccount != null) { Logger.Error("Can't init one uplink with different account!"); return; } component.UplinkAccount = account; } private void OnInit(EntityUid uid, UplinkComponent component, ComponentInit args) { RaiseLocalEvent(uid, new UplinkInitEvent(component)); // if component has a preset info (probably spawn by admin) // create a new account and register it for this uplink if (component.PresetInfo != null) { var account = new UplinkAccount(component.PresetInfo.StartingBalance); _accounts.AddNewAccount(account); SetAccount(component, account); } } private void OnRemove(EntityUid uid, UplinkComponent component, ComponentRemove args) { RaiseLocalEvent(uid, new UplinkRemovedEvent()); } private void OnActivate(EntityUid uid, UplinkComponent component, ActivateInWorldEvent args) { if (args.Handled) return; // check if uplinks activates directly or use some proxy, like a PDA if (!component.ActivatesInHands) return; if (component.UplinkAccount == null) return; if (!EntityManager.TryGetComponent(args.User, out ActorComponent? actor)) return; ToggleUplinkUI(component, actor.PlayerSession); args.Handled = true; } private void OnBalanceChangedBroadcast(UplinkAccountBalanceChanged ev) { foreach (var uplink in EntityManager.EntityQuery<UplinkComponent>()) { if (uplink.UplinkAccount == ev.Account) { UpdateUserInterface(uplink); } } } private void OnRequestUpdateUI(EntityUid uid, UplinkComponent uplink, UplinkRequestUpdateInterfaceMessage args) { UpdateUserInterface(uplink); } private void OnBuy(EntityUid uid, UplinkComponent uplink, UplinkBuyListingMessage message) { if (message.Session.AttachedEntity is not {Valid: true} player) return; if (uplink.UplinkAccount == null) return; if (!_accounts.TryPurchaseItem(uplink.UplinkAccount, message.ItemId, EntityManager.GetComponent<TransformComponent>(player).Coordinates, out var entity)) { SoundSystem.Play(Filter.SinglePlayer(message.Session), uplink.InsufficientFundsSound.GetSound(), uplink.Owner, AudioParams.Default); RaiseNetworkEvent(new UplinkInsufficientFundsMessage(), message.Session.ConnectedClient); return; } if (EntityManager.TryGetComponent(player, out HandsComponent? hands) && EntityManager.TryGetComponent(entity.Value, out SharedItemComponent? item)) { hands.PutInHandOrDrop(item); } SoundSystem.Play(Filter.SinglePlayer(message.Session), uplink.BuySuccessSound.GetSound(), uplink.Owner, AudioParams.Default.WithVolume(-8f)); RaiseNetworkEvent(new UplinkBuySuccessMessage(), message.Session.ConnectedClient); } private void OnWithdrawTC(EntityUid uid, UplinkComponent uplink, UplinkTryWithdrawTC args) { var acc = uplink.UplinkAccount; if (acc == null) return; if (args.Session.AttachedEntity is not {Valid: true} player) return; var cords = EntityManager.GetComponent<TransformComponent>(player).Coordinates; // try to withdraw TCs from account if (!_accounts.TryWithdrawTC(acc, args.TC, cords, out var tcUid)) return; // try to put it into players hands if (EntityManager.TryGetComponent(player, out SharedHandsComponent? hands)) hands.TryPutInAnyHand(tcUid.Value); // play buying sound SoundSystem.Play(Filter.SinglePlayer(args.Session), uplink.BuySuccessSound.GetSound(), uplink.Owner, AudioParams.Default.WithVolume(-8f)); UpdateUserInterface(uplink); } public void ToggleUplinkUI(UplinkComponent component, IPlayerSession session) { var ui = component.Owner.GetUIOrNull(UplinkUiKey.Key); ui?.Toggle(session); UpdateUserInterface(component); } private void UpdateUserInterface(UplinkComponent component) { var ui = component.Owner.GetUIOrNull(UplinkUiKey.Key); if (ui == null) return; var listings = _listing.GetListings().Values.ToArray(); var acc = component.UplinkAccount; UplinkAccountData accData; if (acc != null) accData = new UplinkAccountData(acc.AccountHolder, acc.Balance); else accData = new UplinkAccountData(null, 0); ui.SetState(new UplinkUpdateState(accData, listings)); } public bool AddUplink(EntityUid user, UplinkAccount account, EntityUid? uplinkEntity = null) { // Try to find target item if (uplinkEntity == null) { uplinkEntity = FindUplinkTarget(user); if (uplinkEntity == null) return false; } var uplink = uplinkEntity.Value.EnsureComponent<UplinkComponent>(); SetAccount(uplink, account); return true; } private EntityUid? FindUplinkTarget(EntityUid user) { // Try to find PDA in inventory if (_inventorySystem.TryGetContainerSlotEnumerator(user, out var containerSlotEnumerator)) { while (containerSlotEnumerator.MoveNext(out var pdaUid)) { if(!pdaUid.ContainedEntity.HasValue) continue; if(HasComp<PDAComponent>(pdaUid.ContainedEntity.Value)) return pdaUid.ContainedEntity.Value; } } // Also check hands if (EntityManager.TryGetComponent(user, out HandsComponent? hands)) { var heldItems = hands.GetAllHeldItems(); foreach (var item in heldItems) { if (EntityManager.HasComponent<PDAComponent>(item.Owner)) return item.Owner; } } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.IdentityModel.Claims; using System.IdentityModel.Policy; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.Net; using System.Net.Security; using System.Runtime; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel.Channels; using System.ServiceModel.Diagnostics; using System.ServiceModel.Security.Tokens; using System.Text; using System.Threading; namespace System.ServiceModel.Security { public static class ProtectionLevelHelper { public static bool IsDefined(ProtectionLevel value) { return (value == ProtectionLevel.None || value == ProtectionLevel.Sign || value == ProtectionLevel.EncryptAndSign); } public static void Validate(ProtectionLevel value) { if (!IsDefined(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("value", (int)value, typeof(ProtectionLevel))); } } public static bool IsStronger(ProtectionLevel v1, ProtectionLevel v2) { return ((v1 == ProtectionLevel.EncryptAndSign && v2 != ProtectionLevel.EncryptAndSign) || (v1 == ProtectionLevel.Sign && v2 == ProtectionLevel.None)); } public static bool IsStrongerOrEqual(ProtectionLevel v1, ProtectionLevel v2) { return (v1 == ProtectionLevel.EncryptAndSign || (v1 == ProtectionLevel.Sign && v2 != ProtectionLevel.EncryptAndSign)); } public static ProtectionLevel Max(ProtectionLevel v1, ProtectionLevel v2) { return IsStronger(v1, v2) ? v1 : v2; } public static int GetOrdinal(Nullable<ProtectionLevel> p) { if (p.HasValue) { switch ((ProtectionLevel)p) { default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("p", (int)p, typeof(ProtectionLevel))); case ProtectionLevel.None: return 2; case ProtectionLevel.Sign: return 3; case ProtectionLevel.EncryptAndSign: return 4; } } return 1; } } internal static class SslProtocolsHelper { internal static bool IsDefined(SslProtocols value) { SslProtocols allValues = SslProtocols.None; foreach (var protocol in Enum.GetValues(typeof(SslProtocols))) { allValues |= (SslProtocols)protocol; } return (value & allValues) == value; } internal static void Validate(SslProtocols value) { if (!IsDefined(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("value", (int)value, typeof(SslProtocols))); } } } internal static class TokenImpersonationLevelHelper { internal static bool IsDefined(TokenImpersonationLevel value) { return (value == TokenImpersonationLevel.None || value == TokenImpersonationLevel.Anonymous || value == TokenImpersonationLevel.Identification || value == TokenImpersonationLevel.Impersonation || value == TokenImpersonationLevel.Delegation); } internal static void Validate(TokenImpersonationLevel value) { if (!IsDefined(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("value", (int)value, typeof(TokenImpersonationLevel))); } } private static TokenImpersonationLevel[] s_TokenImpersonationLevelOrder = new TokenImpersonationLevel[] { TokenImpersonationLevel.None, TokenImpersonationLevel.Anonymous, TokenImpersonationLevel.Identification, TokenImpersonationLevel.Impersonation, TokenImpersonationLevel.Delegation }; internal static string ToString(TokenImpersonationLevel impersonationLevel) { if (impersonationLevel == TokenImpersonationLevel.Identification) { return "identification"; } if (impersonationLevel == TokenImpersonationLevel.None) { return "none"; } if (impersonationLevel == TokenImpersonationLevel.Anonymous) { return "anonymous"; } if (impersonationLevel == TokenImpersonationLevel.Impersonation) { return "impersonation"; } if (impersonationLevel == TokenImpersonationLevel.Delegation) { return "delegation"; } Fx.Assert("unknown token impersonation level"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("impersonationLevel", (int)impersonationLevel, typeof(TokenImpersonationLevel))); } internal static bool IsGreaterOrEqual(TokenImpersonationLevel x, TokenImpersonationLevel y) { Validate(x); Validate(y); if (x == y) return true; int px = 0; int py = 0; for (int i = 0; i < s_TokenImpersonationLevelOrder.Length; i++) { if (x == s_TokenImpersonationLevelOrder[i]) px = i; if (y == s_TokenImpersonationLevelOrder[i]) py = i; } return (px > py); } internal static int Compare(TokenImpersonationLevel x, TokenImpersonationLevel y) { int result = 0; if (x != y) { switch (x) { case TokenImpersonationLevel.Identification: result = -1; break; case TokenImpersonationLevel.Impersonation: switch (y) { case TokenImpersonationLevel.Identification: result = 1; break; case TokenImpersonationLevel.Delegation: result = -1; break; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("y", (int)y, typeof(TokenImpersonationLevel))); } break; case TokenImpersonationLevel.Delegation: result = 1; break; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("x", (int)x, typeof(TokenImpersonationLevel))); } } return result; } } internal static class SecurityUtils { public const string Principal = "Principal"; public const string Identities = "Identities"; private static IIdentity s_anonymousIdentity; private static X509SecurityTokenAuthenticator s_nonValidatingX509Authenticator; internal static X509SecurityTokenAuthenticator NonValidatingX509Authenticator { get { if (s_nonValidatingX509Authenticator == null) { s_nonValidatingX509Authenticator = new X509SecurityTokenAuthenticator(X509CertificateValidator.None); } return s_nonValidatingX509Authenticator; } } internal static IIdentity AnonymousIdentity { get { if (s_anonymousIdentity == null) { s_anonymousIdentity = CreateIdentity(string.Empty); } return s_anonymousIdentity; } } public static DateTime MaxUtcDateTime { get { // + and - TimeSpan.TicksPerDay is to compensate the DateTime.ParseExact (to localtime) overflow. return new DateTime(DateTime.MaxValue.Ticks - TimeSpan.TicksPerDay, DateTimeKind.Utc); } } public static DateTime MinUtcDateTime { get { // + and - TimeSpan.TicksPerDay is to compensate the DateTime.ParseExact (to localtime) overflow. return new DateTime(DateTime.MinValue.Ticks + TimeSpan.TicksPerDay, DateTimeKind.Utc); } } internal static IIdentity CreateIdentity(string name) { return new GenericIdentity(name); } internal static EndpointIdentity CreateWindowsIdentity() { return CreateWindowsIdentity(false); } internal static EndpointIdentity CreateWindowsIdentity(NetworkCredential serverCredential) { if (serverCredential != null && !NetworkCredentialHelper.IsDefault(serverCredential)) { string upn; if (serverCredential.Domain != null && serverCredential.Domain.Length > 0) { upn = serverCredential.UserName + "@" + serverCredential.Domain; } else { upn = serverCredential.UserName; } return EndpointIdentity.CreateUpnIdentity(upn); } return CreateWindowsIdentity(); } #if !SUPPORTS_WINDOWSIDENTITY internal static EndpointIdentity CreateWindowsIdentity(bool spnOnly) { EndpointIdentity identity = null; if (spnOnly) { identity = EndpointIdentity.CreateSpnIdentity(String.Format(CultureInfo.InvariantCulture, "host/{0}", DnsCache.MachineName)); } else { throw ExceptionHelper.PlatformNotSupported(); } return identity; } #else private static bool IsSystemAccount(WindowsIdentity self) { SecurityIdentifier sid = self.User; if (sid == null) { return false; } // S-1-5-82 is the prefix for the sid that represents the identity that IIS 7.5 Apppool thread runs under. return (sid.IsWellKnown(WellKnownSidType.LocalSystemSid) || sid.IsWellKnown(WellKnownSidType.NetworkServiceSid) || sid.IsWellKnown(WellKnownSidType.LocalServiceSid) || self.User.Value.StartsWith("S-1-5-82", StringComparison.OrdinalIgnoreCase)); } internal static EndpointIdentity CreateWindowsIdentity(bool spnOnly) { EndpointIdentity identity = null; using (WindowsIdentity self = WindowsIdentity.GetCurrent()) { bool isSystemAccount = IsSystemAccount(self); if (spnOnly || isSystemAccount) { identity = EndpointIdentity.CreateSpnIdentity(String.Format(CultureInfo.InvariantCulture, "host/{0}", DnsCache.MachineName)); } else { // Save windowsIdentity for delay lookup identity = new UpnEndpointIdentity(CloneWindowsIdentityIfNecessary(self)); } } return identity; } internal static WindowsIdentity CloneWindowsIdentityIfNecessary(WindowsIdentity wid) { return CloneWindowsIdentityIfNecessary(wid, null); } internal static WindowsIdentity CloneWindowsIdentityIfNecessary(WindowsIdentity wid, string authType) { if (wid != null) { IntPtr token = UnsafeGetWindowsIdentityToken(wid); if (token != IntPtr.Zero) { return UnsafeCreateWindowsIdentityFromToken(token, authType); } } return wid; } private static IntPtr UnsafeGetWindowsIdentityToken(WindowsIdentity wid) { throw ExceptionHelper.PlatformNotSupported("UnsafeGetWindowsIdentityToken is not supported"); } private static WindowsIdentity UnsafeCreateWindowsIdentityFromToken(IntPtr token, string authType) { if (authType != null) return new WindowsIdentity(token, authType); return new WindowsIdentity(token); } #endif // !SUPPORTS_WINDOWSIDENTITY internal static string GetSpnFromIdentity(EndpointIdentity identity, EndpointAddress target) { bool foundSpn = false; string spn = null; if (identity != null) { if (ClaimTypes.Spn.Equals(identity.IdentityClaim.ClaimType)) { spn = (string)identity.IdentityClaim.Resource; foundSpn = true; } else if (ClaimTypes.Upn.Equals(identity.IdentityClaim.ClaimType)) { spn = (string)identity.IdentityClaim.Resource; foundSpn = true; } else if (ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType)) { spn = string.Format(CultureInfo.InvariantCulture, "host/{0}", (string)identity.IdentityClaim.Resource); foundSpn = true; } } if (!foundSpn) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.Format(SR.CannotDetermineSPNBasedOnAddress, target))); } return spn; } internal static string GetSpnFromTarget(EndpointAddress target) { if (target == null) { throw Fx.AssertAndThrow("target should not be null - expecting an EndpointAddress"); } return string.Format(CultureInfo.InvariantCulture, "host/{0}", target.Uri.DnsSafeHost); } internal static bool IsSupportedAlgorithm(string algorithm, SecurityToken token) { if (token.SecurityKeys == null) { return false; } for (int i = 0; i < token.SecurityKeys.Count; ++i) { if (token.SecurityKeys[i].IsSupportedAlgorithm(algorithm)) { return true; } } return false; } internal static Claim GetPrimaryIdentityClaim(ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies) { return GetPrimaryIdentityClaim(AuthorizationContext.CreateDefaultAuthorizationContext(authorizationPolicies)); } internal static Claim GetPrimaryIdentityClaim(AuthorizationContext authContext) { if (authContext != null) { for (int i = 0; i < authContext.ClaimSets.Count; ++i) { ClaimSet claimSet = authContext.ClaimSets[i]; foreach (Claim claim in claimSet.FindClaims(null, Rights.Identity)) { return claim; } } } return null; } internal static string GenerateId() { return SecurityUniqueId.Create().Value; } internal static ReadOnlyCollection<IAuthorizationPolicy> CreatePrincipalNameAuthorizationPolicies(string principalName) { if (principalName == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("principalName"); Claim identityClaim; Claim primaryPrincipal; if (principalName.Contains("@") || principalName.Contains(@"\")) { identityClaim = new Claim(ClaimTypes.Upn, principalName, Rights.Identity); #if SUPPORTS_WINDOWSIDENTITY primaryPrincipal = Claim.CreateUpnClaim(principalName); #else throw ExceptionHelper.PlatformNotSupported("UPN claim not supported"); #endif // SUPPORTS_WINDOWSIDENTITY } else { identityClaim = new Claim(ClaimTypes.Spn, principalName, Rights.Identity); primaryPrincipal = Claim.CreateSpnClaim(principalName); } List<Claim> claims = new List<Claim>(2); claims.Add(identityClaim); claims.Add(primaryPrincipal); List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>(1); policies.Add(new UnconditionalPolicy(SecurityUtils.CreateIdentity(principalName), new DefaultClaimSet(ClaimSet.Anonymous, claims))); return policies.AsReadOnly(); } internal static string GetIdentityNamesFromContext(AuthorizationContext authContext) { if (authContext == null) return String.Empty; StringBuilder str = new StringBuilder(256); for (int i = 0; i < authContext.ClaimSets.Count; ++i) { ClaimSet claimSet = authContext.ClaimSets[i]; // Windows WindowsClaimSet windows = claimSet as WindowsClaimSet; if (windows != null) { #if SUPPORTS_WINDOWSIDENTITY if (str.Length > 0) str.Append(", "); AppendIdentityName(str, windows.WindowsIdentity); #else throw ExceptionHelper.PlatformNotSupported(ExceptionHelper.WinsdowsStreamSecurityNotSupported); #endif // SUPPORTS_WINDOWSIDENTITY } else { // X509 X509CertificateClaimSet x509 = claimSet as X509CertificateClaimSet; if (x509 != null) { if (str.Length > 0) str.Append(", "); AppendCertificateIdentityName(str, x509.X509Certificate); } } } if (str.Length <= 0) { List<IIdentity> identities = null; object obj; if (authContext.Properties.TryGetValue(SecurityUtils.Identities, out obj)) { identities = obj as List<IIdentity>; } if (identities != null) { for (int i = 0; i < identities.Count; ++i) { IIdentity identity = identities[i]; if (identity != null) { if (str.Length > 0) str.Append(", "); AppendIdentityName(str, identity); } } } } return str.Length <= 0 ? String.Empty : str.ToString(); } internal static void AppendCertificateIdentityName(StringBuilder str, X509Certificate2 certificate) { string value = certificate.SubjectName.Name; if (String.IsNullOrEmpty(value)) { value = certificate.GetNameInfo(X509NameType.DnsName, false); if (String.IsNullOrEmpty(value)) { value = certificate.GetNameInfo(X509NameType.SimpleName, false); if (String.IsNullOrEmpty(value)) { value = certificate.GetNameInfo(X509NameType.EmailName, false); if (String.IsNullOrEmpty(value)) { value = certificate.GetNameInfo(X509NameType.UpnName, false); } } } } // Same format as X509Identity str.Append(String.IsNullOrEmpty(value) ? "<x509>" : value); str.Append("; "); str.Append(certificate.Thumbprint); } internal static void AppendIdentityName(StringBuilder str, IIdentity identity) { string name = null; try { name = identity.Name; } #pragma warning suppress 56500 catch (Exception e) { if (Fx.IsFatal(e)) { throw; } // suppress exception, this is just info. } str.Append(String.IsNullOrEmpty(name) ? "<null>" : name); #if SUPPORTS_WINDOWSIDENTITY // NegotiateStream WindowsIdentity windows = identity as WindowsIdentity; if (windows != null) { if (windows.User != null) { str.Append("; "); str.Append(windows.User.ToString()); } } else { WindowsSidIdentity sid = identity as WindowsSidIdentity; if (sid != null) { str.Append("; "); str.Append(sid.SecurityIdentifier.ToString()); } } #else throw ExceptionHelper.PlatformNotSupported(ExceptionHelper.WinsdowsStreamSecurityNotSupported); #endif // SUPPORTS_WINDOWSIDENTITY } internal static void OpenTokenProviderIfRequired(SecurityTokenProvider tokenProvider, TimeSpan timeout) { OpenCommunicationObject(tokenProvider as ICommunicationObject, timeout); } internal static void CloseTokenProviderIfRequired(SecurityTokenProvider tokenProvider, TimeSpan timeout) { CloseCommunicationObject(tokenProvider, false, timeout); } internal static void AbortTokenProviderIfRequired(SecurityTokenProvider tokenProvider) { CloseCommunicationObject(tokenProvider, true, TimeSpan.Zero); } internal static void OpenTokenAuthenticatorIfRequired(SecurityTokenAuthenticator tokenAuthenticator, TimeSpan timeout) { OpenCommunicationObject(tokenAuthenticator as ICommunicationObject, timeout); } internal static void CloseTokenAuthenticatorIfRequired(SecurityTokenAuthenticator tokenAuthenticator, TimeSpan timeout) { CloseTokenAuthenticatorIfRequired(tokenAuthenticator, false, timeout); } internal static void CloseTokenAuthenticatorIfRequired(SecurityTokenAuthenticator tokenAuthenticator, bool aborted, TimeSpan timeout) { CloseCommunicationObject(tokenAuthenticator, aborted, timeout); } internal static void AbortTokenAuthenticatorIfRequired(SecurityTokenAuthenticator tokenAuthenticator) { CloseCommunicationObject(tokenAuthenticator, true, TimeSpan.Zero); } private static void OpenCommunicationObject(ICommunicationObject obj, TimeSpan timeout) { if (obj != null) obj.Open(timeout); } private static void CloseCommunicationObject(Object obj, bool aborted, TimeSpan timeout) { if (obj != null) { ICommunicationObject co = obj as ICommunicationObject; if (co != null) { if (aborted) { try { co.Abort(); } catch (CommunicationException) { } } else { co.Close(timeout); } } else if (obj is IDisposable) { ((IDisposable)obj).Dispose(); } } } internal static SecurityStandardsManager CreateSecurityStandardsManager(MessageSecurityVersion securityVersion, SecurityTokenManager tokenManager) { SecurityTokenSerializer tokenSerializer = tokenManager.CreateSecurityTokenSerializer(securityVersion.SecurityTokenVersion); return new SecurityStandardsManager(securityVersion, tokenSerializer); } internal static SecurityStandardsManager CreateSecurityStandardsManager(SecurityTokenRequirement requirement, SecurityTokenManager tokenManager) { MessageSecurityTokenVersion securityVersion = (MessageSecurityTokenVersion)requirement.GetProperty<MessageSecurityTokenVersion>(ServiceModelSecurityTokenRequirement.MessageSecurityVersionProperty); if (securityVersion == MessageSecurityTokenVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005BasicSecurityProfile10) return CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10, tokenManager); if (securityVersion == MessageSecurityTokenVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005) return CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11, tokenManager); if (securityVersion == MessageSecurityTokenVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005BasicSecurityProfile10) return CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10, tokenManager); if (securityVersion == MessageSecurityTokenVersion.WSSecurity10WSTrust13WSSecureConversation13BasicSecurityProfile10) return CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10, tokenManager); if (securityVersion == MessageSecurityTokenVersion.WSSecurity11WSTrust13WSSecureConversation13) return CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12, tokenManager); if (securityVersion == MessageSecurityTokenVersion.WSSecurity11WSTrust13WSSecureConversation13BasicSecurityProfile10) return CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10, tokenManager); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } internal static SecurityStandardsManager CreateSecurityStandardsManager(MessageSecurityVersion securityVersion, SecurityTokenSerializer securityTokenSerializer) { if (securityVersion == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("securityVersion")); } if (securityTokenSerializer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("securityTokenSerializer"); } return new SecurityStandardsManager(securityVersion, securityTokenSerializer); } internal static NetworkCredential GetNetworkCredentialsCopy(NetworkCredential networkCredential) { NetworkCredential result; if (networkCredential != null && !NetworkCredentialHelper.IsDefault(networkCredential)) { result = new NetworkCredential(networkCredential.UserName, networkCredential.Password, networkCredential.Domain); } else { result = networkCredential; } return result; } internal static NetworkCredential GetNetworkCredentialOrDefault(NetworkCredential credential) { // Because CredentialCache.DefaultNetworkCredentials is not immutable, we dont use it in our OM. Instead we // use an empty NetworkCredential to denote the default credentials. if (NetworkCredentialHelper.IsNullOrEmpty(credential)) { return CredentialCache.DefaultNetworkCredentials; } return credential; } internal static string AppendWindowsAuthenticationInfo(string inputString, NetworkCredential credential, AuthenticationLevel authenticationLevel, TokenImpersonationLevel impersonationLevel) { const string delimiter = "\0"; // nonprintable characters are invalid for SSPI Domain/UserName/Password if (NetworkCredentialHelper.IsDefault(credential)) { string sid = NetworkCredentialHelper.GetCurrentUserIdAsString(credential); return string.Concat(inputString, delimiter, sid, delimiter, AuthenticationLevelHelper.ToString(authenticationLevel), delimiter, TokenImpersonationLevelHelper.ToString(impersonationLevel)); } return string.Concat(inputString, delimiter, credential.Domain, delimiter, credential.UserName, delimiter, credential.Password, delimiter, AuthenticationLevelHelper.ToString(authenticationLevel), delimiter, TokenImpersonationLevelHelper.ToString(impersonationLevel)); } internal static class NetworkCredentialHelper { static string s_currentUser = string.Empty; const string DefaultCurrentUser = "____CURRENTUSER_NOT_AVAILABLE____"; static internal bool IsNullOrEmpty(NetworkCredential credential) { return credential == null || ( string.IsNullOrEmpty(credential.UserName) && string.IsNullOrEmpty(credential.Domain) && string.IsNullOrEmpty(credential.Password) ); } static internal bool IsDefault(NetworkCredential credential) { return CredentialCache.DefaultNetworkCredentials.Equals(credential); } internal static string GetCurrentUserIdAsString(NetworkCredential credential) { if (!string.IsNullOrEmpty(s_currentUser)) { return s_currentUser; } // CurrentUser could be set muliple times // This is fine because it does not affect the value returned. #if SUPPORTS_WINDOWSIDENTITY try { using (WindowsIdentity self = WindowsIdentity.GetCurrent()) { s_currentUser = self.User.Value; } } catch (PlatformNotSupportedException) { //WindowsIdentity is not supported on *NIX //so returning a username which is very unlikely to be a real username; s_currentUser = DefaultCurrentUser; } #else // There's no way to retrieve the current logged in user Id in UWP apps s_currentUser = DefaultCurrentUser; #endif // SUPPORTS_WINDOWSIDENTITY return s_currentUser; } } internal static byte[] CloneBuffer(byte[] buffer) { byte[] copy = Fx.AllocateByteArray(buffer.Length); Buffer.BlockCopy(buffer, 0, copy, 0, buffer.Length); return copy; } internal static string GetKeyDerivationAlgorithm(SecureConversationVersion version) { string derivationAlgorithm = null; if (version == SecureConversationVersion.WSSecureConversationFeb2005) { derivationAlgorithm = SecurityAlgorithms.Psha1KeyDerivation; } else if (version == SecureConversationVersion.WSSecureConversation13) { derivationAlgorithm = SecurityAlgorithms.Psha1KeyDerivationDec2005; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } return derivationAlgorithm; } internal static X509Certificate2 GetCertificateFromStore(StoreName storeName, StoreLocation storeLocation, X509FindType findType, object findValue, EndpointAddress target) { X509Certificate2 certificate = GetCertificateFromStoreCore(storeName, storeLocation, findType, findValue, target, true); if (certificate == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.CannotFindCert, storeName, storeLocation, findType, findValue))); return certificate; } internal static bool TryGetCertificateFromStore(StoreName storeName, StoreLocation storeLocation, X509FindType findType, object findValue, EndpointAddress target, out X509Certificate2 certificate) { certificate = GetCertificateFromStoreCore(storeName, storeLocation, findType, findValue, target, false); return (certificate != null); } private static X509Certificate2 GetCertificateFromStoreCore(StoreName storeName, StoreLocation storeLocation, X509FindType findType, object findValue, EndpointAddress target, bool throwIfMultipleOrNoMatch) { if (findValue == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("findValue"); } X509Store store = new X509Store(storeName, storeLocation); X509Certificate2Collection certs = null; try { store.Open(OpenFlags.ReadOnly); certs = store.Certificates.Find(findType, findValue, false); if (certs.Count == 1) { // dotnet/wcf#1574 // ORIGINAL CODE: // return new X509Certificate2(certs[0].Handle); return certs[0].CloneCertificateInternal(); } if (throwIfMultipleOrNoMatch) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateCertificateLoadException( storeName, storeLocation, findType, findValue, target, certs.Count)); } else { return null; } } finally { ResetAllCertificates(certs); store.Dispose(); } } internal static Exception CreateCertificateLoadException(StoreName storeName, StoreLocation storeLocation, X509FindType findType, object findValue, EndpointAddress target, int certCount) { if (certCount == 0) { if (target == null) { return new InvalidOperationException(SR.Format(SR.CannotFindCert, storeName, storeLocation, findType, findValue)); } return new InvalidOperationException(SR.Format(SR.CannotFindCertForTarget, storeName, storeLocation, findType, findValue, target)); } if (target == null) { return new InvalidOperationException(SR.Format(SR.FoundMultipleCerts, storeName, storeLocation, findType, findValue)); } return new InvalidOperationException(SR.Format(SR.FoundMultipleCertsForTarget, storeName, storeLocation, findType, findValue, target)); } internal static void FixNetworkCredential(ref NetworkCredential credential) { if (credential == null) { return; } string username = credential.UserName; string domain = credential.Domain; if (!string.IsNullOrEmpty(username) && string.IsNullOrEmpty(domain)) { // do the splitting only if there is exactly 1 \ or exactly 1 @ string[] partsWithSlashDelimiter = username.Split('\\'); string[] partsWithAtDelimiter = username.Split('@'); if (partsWithSlashDelimiter.Length == 2 && partsWithAtDelimiter.Length == 1) { if (!string.IsNullOrEmpty(partsWithSlashDelimiter[0]) && !string.IsNullOrEmpty(partsWithSlashDelimiter[1])) { credential = new NetworkCredential(partsWithSlashDelimiter[1], credential.Password, partsWithSlashDelimiter[0]); } } else if (partsWithSlashDelimiter.Length == 1 && partsWithAtDelimiter.Length == 2) { if (!string.IsNullOrEmpty(partsWithAtDelimiter[0]) && !string.IsNullOrEmpty(partsWithAtDelimiter[1])) { credential = new NetworkCredential(partsWithAtDelimiter[0], credential.Password, partsWithAtDelimiter[1]); } } } } #if SUPPORTS_WINDOWSIDENTITY // NegotiateStream public static void ValidateAnonymityConstraint(WindowsIdentity identity, bool allowUnauthenticatedCallers) { if (!allowUnauthenticatedCallers && identity.User.IsWellKnown(WellKnownSidType.AnonymousSid)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning( new SecurityTokenValidationException(SR.Format(SR.AnonymousLogonsAreNotAllowed))); } } #endif // SUPPORTS_WINDOWSIDENTITY // This is the workaround, Since store.Certificates returns a full collection // of certs in store. These are holding native resources. internal static void ResetAllCertificates(X509Certificate2Collection certificates) { if (certificates != null) { for (int i = 0; i < certificates.Count; ++i) { ResetCertificate(certificates[i]); } } } internal static void ResetCertificate(X509Certificate2 certificate) { // Check that Dispose() and Reset() do the same thing certificate.Dispose(); } } internal struct SecurityUniqueId { private static long s_nextId = 0; private static string s_commonPrefix = "uuid-" + Guid.NewGuid().ToString() + "-"; private long _id; private string _prefix; private string _val; private SecurityUniqueId(string prefix, long id) { _id = id; _prefix = prefix; _val = null; } public static SecurityUniqueId Create() { return Create(s_commonPrefix); } public static SecurityUniqueId Create(string prefix) { return new SecurityUniqueId(prefix, Interlocked.Increment(ref s_nextId)); } public string Value { get { if (_val == null) _val = _prefix + _id.ToString(CultureInfo.InvariantCulture); return _val; } } } internal static class EmptyReadOnlyCollection<T> { public static ReadOnlyCollection<T> Instance = new ReadOnlyCollection<T>(new List<T>()); } internal class OperationWithTimeoutAsyncResult : TraceAsyncResult { private static readonly Action<object> s_scheduledCallback = new Action<object>(OnScheduled); private TimeoutHelper _timeoutHelper; private Action<TimeSpan> _operationWithTimeout; public OperationWithTimeoutAsyncResult(Action<TimeSpan> operationWithTimeout, TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state) { _operationWithTimeout = operationWithTimeout; _timeoutHelper = new TimeoutHelper(timeout); ActionItem.Schedule(s_scheduledCallback, this); } private static void OnScheduled(object state) { OperationWithTimeoutAsyncResult thisResult = (OperationWithTimeoutAsyncResult)state; Exception completionException = null; try { using (thisResult.CallbackActivity == null ? null : ServiceModelActivity.BoundOperation(thisResult.CallbackActivity)) { thisResult._operationWithTimeout(thisResult._timeoutHelper.RemainingTime()); } } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Fx.IsFatal(e)) { throw; } completionException = e; } thisResult.Complete(false, completionException); } public static void End(IAsyncResult result) { End<OperationWithTimeoutAsyncResult>(result); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Security.Claims; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using IdentitySample.Models; using IdentitySample.Models.ManageViewModels; using IdentitySample.Services; namespace IdentitySamples.Controllers { [Authorize] public class ManageController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly IEmailSender _emailSender; private readonly ISmsSender _smsSender; private readonly ILogger _logger; public ManageController( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, IEmailSender emailSender, ISmsSender smsSender, ILoggerFactory loggerFactory) { _userManager = userManager; _signInManager = signInManager; _emailSender = emailSender; _smsSender = smsSender; _logger = loggerFactory.CreateLogger<ManageController>(); } // // GET: /Manage/Index [HttpGet] public async Task<IActionResult> Index(ManageMessageId? message = null) { ViewData["StatusMessage"] = message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed." : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set." : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set." : message == ManageMessageId.Error ? "An error has occurred." : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added." : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed." : ""; var user = await GetCurrentUserAsync(); var model = new IndexViewModel { HasPassword = await _userManager.HasPasswordAsync(user), PhoneNumber = await _userManager.GetPhoneNumberAsync(user), TwoFactor = await _userManager.GetTwoFactorEnabledAsync(user), Logins = await _userManager.GetLoginsAsync(user), BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user) }; return View(model); } // // POST: /Manage/RemoveLogin [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel account) { ManageMessageId? message = ManageMessageId.Error; var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.RemoveLoginAsync(user, account.LoginProvider, account.ProviderKey); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); message = ManageMessageId.RemoveLoginSuccess; } } return RedirectToAction(nameof(ManageLogins), new { Message = message }); } // // GET: /Manage/AddPhoneNumber public IActionResult AddPhoneNumber() { return View(); } // // POST: /Manage/AddPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } // Generate the token and send it var user = await GetCurrentUserAsync(); var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber); await _smsSender.SendSmsAsync(model.PhoneNumber, "Your security code is: " + code); return RedirectToAction(nameof(VerifyPhoneNumber), new { PhoneNumber = model.PhoneNumber }); } // // POST: /Manage/EnableTwoFactorAuthentication [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> EnableTwoFactorAuthentication() { var user = await GetCurrentUserAsync(); if (user != null) { await _userManager.SetTwoFactorEnabledAsync(user, true); await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(1, "User enabled two-factor authentication."); } return RedirectToAction(nameof(Index), "Manage"); } // // POST: /Manage/DisableTwoFactorAuthentication [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> DisableTwoFactorAuthentication() { var user = await GetCurrentUserAsync(); if (user != null) { await _userManager.SetTwoFactorEnabledAsync(user, false); await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(2, "User disabled two-factor authentication."); } return RedirectToAction(nameof(Index), "Manage"); } // // GET: /Manage/VerifyPhoneNumber [HttpGet] public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber) { var code = await _userManager.GenerateChangePhoneNumberTokenAsync(await GetCurrentUserAsync(), phoneNumber); // Send an SMS to verify the phone number return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber }); } // // POST: /Manage/VerifyPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.AddPhoneSuccess }); } } // If we got this far, something failed, redisplay the form ModelState.AddModelError(string.Empty, "Failed to verify phone number"); return View(model); } // // GET: /Manage/RemovePhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> RemovePhoneNumber() { var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.SetPhoneNumberAsync(user, null); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.RemovePhoneSuccess }); } } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } // // GET: /Manage/ChangePassword [HttpGet] public IActionResult ChangePassword() { return View(); } // // POST: /Manage/ChangePassword [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(3, "User changed their password successfully."); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess }); } AddErrors(result); return View(model); } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } // // GET: /Manage/SetPassword [HttpGet] public IActionResult SetPassword() { return View(); } // // POST: /Manage/SetPassword [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> SetPassword(SetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.AddPasswordAsync(user, model.NewPassword); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetPasswordSuccess }); } AddErrors(result); return View(model); } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } //GET: /Manage/ManageLogins [HttpGet] public async Task<IActionResult> ManageLogins(ManageMessageId? message = null) { ViewData["StatusMessage"] = message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed." : message == ManageMessageId.AddLoginSuccess ? "The external login was added." : message == ManageMessageId.Error ? "An error has occurred." : ""; var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var userLogins = await _userManager.GetLoginsAsync(user); var otherLogins = _signInManager.GetExternalAuthenticationSchemes().Where(auth => userLogins.All(ul => auth.AuthenticationScheme != ul.LoginProvider)).ToList(); ViewData["ShowRemoveButton"] = user.PasswordHash != null || userLogins.Count > 1; return View(new ManageLoginsViewModel { CurrentLogins = userLogins, OtherLogins = otherLogins }); } // // POST: /Manage/LinkLogin [HttpPost] [ValidateAntiForgeryToken] public IActionResult LinkLogin(string provider) { // Request a redirect to the external login provider to link a login for the current user var redirectUrl = Url.Action("LinkLoginCallback", "Manage"); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User)); return Challenge(properties, provider); } // // GET: /Manage/LinkLoginCallback [HttpGet] public async Task<ActionResult> LinkLoginCallback() { var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var info = await _signInManager.GetExternalLoginInfoAsync(await _userManager.GetUserIdAsync(user)); if (info == null) { return RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error }); } var result = await _userManager.AddLoginAsync(user, info); var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error; return RedirectToAction(nameof(ManageLogins), new { Message = message }); } #region Helpers private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } public enum ManageMessageId { AddPhoneSuccess, AddLoginSuccess, ChangePasswordSuccess, SetTwoFactorSuccess, SetPasswordSuccess, RemoveLoginSuccess, RemovePhoneSuccess, Error } private Task<ApplicationUser> GetCurrentUserAsync() { return _userManager.GetUserAsync(HttpContext.User); } #endregion } }
using Attest.Fake.Setup.Contracts; namespace Attest.Fake.Setup { /// <summary> /// Represents visitor for different callbacks without return value and no parameters. /// </summary> class MethodCallbackVisitor : IMethodCallbackVisitor { /// <summary> /// Visits exception throwing callback /// </summary> /// <param name="onErrorCallback">Callback</param> public void Visit(OnErrorCallback onErrorCallback) { MethodCallbackVisitorHelper.VisitError(onErrorCallback); } /// <summary> /// Visits successful completion callback /// </summary> /// <param name="onCompleteCallback">Callback</param> public void Visit(OnCompleteCallback onCompleteCallback) { onCompleteCallback.Callback(); } /// <summary> /// Visits progress callback /// </summary> /// <param name="progressCallback">Callback</param> public void Visit(ProgressCallback progressCallback) { MethodCallbackVisitorHelper.VisitProgress(progressCallback, c => c.Accept(this)); } /// <summary> /// Visits cancellation callback /// </summary> /// <param name="onCancelCallback">Callback</param> public void Visit(OnCancelCallback onCancelCallback) { MethodCallbackVisitorHelper.VisitCancel(); } /// <summary> /// Visits never-ending callback. /// </summary> /// <param name="withoutCallback">Callback</param> public void Visit(OnWithoutCallback withoutCallback) { MethodCallbackVisitorHelper.VisitWithout(); } } /// <summary> /// Represents visitor for different callbacks without return value and one parameter. /// </summary> /// <typeparam name="T">The type of the parameter.</typeparam> public class MethodCallbackVisitor<T> : IMethodCallbackVisitor<T> { /// <summary> /// Visits exception throwing callback /// </summary> /// <param name="onErrorCallback">Callback</param> /// <param name="arg">Parameter</param> public void Visit(OnErrorCallback<T> onErrorCallback, T arg) { MethodCallbackVisitorHelper.VisitError(onErrorCallback); } /// <summary> /// Visits successful completion callback /// </summary> /// <param name="onCompleteCallback">Callback</param> /// <param name="arg">Parameter</param> public void Visit(OnCompleteCallback<T> onCompleteCallback, T arg) { onCompleteCallback.Callback(arg); } /// <summary> /// Visits progress callback /// </summary> /// <param name="progressCallback">Callback.</param> /// <param name="arg">Parameter.</param> public void Visit(ProgressCallback<T> progressCallback, T arg) { MethodCallbackVisitorHelper.VisitProgress(progressCallback, c => c.Accept(this, arg)); } /// <summary> /// Visits cancellation callback /// </summary> /// <param name="onCancelCallback">Callback</param> /// <param name="arg">Parameter.</param> public void Visit(OnCancelCallback<T> onCancelCallback, T arg) { MethodCallbackVisitorHelper.VisitCancel(); } /// <summary> /// Visits never-ending callback /// </summary> /// <param name="withoutCallback">Callback</param> /// <param name="arg">Parameter.</param> public void Visit(OnWithoutCallback<T> withoutCallback, T arg) { MethodCallbackVisitorHelper.VisitWithout(); } } /// <summary> /// Represents visitor for different callbacks without return value and two parameters. /// </summary> /// <typeparam name="T1">The type of the first parameter.</typeparam> /// <typeparam name="T2">The type of the second parameter.</typeparam> /// <seealso cref="MethodCallbackVisitorHelper" /> public class MethodCallbackVisitor<T1, T2> : IMethodCallbackVisitor<T1, T2> { /// <summary> /// Visits exception throwing callback /// </summary> /// <param name="onErrorCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> public void Visit(OnErrorCallback<T1, T2> onErrorCallback, T1 arg1, T2 arg2) { MethodCallbackVisitorHelper.VisitError(onErrorCallback); } /// <summary> /// Visits successful completion callback /// </summary> /// <param name="onCompleteCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> public void Visit(OnCompleteCallback<T1, T2> onCompleteCallback, T1 arg1, T2 arg2) { onCompleteCallback.Callback(arg1, arg2); } /// <summary> /// Visits progress callback /// </summary> /// <param name="progressCallback">Callback.</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> public void Visit(ProgressCallback<T1, T2> progressCallback, T1 arg1, T2 arg2) { MethodCallbackVisitorHelper.VisitProgress(progressCallback, c => c.Accept(this, arg1, arg2)); } /// <summary> /// Visits cancellation callback /// </summary> /// <param name="onCancelCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> public void Visit(OnCancelCallback<T1, T2> onCancelCallback, T1 arg1, T2 arg2) { MethodCallbackVisitorHelper.VisitCancel(); } /// <summary> /// Visits never-ending callback /// </summary> /// <param name="withoutCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> public void Visit(OnWithoutCallback<T1, T2> withoutCallback, T1 arg1, T2 arg2) { MethodCallbackVisitorHelper.VisitWithout(); } } /// <summary> /// Represents visitor for different callbacks without return value and three parameters. /// </summary> /// <typeparam name="T1">The type of the first parameter.</typeparam> /// <typeparam name="T2">The type of the second parameter.</typeparam> /// <typeparam name="T3">The type of the third parameter.</typeparam> /// <seealso cref="MethodCallbackVisitorHelper" /> public class MethodCallbackVisitor<T1, T2, T3> : IMethodCallbackVisitor<T1, T2, T3> { /// <summary> /// Visits exception throwing callback /// </summary> /// <param name="onErrorCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> public void Visit(OnErrorCallback<T1, T2, T3> onErrorCallback, T1 arg1, T2 arg2, T3 arg3) { MethodCallbackVisitorHelper.VisitError(onErrorCallback); } /// <summary> /// Visits successful completion callback /// </summary> /// <param name="onCompleteCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> public void Visit(OnCompleteCallback<T1, T2, T3> onCompleteCallback, T1 arg1, T2 arg2, T3 arg3) { onCompleteCallback.Callback(arg1, arg2, arg3); } /// <summary> /// Visits progress callback /// </summary> /// <param name="progressCallback">Callback.</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> public void Visit(ProgressCallback<T1, T2, T3> progressCallback, T1 arg1, T2 arg2, T3 arg3) { MethodCallbackVisitorHelper.VisitProgress(progressCallback, c => c.Accept(this, arg1, arg2, arg3)); } /// <summary> /// Visits cancellation callback /// </summary> /// <param name="onCancelCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> public void Visit(OnCancelCallback<T1, T2, T3> onCancelCallback, T1 arg1, T2 arg2, T3 arg3) { MethodCallbackVisitorHelper.VisitCancel(); } /// <summary> /// Visits never-ending callback /// </summary> /// <param name="withoutCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> public void Visit(OnWithoutCallback<T1, T2, T3> withoutCallback, T1 arg1, T2 arg2, T3 arg3) { MethodCallbackVisitorHelper.VisitWithout(); } } /// <summary> /// Represents visitor for different callbacks without return value and four parameters. /// </summary> /// <typeparam name="T1">The type of the first parameter.</typeparam> /// <typeparam name="T2">The type of the second parameter.</typeparam> /// <typeparam name="T3">The type of the third parameter.</typeparam> /// <typeparam name="T4">The type of the fourth parameter.</typeparam> /// <seealso cref="MethodCallbackVisitorHelper" /> public class MethodCallbackVisitor<T1, T2, T3, T4> : IMethodCallbackVisitor<T1, T2, T3, T4> { /// <summary> /// Visits exception throwing callback /// </summary> /// <param name="onErrorCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> /// <param name="arg4">Fourth parameter</param> public void Visit(OnErrorCallback<T1, T2, T3, T4> onErrorCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4) { MethodCallbackVisitorHelper.VisitError(onErrorCallback); } /// <summary> /// Visits successful completion callback /// </summary> /// <param name="onCompleteCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> /// <param name="arg4">Fourth parameter</param> public void Visit(OnCompleteCallback<T1, T2, T3, T4> onCompleteCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4) { onCompleteCallback.Callback(arg1, arg2, arg3, arg4); } /// <summary> /// Visits progress callback /// </summary> /// <param name="progressCallback">Callback.</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> /// <param name="arg4">Fourth parameter</param> public void Visit(ProgressCallback<T1, T2, T3, T4> progressCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4) { MethodCallbackVisitorHelper.VisitProgress(progressCallback, c => c.Accept(this, arg1, arg2, arg3, arg4)); } /// <summary> /// Visits cancellation callback /// </summary> /// <param name="onCancelCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> /// <param name="arg4">Fourth parameter</param> public void Visit(OnCancelCallback<T1, T2, T3, T4> onCancelCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4) { MethodCallbackVisitorHelper.VisitCancel(); } /// <summary> /// Visits never-ending callback /// </summary> /// <param name="withoutCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> /// <param name="arg4">Fourth parameter</param> public void Visit(OnWithoutCallback<T1, T2, T3, T4> withoutCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4) { MethodCallbackVisitorHelper.VisitWithout(); } } /// <summary> /// Represents visitor for different callbacks without return value and five parameters. /// </summary> /// <typeparam name="T1">The type of the first parameter.</typeparam> /// <typeparam name="T2">The type of the second parameter.</typeparam> /// <typeparam name="T3">The type of the third parameter.</typeparam> /// <typeparam name="T4">The type of the fourth parameter.</typeparam> /// <typeparam name="T5">The type of the fifth parameter.</typeparam> /// <seealso cref="MethodCallbackVisitorHelper" /> public class MethodCallbackVisitor<T1, T2, T3, T4, T5> : IMethodCallbackVisitor<T1, T2, T3, T4, T5> { /// <summary> /// Visits exception throwing callback /// </summary> /// <param name="onErrorCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> /// <param name="arg4">Fourth parameter</param> /// <param name="arg5">Fifth parameter</param> public void Visit(OnErrorCallback<T1, T2, T3, T4, T5> onErrorCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) { MethodCallbackVisitorHelper.VisitError(onErrorCallback); } /// <summary> /// Visits successful completion callback /// </summary> /// <param name="onCompleteCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> /// <param name="arg4">Fourth parameter</param> /// <param name="arg5">Fifth parameter</param> public void Visit(OnCompleteCallback<T1, T2, T3, T4, T5> onCompleteCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) { onCompleteCallback.Callback(arg1, arg2, arg3, arg4, arg5); } /// <summary> /// Visits progress callback /// </summary> /// <param name="progressCallback">Callback.</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> /// <param name="arg4">Fourth parameter</param> /// <param name="arg5">Fifth parameter</param> public void Visit(ProgressCallback<T1, T2, T3, T4, T5> progressCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) { MethodCallbackVisitorHelper.VisitProgress(progressCallback, c => c.Accept(this, arg1, arg2, arg3, arg4, arg5)); } /// <summary> /// Visits cancellation callback /// </summary> /// <param name="onCancelCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> /// <param name="arg4">Fourth parameter</param> /// <param name="arg5">Fifth parameter</param> public void Visit(OnCancelCallback<T1, T2, T3, T4, T5> onCancelCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) { MethodCallbackVisitorHelper.VisitCancel(); } /// <summary> /// Visits never-ending callback /// </summary> /// <param name="withoutCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> /// <param name="arg4">Fourth parameter</param> /// <param name="arg5">Fifth parameter</param> public void Visit(OnWithoutCallback<T1, T2, T3, T4, T5> withoutCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) { MethodCallbackVisitorHelper.VisitWithout(); } } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using org.swyn.foundation.utils; namespace tdbadmin { /// <summary> /// Summary description for Country. /// </summary> public class FPricetype : System.Windows.Forms.Form { private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.GroupBox TDB_abgrp; private System.Windows.Forms.Button TDB_ab_clr; private System.Windows.Forms.Button TDB_ab_sel; private System.Windows.Forms.Button TDB_ab_exit; private System.Windows.Forms.Button TDB_ab_del; private System.Windows.Forms.Button TDB_ab_upd; private System.Windows.Forms.Button TDB_ab_ins; private System.Windows.Forms.Label tdb_e_id; private System.Windows.Forms.TextBox tdb_e_bez; private System.Windows.Forms.TextBox tdb_e_text; private System.Windows.Forms.Label tdb_l_text; private System.Windows.Forms.Label tdb_l_bez; private System.Windows.Forms.Label tdb_l_id; private tdbgui.GUIpricet PT; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public FPricetype() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // PT = new tdbgui.GUIpricet(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.groupBox1 = new System.Windows.Forms.GroupBox(); this.tdb_e_id = new System.Windows.Forms.Label(); this.tdb_e_bez = new System.Windows.Forms.TextBox(); this.tdb_e_text = new System.Windows.Forms.TextBox(); this.tdb_l_text = new System.Windows.Forms.Label(); this.tdb_l_bez = new System.Windows.Forms.Label(); this.tdb_l_id = new System.Windows.Forms.Label(); this.TDB_abgrp = new System.Windows.Forms.GroupBox(); this.TDB_ab_clr = new System.Windows.Forms.Button(); this.TDB_ab_sel = new System.Windows.Forms.Button(); this.TDB_ab_exit = new System.Windows.Forms.Button(); this.TDB_ab_del = new System.Windows.Forms.Button(); this.TDB_ab_upd = new System.Windows.Forms.Button(); this.TDB_ab_ins = new System.Windows.Forms.Button(); this.groupBox1.SuspendLayout(); this.TDB_abgrp.SuspendLayout(); this.SuspendLayout(); // // groupBox1 // this.groupBox1.Controls.Add(this.tdb_e_id); this.groupBox1.Controls.Add(this.tdb_e_bez); this.groupBox1.Controls.Add(this.tdb_e_text); this.groupBox1.Controls.Add(this.tdb_l_text); this.groupBox1.Controls.Add(this.tdb_l_bez); this.groupBox1.Controls.Add(this.tdb_l_id); this.groupBox1.Dock = System.Windows.Forms.DockStyle.Fill; this.groupBox1.Location = new System.Drawing.Point(0, 0); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(608, 245); this.groupBox1.TabIndex = 13; this.groupBox1.TabStop = false; this.groupBox1.Text = "Description"; // // tdb_e_id // this.tdb_e_id.Location = new System.Drawing.Point(136, 24); this.tdb_e_id.Name = "tdb_e_id"; this.tdb_e_id.Size = new System.Drawing.Size(64, 16); this.tdb_e_id.TabIndex = 9; // // tdb_e_bez // this.tdb_e_bez.Location = new System.Drawing.Point(136, 40); this.tdb_e_bez.Name = "tdb_e_bez"; this.tdb_e_bez.Size = new System.Drawing.Size(456, 20); this.tdb_e_bez.TabIndex = 0; this.tdb_e_bez.Text = ""; // // tdb_e_text // this.tdb_e_text.Location = new System.Drawing.Point(136, 88); this.tdb_e_text.Multiline = true; this.tdb_e_text.Name = "tdb_e_text"; this.tdb_e_text.Size = new System.Drawing.Size(456, 88); this.tdb_e_text.TabIndex = 2; this.tdb_e_text.Text = ""; // // tdb_l_text // this.tdb_l_text.Location = new System.Drawing.Point(8, 121); this.tdb_l_text.Name = "tdb_l_text"; this.tdb_l_text.RightToLeft = System.Windows.Forms.RightToLeft.No; this.tdb_l_text.TabIndex = 4; this.tdb_l_text.Text = "Description"; // // tdb_l_bez // this.tdb_l_bez.Location = new System.Drawing.Point(8, 39); this.tdb_l_bez.Name = "tdb_l_bez"; this.tdb_l_bez.TabIndex = 2; this.tdb_l_bez.Text = "Title"; // // tdb_l_id // this.tdb_l_id.Location = new System.Drawing.Point(8, 21); this.tdb_l_id.Name = "tdb_l_id"; this.tdb_l_id.TabIndex = 1; this.tdb_l_id.Text = "ID"; // // TDB_abgrp // this.TDB_abgrp.Controls.Add(this.TDB_ab_clr); this.TDB_abgrp.Controls.Add(this.TDB_ab_sel); this.TDB_abgrp.Controls.Add(this.TDB_ab_exit); this.TDB_abgrp.Controls.Add(this.TDB_ab_del); this.TDB_abgrp.Controls.Add(this.TDB_ab_upd); this.TDB_abgrp.Controls.Add(this.TDB_ab_ins); this.TDB_abgrp.Dock = System.Windows.Forms.DockStyle.Bottom; this.TDB_abgrp.Location = new System.Drawing.Point(0, 192); this.TDB_abgrp.Name = "TDB_abgrp"; this.TDB_abgrp.Size = new System.Drawing.Size(608, 53); this.TDB_abgrp.TabIndex = 15; this.TDB_abgrp.TabStop = false; this.TDB_abgrp.Text = "Actions"; // // TDB_ab_clr // this.TDB_ab_clr.Dock = System.Windows.Forms.DockStyle.Right; this.TDB_ab_clr.Location = new System.Drawing.Point(455, 16); this.TDB_ab_clr.Name = "TDB_ab_clr"; this.TDB_ab_clr.Size = new System.Drawing.Size(75, 34); this.TDB_ab_clr.TabIndex = 10; this.TDB_ab_clr.Text = "Clear"; this.TDB_ab_clr.Click += new System.EventHandler(this.TDB_ab_clr_Click); // // TDB_ab_sel // this.TDB_ab_sel.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.Byte)(192)), ((System.Byte)(255))); this.TDB_ab_sel.Dock = System.Windows.Forms.DockStyle.Left; this.TDB_ab_sel.Location = new System.Drawing.Point(228, 16); this.TDB_ab_sel.Name = "TDB_ab_sel"; this.TDB_ab_sel.Size = new System.Drawing.Size(80, 34); this.TDB_ab_sel.TabIndex = 8; this.TDB_ab_sel.Text = "Select"; this.TDB_ab_sel.Click += new System.EventHandler(this.TDB_ab_sel_Click); // // TDB_ab_exit // this.TDB_ab_exit.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(0)), ((System.Byte)(192)), ((System.Byte)(192))); this.TDB_ab_exit.Dock = System.Windows.Forms.DockStyle.Right; this.TDB_ab_exit.Location = new System.Drawing.Point(530, 16); this.TDB_ab_exit.Name = "TDB_ab_exit"; this.TDB_ab_exit.Size = new System.Drawing.Size(75, 34); this.TDB_ab_exit.TabIndex = 9; this.TDB_ab_exit.Text = "Exit"; this.TDB_ab_exit.Click += new System.EventHandler(this.TDB_ab_exit_Click); // // TDB_ab_del // this.TDB_ab_del.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(192)), ((System.Byte)(192))); this.TDB_ab_del.Dock = System.Windows.Forms.DockStyle.Left; this.TDB_ab_del.Location = new System.Drawing.Point(153, 16); this.TDB_ab_del.Name = "TDB_ab_del"; this.TDB_ab_del.Size = new System.Drawing.Size(75, 34); this.TDB_ab_del.TabIndex = 7; this.TDB_ab_del.Text = "Delete"; this.TDB_ab_del.Click += new System.EventHandler(this.TDB_ab_del_Click); // // TDB_ab_upd // this.TDB_ab_upd.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(192)), ((System.Byte)(192))); this.TDB_ab_upd.Dock = System.Windows.Forms.DockStyle.Left; this.TDB_ab_upd.Location = new System.Drawing.Point(78, 16); this.TDB_ab_upd.Name = "TDB_ab_upd"; this.TDB_ab_upd.Size = new System.Drawing.Size(75, 34); this.TDB_ab_upd.TabIndex = 6; this.TDB_ab_upd.Text = "Update"; this.TDB_ab_upd.Click += new System.EventHandler(this.TDB_ab_upd_Click); // // TDB_ab_ins // this.TDB_ab_ins.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(192)), ((System.Byte)(192))); this.TDB_ab_ins.Dock = System.Windows.Forms.DockStyle.Left; this.TDB_ab_ins.Location = new System.Drawing.Point(3, 16); this.TDB_ab_ins.Name = "TDB_ab_ins"; this.TDB_ab_ins.Size = new System.Drawing.Size(75, 34); this.TDB_ab_ins.TabIndex = 5; this.TDB_ab_ins.Text = "Insert"; this.TDB_ab_ins.Click += new System.EventHandler(this.TDB_ab_ins_Click); // // FPriceType // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(608, 245); this.Controls.Add(this.TDB_abgrp); this.Controls.Add(this.groupBox1); this.Name = "FPriceType"; this.Text = "Price Type"; this.groupBox1.ResumeLayout(false); this.TDB_abgrp.ResumeLayout(false); this.ResumeLayout(false); } #endregion #region Form callbacks private void TDB_ab_sel_Click(object sender, System.EventArgs e) { SelForm Fsel = new SelForm(); PT.Sel(Fsel.GetLV); Fsel.Accept += new EventHandler(TDB_ab_sel_Click_Return); Fsel.ShowDialog(this); } void TDB_ab_sel_Click_Return(object sender, EventArgs e) { int id = -1, rows = 0; SelForm Fsel = (SelForm)sender; id = Fsel.GetID; PT.Get(id, ref rows); tdb_e_id.Text = PT.ObjId.ToString(); tdb_e_bez.Text = PT.ObjBez; tdb_e_text.Text = PT.ObjText; } private void TDB_ab_exit_Click(object sender, System.EventArgs e) { Close(); } private void TDB_ab_ins_Click(object sender, System.EventArgs e) { PT.InsUpd(true, tdb_e_bez.Text, tdb_e_text.Text); tdb_e_id.Text = PT.ObjId.ToString(); } private void TDB_ab_upd_Click(object sender, System.EventArgs e) { PT.InsUpd(false, tdb_e_bez.Text, tdb_e_text.Text); } private void TDB_ab_del_Click(object sender, System.EventArgs e) { int rows = 0; PT.Get(Convert.ToInt32(tdb_e_id.Text), ref rows); PT.Delete(); } private void TDB_ab_clr_Click(object sender, System.EventArgs e) { tdb_e_id.Text = ""; tdb_e_bez.Text = ""; tdb_e_text.Text = ""; } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; using UIKit; namespace Xamarin.Forms.Platform.iOS { public class EventTracker : IDisposable { readonly NotifyCollectionChangedEventHandler _collectionChangedHandler; readonly Dictionary<IGestureRecognizer, UIGestureRecognizer> _gestureRecognizers = new Dictionary<IGestureRecognizer, UIGestureRecognizer>(); readonly IVisualElementRenderer _renderer; bool _disposed; UIView _handler; double _previousScale = 1.0; UITouchEventArgs _shouldReceive; public EventTracker(IVisualElementRenderer renderer) { if (renderer == null) throw new ArgumentNullException("renderer"); _collectionChangedHandler = ModelGestureRecognizersOnCollectionChanged; _renderer = renderer; _renderer.ElementChanged += OnElementChanged; } ObservableCollection<IGestureRecognizer> ElementGestureRecognizers { get { if (_renderer?.Element is View) return ((View)_renderer.Element).GestureRecognizers as ObservableCollection<IGestureRecognizer>; return null; } } public void Dispose() { if (_disposed) return; _disposed = true; foreach (var kvp in _gestureRecognizers) { _handler.RemoveGestureRecognizer(kvp.Value); kvp.Value.Dispose(); } _gestureRecognizers.Clear(); if (ElementGestureRecognizers != null) ElementGestureRecognizers.CollectionChanged -= _collectionChangedHandler; _handler = null; } public void LoadEvents(UIView handler) { if (_disposed) throw new ObjectDisposedException(null); _shouldReceive = (r, t) => t.View is IVisualElementRenderer; _handler = handler; OnElementChanged(this, new VisualElementChangedEventArgs(null, _renderer.Element)); } protected virtual UIGestureRecognizer GetNativeRecognizer(IGestureRecognizer recognizer) { if (recognizer == null) return null; var weakRecognizer = new WeakReference(recognizer); var weakEventTracker = new WeakReference(this); var tapRecognizer = recognizer as TapGestureRecognizer; if (tapRecognizer != null) { var uiRecognizer = CreateTapRecognizer(1, tapRecognizer.NumberOfTapsRequired, r => { var tapGestureRecognizer = weakRecognizer.Target as TapGestureRecognizer; var eventTracker = weakEventTracker.Target as EventTracker; var view = eventTracker?._renderer?.Element as View; if (tapGestureRecognizer != null && view != null) tapGestureRecognizer.SendTapped(view); }); return uiRecognizer; } var pinchRecognizer = recognizer as PinchGestureRecognizer; if (pinchRecognizer != null) { double startingScale = 1; var uiRecognizer = CreatePinchRecognizer(r => { var pinchGestureRecognizer = weakRecognizer.Target as IPinchGestureController; var eventTracker = weakEventTracker.Target as EventTracker; var view = eventTracker?._renderer?.Element as View; if (pinchGestureRecognizer != null && eventTracker != null && view != null) { var oldScale = eventTracker._previousScale; var originPoint = r.LocationInView(null); originPoint = UIApplication.SharedApplication.KeyWindow.ConvertPointToView(originPoint, eventTracker._renderer.NativeView); var scaledPoint = new Point(originPoint.X / view.Width, originPoint.Y / view.Height); switch (r.State) { case UIGestureRecognizerState.Began: if (r.NumberOfTouches < 2) return; pinchGestureRecognizer.SendPinchStarted(view, scaledPoint); startingScale = view.Scale; break; case UIGestureRecognizerState.Changed: if (r.NumberOfTouches < 2 && pinchGestureRecognizer.IsPinching) { r.State = UIGestureRecognizerState.Ended; pinchGestureRecognizer.SendPinchEnded(view); return; } var delta = 1.0; var dif = Math.Abs(r.Scale - oldScale) * startingScale; if (oldScale < r.Scale) delta = 1 + dif; if (oldScale > r.Scale) delta = 1 - dif; pinchGestureRecognizer.SendPinch(view, delta, scaledPoint); eventTracker._previousScale = r.Scale; break; case UIGestureRecognizerState.Cancelled: case UIGestureRecognizerState.Failed: if (pinchGestureRecognizer.IsPinching) pinchGestureRecognizer.SendPinchCanceled(view); break; case UIGestureRecognizerState.Ended: if (pinchGestureRecognizer.IsPinching) pinchGestureRecognizer.SendPinchEnded(view); eventTracker._previousScale = 1; break; } } }); return uiRecognizer; } var panRecognizer = recognizer as PanGestureRecognizer; if (panRecognizer != null) { var uiRecognizer = CreatePanRecognizer(panRecognizer.TouchPoints, r => { var eventTracker = weakEventTracker.Target as EventTracker; var view = eventTracker?._renderer?.Element as View; var panGestureRecognizer = weakRecognizer.Target as IPanGestureController; if (panGestureRecognizer != null && view != null) { switch (r.State) { case UIGestureRecognizerState.Began: if (r.NumberOfTouches != panRecognizer.TouchPoints) return; panGestureRecognizer.SendPanStarted(view, Application.Current.PanGestureId); break; case UIGestureRecognizerState.Changed: if (r.NumberOfTouches != panRecognizer.TouchPoints) { r.State = UIGestureRecognizerState.Ended; panGestureRecognizer.SendPanCompleted(view, Application.Current.PanGestureId); Application.Current.PanGestureId++; return; } var translationInView = r.TranslationInView(_handler); panGestureRecognizer.SendPan(view, translationInView.X, translationInView.Y, Application.Current.PanGestureId); break; case UIGestureRecognizerState.Cancelled: case UIGestureRecognizerState.Failed: panGestureRecognizer.SendPanCanceled(view, Application.Current.PanGestureId); Application.Current.PanGestureId++; break; case UIGestureRecognizerState.Ended: if (r.NumberOfTouches != panRecognizer.TouchPoints) { panGestureRecognizer.SendPanCompleted(view, Application.Current.PanGestureId); Application.Current.PanGestureId++; } break; } } }); return uiRecognizer; } return null; } UIPanGestureRecognizer CreatePanRecognizer(int numTouches, Action<UIPanGestureRecognizer> action) { var result = new UIPanGestureRecognizer(action); result.MinimumNumberOfTouches = result.MaximumNumberOfTouches = (uint)numTouches; return result; } UIPinchGestureRecognizer CreatePinchRecognizer(Action<UIPinchGestureRecognizer> action) { var result = new UIPinchGestureRecognizer(action); return result; } UITapGestureRecognizer CreateTapRecognizer(int numFingers, int numTaps, Action<UITapGestureRecognizer> action) { var result = new UITapGestureRecognizer(action); result.NumberOfTouchesRequired = (uint)numFingers; result.NumberOfTapsRequired = (uint)numTaps; return result; } void LoadRecognizers() { if (ElementGestureRecognizers == null) return; foreach (var recognizer in ElementGestureRecognizers) { if (_gestureRecognizers.ContainsKey(recognizer)) continue; var nativeRecognizer = GetNativeRecognizer(recognizer); if (nativeRecognizer != null) { nativeRecognizer.ShouldReceiveTouch = _shouldReceive; _handler.AddGestureRecognizer(nativeRecognizer); _gestureRecognizers[recognizer] = nativeRecognizer; } } var toRemove = _gestureRecognizers.Keys.Where(key => !ElementGestureRecognizers.Contains(key)).ToArray(); foreach (var gestureRecognizer in toRemove) { var uiRecognizer = _gestureRecognizers[gestureRecognizer]; _gestureRecognizers.Remove(gestureRecognizer); _handler.RemoveGestureRecognizer(uiRecognizer); uiRecognizer.Dispose(); } } void ModelGestureRecognizersOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs) { LoadRecognizers(); } void OnElementChanged(object sender, VisualElementChangedEventArgs e) { if (e.OldElement != null) { // unhook var oldView = e.OldElement as View; if (oldView != null) { var oldRecognizers = (ObservableCollection<IGestureRecognizer>)oldView.GestureRecognizers; oldRecognizers.CollectionChanged -= _collectionChangedHandler; } } if (e.NewElement != null) { // hook if (ElementGestureRecognizers != null) { ElementGestureRecognizers.CollectionChanged += _collectionChangedHandler; LoadRecognizers(); } } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using ScriptCs.Dnx.Contracts; using System.Linq; namespace ScriptCs.Dnx.Core { public class Repl : ScriptExecutor, IRepl { private readonly string[] _scriptArgs; private readonly IObjectSerializer _serializer; private readonly ILog _log; public Repl( string[] scriptArgs, IFileSystem fileSystem, IScriptEngine scriptEngine, IObjectSerializer serializer, ILogProvider logProvider, IScriptLibraryComposer composer, IConsole console, IFilePreProcessor filePreProcessor, IEnumerable<IReplCommand> replCommands) : base(fileSystem, filePreProcessor, scriptEngine, logProvider, composer) { if (serializer == null) throw new ArgumentNullException(nameof(serializer)); if (logProvider == null) throw new ArgumentNullException(nameof(logProvider)); if (console == null) throw new ArgumentNullException(nameof(console)); _scriptArgs = scriptArgs; _serializer = serializer; _log = logProvider.ForCurrentType(); Console = console; Commands = replCommands != null ? replCommands.Where(x => x.CommandName != null).ToDictionary(x => x.CommandName, x => x) : new Dictionary<string, IReplCommand>(); } public string Buffer { get; set; } public IConsole Console { get; private set; } public Dictionary<string, IReplCommand> Commands { get; private set; } public override void Terminate() { base.Terminate(); _log.Debug("Exiting console"); Console.Exit(); } public override ScriptResult Execute(string script, params string[] scriptArgs) { if (script == null) throw new ArgumentNullException(nameof(script)); try { if (script.StartsWith(":")) { var tokens = script.Split(' '); if (tokens[0].Length > 1) { var command = Commands.FirstOrDefault(x => x.Key == tokens[0].Substring(1)); if (command.Value != null) { var argsToPass = new List<object>(); foreach (var argument in tokens.Skip(1)) { var argumentResult = ScriptEngine.Execute( argument, _scriptArgs, References, Namespaces, ScriptPackSession); if (argumentResult.CompileExceptionInfo != null) { throw new Exception( GetInvalidCommandArgumentMessage(argument), argumentResult.CompileExceptionInfo.SourceException); } if (argumentResult.ExecuteExceptionInfo != null) { throw new Exception( GetInvalidCommandArgumentMessage(argument), argumentResult.ExecuteExceptionInfo.SourceException); } if (!argumentResult.IsCompleteSubmission) { throw new Exception(GetInvalidCommandArgumentMessage(argument)); } argsToPass.Add(argumentResult.ReturnValue); } var commandResult = command.Value.Execute(this, argsToPass.ToArray()); return ProcessCommandResult(commandResult); } } } var preProcessResult = FilePreProcessor.ProcessScript(script); ImportNamespaces(preProcessResult.Namespaces.ToArray()); foreach (var reference in preProcessResult.References) { var referencePath = FileSystem.GetFullPath(Path.Combine(FileSystem.BinFolder, reference)); AddReferences(FileSystem.FileExists(referencePath) ? referencePath : reference); } Console.ForegroundColor = ConsoleColor.Cyan; InjectScriptLibraries(FileSystem.CurrentDirectory, preProcessResult, ScriptPackSession.State); Buffer = (Buffer == null) ? preProcessResult.Code : Buffer + Environment.NewLine + preProcessResult.Code; var namespaces = Namespaces.Union(preProcessResult.Namespaces); var references = References.Union(preProcessResult.References); var result = ScriptEngine.Execute(Buffer, _scriptArgs, references, namespaces, ScriptPackSession); if (result == null) return ScriptResult.Empty; if (result.CompileExceptionInfo != null) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(result.CompileExceptionInfo.SourceException.Message); } if (result.ExecuteExceptionInfo != null) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(result.ExecuteExceptionInfo.SourceException.Message); } if (result.InvalidNamespaces.Any()) { RemoveNamespaces(result.InvalidNamespaces.ToArray()); } if (!result.IsCompleteSubmission) { return result; } if (result.ReturnValue != null) { Console.ForegroundColor = ConsoleColor.Yellow; var serializedResult = _serializer.Serialize(result.ReturnValue); Console.WriteLine(serializedResult); } Buffer = null; return result; } catch (FileNotFoundException fileEx) { RemoveReferences(fileEx.FileName); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(Environment.NewLine + fileEx + Environment.NewLine); return new ScriptResult(compilationException: fileEx); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(Environment.NewLine + ex + Environment.NewLine); return new ScriptResult(executionException: ex); } finally { Console.ResetColor(); } } private static string GetInvalidCommandArgumentMessage(string argument) { return string.Format(CultureInfo.InvariantCulture, "Argument is not a valid expression: {0}", argument); } private ScriptResult ProcessCommandResult(object commandResult) { Buffer = null; if (commandResult != null) { if (commandResult is ScriptResult) { var scriptCommandResult = commandResult as ScriptResult; if (scriptCommandResult.ReturnValue != null) { Console.WriteLine(_serializer.Serialize(scriptCommandResult.ReturnValue)); } return scriptCommandResult; } //if command has a result, print it Console.WriteLine(_serializer.Serialize(commandResult)); return new ScriptResult(returnValue: commandResult); } return ScriptResult.Empty; } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact [email protected]. /// /// SyncListResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; namespace Twilio.Rest.Preview.Sync.Service { public class SyncListResource : Resource { private static Request BuildFetchRequest(FetchSyncListOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Preview, "/Sync/Services/" + options.PathServiceSid + "/Lists/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch SyncList parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of SyncList </returns> public static SyncListResource Fetch(FetchSyncListOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch SyncList parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of SyncList </returns> public static async System.Threading.Tasks.Task<SyncListResource> FetchAsync(FetchSyncListOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// fetch /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathSid"> The sid </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of SyncList </returns> public static SyncListResource Fetch(string pathServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchSyncListOptions(pathServiceSid, pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathSid"> The sid </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of SyncList </returns> public static async System.Threading.Tasks.Task<SyncListResource> FetchAsync(string pathServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchSyncListOptions(pathServiceSid, pathSid); return await FetchAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteSyncListOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Preview, "/Sync/Services/" + options.PathServiceSid + "/Lists/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// delete /// </summary> /// <param name="options"> Delete SyncList parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of SyncList </returns> public static bool Delete(DeleteSyncListOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="options"> Delete SyncList parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of SyncList </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteSyncListOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// delete /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathSid"> The sid </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of SyncList </returns> public static bool Delete(string pathServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteSyncListOptions(pathServiceSid, pathSid); return Delete(options, client); } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathSid"> The sid </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of SyncList </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteSyncListOptions(pathServiceSid, pathSid); return await DeleteAsync(options, client); } #endif private static Request BuildCreateRequest(CreateSyncListOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Preview, "/Sync/Services/" + options.PathServiceSid + "/Lists", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// create /// </summary> /// <param name="options"> Create SyncList parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of SyncList </returns> public static SyncListResource Create(CreateSyncListOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="options"> Create SyncList parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of SyncList </returns> public static async System.Threading.Tasks.Task<SyncListResource> CreateAsync(CreateSyncListOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// create /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="uniqueName"> The unique_name </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of SyncList </returns> public static SyncListResource Create(string pathServiceSid, string uniqueName = null, ITwilioRestClient client = null) { var options = new CreateSyncListOptions(pathServiceSid){UniqueName = uniqueName}; return Create(options, client); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="uniqueName"> The unique_name </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of SyncList </returns> public static async System.Threading.Tasks.Task<SyncListResource> CreateAsync(string pathServiceSid, string uniqueName = null, ITwilioRestClient client = null) { var options = new CreateSyncListOptions(pathServiceSid){UniqueName = uniqueName}; return await CreateAsync(options, client); } #endif private static Request BuildReadRequest(ReadSyncListOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Preview, "/Sync/Services/" + options.PathServiceSid + "/Lists", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// read /// </summary> /// <param name="options"> Read SyncList parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of SyncList </returns> public static ResourceSet<SyncListResource> Read(ReadSyncListOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<SyncListResource>.FromJson("lists", response.Content); return new ResourceSet<SyncListResource>(page, options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="options"> Read SyncList parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of SyncList </returns> public static async System.Threading.Tasks.Task<ResourceSet<SyncListResource>> ReadAsync(ReadSyncListOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<SyncListResource>.FromJson("lists", response.Content); return new ResourceSet<SyncListResource>(page, options, client); } #endif /// <summary> /// read /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of SyncList </returns> public static ResourceSet<SyncListResource> Read(string pathServiceSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadSyncListOptions(pathServiceSid){PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of SyncList </returns> public static async System.Threading.Tasks.Task<ResourceSet<SyncListResource>> ReadAsync(string pathServiceSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadSyncListOptions(pathServiceSid){PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<SyncListResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<SyncListResource>.FromJson("lists", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<SyncListResource> NextPage(Page<SyncListResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Preview) ); var response = client.Request(request); return Page<SyncListResource>.FromJson("lists", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<SyncListResource> PreviousPage(Page<SyncListResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Preview) ); var response = client.Request(request); return Page<SyncListResource>.FromJson("lists", response.Content); } /// <summary> /// Converts a JSON string into a SyncListResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> SyncListResource object represented by the provided JSON </returns> public static SyncListResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<SyncListResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The sid /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The unique_name /// </summary> [JsonProperty("unique_name")] public string UniqueName { get; private set; } /// <summary> /// The account_sid /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The service_sid /// </summary> [JsonProperty("service_sid")] public string ServiceSid { get; private set; } /// <summary> /// The url /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } /// <summary> /// The links /// </summary> [JsonProperty("links")] public Dictionary<string, string> Links { get; private set; } /// <summary> /// The revision /// </summary> [JsonProperty("revision")] public string Revision { get; private set; } /// <summary> /// The date_created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The date_updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The created_by /// </summary> [JsonProperty("created_by")] public string CreatedBy { get; private set; } private SyncListResource() { } } }
using System; using System.IO; using OpenADK.Library; using OpenADK.Library.Impl; using OpenADK.Library.Infra; using OpenADK.Library.us.Student; using NUnit.Framework; using Library.UnitTesting.Framework; namespace Library.Nunit.US.Impl { [TestFixture] public class RequestCacheFileTests { private String[] fStateObjects; private String[] fMsgIds; private RequestCache fRC; private Agent fAgent; [SetUp] public void setUp() { Adk.Initialize(); fAgent = new TestAgent(); fAgent.Initialize(); } [TearDown] public void tearDown() { if (fRC != null) { fRC.Close(); fRC = null; } String fname = fAgent.HomeDir + Path.DirectorySeparatorChar + "work" + Path.DirectorySeparatorChar + "requestcache.adk"; File.Delete(fname); //File f = new File(fname); //f.delete(); } /** * Tests that the RequestCache file persists information between requests * @throws Exception */ [Test] public void testSimpleCase() { fRC = RequestCache.GetInstance(fAgent); storeAssertedRequests(fRC); assertStoredRequests(fRC, true); } /** * Tests that the RequestCache file persists information between restarts * @throws Exception */ [Test] public void testPersistence() { fRC = RequestCache.GetInstance(fAgent); storeAssertedRequests(fRC); fRC.Close(); // Create a new instance. This one should retrieve its settings from the persistence mechanism fRC = RequestCache.GetInstance(fAgent); assertStoredRequests(fRC, true); fRC.Close(); fRC = RequestCache.GetInstance(fAgent); Assertion.AssertEquals("Should have zero pending requests", 0, fRC.ActiveRequestCount); } /** * Tests that the RequestCache file persists information between restarts * Even if the state object is not able to be deserialized * @throws Exception */ [Test] public void testPersistenceWithBadState() { //create new cache for agent RequestCache cache = RequestCache.GetInstance(fAgent); //create new queryobject SIF_QueryObject obj = new SIF_QueryObject(""); //create query, telling it what type of query it is(passing it queryobj) SIF_Query query = new SIF_Query(obj); //create new sif request SIF_Request request = new SIF_Request(); //set query property request.SIF_Query = query; Query q = new Query(StudentDTD.STUDENTPERSONAL); String testStateItem = Adk.MakeGuid(); String requestMsgId = Adk.MakeGuid(); String testObjectType = Adk.MakeGuid(); TestState ts = new TestState(); ts.State = testStateItem; ts.setCreateErrorOnRead(true); q.UserData = ts; storeRequest(cache, request, q, requestMsgId, testObjectType); cache.Close(); // Create a new instance. This one should retrieve its settings from the persistence mechanism cache = RequestCache.GetInstance(fAgent); IRequestInfo ri = cache.GetRequestInfo(requestMsgId, null); //if state is null, should still return ri object Assertion.AssertNotNull("RequestInfo was null", ri); Assertion.AssertEquals("MessageId", requestMsgId, ri.MessageId); Assertion.AssertEquals("ObjectType", testObjectType, ri.ObjectType); ts = (TestState) ri.UserData; // In order for this to be a valid test, the TestState class should have thrown // an exception during deserialization and should be null here. Assertion.AssertNull("UserData should be null", ts); } [Test] public void testInstanceMultipleInvocations() { for (int i = 0; i < 3; i++) { testPersistence(); } } [Test] public void testPersistenceMultipleInvocations() { for (int i = 0; i < 3; i++) { testSimpleCase(); } } [Test] public void testPersistenceWithRemoval() { fRC = RequestCache.GetInstance(fAgent); SIF_QueryObject obj = new SIF_QueryObject(""); SIF_Query query = new SIF_Query(obj); SIF_Request request = new SIF_Request(); request.SIF_Query = query; Query q = new Query(StudentDTD.STUDENTPERSONAL); String testStateItem = Adk.MakeGuid(); TestState ts = new TestState(); ts.State = testStateItem; q.UserData = ts; fMsgIds = new String[10]; // Add 10 entries to the cache, interspersed with other entries that are removed for (int i = 0; i < 10; i++) { String phantom1 = Adk.MakeGuid(); String phantom2 = Adk.MakeGuid(); storeRequest(fRC, request, q, phantom1, "foo"); fMsgIds[i] = Adk.MakeGuid(); storeRequest(fRC, request, q, fMsgIds[i], "Object_" + i); storeRequest(fRC, request, q, phantom2, "bar"); fRC.GetRequestInfo(phantom1, null); fRC.GetRequestInfo(phantom2, null); } // remove every other entry, close, re-open and assert that the correct entries are there for (int i = 0; i < 10; i += 2) { fRC.GetRequestInfo(fMsgIds[i], null); } Assertion.AssertEquals("Before closing Should have five objects", 5, fRC.ActiveRequestCount); fRC.Close(); // Create a new instance. This one should retrieve its settings from the persistence mechanism fRC = RequestCache.GetInstance(fAgent); Assertion.AssertEquals("After Re-Openeing Should have five objects", 5, fRC.ActiveRequestCount); for (int i = 1; i < 10; i += 2) { IRequestInfo cachedInfo = fRC.GetRequestInfo(fMsgIds[i], null); Assertion.AssertNotNull("No cachedID returned for " + i, cachedInfo); } Assertion.AssertEquals("Should have zero objects", 0, fRC.ActiveRequestCount); } /** * Tests that the RequestCacheFile class handles the case of the * cache file becoming readonly * @throws Exception */ [Test] public void testWithReadOnlyFile() { // Make the existing cache file readonly String fname = fAgent.HomeDir + Path.DirectorySeparatorChar + "work" + Path.DirectorySeparatorChar + "requests.adk"; FileInfo fi = new FileInfo(fname); //= new File(fname); if (!fi.Exists) { StreamWriter sw = fi.CreateText(); //sw.WriteLine(""); sw.Flush(); sw.Close(); // RandomAccessFile raf = new RandomAccessFile(fname, "rw"); // raf.setLength(0); //raf.close(); } fi.IsReadOnly = true; try { fRC = RequestCache.GetInstance(fAgent); //this should throw adk exception } catch (AdkException) { return; } finally { fi.IsReadOnly = false; fi.Delete(); } //should never get here Assertion.AssertEquals("Exception should have been thrown because request cache file is readonly", true, false); } /** * Tests that the RequestCache file persists information between restarts, even if it starts * with a corrupt file * @throws Exception */ [Test] public void testWithCorruptFile() { // Delete the existing cache file, if it exists String fname = fAgent.HomeDir + Path.DirectorySeparatorChar + "work" + Path.DirectorySeparatorChar + "requestcache.adk"; FileInfo fi = new FileInfo(fname); StreamWriter sw = fi.CreateText(); sw.WriteLine("!@#$!@#$"); sw.Flush(); sw.Close(); //RandomAccessFile raf = new RandomAccessFile(fname, "rw"); //raf.writeChars("!@#$!@#$"); // raf.close(); fRC = RequestCache.GetInstance(fAgent); storeAssertedRequests(fRC); fRC.Close(); // Create a new instance. This one should retrieve its settings from the persistence mechanism fRC = RequestCache.GetInstance(fAgent); assertStoredRequests(fRC, true); } [Test] public void testWithLegacyFile() { //assertStoredRequests(fRC, true); // Copy the legacy requests.adk file to the agent work directory //FileInfo legacyFile = new FileInfo("requests.adk"); //Assertion.Assert("Saved legacy file does [not?] exist", legacyFile.Exists); //FileInfo copiedFile = new FileInfo(fAgent.HomeDir + Path.DirectorySeparatorChar + "work" + Path.DirectorySeparatorChar + "requests.adk"); //if (copiedFile.Exists) //{ // copiedFile.Delete(); //} //// Copy the file //legacyFile.CopyTo(copiedFile.FullName, true); // Now open up an instance of the request cache and verify that the contents are there fRC = RequestCache.GetInstance(fAgent); SIF_QueryObject obj = new SIF_QueryObject(""); SIF_Query query = new SIF_Query(obj); SIF_Request request = new SIF_Request(); request.SIF_Query = query; Query q; TestState ts; fMsgIds = new String[10]; fStateObjects = new String[10]; // Add 10 entries to the cache for (int i = 0; i < 10; i++) { ts = new TestState(); ts.State = Adk.MakeGuid(); fStateObjects[i] = (String) ts.State; q = new Query(StudentDTD.STUDENTPERSONAL); q.UserData = ts; fMsgIds[i] = Adk.MakeGuid(); storeRequest(fRC, request, q, fMsgIds[i], "Object_" + i.ToString()); } Assertion.AssertEquals("Active request count", 10, fRC.ActiveRequestCount); // Lookup each setting, for (int i = 0; i < 10; i++) { IRequestInfo reqInfo = fRC.LookupRequestInfo(fMsgIds[i], null); Assertion.AssertEquals("Initial lookup", "Object_" + i.ToString(), reqInfo.ObjectType); } // Lookup each setting, for (int i = 0; i < 10; i++) { IRequestInfo reqInfo = fRC.GetRequestInfo(fMsgIds[i], null); Assertion.AssertEquals("Initial lookup", "Object_" + i.ToString(), reqInfo.ObjectType); } // all messages should now be removed from the queue Assertion.AssertEquals("Cache should be empty", 0, fRC.ActiveRequestCount); // Now run one of our other tests testPersistence(); } /** * Stores the items in the cache that will later be asserted * @param cache */ private void storeAssertedRequests(RequestCache cache) { SIF_QueryObject obj = new SIF_QueryObject(""); SIF_Query query = new SIF_Query(obj); SIF_Request request = new SIF_Request(); request.SIF_Query = query; Query q; TestState ts; fMsgIds = new String[10]; fStateObjects = new String[10]; // Add 10 entries to the cache, interspersed with other entries that are removed for (int i = 0; i < 10; i++) { ts = new TestState(); ts.State = Adk.MakeGuid(); fStateObjects[i] = ts.State; q = new Query(StudentDTD.STUDENTPERSONAL); q.UserData = ts; String phantom1 = Adk.MakeGuid(); String phantom2 = Adk.MakeGuid(); storeRequest(cache, request, q, phantom1, "foo"); fMsgIds[i] = Adk.MakeGuid(); storeRequest(cache, request, q, fMsgIds[i], "Object_" + i.ToString()); storeRequest(cache, request, q, phantom2, "bar"); cache.GetRequestInfo(phantom1, null); cache.GetRequestInfo(phantom2, null); } } private void storeRequest( RequestCache rc, SIF_Request request, Query q, String msgID, String objectName) { //request.getSIF_Query().getSIF_QueryObject().setObjectName(objectName); request.SIF_Query.SIF_QueryObject.ObjectName = objectName; request.Header.SIF_MsgId = msgID; rc.StoreRequestInfo(request, q, null); } /** * Asserts that the items stored in the storeAssertedRequests call * are still in the cache * @param cache The RequestCache class to assert * @param testRemoval True if the items in the cache should be removed * and asserted that they are removed */ private void assertStoredRequests(RequestCache cache, Boolean testRemoval) { Assertion.AssertEquals("Active request count", fMsgIds.Length, cache.ActiveRequestCount); // Lookup each setting, for (int i = 0; i < fMsgIds.Length; i++) { IRequestInfo reqInfo = cache.LookupRequestInfo(fMsgIds[i], null); Assertion.AssertEquals("Initial lookup", "Object_" + i.ToString(), reqInfo.ObjectType); Assertion.AssertEquals("User Data is missing for " + i, fStateObjects[i], (String) ((TestState) reqInfo.UserData).State); } if (testRemoval) { // Lookup each setting, for (int i = 0; i < fMsgIds.Length; i++) { IRequestInfo reqInfo = cache.GetRequestInfo(fMsgIds[i], null); Assertion.AssertEquals("Initial lookup", "Object_" + i.ToString(), reqInfo.ObjectType); Assertion.AssertEquals("User Data is missing for " + i, fStateObjects[i], (String) ((TestState) reqInfo.UserData).State); } // all messages should now be removed from the queue Assertion.AssertEquals("Cache should be empty", 0, cache.ActiveRequestCount); } } } //end class } //end namespace
using System; using System.Collections.Generic; using System.Globalization; using Verse.ParserDescriptors.Recurse; namespace Verse.Schemas.JSON { internal class ValueDecoder : IDecoder<Value> { #region Attributes private readonly Dictionary<Type, object> converters = new Dictionary<Type, object> { { typeof (bool), new Converter<Value, bool>(ValueDecoder.ToBoolean) }, { typeof (char), new Converter<Value, char>(ValueDecoder.ToCharacter) }, { typeof (decimal), new Converter<Value, decimal>(ValueDecoder.ToDecimal) }, { typeof (float), new Converter<Value, float>(ValueDecoder.ToFloat32) }, { typeof (double), new Converter<Value, double>(ValueDecoder.ToFloat64) }, { typeof (sbyte), new Converter<Value, sbyte>(ValueDecoder.ToInteger8s) }, { typeof (byte), new Converter<Value, byte>(ValueDecoder.ToInteger8u) }, { typeof (short), new Converter<Value, short>(ValueDecoder.ToInteger16s) }, { typeof (ushort), new Converter<Value, ushort>(ValueDecoder.ToInteger16u) }, { typeof (int), new Converter<Value, int>(ValueDecoder.ToInteger32s) }, { typeof (uint), new Converter<Value, uint>(ValueDecoder.ToInteger32u) }, { typeof (long), new Converter<Value, long>(ValueDecoder.ToInteger64s) }, { typeof (ulong), new Converter<Value, ulong>(ValueDecoder.ToInteger64u) }, { typeof (string), new Converter<Value, string>(ValueDecoder.ToString) }, { typeof (Value), new Converter<Value, Value>((v) => v) } }; #endregion #region Methods / Public public Converter<Value, TValue> Get<TValue>() { object box; if (!this.converters.TryGetValue(typeof (TValue), out box)) throw new InvalidCastException(string.Format(CultureInfo.InvariantCulture, "no available converter from JSON value to type '{0}'", typeof (TValue))); return (Converter<Value, TValue>)box; } public void Set<TValue>(Converter<Value, TValue> converter) { if (converter == null) throw new ArgumentNullException("converter"); this.converters[typeof (TValue)] = converter; } #endregion #region Methods / Private private static bool ToBoolean(Value value) { switch (value.Type) { case Content.Boolean: return value.Boolean; case Content.DecimalNumber: return value.DecimalNumber != 0; case Content.String: return !string.IsNullOrEmpty(value.String); default: return false; } } private static char ToCharacter(Value value) { switch (value.Type) { case Content.Boolean: return value.Boolean ? '1' : '\0'; case Content.DecimalNumber: // ReSharper disable once CompareOfFloatsByEqualityOperator return value.DecimalNumber != 0 ? '1' : '\0'; case Content.String: return value.String.Length > 0 ? value.String[0] : '\0'; default: return '\0'; } } private static decimal ToDecimal(Value value) { decimal number; switch (value.Type) { case Content.Boolean: return value.Boolean ? 1 : 0; case Content.DecimalNumber: return value.DecimalNumber; case Content.String: if (decimal.TryParse(value.String, NumberStyles.Float, CultureInfo.InvariantCulture, out number)) return number; return 0; default: return 0; } } private static float ToFloat32(Value value) { float number; switch (value.Type) { case Content.Boolean: return value.Boolean ? 1 : 0; case Content.DecimalNumber: return (float)value.DecimalNumber; case Content.String: if (float.TryParse(value.String, NumberStyles.Float, CultureInfo.InvariantCulture, out number)) return number; return 0; default: return 0; } } private static double ToFloat64(Value value) { double number; switch (value.Type) { case Content.Boolean: return value.Boolean ? 1 : 0; case Content.DecimalNumber: return (double) value.DecimalNumber; case Content.String: if (double.TryParse(value.String, NumberStyles.Float, CultureInfo.InvariantCulture, out number)) return number; return 0; default: return 0; } } private static sbyte ToInteger8s(Value value) { sbyte number; switch (value.Type) { case Content.Boolean: return value.Boolean ? (sbyte)1 : (sbyte)0; case Content.DecimalNumber: return (sbyte)value.DecimalNumber; case Content.String: if (sbyte.TryParse(value.String, NumberStyles.Integer, CultureInfo.InvariantCulture, out number)) return number; return 0; default: return 0; } } private static byte ToInteger8u(Value value) { byte number; switch (value.Type) { case Content.Boolean: return value.Boolean ? (byte)1 : (byte)0; case Content.DecimalNumber: return (byte)value.DecimalNumber; case Content.String: if (byte.TryParse(value.String, NumberStyles.Integer, CultureInfo.InvariantCulture, out number)) return number; return 0; default: return 0; } } private static short ToInteger16s(Value value) { short number; switch (value.Type) { case Content.Boolean: return value.Boolean ? (short)1 : (short)0; case Content.DecimalNumber: return (short)value.DecimalNumber; case Content.String: if (short.TryParse(value.String, NumberStyles.Integer, CultureInfo.InvariantCulture, out number)) return number; return 0; default: return 0; } } private static ushort ToInteger16u(Value value) { ushort number; switch (value.Type) { case Content.Boolean: return value.Boolean ? (ushort)1 : (ushort)0; case Content.DecimalNumber: return (ushort)value.DecimalNumber; case Content.String: if (ushort.TryParse(value.String, NumberStyles.Integer, CultureInfo.InvariantCulture, out number)) return number; return 0; default: return 0; } } private static int ToInteger32s(Value value) { int number; switch (value.Type) { case Content.Boolean: return value.Boolean ? 1 : 0; case Content.DecimalNumber: return (int)value.DecimalNumber; case Content.String: if (int.TryParse(value.String, NumberStyles.Integer, CultureInfo.InvariantCulture, out number)) return number; return 0; default: return 0; } } private static uint ToInteger32u(Value value) { uint number; switch (value.Type) { case Content.Boolean: return value.Boolean ? 1u : 0; case Content.DecimalNumber: return (uint)value.DecimalNumber; case Content.String: if (uint.TryParse(value.String, NumberStyles.Integer, CultureInfo.InvariantCulture, out number)) return number; return 0; default: return 0; } } private static long ToInteger64s(Value value) { long number; switch (value.Type) { case Content.Boolean: return value.Boolean ? 1 : 0; case Content.DecimalNumber: return (long)value.DecimalNumber; case Content.String: if (long.TryParse(value.String, NumberStyles.Integer, CultureInfo.InvariantCulture, out number)) return number; return 0; default: return 0; } } private static ulong ToInteger64u(Value value) { ulong number; switch (value.Type) { case Content.Boolean: return value.Boolean ? 1u : 0; case Content.DecimalNumber: return (ulong)value.DecimalNumber; case Content.String: if (ulong.TryParse(value.String, NumberStyles.Integer, CultureInfo.InvariantCulture, out number)) return number; return 0; default: return 0; } } private static string ToString(Value value) { switch (value.Type) { case Content.Boolean: return value.Boolean ? "1" : string.Empty; case Content.DecimalNumber: return value.DecimalNumber.ToString(CultureInfo.InvariantCulture); case Content.String: return value.String; default: return string.Empty; } } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Classification { public partial class TotalClassifierTests : AbstractCSharpClassifierTests { internal override async Task<IEnumerable<ClassifiedSpan>> GetClassificationSpansAsync( string code, TextSpan textSpan, CSharpParseOptions options) { using (var workspace = TestWorkspace.CreateCSharp(code, options)) { var document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id); var syntaxTree = await document.GetSyntaxTreeAsync(); var service = document.GetLanguageService<IClassificationService>(); var classifiers = service.GetDefaultSyntaxClassifiers(); var extensionManager = workspace.Services.GetService<IExtensionManager>(); var semanticClassifications = new List<ClassifiedSpan>(); var syntacticClassifications = new List<ClassifiedSpan>(); await service.AddSemanticClassificationsAsync(document, textSpan, extensionManager.CreateNodeExtensionGetter(classifiers, c => c.SyntaxNodeTypes), extensionManager.CreateTokenExtensionGetter(classifiers, c => c.SyntaxTokenKinds), semanticClassifications, CancellationToken.None); service.AddSyntacticClassifications(syntaxTree, textSpan, syntacticClassifications, CancellationToken.None); var classificationsSpans = new HashSet<TextSpan>(); // Add all the semantic classifications in. var allClassifications = new List<ClassifiedSpan>(semanticClassifications); classificationsSpans.AddRange(allClassifications.Select(t => t.TextSpan)); // Add the syntactic classifications. But only if they don't conflict with a semantic // classification. allClassifications.AddRange( from t in syntacticClassifications where !classificationsSpans.Contains(t.TextSpan) select t); return allClassifications; } } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task VarAsUsingAliasForNamespace() { await TestAsync( @"using var = System;", Keyword("using"), Identifier("var"), Operators.Equals, Identifier("System"), Punctuation.Semicolon); } [Fact, Trait(Traits.Feature, Traits.Features.Classification), WorkItem(547068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547068")] public async Task Bug17819() { await TestAsync( @"_ _() { } ///<param name='_ }", Identifier("_"), Identifier("_"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("param"), XmlDoc.AttributeName(" "), XmlDoc.AttributeName("name"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes("'"), Identifier("_"), Punctuation.CloseCurly); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task VarAsUsingAliasForClass() { await TestAsync( @"using var = System.Math;", Keyword("using"), Class("var"), Operators.Equals, Identifier("System"), Operators.Dot, Class("Math"), Punctuation.Semicolon); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task VarAsUsingAliasForDelegate() { await TestAsync( @"using var = System.Action;", Keyword("using"), Delegate("var"), Operators.Equals, Identifier("System"), Operators.Dot, Delegate("Action"), Punctuation.Semicolon); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task VarAsUsingAliasForStruct() { await TestAsync( @"using var = System.DateTime;", Keyword("using"), Struct("var"), Operators.Equals, Identifier("System"), Operators.Dot, Struct("DateTime"), Punctuation.Semicolon); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task VarAsUsingAliasForEnum() { await TestAsync( @"using var = System.DayOfWeek;", Keyword("using"), Enum("var"), Operators.Equals, Identifier("System"), Operators.Dot, Enum("DayOfWeek"), Punctuation.Semicolon); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task VarAsUsingAliasForInterface() { await TestAsync( @"using var = System.IDisposable;", Keyword("using"), Interface("var"), Operators.Equals, Identifier("System"), Operators.Dot, Interface("IDisposable"), Punctuation.Semicolon); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task VarAsConstructorName() { await TestAsync( @"class var { var() { } }", Keyword("class"), Class("var"), Punctuation.OpenCurly, Identifier("var"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task UsingAliasGlobalNamespace() { await TestAsync( @"using IO = global::System.IO;", Keyword("using"), Identifier("IO"), Operators.Equals, Keyword("global"), Operators.Text("::"), Identifier("System"), Operators.Dot, Identifier("IO"), Punctuation.Semicolon); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task PartialDynamicWhere() { var code = @"partial class partial<where> where where : partial<where> { static dynamic dynamic<partial>() { return dynamic<dynamic>(); } } "; await TestAsync(code, Keyword("partial"), Keyword("class"), Class("partial"), Punctuation.OpenAngle, TypeParameter("where"), Punctuation.CloseAngle, Keyword("where"), TypeParameter("where"), Punctuation.Colon, Class("partial"), Punctuation.OpenAngle, TypeParameter("where"), Punctuation.CloseAngle, Punctuation.OpenCurly, Keyword("static"), Keyword("dynamic"), Identifier("dynamic"), Punctuation.OpenAngle, TypeParameter("partial"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("return"), Identifier("dynamic"), Punctuation.OpenAngle, Keyword("dynamic"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] [WorkItem(543123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543123")] public async Task VarInForeach() { await TestInMethodAsync(@"foreach (var v in args) { }", Keyword("foreach"), Punctuation.OpenParen, Keyword("var"), Identifier("v"), Keyword("in"), Identifier("args"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task ValueInSetterAndAnonymousTypePropertyName() { await TestAsync( @"class C { int P { set { var t = new { value = value }; } } }", Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Identifier("P"), Punctuation.OpenCurly, Keyword("set"), Punctuation.OpenCurly, Keyword("var"), Identifier("t"), Operators.Equals, Keyword("new"), Punctuation.OpenCurly, Identifier("value"), Operators.Equals, Keyword("value"), Punctuation.CloseCurly, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task TestValueInEvent() { await TestInClassAsync( @"event int Bar { add { this.value = value; } remove { this.value = value; } }", Keyword("event"), Keyword("int"), Identifier("Bar"), Punctuation.OpenCurly, Keyword("add"), Punctuation.OpenCurly, Keyword("this"), Operators.Dot, Identifier("value"), Operators.Equals, Keyword("value"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("remove"), Punctuation.OpenCurly, Keyword("this"), Operators.Dot, Identifier("value"), Operators.Equals, Keyword("value"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task TestValueInProperty() { await TestInClassAsync( @"int Foo { get { this.value = value; } set { this.value = value; } }", Keyword("int"), Identifier("Foo"), Punctuation.OpenCurly, Keyword("get"), Punctuation.OpenCurly, Keyword("this"), Operators.Dot, Identifier("value"), Operators.Equals, Identifier("value"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("set"), Punctuation.OpenCurly, Keyword("this"), Operators.Dot, Identifier("value"), Operators.Equals, Keyword("value"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task ValueFieldInSetterAccessedThroughThis() { await TestInClassAsync( @"int P { set { this.value = value; } }", Keyword("int"), Identifier("P"), Punctuation.OpenCurly, Keyword("set"), Punctuation.OpenCurly, Keyword("this"), Operators.Dot, Identifier("value"), Operators.Equals, Keyword("value"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task NewOfInterface() { await TestInMethodAsync( @"object o = new System.IDisposable();", Keyword("object"), Identifier("o"), Operators.Equals, Keyword("new"), Identifier("System"), Operators.Dot, Interface("IDisposable"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); } [WorkItem(545611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545611")] [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task TestVarConstructor() { await TestAsync( @"class var { void Main() { new var(); } }", Keyword("class"), Class("var"), Punctuation.OpenCurly, Keyword("void"), Identifier("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("new"), Class("var"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(545609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545609")] [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task TestVarTypeParameter() { await TestAsync( @"class X { void Foo<var>() { var x; } }", Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Identifier("Foo"), Punctuation.OpenAngle, TypeParameter("var"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, TypeParameter("var"), Identifier("x"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(545610, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545610")] [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task TestVarAttribute1() { await TestAsync( @"using System; [var] class var : Attribute { }", Keyword("using"), Identifier("System"), Punctuation.Semicolon, Punctuation.OpenBracket, Class("var"), Punctuation.CloseBracket, Keyword("class"), Class("var"), Punctuation.Colon, Class("Attribute"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [WorkItem(545610, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545610")] [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task TestVarAttribute2() { await TestAsync( @"using System; [var] class varAttribute : Attribute { }", Keyword("using"), Identifier("System"), Punctuation.Semicolon, Punctuation.OpenBracket, Class("var"), Punctuation.CloseBracket, Keyword("class"), Class("varAttribute"), Punctuation.Colon, Class("Attribute"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [WorkItem(546170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546170")] [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task TestStandaloneTypeName() { await TestAsync( @"using System; class C { static void Main() { var tree = Console } }", Keyword("using"), Identifier("System"), Punctuation.Semicolon, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Identifier("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Identifier("tree"), Operators.Equals, Class("Console"), Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(546403, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546403")] [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task TestNamespaceClassAmbiguities() { await TestAsync( @"class C { } namespace C { }", Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("namespace"), Identifier("C"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task NameAttributeValue() { await TestAsync( @"class Program<T> { /// <param name=""x""/> void Foo(int x) { } }", Keyword("class"), Class("Program"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("param"), XmlDoc.AttributeName(" "), XmlDoc.AttributeName("name"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes("\""), Identifier("x"), XmlDoc.AttributeQuotes("\""), XmlDoc.Delimiter("/>"), Keyword("void"), Identifier("Foo"), Punctuation.OpenParen, Keyword("int"), Identifier("x"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task Cref1() { await TestAsync( @"/// <see cref=""Program{T}""/> class Program<T> { void Foo() { } }", XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("see"), XmlDoc.AttributeName(" "), XmlDoc.AttributeName("cref"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes("\""), Class("Program"), Punctuation.OpenCurly, TypeParameter("T"), Punctuation.CloseCurly, XmlDoc.AttributeQuotes("\""), XmlDoc.Delimiter("/>"), Keyword("class"), Class("Program"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Keyword("void"), Identifier("Foo"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task CrefNamespaceIsNotClass() { await TestAsync( @"/// <see cref=""N""/> namespace N { class Program { } }", XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("see"), XmlDoc.AttributeName(" "), XmlDoc.AttributeName("cref"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes("\""), Identifier("N"), XmlDoc.AttributeQuotes("\""), XmlDoc.Delimiter("/>"), Keyword("namespace"), Identifier("N"), Punctuation.OpenCurly, Keyword("class"), Class("Program"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task InterfacePropertyWithSameNameShouldBePreferredToType() { await TestAsync( @"interface IFoo { int IFoo { get; set; } void Bar(int x = IFoo); }", Keyword("interface"), Interface("IFoo"), Punctuation.OpenCurly, Keyword("int"), Identifier("IFoo"), Punctuation.OpenCurly, Keyword("get"), Punctuation.Semicolon, Keyword("set"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("void"), Identifier("Bar"), Punctuation.OpenParen, Keyword("int"), Identifier("x"), Operators.Equals, Identifier("IFoo"), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly); } [WorkItem(633, "https://github.com/dotnet/roslyn/issues/633")] [WpfFact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task XmlDocCref() { await TestAsync( @"/// <summary> /// <see cref=""MyClass.MyClass(int)""/> /// </summary> class MyClass { public MyClass(int x) { } }", XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("see"), XmlDoc.AttributeName(" "), XmlDoc.AttributeName("cref"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes("\""), Class("MyClass"), Operators.Dot, Identifier("MyClass"), Punctuation.OpenParen, Keyword("int"), Punctuation.CloseParen, XmlDoc.AttributeQuotes("\""), XmlDoc.Delimiter("/>"), XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("MyClass"), Punctuation.OpenCurly, Keyword("public"), Identifier("MyClass"), Punctuation.OpenParen, Keyword("int"), Identifier("x"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task TestGenericTypeWithNoArity() { await TestAsync( @" using System.Collections.Generic; class Program : IReadOnlyCollection { }", Keyword("using"), Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("Generic"), Punctuation.Semicolon, Keyword("class"), Class("Program"), Punctuation.Colon, Interface("IReadOnlyCollection"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task TestGenericTypeWithWrongArity() { await TestAsync( @" using System.Collections.Generic; class Program : IReadOnlyCollection<int,string> { }", Keyword("using"), Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("Generic"), Punctuation.Semicolon, Keyword("class"), Class("Program"), Punctuation.Colon, Identifier("IReadOnlyCollection"), Punctuation.OpenAngle, Keyword("int"), Punctuation.Comma, Keyword("string"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Cdn { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for CustomDomainsOperations. /// </summary> public static partial class CustomDomainsOperationsExtensions { /// <summary> /// Lists all of the existing custom domains within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> public static IPage<CustomDomain> ListByEndpoint(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName) { return operations.ListByEndpointAsync(resourceGroupName, profileName, endpointName).GetAwaiter().GetResult(); } /// <summary> /// Lists all of the existing custom domains within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<CustomDomain>> ListByEndpointAsync(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByEndpointWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets an exisitng custom domain within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> public static CustomDomain Get(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName) { return operations.GetAsync(resourceGroupName, profileName, endpointName, customDomainName).GetAwaiter().GetResult(); } /// <summary> /// Gets an exisitng custom domain within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CustomDomain> GetAsync(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, customDomainName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a new custom domain within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> /// <param name='hostName'> /// The host name of the custom domain. Must be a domain name. /// </param> public static CustomDomain Create(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, string hostName) { return operations.CreateAsync(resourceGroupName, profileName, endpointName, customDomainName, hostName).GetAwaiter().GetResult(); } /// <summary> /// Creates a new custom domain within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> /// <param name='hostName'> /// The host name of the custom domain. Must be a domain name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CustomDomain> CreateAsync(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, string hostName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, customDomainName, hostName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes an existing custom domain within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> public static CustomDomain Delete(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName) { return operations.DeleteAsync(resourceGroupName, profileName, endpointName, customDomainName).GetAwaiter().GetResult(); } /// <summary> /// Deletes an existing custom domain within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CustomDomain> DeleteAsync(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DeleteWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, customDomainName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Disable https delivery of the custom domain. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> public static CustomDomain DisableCustomHttps(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName) { return operations.DisableCustomHttpsAsync(resourceGroupName, profileName, endpointName, customDomainName).GetAwaiter().GetResult(); } /// <summary> /// Disable https delivery of the custom domain. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CustomDomain> DisableCustomHttpsAsync(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DisableCustomHttpsWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, customDomainName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Enable https delivery of the custom domain. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> public static CustomDomain EnableCustomHttps(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName) { return operations.EnableCustomHttpsAsync(resourceGroupName, profileName, endpointName, customDomainName).GetAwaiter().GetResult(); } /// <summary> /// Enable https delivery of the custom domain. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CustomDomain> EnableCustomHttpsAsync(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.EnableCustomHttpsWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, customDomainName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a new custom domain within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> /// <param name='hostName'> /// The host name of the custom domain. Must be a domain name. /// </param> public static CustomDomain BeginCreate(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, string hostName) { return operations.BeginCreateAsync(resourceGroupName, profileName, endpointName, customDomainName, hostName).GetAwaiter().GetResult(); } /// <summary> /// Creates a new custom domain within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> /// <param name='hostName'> /// The host name of the custom domain. Must be a domain name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CustomDomain> BeginCreateAsync(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, string hostName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, customDomainName, hostName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes an existing custom domain within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> public static CustomDomain BeginDelete(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName) { return operations.BeginDeleteAsync(resourceGroupName, profileName, endpointName, customDomainName).GetAwaiter().GetResult(); } /// <summary> /// Deletes an existing custom domain within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CustomDomain> BeginDeleteAsync(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, customDomainName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all of the existing custom domains within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<CustomDomain> ListByEndpointNext(this ICustomDomainsOperations operations, string nextPageLink) { return operations.ListByEndpointNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Lists all of the existing custom domains within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<CustomDomain>> ListByEndpointNextAsync(this ICustomDomainsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByEndpointNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// // Copyright 2011, Novell, Inc. // Copyright 2011, Regan Sarwas // // // 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. // // // PdfKit.cs: Bindings for the PdfKit API // using System; using System.Drawing; using MonoMac.AppKit; using MonoMac.Foundation; using MonoMac.ObjCRuntime; // Verify/Test Delegate Models // Check for missing NullAllowed on all object properties // Test methods returning typed arrays in lieu of NSArray // Check classes with no public inits - Should I make the constructors private? // Check the few abnormal properties namespace MonoMac.PdfKit { [BaseType (typeof (NSObject), Name="PDFAction")] public interface PdfAction { //This is an abstract superclass with no public init - should it have a private constructor?? //As it is, I can create instances, that segfault when you access the type method. //marking the method as [Abstract] doesn't work because the subclasses do not explictly //define this method (although they implement it) [Export ("type")] string Type { get; } } [BaseType (typeof (PdfAction), Name="PDFActionGoTo")] public interface PdfActionGoTo { [Export ("initWithDestination:")] IntPtr Constructor (PdfDestination destination); [Export ("destination")] PdfDestination Destination { get; set; } } [BaseType (typeof (PdfAction), Name="PDFActionNamed")] public interface PdfActionNamed { [Export ("initWithName:")] IntPtr Constructor (PdfActionNamedName name); [Export ("name")] PdfActionNamedName Name { get; set; } } [BaseType (typeof (PdfAction), Name="PDFActionRemoteGoTo")] public interface PdfActionRemoteGoTo { [Export ("initWithPageIndex:atPoint:fileURL:")] IntPtr Constructor (int pageIndex, PointF point, NSUrl fileUrl); [Export ("pageIndex")] int PageIndex { get; set; } [Export ("point")] PointF Point { get; set; } [Export ("URL")] NSUrl Url { get; set; } } [BaseType (typeof (PdfAction), Name="PDFActionResetForm")] public interface PdfActionResetForm { //has a public Init ??? //NSArray of NSString [Export ("fields"), NullAllowed] string [] Fields { get; set; } [Export ("fieldsIncludedAreCleared")] bool FieldsIncludedAreCleared { get; set; } } [BaseType (typeof (PdfAction), Name="PDFActionURL")] public interface PdfActionUrl { [Export ("initWithURL:")] IntPtr Constructor (NSUrl url); [Export ("URL")] NSUrl Url { get; set; } } [BaseType (typeof (NSObject), Name="PDFAnnotation")] public interface PdfAnnotation { [Export ("initWithBounds:")] IntPtr Constructor (RectangleF bounds); [Export ("page")] PdfPage Page { get; } [Export ("type")] string Type { get; } [Export ("bounds")] RectangleF Bounds { get; set; } [Export ("modificationDate")] NSDate ModificationDate { get; set; } [Export ("userName")] string UserName { get; set; } [Export ("popup")] PdfAnnotationPopup Popup { get; set; } [Export ("shouldDisplay")] bool ShouldDisplay { get; set; } [Export ("shouldPrint")] bool ShouldPrint { get; set; } [Export ("border")] PdfBorder Border { get; set; } [Export ("color")] NSColor Color { get; set; } [Export ("mouseUpAction")] PdfAction MouseUpAction { get; set; } [Export ("contents")] string Contents { get; set; } [Export ("toolTip")] string ToolTip { get; } [Export ("hasAppearanceStream")] bool HasAppearanceStream { get; } [Export ("removeAllAppearanceStreams")] void RemoveAllAppearanceStreams (); [Export ("drawWithBox:")] void Draw (PdfDisplayBox box); } [BaseType (typeof (PdfAnnotation), Name="PDFAnnotationButtonWidget")] public interface PdfAnnotationButtonWidget { [Export ("controlType")] PdfWidgetControlType ControlType { get; set; } [Export ("state")] int State { get; set; } [Export ("highlighted")] bool Highlighted { [Bind ("isHighlighted")] get; set; } [Export ("backgroundColor")] NSColor BackgroundColor { get; set; } [Export ("allowsToggleToOff")] bool AllowsToggleToOff { get; } [Export ("font")] NSFont Font { get; set; } [Export ("fontColor")] NSColor FontColor { get; set; } [Export ("caption")] string Caption { get; set; } [Export ("fieldName")] string FieldName { get; set; } [Export ("onStateValue")] string OnStateValue { get; set; } } [BaseType (typeof (PdfAnnotation), Name="PDFAnnotationChoiceWidget")] public interface PdfAnnotationChoiceWidget { [Export ("stringValue")] string Text { get; set; } [Export ("backgroundColor")] NSColor BackgroundColor { get; set; } [Export ("font")] NSFont Font { get; set; } [Export ("fontColor")] NSColor FontColor { get; set; } [Export ("fieldName")] string FieldName { get; set; } [Export ("isListChoice")] bool IsListChoice { get; set; } // NSArray of NSString [Export ("choices")] string [] Choices { get; set; } } [BaseType (typeof (PdfAnnotation), Name="PDFAnnotationCircle")] public interface PdfAnnotationCircle { [Export ("interiorColor")] NSColor InteriorColor { get; set; } } [BaseType (typeof (PdfAnnotation), Name="PDFAnnotationFreeText")] public interface PdfAnnotationFreeText { [Export ("font")] NSFont Font { get; set; } [Export ("fontColor")] NSColor FontColor { get; set; } [Export ("alignment")] NSTextAlignment Alignment { get; set; } } [BaseType (typeof (PdfAnnotation), Name="PDFAnnotationInk")] public interface PdfAnnotationInk { [Export ("paths")] NSBezierPath [] Paths { get; } [Export ("addBezierPath:path")] void AddBezierPathpath (NSBezierPath path); [Export ("removeBezierPath:path")] void RemoveBezierPathpath (NSBezierPath path); } [BaseType (typeof (PdfAnnotation), Name="PDFAnnotationLine")] public interface PdfAnnotationLine { [Export ("startPoint")] PointF StartPoint { get; set; } [Export ("endPoint")] PointF EndPoint { get; set; } [Export ("startLineStyle")] PdfLineStyle StartLineStyle { get; set; } [Export ("endLineStyle")] PdfLineStyle EndLineStyle { get; set; } [Export ("interiorColor")] NSColor InteriorColor { get; set; } } [BaseType (typeof (PdfAnnotation), Name="PDFAnnotationLink")] public interface PdfAnnotationLink { [Export ("destination")] PdfDestination Destination { get; set; } [Export ("URL")] NSUrl Url { get; set; } [Export ("setHighlighted:")] void SetHighlighted (bool highlighted); } [BaseType (typeof (PdfAnnotation), Name="PDFAnnotationMarkup")] public interface PdfAnnotationMarkup { //bindings cannot box PointF[] to NSArray [Export ("quadrilateralPoints")] NSArray QuadrilateralPoints { get; set; } //PointF [] QuadrilateralPoints { get; set; } [Export ("markupType")] PdfMarkupType MarkupType { get; set; } } [BaseType (typeof (PdfAnnotation), Name="PDFAnnotationPopup")] public interface PdfAnnotationPopup { [Export ("isOpen")] bool IsOpen { get; set; } } [BaseType (typeof (PdfAnnotation), Name="PDFAnnotationSquare")] public interface PdfAnnotationSquare { [Export ("interiorColor")] NSColor InteriorColor { get; set; } } [BaseType (typeof (PdfAnnotation), Name="PDFAnnotationStamp")] public interface PdfAnnotationStamp { [Export ("name")] string Name { get; set; } } [BaseType (typeof (PdfAnnotation), Name="PDFAnnotationText")] public interface PdfAnnotationText { [Export ("iconType")] PdfTextAnnotationIconType IconType { get; set; } } [BaseType (typeof (PdfAnnotation), Name="PDFAnnotationTextWidget")] public interface PdfAnnotationTextWidget { [Export ("stringValue")] string StringValue { get; set; } [Export ("backgroundColor")] NSColor BackgroundColor { get; set; } [Export ("rotation")] int Rotation { get; set; } [Export ("font")] NSFont Font { get; set; } [Export ("fontColor")] NSColor FontColor { get; set; } [Export ("alignment")] NSTextAlignment Alignment { get; set; } [Export ("maximumLength")] int MaximumLength { get; set; } [Export ("fieldName")] string FieldName { get; set; } } [BaseType (typeof (NSObject), Name="PDFBorder")] public interface PdfBorder { [Export ("style")] PdfBorderStyle Style { get; set; } [Export ("lineWidth")] float LineWidth { get; set; } [Export ("horizontalCornerRadius")] float HorizontalCornerRadius { get; set; } [Export ("verticalCornerRadius")] float VerticalCornerRadius { get; set; } //FIXME //NSArray of NSNumber see Docs say see NSBezierPath, which uses float [] [Export ("dashPattern")] NSArray DashPattern { get; set; } //float [] DashPattern { get; set; } [Export ("drawInRect:rect")] void Draw (RectangleF rect); } [BaseType (typeof (NSObject), Name="PDFDestination")] public interface PdfDestination { [Export ("initWithPage:atPoint:")] IntPtr Constructor (PdfPage page, PointF point); [Export ("page")] PdfPage Page { get; } [Export ("point")] PointF Point { get; } //Should Compare be more more .Net ified ? [Export ("compare:")] NSComparisonResult Compare (PdfDestination destination); } //Add attributes for delegates/events [BaseType (typeof (NSObject), Name="PDFDocument", Delegates=new string [] { "WeakDelegate" }, Events=new Type [] { typeof (PdfDocumentDelegate)})] public interface PdfDocument { [Export ("initWithURL:")] IntPtr Constructor (NSUrl url); [Export ("initWithData:")] IntPtr Constructor (NSData data); [Export ("documentURL")] NSUrl DocumentUrl { get; } //[Export ("documentRef")] //CGPdfDocumentRef DocumentRef { get; } [Export ("documentAttributes")] NSDictionary DocumentAttributes { get; set; } [Export ("majorVersion")] int MajorVersion { get; } [Export ("minorVersion")] int MinorVersion { get; } [Export ("isEncrypted")] bool IsEncrypted { get; } [Export ("isLocked")] bool IsLocked { get; } [Export ("unlockWithPassword:")] bool Unlock (string password); [Export ("allowsPrinting")] bool AllowsPrinting { get; } [Export ("allowsCopying")] bool AllowsCopying { get; } [Export ("permissionsStatus")] PdfDocumentPermissions PermissionsStatus { get; } [Export ("string")] string Text { get; } [Export ("delegate", ArgumentSemantic.Assign), NullAllowed] NSObject WeakDelegate { get; set; } [Wrap ("WeakDelegate")] PdfDocumentDelegate Delegate { get; set; } [Export ("dataRepresentation")] NSData GetDataRepresentation (); [Export ("dataRepresentationWithOptions:")] NSData GetDataRepresentation (NSDictionary options); [Export ("writeToFile:")] bool Write (string path); [Export ("writeToFile:withOptions:")] bool Write (string path, NSDictionary options); [Export ("writeToURL:")] bool Write (NSUrl url); [Export ("writeToURL:withOptions:")] bool Write (NSUrl url, NSDictionary options); [Export ("outlineRoot")] PdfOutline OutlineRoot { get; set; } [Export ("outlineItemForSelection:")] PdfOutline OutlineItem (PdfSelection selection); [Export ("pageCount")] int PageCount { get; } [Export ("pageAtIndex:")] PdfPage GetPage (int index); [Export ("indexForPage:")] int GetPageIndex (PdfPage page); [Export ("insertPage:atIndex:")] void InsertPage (PdfPage page, int index); [Export ("removePageAtIndex:")] void RemovePage (int index); [Export ("exchangePageAtIndex:withPageAtIndex:")] void ExchangePages (int indexA, int indexB); // Check on how Classes map to Types [Export ("pageClass")] Class PageClass { get; } // Shouldn't options should be a bit flag of comparison methods - find enum. [Export ("findString:withOptions:")] PdfSelection [] Find (string text, int options); [Export ("beginFindString:withOptions:")] void FindAsync (string text, int options); [Export ("beginFindStrings:withOptions:")] void FindAsync (string [] text, int options); [Export ("findString:fromSelection:withOptions:")] PdfSelection Find (string text, PdfSelection selection, int options); [Export ("isFinding")] bool IsFinding { get; } [Export ("cancelFindString")] void CancelFind (); [Export ("selectionForEntireDocument")] PdfSelection SelectEntireDocument (); [Export ("selectionFromPage:atPoint:toPage:atPoint:")] PdfSelection GetSelection (PdfPage startPage, PointF startPoint, PdfPage endPage, PointF endPoint); [Export ("selectionFromPage:atCharacterIndex:toPage:atCharacterIndex:")] PdfSelection GetSelection (PdfPage startPage, int startCharIndex, PdfPage endPage, int endCharIndex); } [BaseType (typeof (NSObject))] [Model] public interface PdfDocumentDelegate { [Export ("didMatchString:"), EventArgs ("PdfSelection")] void DidMatchString (PdfSelection sender); //the delegate method needs to take at least one parameter //[Export ("classForPage"), DelegateName ("ClassForPageDelegate"), DefaultValue (null)] //Class ClassForPage (); [Export ("classForAnnotationClass:"), DelegateName ("ClassForAnnotationClassDelegate"), DefaultValue (null)] Class ClassForAnnotationClass (Class sender); [Export ("documentDidEndDocumentFind:"), EventArgs ("NSNotification")] void FindFinished (NSNotification notification); [Export ("documentDidBeginPageFind:"), EventArgs ("NSNotification")] void PageFindStarted (NSNotification notification); [Export ("documentDidEndPageFind:"), EventArgs ("NSNotification")] void PageFindFinished (NSNotification notification); [Export ("documentDidFindMatch:"), EventArgs ("NSNotification")] void MatchFound (NSNotification notification); } [BaseType (typeof (NSObject), Name="PDFOutline")] public interface PdfOutline { // Why did this have a special init???? // Constructor/class needs special documentation on how to use one that is created (not obtained from another object). [Export ("document")] PdfDocument Document { get; } [Export ("parent")] PdfOutline Parent { get; } [Export ("numberOfChildren")] int ChildrenCount { get; } [Export ("index")] int Index { get; } [Export ("childAtIndex:")] PdfOutline Child (int index); [Export ("insertChild:atIndex:")] void InsertChild (PdfOutline child, int index); [Export ("removeFromParent")] void RemoveFromParent (); [Export ("label")] string Label { get; set; } [Export ("isOpen")] bool IsOpen { get; set; } [Export ("destination")] PdfDestination Destination { get; set; } [Export ("action")] PdfAction Action { get; set; } } [BaseType (typeof (NSObject), Name="PDFPage")] public interface PdfPage { [Export ("initWithImage:")] IntPtr Constructor (NSImage image); [Export ("document")] PdfDocument Document { get; } //[Export ("pageRef")] //CGPdfPageRef PageRef { get; } [Export ("label")] string Label { get; } [Export ("boundsForBox:box")] RectangleF GetBoundsForBox (PdfDisplayBox box); [Export ("setBounds:forBox:")] void SetBoundsForBox (RectangleF bounds, PdfDisplayBox box); [Export ("rotation")] int Rotation { get; set; } //Check Docs say: "array will _most likely_ be typed to subclasses of the PdfAnnotation class" //do they mean that if it isn't a subclass it is the base class ?? //Maybe we should be safe and return NSArray ?? [Export ("annotations")] PdfAnnotation [] Annotations { get; } [Export ("displaysAnnotations")] bool DisplaysAnnotations { get; set; } [Export ("addAnnotation:")] void AddAnnotation (PdfAnnotation annotation); [Export ("removeAnnotation:")] void RemoveAnnotation (PdfAnnotation annotation); [Export ("annotationAtPoint:point")] PdfAnnotation GetAnnotation (PointF point); [Export ("drawWithBox:")] void Draw (PdfDisplayBox box); [Export ("transformContextForBox:")] void TransformContext (PdfDisplayBox box); [Export ("numberOfCharacters")] int CharacterCount { get; } [Export ("string")] string Text { get; } [Export ("attributedString")] NSAttributedString AttributedString { get; } [Export ("characterBoundsAtIndex:")] RectangleF GetCharacterBounds (int index); [Export ("characterIndexAtPoint:")] int GetCharacterIndex (PointF point); [Export ("selectionForRect:")] PdfSelection GetSelection (RectangleF rect); [Export ("selectionForWordAtPoint:")] PdfSelection SelectWord (PointF point); [Export ("selectionForLineAtPoint:")] PdfSelection SelectLine (PointF point); [Export ("selectionFromPoint:toPoint:")] PdfSelection GetSelection (PointF startPoint, PointF endPoint); [Export ("selectionForRange:")] PdfSelection GetSelection (NSRange range); [Export ("dataRepresentation")] NSData DataRepresentation { get; } } [BaseType (typeof (NSObject), Name="PDFSelection")] public interface PdfSelection { [Export ("initWithDocument:")] IntPtr Constructor (PdfDocument document); //verify NSArray [Export ("pages")] PdfPage [] Pages { get; } [Export ("color")] NSColor Color { get; set; } [Export ("string")] string Text { get; } [Export ("attributedString")] NSAttributedString AttributedString { get; } [Export ("boundsForPage:page")] RectangleF GetBoundsForPage (PdfPage page); //verify NSArray [Export ("selectionsByLine")] PdfSelection [] SelectionsByLine (); [Export ("addSelection:")] void AddSelection (PdfSelection selection); [Export ("addSelections:")] void AddSelections (PdfSelection [] selections); [Export ("extendSelectionAtEnd:")] void ExtendSelectionAtEnd (int succeed); [Export ("extendSelectionAtStart:")] void ExtendSelectionAtStart (int precede); [Export ("drawForPage:active:")] void Draw (PdfPage page, bool active); [Export ("drawForPage:withBox:active:")] void Draw (PdfPage page, PdfDisplayBox box, bool active); } [BaseType (typeof (NSView), Name="PDFThumbnailView")] public interface PdfThumbnailView { [Export ("PDFView")] PdfView PdfView { get; set; } [Export ("thumbnailSize")] SizeF ThumbnailSize { get; set; } [Export ("maximumNumberOfColumns")] int MaximumNumberOfColumns { get; set; } [Export ("labelFont")] NSFont LabelFont { get; set; } [Export ("backgroundColor")] NSColor BackgroundColor { get; set; } [Export ("allowsDragging")] bool AllowsDragging { get; set; } [Export ("allowsMultipleSelection")] bool AllowsMultipleSelection { get; set; } //verify NSArray [Export ("selectedPages")] PdfPage [] SelectedPages { get; } } [BaseType (typeof (NSView), Name="PDFView", Delegates=new string [] { "WeakDelegate" }, Events=new Type [] { typeof (PdfViewDelegate)})] public interface PdfView { [Export ("document")] PdfDocument Document { get; set; } [Export ("canGoToFirstPage")] bool CanGoToFirstPage { get; } //Verify [Export ("goToFirstPage:")] void GoToFirstPage (NSObject sender); [Export ("canGoToLastPage")] bool CanGoToLastPage { get; } [Export ("goToLastPage:")] void GoToLastPage (NSObject sender); [Export ("canGoToNextPage")] bool CanGoToNextPage { get; } [Export ("goToNextPage:")] void GoToNextPage (NSObject sender); [Export ("canGoToPreviousPage")] bool CanGoToPreviousPage { get; } [Export ("goToPreviousPage:")] void GoToPreviousPage (NSObject sender); [Export ("canGoBack")] bool CanGoBack { get; } [Export ("goBack:")] void GoBack (NSObject sender); [Export ("canGoForward")] bool CanGoForward { get; } [Export ("goForward:")] void GoForward (NSObject sender); [Export ("currentPage")] PdfPage CurrentPage { get; } [Export ("goToPage:")] void GoToPage (PdfPage page); [Export ("currentDestination")] PdfDestination CurrentDestination { get; } [Export ("goToDestination:")] void GoToDestination (PdfDestination destination); [Export ("goToSelection:")] void GoToSelection (PdfSelection selection); [Export ("goToRect:onPage:")] void GoToRectangle (RectangleF rect, PdfPage page); [Export ("displayMode")] PdfDisplayMode DisplayMode { get; set; } [Export ("displaysPageBreaks")] bool DisplaysPageBreaks { get; set; } [Export ("displayBox")] PdfDisplayBox DisplayBox { get; set; } [Export ("displaysAsBook")] bool DisplaysAsBook { get; set; } [Export ("shouldAntiAlias")] bool ShouldAntiAlias { get; set; } [Export ("greekingThreshold")] float GreekingThreshold { get; set; } [Export ("takeBackgroundColorFrom:")] void TakeBackgroundColor (NSObject sender); [Export ("backgroundColor")] NSColor BackgroundColor { get; set; } [Export ("delegate", ArgumentSemantic.Assign), NullAllowed] NSObject WeakDelegate { get; set; } [Wrap ("WeakDelegate")] PdfViewDelegate Delegate { get; set; } [Export ("scaleFactor")] float ScaleFactor { get; set; } [Export ("zoomIn:")] void ZoomIn (NSObject sender); [Export ("canZoomIn")] bool CanZoomIn { get; } [Export ("zoomOut:")] void ZoomOut (NSObject sender); [Export ("canZoomOut")] bool CanZoomOut { get; } [Export ("autoScales")] bool AutoScales { get; set; } [Export ("areaOfInterestForMouse:")] PdfAreaOfInterest GetAreaOfInterest (NSEvent mouseEvent); [Export ("setCursorForAreaOfInterest:")] void SetCursor (PdfAreaOfInterest area); [Export ("performAction:")] void PerformAction (PdfAction action); [Export ("currentSelection")] PdfSelection CurrentSelection { get; set; } [Export ("setCurrentSelection:animate:")] void SetCurrentSelection (PdfSelection selection, bool animate); [Export ("clearSelection")] void ClearSelection (); [Export ("selectAll:")] void SelectAll (NSObject sender); [Export ("scrollSelectionToVisible:")] void ScrollSelectionToVisible (NSObject sender); // Verify NSArray [Export ("highlightedSelections")] PdfSelection [] HighlightedSelections { get; set; } [Export ("takePasswordFrom:")] void TakePasswordFrom (NSObject sender); [Export ("drawPage:")] void DrawPage (PdfPage page); [Export ("drawPagePost:")] void DrawPagePost (PdfPage page); [Export ("copy:")] void Copy (NSObject sender); [Export ("printWithInfo:autoRotate:doRotate")] void Print (NSPrintInfo printInfo, bool doRotate); [Export ("printWithInfo:autoRotate:pageScaling:")] void Print (NSPrintInfo printInfo, bool doRotate, PdfPrintScalingMode scaleMode); [Export ("pageForPoint:nearest:")] PdfPage GetPage (PointF point, bool nearest); [Export ("convertPoint:toPage:")] PointF ConvertPointToPage (PointF point, PdfPage page); [Export ("convertRect:toPage:")] RectangleF ConvertRectangleToPage (RectangleF rect, PdfPage page); [Export ("convertPoint:fromPage:")] PointF ConvertPointFromPage (PointF point, PdfPage page); [Export ("convertRect:fromPage:")] RectangleF ConvertRectangleFromPage (RectangleF rect, PdfPage page); [Export ("documentView")] NSView DocumentView { get; } [Export ("layoutDocumentView")] void LayoutDocumentView (); [Export ("annotationsChangedOnPage:")] void AnnotationsChanged (PdfPage page); [Export ("rowSizeForPage:")] SizeF RowSize (PdfPage page); [Export ("allowsDragging")] bool AllowsDragging { get; set; } //Verify NSArray [Export ("visiblePages")] PdfPage [] VisiblePages { get; } [Export ("enableDataDetectors")] bool EnableDataDetectors { get; set; } } //Verify delegate methods. There are default actions (not just return null ) that should occur //if the delegate does not implement the method. [BaseType (typeof (NSObject))] [Model] public interface PdfViewDelegate { //from docs: 'By default, the scale factor is restricted to a range between 0.1 and 10.0 inclusive.' [Export ("PDFViewWillChangeScaleFactor:toScale:"), DelegateName ("PdfViewScale"), DefaultValueFromArgument ("scale")] float WillChangeScaleFactor (PdfView sender, float scale); [Export ("PDFViewWillClickOnLink:withURL:"), EventArgs ("PdfViewUrl")] void WillClickOnLink (PdfView sender, NSUrl url); // from the docs: 'By default, this method uses the string, if any, associated with the // 'Title' key in the view's PDFDocument attribute dictionary. If there is no such string, // this method uses the last path component if the document is URL-based. [Export ("PDFViewPrintJobTitle:"), DelegateName ("PdfViewTitle"), DefaultValue ("String.Empty")] string TitleOfPrintJob (PdfView sender); [Export ("PDFViewPerformFind:"), EventArgs ("PdfView")] void PerformFind (PdfView sender); [Export ("PDFViewPerformGoToPage:"), EventArgs ("PdfView")] void PerformGoToPage (PdfView sender); [Export ("PDFViewPerformPrint:"), EventArgs ("PdfView")] void PerformPrint (PdfView sender); [Export ("PDFViewOpenPDF:forRemoteGoToAction:"), EventArgs ("PdfViewAction")] void OpenPdf (PdfView sender, PdfActionRemoteGoTo action); } }
using System; using System.Diagnostics; using System.ServiceModel; using System.ServiceModel.Channels; using System.Xml; using SolarWinds.InformationService.Contract2.Bindings; using SolarWinds.Logging; namespace SolarWinds.InformationService.Contract2 { public class InfoServiceProxy : IStreamInformationService, IDisposable { private readonly static Log _log = new Log(); private static readonly TimeSpan longRunningQueryTime = TimeSpan.FromSeconds(15); private ChannelFactory<IStreamInformationServiceChannel> _channelFactory; private IStreamInformationServiceChannel _infoService; private TimeSpan _operationTimeout = TimeSpan.FromMinutes(60); private InfoServiceActivityMonitor _activityMonitor = null; public TimeSpan OperationTimeout { get { return _operationTimeout; } set { _operationTimeout = value; } } public IChannel Channel { get { return _infoService; } } public IClientChannel ClientChannel { get { return _infoService; } } public ChannelFactory<IStreamInformationServiceChannel> ChannelFactory { get { return _channelFactory; } } #region Constructors public InfoServiceProxy(string endpointConfiguration) { if (endpointConfiguration == null) throw new ArgumentNullException("endpointConfiguration"); _channelFactory = CreateChannelFactory(endpointConfiguration); FixBinding(); } public InfoServiceProxy(string endpointConfiguration, ServiceCredentials credentials) : this(endpointConfiguration) { if (credentials == null) throw new ArgumentNullException("credentials"); credentials.ApplyTo(_channelFactory); } public InfoServiceProxy(string endpointConfiguration, string remoteAddress) { if (endpointConfiguration == null) throw new ArgumentNullException("endpointConfiguration"); if (remoteAddress == null) throw new ArgumentNullException("remoteAddress"); _channelFactory = CreateChannelFactory(endpointConfiguration, new EndpointAddress(remoteAddress)); FixBinding(); } public InfoServiceProxy(string endpointConfiguration, string remoteAddress, ServiceCredentials credentials) : this(endpointConfiguration, remoteAddress) { if (credentials == null) throw new ArgumentNullException("credentials"); credentials.ApplyTo(_channelFactory); } public InfoServiceProxy(Uri address) { if (address == null) throw new ArgumentNullException("address"); NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport); binding.Security.Mode = SecurityMode.Transport; binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows; Initialize(new EndpointAddress(address), binding, new WindowsCredential()); } public InfoServiceProxy(Uri address, Binding binding, ServiceCredentials credentials) { if (address == null) throw new ArgumentNullException("address"); Initialize(new EndpointAddress(address), binding, credentials); } public InfoServiceProxy(EndpointAddress address, Binding binding, ServiceCredentials credentials) { Initialize(address, binding, credentials); } #endregion private void FixBinding() { BindingElementCollection elements = _channelFactory.Endpoint.Binding.CreateBindingElements(); SslStreamSecurityBindingElement element = elements.Find<SslStreamSecurityBindingElement>(); if (element != null) { element.IdentityVerifier = new SWIdentityVerifier(); CustomBinding newbinding = new CustomBinding(elements); // Transfer timeout settings from the old binding to the new Binding binding = _channelFactory.Endpoint.Binding; newbinding.CloseTimeout = binding.CloseTimeout; newbinding.OpenTimeout = binding.OpenTimeout; newbinding.ReceiveTimeout = binding.ReceiveTimeout; newbinding.SendTimeout = binding.SendTimeout; _channelFactory.Endpoint.Binding = newbinding; } CorrectChannelFactory(); } private void Initialize(EndpointAddress address, Binding binding, ServiceCredentials credentials) { if (address == null) throw new ArgumentNullException("address"); if (credentials == null) throw new ArgumentNullException("credentials"); if (binding == null) throw new ArgumentNullException("binding"); BindingElementCollection elements = binding.CreateBindingElements(); SslStreamSecurityBindingElement element = elements.Find<SslStreamSecurityBindingElement>(); if (element != null) { element.IdentityVerifier = new SWIdentityVerifier(); CustomBinding newbinding = new CustomBinding(elements); // Transfer timeout settings from the old binding to the new newbinding.CloseTimeout = binding.CloseTimeout; newbinding.OpenTimeout = binding.OpenTimeout; newbinding.ReceiveTimeout = binding.ReceiveTimeout; newbinding.SendTimeout = binding.SendTimeout; binding = newbinding; } _channelFactory = CreateChannelFactory(binding, address); credentials.ApplyTo(_channelFactory); CorrectChannelFactory(); } private void CorrectChannelFactory() { // ???: how can I detect that channel binding is securited _activityMonitor = new InfoServiceActivityMonitor(); _channelFactory.Endpoint.Behaviors.Add(_activityMonitor); } #region IInfoService Members public virtual XmlElement Invoke(string entity, string verb, params XmlElement[] parameters) { var stopwatch = new Stopwatch(); try { if (_infoService == null) { Open(); } stopwatch.Start(); return _infoService.Invoke(entity, verb, parameters); } catch (FaultException<InfoServiceFaultContract> ex) { _log.Error("Error executing invoke: " + ex.Detail.Message + Environment.NewLine + entity + "." + verb); throw; } finally { stopwatch.Stop(); if (stopwatch.Elapsed > longRunningQueryTime) { _log.WarnFormat("Support! -- LONG RUNNING INVOKE: {0} ms: {1}:{2}", stopwatch.Elapsed.TotalMilliseconds, verb, entity); } } } public virtual Message Query(QueryXmlRequest query) { _log.DebugFormat("Query: {0}", query.query); if (_log.IsDebugEnabled && query.parameters.Count > 0) { _log.Debug("Parameters: "); foreach (var parameter in query.parameters) _log.DebugFormat("\t{0}={1}", parameter.Key, parameter.Value); } var stopwatch = new Stopwatch(); try { if (_infoService == null) { Open(); } stopwatch.Start(); return _infoService.Query(query); } catch (FaultException<InfoServiceFaultContract> ex) { _log.Error("Error executing query: " + ex.Detail.Message + Environment.NewLine + query.query); throw; } catch (Exception ex) { _log.ErrorFormat("Error executing query: {0} {1} {2}", ex, Environment.NewLine, query.query); foreach (var parameter in query.parameters) _log.ErrorFormat("\t{0}={1}", parameter.Key, parameter.Value); throw; } finally { stopwatch.Stop(); if (stopwatch.Elapsed > longRunningQueryTime) { _log.WarnFormat("Support! -- LONG RUNNING QUERY: {0} ms: {1}", stopwatch.Elapsed.TotalMilliseconds, query.query); } } } public virtual string Create(string entityType, PropertyBag properties) { var stopwatch = new Stopwatch(); try { if (_infoService == null) { Open(); } stopwatch.Start(); return _infoService.Create(entityType, properties); } catch (FaultException<InfoServiceFaultContract> ex) { _log.Error("Error executing create operation: " + ex.Detail.Message + Environment.NewLine + entityType + Environment.NewLine + properties); throw; } finally { stopwatch.Stop(); if (stopwatch.Elapsed > longRunningQueryTime) { _log.WarnFormat("Support! -- LONG RUNNING CREATE: {0} ms: {1}", stopwatch.Elapsed.TotalMilliseconds, entityType); } } } public virtual PropertyBag Read(string uri) { var stopwatch = new Stopwatch(); try { if (_infoService == null) { Open(); } stopwatch.Start(); return _infoService.Read(uri); } catch (FaultException<InfoServiceFaultContract> ex) { _log.Error("Error executing read operation: " + ex.Detail.Message + Environment.NewLine + uri); throw; } finally { stopwatch.Stop(); if (stopwatch.Elapsed > longRunningQueryTime) { _log.WarnFormat("Support! -- LONG RUNNING READ: {0} ms: {1}", stopwatch.Elapsed.TotalMilliseconds, uri); } } } public virtual void Update(string uri, PropertyBag propertiesToUpdate) { var stopwatch = new Stopwatch(); try { if (_infoService == null) { Open(); } stopwatch.Start(); _infoService.Update(uri, propertiesToUpdate); } catch (FaultException<InfoServiceFaultContract> ex) { _log.Error("Error executing update operation: " + ex.Detail.Message + Environment.NewLine + uri + Environment.NewLine + propertiesToUpdate); throw; } finally { stopwatch.Stop(); if (stopwatch.Elapsed > longRunningQueryTime) { _log.WarnFormat("Support! -- LONG RUNNING UPDATE: {0} ms: {1}", stopwatch.Elapsed.TotalMilliseconds, uri); } } } public virtual void BulkUpdate(string[] uris, PropertyBag propertiesToUpdate) { var stopwatch = new Stopwatch(); try { if (_infoService == null) { Open(); } stopwatch.Start(); _infoService.BulkUpdate(uris, propertiesToUpdate); } catch (FaultException<InfoServiceFaultContract> ex) { _log.Error("Error executing bulk update operation: " + ex.Detail.Message + Environment.NewLine + String.Join(Environment.NewLine, uris) + Environment.NewLine + propertiesToUpdate); throw; } finally { stopwatch.Stop(); if (stopwatch.Elapsed > longRunningQueryTime) { _log.WarnFormat("Support! -- LONG RUNNING BULK UPDATE: {0} ms", stopwatch.Elapsed.TotalMilliseconds); } } } public virtual void Delete(string uri) { var stopwatch = new Stopwatch(); try { if (_infoService == null) { Open(); } stopwatch.Start(); _infoService.Delete(uri); } catch (FaultException<InfoServiceFaultContract> ex) { _log.Error("Error executing delete operation: " + ex.Detail.Message + Environment.NewLine + uri); throw; } finally { stopwatch.Stop(); if (stopwatch.Elapsed > longRunningQueryTime) { _log.WarnFormat("Support! -- LONG RUNNING DELETE: {0} ms: {1}", stopwatch.Elapsed.TotalMilliseconds, uri); } } } public virtual void BulkDelete(string[] uris) { var stopwatch = new Stopwatch(); try { if (_infoService == null) { Open(); } stopwatch.Start(); _infoService.BulkDelete(uris); } catch (FaultException<InfoServiceFaultContract> ex) { _log.Error("Error executing bulk delete operation: " + ex.Detail.Message + Environment.NewLine + String.Join(Environment.NewLine, uris)); throw; } finally { stopwatch.Stop(); if (stopwatch.Elapsed > longRunningQueryTime) { _log.WarnFormat("Support! -- LONG RUNNING BULK DELETE: {0} ms", stopwatch.Elapsed.TotalMilliseconds); } } } #endregion #region IStreamedInfoService Members public VerbInvokeResponse StreamedInvoke(VerbInvokeArguments parameter) { var stopwatch = new Stopwatch(); try { if (_infoService == null) { Open(); } stopwatch.Start(); return _infoService.StreamedInvoke(parameter); } catch (FaultException<InfoServiceFaultContract> ex) { _log.Error("Error executing invoke: " + ex.Detail.Message + Environment.NewLine + parameter.Entity + "." + parameter.Verb); throw; } finally { stopwatch.Stop(); if (stopwatch.Elapsed > longRunningQueryTime) { _log.WarnFormat("Support! -- LONG RUNNING INVOKE: {0} ms: {1}:{2}", stopwatch.Elapsed.TotalMilliseconds, parameter.Verb, parameter.Entity); } } } #endregion public void Open() { try { if (_infoService == null) { if (_activityMonitor != null) _activityMonitor.Reset(); _infoService = _channelFactory.CreateChannel(); _infoService.OperationTimeout = _operationTimeout; _infoService.Open(); } } catch (Exception ex) { _log.Error("An error occured opening a connection to the orion communication service.", ex); throw; } } public void Abort() { if (_infoService == null) return; ValidateUsedConnection(); _infoService.Abort(); _channelFactory.Abort(); } public void Close() { if (_infoService == null) return; ValidateUsedConnection(); try { _infoService.Close(); } catch (TimeoutException exception) { _infoService.Abort(); _log.Error("Error closing exception.", exception); } catch (CommunicationException exception) { _infoService.Abort(); _log.Error("Error closing exception.", exception); } _infoService = null; } #region Create Channel Factory private static ChannelFactory<IStreamInformationServiceChannel> CreateChannelFactory(Binding binding, EndpointAddress address) { if (_log.IsDebugEnabled) _log.DebugFormat("Creating channel factory for Information Service @ {0}", address.Uri); return new ChannelFactory<IStreamInformationServiceChannel>(binding, address); } private static ChannelFactory<IStreamInformationServiceChannel> CreateChannelFactory(string endpointConfiguration) { if (_log.IsDebugEnabled) _log.DebugFormat("Creating channel factory for Information Service using endpoint configuration '{0}'", endpointConfiguration); return new ChannelFactory<IStreamInformationServiceChannel>(endpointConfiguration); } private static ChannelFactory<IStreamInformationServiceChannel> CreateChannelFactory(string endpointConfiguration, EndpointAddress remoteAddress) { if (_log.IsDebugEnabled) _log.DebugFormat("Creating channel factory for Information Service using endpoint configuration '{0}' and remote address '{1}'", endpointConfiguration, remoteAddress.ToString()); return new ChannelFactory<IStreamInformationServiceChannel>(endpointConfiguration, remoteAddress); } #endregion private void ValidateUsedConnection() { if (_infoService == null) return; if (_activityMonitor == null || _activityMonitor.RequestSent) return; _log.Info("Non-used connection was opened. Information for developers. No impact on product functionality. See verbose log for more details."); _log.VerboseFormat("StackTrace: {0}", Environment.StackTrace); try { // // kick of simple query because of // https://connect.microsoft.com/VisualStudio/feedback/details/499859/wcf-pending-secure-conversions-are-not-cleaned-up-in-specific-scenario // using (_infoService.Query(new QueryXmlRequest("SELECT TOP 1 1 as Test FROM Metadata.Entity"))) { } } catch { } } #region IDisposable Members protected virtual void Dispose(bool disposing) { if (disposing) { Close(); try { _channelFactory.Close(); } catch (TimeoutException) { _channelFactory.Abort(); } catch (CommunicationException) { _channelFactory.Abort(); } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~InfoServiceProxy() { Dispose(false); } #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.Diagnostics; using System.Runtime.InteropServices; namespace System.Text { // ASCIIEncoding // // Note that ASCIIEncoding is optimized with no best fit and ? for fallback. // It doesn't come in other flavors. // // Note: ASCIIEncoding is the only encoding that doesn't do best fit (windows has best fit). // // Note: IsAlwaysNormalized remains false because 1/2 the code points are unassigned, so they'd // use fallbacks, and we cannot guarantee that fallbacks are normalized. public class ASCIIEncoding : Encoding { // Allow for devirtualization (see https://github.com/dotnet/coreclr/pull/9230) internal sealed class ASCIIEncodingSealed : ASCIIEncoding { } // Used by Encoding.ASCII for lazy initialization // The initialization code will not be run until a static member of the class is referenced internal static readonly ASCIIEncodingSealed s_default = new ASCIIEncodingSealed(); public ASCIIEncoding() : base(Encoding.CodePageASCII) { } internal override void SetDefaultFallbacks() { // For ASCIIEncoding we just use default replacement fallback this.encoderFallback = EncoderFallback.ReplacementFallback; this.decoderFallback = DecoderFallback.ReplacementFallback; } // WARNING: GetByteCount(string chars), GetBytes(string chars,...), and GetString(byte[] byteIndex...) // WARNING: have different variable names than EncodingNLS.cs, so this can't just be cut & pasted, // WARNING: or it'll break VB's way of calling these. // // The following methods are copied from EncodingNLS.cs. // Unfortunately EncodingNLS.cs is internal and we're public, so we have to re-implement them here. // These should be kept in sync for the following classes: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // Returns the number of bytes required to encode a range of characters in // a character array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount(char[] chars, int index, int count) { // Validate input parameters if (chars == null) throw new ArgumentNullException("chars", SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - index < count) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); // If no input, return 0, avoid fixed empty array problem if (count == 0) return 0; // Just call the pointer version fixed (char* pChars = chars) return GetByteCount(pChars + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount(String chars) { // Validate input if (chars==null) throw new ArgumentNullException("chars"); fixed (char* pChars = chars) return GetByteCount(pChars, chars.Length, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetByteCount(char* chars, int count) { // Validate Parameters if (chars == null) throw new ArgumentNullException("chars", SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); // Call it with empty encoder return GetByteCount(chars, count, null); } // Parent method is safe. // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding public override unsafe int GetBytes(String chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCount); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); int byteCount = bytes.Length - byteIndex; fixed (char* pChars = chars) fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes)) return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // Encodes a range of characters in a character array into a range of bytes // in a byte array. An exception occurs if the byte array is not large // enough to hold the complete encoding of the characters. The // GetByteCount method can be used to determine the exact number of // bytes that will be produced for a given range of characters. // Alternatively, the GetMaxByteCount method can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); // If nothing to encode return 0 if (charCount == 0) return 0; // Just call pointer version int byteCount = bytes.Length - byteIndex; fixed (char* pChars = chars) fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes)) // Remember that byteCount is # to decode, not size of array. return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); return GetBytes(chars, charCount, bytes, byteCount, null); } // Returns the number of characters produced by decoding a range of bytes // in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetCharCount(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); // If no input just return 0, fixed doesn't like 0 length arrays if (count == 0) return 0; // Just call pointer version fixed (byte* pBytes = bytes) return GetCharCount(pBytes + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetCharCount(byte* bytes, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); return GetCharCount(bytes, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if ( bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index); // If no input, return 0 & avoid fixed problem if (byteCount == 0) return 0; // Just call pointer version int charCount = chars.Length - charIndex; fixed (byte* pBytes = bytes) fixed (char* pChars = &MemoryMarshal.GetReference((Span<char>)chars)) // Remember that charCount is # to decode, not size of array return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); return GetChars(bytes, byteCount, chars, charCount, null); } // Returns a string containing the decoded representation of a range of // bytes in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe String GetString(byte[] bytes, int byteIndex, int byteCount) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); // Avoid problems with empty input buffer if (byteCount == 0) return String.Empty; fixed (byte* pBytes = bytes) return String.CreateStringFromEncoding( pBytes + byteIndex, byteCount, this); } // // End of standard methods copied from EncodingNLS.cs // // GetByteCount // Note: We start by assuming that the output will be the same as count. Having // an encoder or fallback may change that assumption internal override unsafe int GetByteCount(char* chars, int charCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetByteCount]count is negative"); Debug.Assert(chars != null, "[ASCIIEncoding.GetByteCount]chars is null"); // Assert because we shouldn't be able to have a null encoder. Debug.Assert(encoderFallback != null, "[ASCIIEncoding.GetByteCount]Attempting to use null fallback encoder"); char charLeftOver = (char)0; EncoderReplacementFallback fallback = null; // Start by assuming default count, then +/- for fallback characters char* charEnd = chars + charCount; // For fallback we may need a fallback buffer, we know we aren't default fallback. EncoderFallbackBuffer fallbackBuffer = null; char* charsForFallback; if (encoder != null) { charLeftOver = encoder._charLeftOver; Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate"); fallback = encoder.Fallback as EncoderReplacementFallback; // We mustn't have left over fallback data when counting if (encoder.InternalHasFallbackBuffer) { // We always need the fallback buffer in get bytes so we can flush any remaining ones if necessary fallbackBuffer = encoder.FallbackBuffer; if (fallbackBuffer.Remaining > 0 && encoder._throwOnOverflow) throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, this.EncodingName, encoder.Fallback.GetType())); // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false); } // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert Debug.Assert(!encoder._throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetByteCount]Expected empty fallback buffer"); } else { fallback = this.EncoderFallback as EncoderReplacementFallback; } // If we have an encoder AND we aren't using default fallback, // then we may have a complicated count. if (fallback != null && fallback.MaxCharCount == 1) { // Replacement fallback encodes surrogate pairs as two ?? (or two whatever), so return size is always // same as input size. // Note that no existing SBCS code pages map code points to supplimentary characters, so this is easy. // We could however have 1 extra byte if the last call had an encoder and a funky fallback and // if we don't use the funky fallback this time. // Do we have an extra char left over from last time? if (charLeftOver > 0) charCount++; return (charCount); } // Count is more complicated if you have a funky fallback // For fallback we may need a fallback buffer, we know we're not default fallback int byteCount = 0; // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate"); Debug.Assert(encoder != null, "[ASCIIEncoding.GetByteCount]Expected encoder"); // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false); // This will fallback a pair if *chars is a low surrogate charsForFallback = chars; // Avoid passing chars by reference to allow it to be enregistered fallbackBuffer.InternalFallback(charLeftOver, ref charsForFallback); chars = charsForFallback; } // 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' : fallbackBuffer.InternalGetNextChar()) != 0 || chars < charEnd) { // First unwind any fallback if (ch == 0) { // No fallback, just get next char ch = *chars; chars++; } // Check for fallback, this'll catch surrogate pairs too. // no chars >= 0x80 are allowed. if (ch > 0x7f) { if (fallbackBuffer == null) { // Initialize the buffer if (encoder == null) fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(charEnd - charCount, charEnd, encoder, false); } // Get Fallback charsForFallback = chars; // Avoid passing chars by reference to allow it to be enregistered fallbackBuffer.InternalFallback(ch, ref charsForFallback); chars = charsForFallback; continue; } // We'll use this one byteCount++; } Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[ASCIIEncoding.GetByteCount]Expected Empty fallback buffer"); return byteCount; } internal 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, "[ASCIIEncoding.GetBytes]bytes is null"); Debug.Assert(byteCount >= 0, "[ASCIIEncoding.GetBytes]byteCount is negative"); Debug.Assert(chars != null, "[ASCIIEncoding.GetBytes]chars is null"); Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetBytes]charCount is negative"); // Assert because we shouldn't be able to have a null encoder. Debug.Assert(encoderFallback != null, "[ASCIIEncoding.GetBytes]Attempting to use null encoder fallback"); // Get any left over characters char charLeftOver = (char)0; EncoderReplacementFallback fallback = null; // For fallback we may need a fallback buffer, we know we aren't default fallback. EncoderFallbackBuffer fallbackBuffer = null; char* charsForFallback; // prepare our end char* charEnd = chars + charCount; byte* byteStart = bytes; char* charStart = chars; if (encoder != null) { charLeftOver = encoder._charLeftOver; fallback = encoder.Fallback as EncoderReplacementFallback; // We mustn't have left over fallback data when counting if (encoder.InternalHasFallbackBuffer) { // We always need the fallback buffer in get bytes so we can flush any remaining ones if necessary fallbackBuffer = encoder.FallbackBuffer; if (fallbackBuffer.Remaining > 0 && encoder._throwOnOverflow) throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, this.EncodingName, encoder.Fallback.GetType())); // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true); } Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetBytes]leftover character should be high surrogate"); // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert Debug.Assert(!encoder._throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetBytes]Expected empty fallback buffer"); } else { fallback = this.EncoderFallback as EncoderReplacementFallback; } // See if we do the fast default or slightly slower fallback if (fallback != null && fallback.MaxCharCount == 1) { // Fast version char cReplacement = fallback.DefaultString[0]; // Check for replacements in range, otherwise fall back to slow version. if (cReplacement <= (char)0x7f) { // We should have exactly as many output bytes as input bytes, unless there's a left // over character, in which case we may need one more. // If we had a left over character will have to add a ? (This happens if they had a funky // fallback last time, but not this time.) (We can't spit any out though // because with fallback encoder each surrogate is treated as a seperate code point) if (charLeftOver > 0) { // Have to have room // Throw even if doing no throw version because this is just 1 char, // so buffer will never be big enough if (byteCount == 0) ThrowBytesOverflow(encoder, true); // This'll make sure we still have more room and also make sure our return value is correct. *(bytes++) = (byte)cReplacement; byteCount--; // We used one of the ones we were counting. } // This keeps us from overrunning our output buffer if (byteCount < charCount) { // Throw or make buffer smaller? ThrowBytesOverflow(encoder, byteCount < 1); // Just use what we can charEnd = chars + byteCount; } // We just do a quick copy while (chars < charEnd) { char ch2 = *(chars++); if (ch2 >= 0x0080) *(bytes++) = (byte)cReplacement; else *(bytes++) = unchecked((byte)(ch2)); } // Clear encoder if (encoder != null) { encoder._charLeftOver = (char)0; encoder._charsUsed = (int)(chars - charStart); } return (int)(bytes - byteStart); } } // Slower version, have to do real fallback. // prepare our end byte* byteEnd = bytes + byteCount; // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { // Initialize the buffer Debug.Assert(encoder != null, "[ASCIIEncoding.GetBytes]Expected non null encoder if we have surrogate left over"); fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(chars, charEnd, encoder, true); // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback // This will fallback a pair if *chars is a low surrogate charsForFallback = chars; // Avoid passing chars by reference to allow it to be enregistered fallbackBuffer.InternalFallback(charLeftOver, ref charsForFallback); chars = charsForFallback; } // 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' : fallbackBuffer.InternalGetNextChar()) != 0 || chars < charEnd) { // First unwind any fallback if (ch == 0) { // No fallback, just get next char ch = *chars; chars++; } // Check for fallback, this'll catch surrogate pairs too. // All characters >= 0x80 must fall back. if (ch > 0x7f) { // Initialize the buffer if (fallbackBuffer == null) { if (encoder == null) fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(charEnd - charCount, charEnd, encoder, true); } // Get Fallback charsForFallback = chars; // Avoid passing chars by reference to allow it to be enregistered fallbackBuffer.InternalFallback(ch, ref charsForFallback); chars = charsForFallback; // Go ahead & continue (& do the fallback) continue; } // We'll use this one // Bounds check if (bytes >= byteEnd) { // didn't use this char, we'll throw or use buffer if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false) { Debug.Assert(chars > charStart || bytes == byteStart, "[ASCIIEncoding.GetBytes]Expected chars to have advanced already."); chars--; // don't use last char } else fallbackBuffer.MovePrevious(); // Are we throwing or using buffer? ThrowBytesOverflow(encoder, bytes == byteStart); // throw? break; // don't throw, stop } // Go ahead and add it *bytes = unchecked((byte)ch); bytes++; } // Need to do encoder stuff if (encoder != null) { // Fallback stuck it in encoder if necessary, but we have to clear MustFlush cases if (fallbackBuffer != null && !fallbackBuffer.bUsedEncoder) // Clear it in case of MustFlush encoder._charLeftOver = (char)0; // Set our chars used count encoder._charsUsed = (int)(chars - charStart); } Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 || (encoder != null && !encoder._throwOnOverflow), "[ASCIIEncoding.GetBytes]Expected Empty fallback buffer at end"); return (int)(bytes - byteStart); } // This is internal and called by something else, internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder) { // Just assert, we're called internally so these should be safe, checked already Debug.Assert(bytes != null, "[ASCIIEncoding.GetCharCount]bytes is null"); Debug.Assert(count >= 0, "[ASCIIEncoding.GetCharCount]byteCount is negative"); // ASCII doesn't do best fit, so don't have to check for it, find out which decoder fallback we're using DecoderReplacementFallback fallback = null; if (decoder == null) fallback = this.DecoderFallback as DecoderReplacementFallback; else { fallback = decoder.Fallback as DecoderReplacementFallback; Debug.Assert(!decoder._throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetCharCount]Expected empty fallback buffer"); } if (fallback != null && fallback.MaxCharCount == 1) { // Just return length, SBCS stay the same length because they don't map to surrogate // pairs and we don't have a decoder fallback. return count; } // Only need decoder fallback buffer if not using default replacement fallback, no best fit for ASCII DecoderFallbackBuffer fallbackBuffer = null; // Have to do it the hard way. // Assume charCount will be == count int charCount = count; byte[] byteBuffer = new byte[1]; // Do it our fast way byte* byteEnd = bytes + count; // Quick loop while (bytes < byteEnd) { // Faster if don't use *bytes++; byte b = *bytes; bytes++; // If unknown we have to do fallback count if (b >= 0x80) { if (fallbackBuffer == null) { if (decoder == null) fallbackBuffer = this.DecoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; fallbackBuffer.InternalInitialize(byteEnd - count, null); } // Use fallback buffer byteBuffer[0] = b; charCount--; // Have to unreserve the one we already allocated for b charCount += fallbackBuffer.InternalFallback(byteBuffer, bytes); } } // Fallback buffer must be empty Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[ASCIIEncoding.GetCharCount]Expected Empty fallback buffer"); // Converted sequence is same length as input return charCount; } internal override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS decoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(bytes != null, "[ASCIIEncoding.GetChars]bytes is null"); Debug.Assert(byteCount >= 0, "[ASCIIEncoding.GetChars]byteCount is negative"); Debug.Assert(chars != null, "[ASCIIEncoding.GetChars]chars is null"); Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetChars]charCount is negative"); // Do it fast way if using ? replacement fallback byte* byteEnd = bytes + byteCount; byte* byteStart = bytes; char* charStart = chars; // Note: ASCII doesn't do best fit, but we have to fallback if they use something > 0x7f // Only need decoder fallback buffer if not using ? fallback. // ASCII doesn't do best fit, so don't have to check for it, find out which decoder fallback we're using DecoderReplacementFallback fallback = null; char* charsForFallback; if (decoder == null) fallback = this.DecoderFallback as DecoderReplacementFallback; else { fallback = decoder.Fallback as DecoderReplacementFallback; Debug.Assert(!decoder._throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetChars]Expected empty fallback buffer"); } if (fallback != null && fallback.MaxCharCount == 1) { // Try it the fast way char replacementChar = fallback.DefaultString[0]; // Need byteCount chars, otherwise too small buffer if (charCount < byteCount) { // Need at least 1 output byte, throw if must throw ThrowCharsOverflow(decoder, charCount < 1); // Not throwing, use what we can byteEnd = bytes + charCount; } // Quick loop, just do '?' replacement because we don't have fallbacks for decodings. while (bytes < byteEnd) { byte b = *(bytes++); if (b >= 0x80) // This is an invalid byte in the ASCII encoding. *(chars++) = replacementChar; else *(chars++) = unchecked((char)b); } // bytes & chars used are the same if (decoder != null) decoder._bytesUsed = (int)(bytes - byteStart); return (int)(chars - charStart); } // Slower way's going to need a fallback buffer DecoderFallbackBuffer fallbackBuffer = null; byte[] byteBuffer = new byte[1]; char* charEnd = chars + charCount; // Not quite so fast loop while (bytes < byteEnd) { // Faster if don't use *bytes++; byte b = *(bytes); bytes++; if (b >= 0x80) { // This is an invalid byte in the ASCII encoding. if (fallbackBuffer == null) { if (decoder == null) fallbackBuffer = this.DecoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; fallbackBuffer.InternalInitialize(byteEnd - byteCount, charEnd); } // Use fallback buffer byteBuffer[0] = b; // Note that chars won't get updated unless this succeeds charsForFallback = chars; // Avoid passing chars by reference to allow it to be enregistered bool fallbackResult = fallbackBuffer.InternalFallback(byteBuffer, bytes, ref charsForFallback); chars = charsForFallback; if (!fallbackResult) { // May or may not throw, but we didn't get this byte Debug.Assert(bytes > byteStart || chars == charStart, "[ASCIIEncoding.GetChars]Expected bytes to have advanced already (fallback case)"); bytes--; // unused byte fallbackBuffer.InternalReset(); // Didn't fall this back ThrowCharsOverflow(decoder, chars == charStart); // throw? break; // don't throw, but stop loop } } else { // Make sure we have buffer space if (chars >= charEnd) { Debug.Assert(bytes > byteStart || chars == charStart, "[ASCIIEncoding.GetChars]Expected bytes to have advanced already (normal case)"); bytes--; // unused byte ThrowCharsOverflow(decoder, chars == charStart); // throw? break; // don't throw, but stop loop } *(chars) = unchecked((char)b); chars++; } } // Might have had decoder fallback stuff. if (decoder != null) decoder._bytesUsed = (int)(bytes - byteStart); // Expect Empty fallback buffer for GetChars Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[ASCIIEncoding.GetChars]Expected Empty fallback buffer"); return (int)(chars - charStart); } public override int GetMaxByteCount(int charCount) { if (charCount < 0) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); // 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; // 1 to 1 for most characters. Only surrogates with fallbacks have less. if (byteCount > 0x7fffffff) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GetByteCountOverflow); return (int)byteCount; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); // Just return length, SBCS stay the same length because they don't map to surrogate long charCount = (long)byteCount; // 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(nameof(byteCount), SR.ArgumentOutOfRange_GetCharCountOverflow); return (int)charCount; } // True if and only if the encoding only uses single byte code points. (Ie, ASCII, 1252, etc) public override bool IsSingleByte { get { return true; } } public override Decoder GetDecoder() { return new DecoderNLS(this); } public override Encoder GetEncoder() { return new EncoderNLS(this); } } }
using System; using System.Collections.Specialized; using System.Net; using Newtonsoft.Json; using SteamKit2; namespace SteamTrade.TradeWebAPI { /// <summary> /// This class provides the interface into the Web API for trading on the /// Steam network. /// </summary> public class TradeSession { private const string SteamCommunityDomain = "steamcommunity.com"; private const string SteamTradeUrl = "http://steamcommunity.com/trade/{0}/"; private string sessionIdEsc; private string baseTradeURL; private CookieContainer cookies; private readonly string steamLogin; private readonly string sessionId; private readonly SteamID OtherSID; /// <summary> /// Initializes a new instance of the <see cref="TradeSession"/> class. /// </summary> /// <param name="sessionId">The session id.</param> /// <param name="steamLogin">The current steam login.</param> /// <param name="otherSid">The Steam id of the other trading partner.</param> public TradeSession(string sessionId, string steamLogin, SteamID otherSid) { this.sessionId = sessionId; this.steamLogin = steamLogin; OtherSID = otherSid; Init(); } #region Trade status properties /// <summary> /// Gets the LogPos number of the current trade. /// </summary> /// <remarks>This is not automatically updated by this class.</remarks> internal int LogPos { get; set; } /// <summary> /// Gets the version number of the current trade. This increments on /// every item added or removed from a trade. /// </summary> /// <remarks>This is not automatically updated by this class.</remarks> internal int Version { get; set; } #endregion Trade status properties #region Trade Web API command methods /// <summary> /// Gets the trade status. /// </summary> /// <returns>A deserialized JSON object into <see cref="TradeStatus"/></returns> /// <remarks> /// This is the main polling method for trading and must be done at a /// periodic rate (probably around 1 second). /// </remarks> internal TradeStatus GetStatus() { var data = new NameValueCollection (); data.Add ("sessionid", sessionIdEsc); data.Add ("logpos", "" + LogPos); data.Add ("version", "" + Version); string response = Fetch (baseTradeURL + "tradestatus", "POST", data); return JsonConvert.DeserializeObject<TradeStatus> (response); } /// <summary> /// Gets the foriegn inventory. /// </summary> /// <param name="otherId">The other id.</param> /// <returns>A dynamic JSON object.</returns> internal dynamic GetForiegnInventory(SteamID otherId) { return GetForiegnInventory(otherId, 440, 2); } internal dynamic GetForiegnInventory(SteamID otherId, long contextId, int appid) { try { string path = string.Format("foreigninventory/?sessionid={0}&steamid={1}&appid={2}&contextid={3}", sessionIdEsc, otherId.ConvertToUInt64(), appid, contextId); string response = Fetch(baseTradeURL + path, "GET"); return JsonConvert.DeserializeObject(response); } catch (Exception) { return JsonConvert.DeserializeObject("{\"success\":\"false\"}"); } } /// <summary> /// Sends a message to the user over the trade chat. /// </summary> internal bool SendMessageWebCmd(string msg) { var data = new NameValueCollection (); data.Add ("sessionid", sessionIdEsc); data.Add ("message", msg); data.Add ("logpos", "" + LogPos); data.Add ("version", "" + Version); string result = Fetch (baseTradeURL + "chat", "POST", data); dynamic json = JsonConvert.DeserializeObject(result); return IsSuccess(json); } /// <summary> /// Adds a specified itom by its itemid. Since each itemid is /// unique to each item, you'd first have to find the item, or /// use AddItemByDefindex instead. /// </summary> /// <returns> /// Returns false if the item doesn't exist in the Bot's inventory, /// and returns true if it appears the item was added. /// </returns> internal bool AddItemWebCmd(ulong itemid, int slot,int appid,long contextid) { var data = new NameValueCollection (); data.Add ("sessionid", sessionIdEsc); data.Add("appid", "" + appid); data.Add ("contextid", "" + contextid); data.Add ("itemid", "" + itemid); data.Add ("slot", "" + slot); string result = Fetch(baseTradeURL + "additem", "POST", data); dynamic json = JsonConvert.DeserializeObject(result); return IsSuccess(json); } /// <summary> /// Removes an item by its itemid. Read AddItem about itemids. /// Returns false if the item isn't in the offered items, or /// true if it appears it succeeded. /// </summary> internal bool RemoveItemWebCmd(ulong itemid, int slot, int appid, long contextid) { var data = new NameValueCollection (); data.Add ("sessionid", sessionIdEsc); data.Add("appid", "" + appid); data.Add("contextid", "" + contextid); data.Add ("itemid", "" + itemid); data.Add ("slot", "" + slot); string result = Fetch (baseTradeURL + "removeitem", "POST", data); dynamic json = JsonConvert.DeserializeObject(result); return IsSuccess(json); } /// <summary> /// Sets the bot to a ready status. /// </summary> internal bool SetReadyWebCmd(bool ready) { var data = new NameValueCollection (); data.Add ("sessionid", sessionIdEsc); data.Add ("ready", ready ? "true" : "false"); data.Add ("version", "" + Version); string result = Fetch (baseTradeURL + "toggleready", "POST", data); dynamic json = JsonConvert.DeserializeObject(result); return IsSuccess(json); } /// <summary> /// Accepts the trade from the user. Returns a deserialized /// JSON object. /// </summary> internal bool AcceptTradeWebCmd() { var data = new NameValueCollection (); data.Add ("sessionid", sessionIdEsc); data.Add ("version", "" + Version); string response = Fetch (baseTradeURL + "confirm", "POST", data); dynamic json = JsonConvert.DeserializeObject(response); return IsSuccess(json); } /// <summary> /// Cancel the trade. This calls the OnClose handler, as well. /// </summary> internal bool CancelTradeWebCmd () { var data = new NameValueCollection (); data.Add ("sessionid", sessionIdEsc); string result = Fetch (baseTradeURL + "cancel", "POST", data); dynamic json = JsonConvert.DeserializeObject(result); return IsSuccess(json); } private bool IsSuccess(dynamic json) { if(json == null) return false; try { //Sometimes, the response looks like this: {"success":false,"results":{"success":11}} //I believe this is Steam's way of asking the trade window (which is actually a webpage) to refresh, following a large successful update return (json.success == "true" || (json.results != null && json.results.success == "11")); } catch(Exception) { return false; } } #endregion Trade Web API command methods string Fetch (string url, string method, NameValueCollection data = null) { return SteamWeb.Fetch (url, method, data, cookies); } private void Init() { sessionIdEsc = Uri.UnescapeDataString(sessionId); Version = 1; cookies = new CookieContainer(); cookies.Add (new Cookie ("sessionid", sessionId, String.Empty, SteamCommunityDomain)); cookies.Add (new Cookie ("steamLogin", steamLogin, String.Empty, SteamCommunityDomain)); baseTradeURL = String.Format (SteamTradeUrl, OtherSID.ConvertToUInt64()); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics.EngineV1; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Traits = Microsoft.CodeAnalysis.Test.Utilities.Traits; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics { public class DiagnosticStateTests : TestBase { [Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)] public async Task SerializationTest_Document() { using (var workspace = new TestWorkspace(TestExportProvider.ExportProviderWithCSharpAndVisualBasic, workspaceKind: "DiagnosticTest")) { var utcTime = DateTime.UtcNow; var version1 = VersionStamp.Create(utcTime); var version2 = VersionStamp.Create(utcTime.AddDays(1)); var document = workspace.CurrentSolution.AddProject("TestProject", "TestProject", LanguageNames.CSharp).AddDocument("TestDocument", ""); var diagnostics = new[] { new DiagnosticData( "test1", "Test", "test1 message", "test1 message format", DiagnosticSeverity.Info, DiagnosticSeverity.Info, false, 1, ImmutableArray<string>.Empty, ImmutableDictionary<string, string>.Empty, workspace, document.Project.Id, new DiagnosticDataLocation(document.Id, new TextSpan(10, 20), "originalFile1", 30, 30, 40, 40, "mappedFile1", 10, 10, 20, 20)), new DiagnosticData( "test2", "Test", "test2 message", "test2 message format", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 0, ImmutableArray.Create<string>("Test2"), ImmutableDictionary<string, string>.Empty.Add("propertyKey", "propertyValue"), workspace, document.Project.Id, new DiagnosticDataLocation(document.Id, new TextSpan(30, 40), "originalFile2", 70, 70, 80, 80, "mappedFile2", 50, 50, 60, 60), title: "test2 title", description: "test2 description", helpLink: "http://test2link"), new DiagnosticData( "test3", "Test", "test3 message", "test3 message format", DiagnosticSeverity.Error, DiagnosticSeverity.Warning, true, 2, ImmutableArray.Create<string>("Test3", "Test3_2"), ImmutableDictionary<string, string>.Empty.Add("p1Key", "p1Value").Add("p2Key", "p2Value"), workspace, document.Project.Id, new DiagnosticDataLocation(document.Id, new TextSpan(50, 60), "originalFile3", 110, 110, 120, 120, "mappedFile3", 90, 90, 100, 100), title: "test3 title", description: "test3 description", helpLink: "http://test3link"), }; var original = new DiagnosticIncrementalAnalyzer.AnalysisData(version1, version2, diagnostics.ToImmutableArray()); var state = new DiagnosticIncrementalAnalyzer.DiagnosticState("Test", VersionStamp.Default, LanguageNames.CSharp); await state.PersistAsync(document, original, CancellationToken.None); var recovered = await state.TryGetExistingDataAsync(document, CancellationToken.None); Assert.Equal(original.TextVersion, recovered.TextVersion); Assert.Equal(original.DataVersion, recovered.DataVersion); AssertDiagnostics(original.Items, recovered.Items); } } [Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)] public async Task SerializationTest_Project() { using (var workspace = new TestWorkspace(TestExportProvider.ExportProviderWithCSharpAndVisualBasic, workspaceKind: "DiagnosticTest")) { var utcTime = DateTime.UtcNow; var version1 = VersionStamp.Create(utcTime); var version2 = VersionStamp.Create(utcTime.AddDays(1)); var document = workspace.CurrentSolution.AddProject("TestProject", "TestProject", LanguageNames.CSharp).AddDocument("TestDocument", ""); var diagnostics = new[] { new DiagnosticData( "test1", "Test", "test1 message", "test1 message format", DiagnosticSeverity.Info, DiagnosticSeverity.Info, false, 1, ImmutableArray<string>.Empty, ImmutableDictionary<string, string>.Empty, workspace, document.Project.Id, description: "test1 description", helpLink: "http://test1link"), new DiagnosticData( "test2", "Test", "test2 message", "test2 message format", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 0, ImmutableArray.Create<string>("Test2"), ImmutableDictionary<string, string>.Empty.Add("p1Key", "p2Value"), workspace, document.Project.Id), new DiagnosticData( "test3", "Test", "test3 message", "test3 message format", DiagnosticSeverity.Error, DiagnosticSeverity.Warning, true, 2, ImmutableArray.Create<string>("Test3", "Test3_2"), ImmutableDictionary<string, string>.Empty.Add("p2Key", "p2Value").Add("p1Key", "p1Value"), workspace, document.Project.Id, description: "test3 description", helpLink: "http://test3link"), }; var original = new DiagnosticIncrementalAnalyzer.AnalysisData(version1, version2, diagnostics.ToImmutableArray()); var state = new DiagnosticIncrementalAnalyzer.DiagnosticState("Test", VersionStamp.Default, LanguageNames.CSharp); await state.PersistAsync(document.Project, original, CancellationToken.None); var recovered = await state.TryGetExistingDataAsync(document.Project, CancellationToken.None); Assert.Equal(original.TextVersion, recovered.TextVersion); Assert.Equal(original.DataVersion, recovered.DataVersion); AssertDiagnostics(original.Items, recovered.Items); } } [WorkItem(6104)] [Fact] public void DiagnosticEquivalence() { #if DEBUG var source = @"class C { static int F(string s) { return 1; } static int x = F(new { }); static int y = F(new { A = 1 }); }"; var tree = SyntaxFactory.ParseSyntaxTree(source); var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, concurrentBuild: false); var compilation = CSharpCompilation.Create(GetUniqueName(), new[] { tree }, new[] { MscorlibRef }, options); var model = compilation.GetSemanticModel(tree); // Each call to GetDiagnostics will bind field initializers // (see https://github.com/dotnet/roslyn/issues/6264). var diagnostics1 = model.GetDiagnostics().ToArray(); var diagnostics2 = model.GetDiagnostics().ToArray(); diagnostics1.Verify( // (4,22): error CS1503: Argument 1: cannot convert from '<empty anonymous type>' to 'string' // static int x = F(new { }); Diagnostic(1503, "new { }").WithArguments("1", "<empty anonymous type>", "string").WithLocation(4, 22), // (5,22): error CS1503: Argument 1: cannot convert from '<anonymous type: int A>' to 'string' // static int y = F(new { A = 1 }); Diagnostic(1503, "new { A = 1 }").WithArguments("1", "<anonymous type: int A>", "string").WithLocation(5, 22)); Assert.NotSame(diagnostics1[0], diagnostics2[0]); Assert.NotSame(diagnostics1[1], diagnostics2[1]); Assert.Equal(diagnostics1, diagnostics2); Assert.True(DiagnosticIncrementalAnalyzer.AreEquivalent(diagnostics1, diagnostics2)); // Verify that not all collections are treated as equivalent. diagnostics1 = new[] { diagnostics1[0] }; diagnostics2 = new[] { diagnostics2[1] }; Assert.NotEqual(diagnostics1, diagnostics2); Assert.False(DiagnosticIncrementalAnalyzer.AreEquivalent(diagnostics1, diagnostics2)); #endif } private static void AssertDiagnostics(ImmutableArray<DiagnosticData> items1, ImmutableArray<DiagnosticData> items2) { Assert.Equal(items1.Length, items2.Length); for (var i = 0; i < items1.Length; i++) { AssertDiagnostics(items1[i], items2[i]); } } private static void AssertDiagnostics(DiagnosticData item1, DiagnosticData item2) { Assert.Equal(item1.Id, item2.Id); Assert.Equal(item1.Category, item2.Category); Assert.Equal(item1.Message, item2.Message); Assert.Equal(item1.ENUMessageForBingSearch, item2.ENUMessageForBingSearch); Assert.Equal(item1.Severity, item2.Severity); Assert.Equal(item1.IsEnabledByDefault, item2.IsEnabledByDefault); Assert.Equal(item1.WarningLevel, item2.WarningLevel); Assert.Equal(item1.DefaultSeverity, item2.DefaultSeverity); Assert.Equal(item1.CustomTags.Count, item2.CustomTags.Count); for (var j = 0; j < item1.CustomTags.Count; j++) { Assert.Equal(item1.CustomTags[j], item2.CustomTags[j]); } Assert.Equal(item1.Properties.Count, item2.Properties.Count); Assert.True(item1.Properties.SetEquals(item2.Properties)); Assert.Equal(item1.Workspace, item2.Workspace); Assert.Equal(item1.ProjectId, item2.ProjectId); Assert.Equal(item1.DocumentId, item2.DocumentId); Assert.Equal(item1.HasTextSpan, item2.HasTextSpan); if (item1.HasTextSpan) { Assert.Equal(item1.TextSpan, item2.TextSpan); } Assert.Equal(item1.DataLocation?.MappedFilePath, item2.DataLocation?.MappedFilePath); Assert.Equal(item1.DataLocation?.MappedStartLine, item2.DataLocation?.MappedStartLine); Assert.Equal(item1.DataLocation?.MappedStartColumn, item2.DataLocation?.MappedStartColumn); Assert.Equal(item1.DataLocation?.MappedEndLine, item2.DataLocation?.MappedEndLine); Assert.Equal(item1.DataLocation?.MappedEndColumn, item2.DataLocation?.MappedEndColumn); Assert.Equal(item1.DataLocation?.OriginalFilePath, item2.DataLocation?.OriginalFilePath); Assert.Equal(item1.DataLocation?.OriginalStartLine, item2.DataLocation?.OriginalStartLine); Assert.Equal(item1.DataLocation?.OriginalStartColumn, item2.DataLocation?.OriginalStartColumn); Assert.Equal(item1.DataLocation?.OriginalEndLine, item2.DataLocation?.OriginalEndLine); Assert.Equal(item1.DataLocation?.OriginalEndColumn, item2.DataLocation?.OriginalEndColumn); Assert.Equal(item1.Description, item2.Description); Assert.Equal(item1.HelpLink, item2.HelpLink); } [ExportWorkspaceServiceFactory(typeof(IPersistentStorageService), "DiagnosticTest"), Shared] public class PersistentStorageServiceFactory : IWorkspaceServiceFactory { public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { return new Service(); } public class Service : IPersistentStorageService { private readonly Storage _instance = new Storage(); IPersistentStorage IPersistentStorageService.GetStorage(Solution solution) { return _instance; } internal class Storage : IPersistentStorage { private readonly Dictionary<object, Stream> _map = new Dictionary<object, Stream>(); public Task<Stream> ReadStreamAsync(string name, CancellationToken cancellationToken = default(CancellationToken)) { var stream = _map[name]; stream.Position = 0; return Task.FromResult(stream); } public Task<Stream> ReadStreamAsync(Project project, string name, CancellationToken cancellationToken = default(CancellationToken)) { var stream = _map[Tuple.Create(project, name)]; stream.Position = 0; return Task.FromResult(stream); } public Task<Stream> ReadStreamAsync(Document document, string name, CancellationToken cancellationToken = default(CancellationToken)) { var stream = _map[Tuple.Create(document, name)]; stream.Position = 0; return Task.FromResult(stream); } public Task<bool> WriteStreamAsync(string name, Stream stream, CancellationToken cancellationToken = default(CancellationToken)) { _map[name] = new MemoryStream(); stream.CopyTo(_map[name]); return SpecializedTasks.True; } public Task<bool> WriteStreamAsync(Project project, string name, Stream stream, CancellationToken cancellationToken = default(CancellationToken)) { _map[Tuple.Create(project, name)] = new MemoryStream(); stream.CopyTo(_map[Tuple.Create(project, name)]); return SpecializedTasks.True; } public Task<bool> WriteStreamAsync(Document document, string name, Stream stream, CancellationToken cancellationToken = default(CancellationToken)) { _map[Tuple.Create(document, name)] = new MemoryStream(); stream.CopyTo(_map[Tuple.Create(document, name)]); return SpecializedTasks.True; } protected virtual void Dispose(bool disposing) { } public void Dispose() { Dispose(true); } } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEngine; using UnityEditor.Experimental.VFX; using UnityEngine.Experimental.VFX; using UnityEngine.Profiling; namespace UnityEditor.VFX { class VFXObject : ScriptableObject { public Action<VFXObject> onModified; void OnValidate() { Modified(); } public void Modified() { if (onModified != null) onModified(this); } } [Serializable] abstract class VFXModel : VFXObject { public enum InvalidationCause { kStructureChanged, // Model structure (hierarchy) has changed kParamChanged, // Some parameter values have changed kSettingChanged, // A setting value has changed kSpaceChanged, // Space has been changed kConnectionChanged, // Connection have changed kExpressionInvalidated, // No direct change to the model but a change in connection was propagated from the parents kExpressionGraphChanged,// Expression graph must be recomputed kUIChanged, // UI stuff has changed } public new virtual string name { get { return string.Empty; } } public virtual string libraryName { get { return name; } } public delegate void InvalidateEvent(VFXModel model, InvalidationCause cause); public event InvalidateEvent onInvalidateDelegate; protected VFXModel() { m_UICollapsed = true; } public virtual void OnEnable() { if (m_Children == null) m_Children = new List<VFXModel>(); else { int nbRemoved = m_Children.RemoveAll(c => c == null);// Remove bad references if any if (nbRemoved > 0) Debug.Log(String.Format("Remove {0} child(ren) that couldnt be deserialized from {1} of type {2}", nbRemoved, name, GetType())); } } public virtual void Sanitize(int version) {} public virtual void OnUnknownChange() { } public virtual void CollectDependencies(HashSet<ScriptableObject> objs) { foreach (var child in children) { objs.Add(child); child.CollectDependencies(objs); } } protected virtual void OnInvalidate(VFXModel model, InvalidationCause cause) { if (onInvalidateDelegate != null) { Profiler.BeginSample("VFXEditor.OnInvalidateDelegate"); try { onInvalidateDelegate(model, cause); } finally { Profiler.EndSample(); } } } protected virtual void OnAdded() {} protected virtual void OnRemoved() {} public virtual bool AcceptChild(VFXModel model, int index = -1) { return false; } public void AddChild(VFXModel model, int index = -1, bool notify = true) { int realIndex = index == -1 ? m_Children.Count : index; if (model.m_Parent != this || realIndex != GetIndex(model)) { if (!AcceptChild(model, index)) throw new ArgumentException("Cannot attach " + model + " to " + this); model.Detach(notify && model.m_Parent != this); // Dont notify if the owner is already this to avoid double invalidation realIndex = index == -1 ? m_Children.Count : index; // Recompute as the child may have been removed m_Children.Insert(realIndex, model); model.m_Parent = this; model.OnAdded(); if (notify) Invalidate(InvalidationCause.kStructureChanged); } } public void RemoveChild(VFXModel model, bool notify = true) { if (model.m_Parent != this) return; model.OnRemoved(); m_Children.Remove(model); model.m_Parent = null; if (notify) Invalidate(InvalidationCause.kStructureChanged); } public void RemoveAllChildren(bool notify = true) { while (m_Children.Count > 0) RemoveChild(m_Children[m_Children.Count - 1], notify); } public VFXModel GetParent() { return m_Parent; } public T GetFirstOfType<T>() where T : VFXModel { if (this is T) return this as T; var parent = GetParent(); if (parent == null) return null; return parent.GetFirstOfType<T>(); } public void Attach(VFXModel parent, bool notify = true) { parent.AddChild(this, -1, notify); } public void Detach(bool notify = true) { if (m_Parent == null) return; m_Parent.RemoveChild(this, notify); } public IEnumerable<VFXModel> children { get { return m_Children; } } public VFXModel this[int index] { get { return m_Children[index]; } } public Vector2 position { get { return m_UIPosition; } set { if (m_UIPosition != value) { m_UIPosition = value; Invalidate(InvalidationCause.kUIChanged); } } } public bool collapsed { get { return m_UICollapsed; } set { if (m_UICollapsed != value) { m_UICollapsed = value; Invalidate(InvalidationCause.kUIChanged); } } } public bool superCollapsed { get { return m_UISuperCollapsed; } set { if (m_UISuperCollapsed != value) { m_UISuperCollapsed = value; Invalidate(InvalidationCause.kUIChanged); } } } public int GetNbChildren() { return m_Children.Count; } public int GetIndex(VFXModel child) { return m_Children.IndexOf(child); } public void SetSettingValue(string name, object value) { SetSettingValue(name, value, true); } protected void SetSettingValue(string name, object value, bool notify) { var field = GetType().GetField(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (field == null) { throw new ArgumentException(string.Format("Unable to find field {0} in {1}", name, GetType().ToString())); } var currentValue = field.GetValue(this); if (currentValue != value) { field.SetValue(this, value); if (notify) { Invalidate(InvalidationCause.kSettingChanged); } } } public void Invalidate(InvalidationCause cause) { Modified(); string sampleName = GetType().Name + "-" + name + "-" + cause; Profiler.BeginSample("VFXEditor.Invalidate" + sampleName); try { Invalidate(this, cause); } finally { Profiler.EndSample(); } } protected virtual void Invalidate(VFXModel model, InvalidationCause cause) { OnInvalidate(model, cause); if (m_Parent != null) m_Parent.Invalidate(model, cause); } public IEnumerable<FieldInfo> GetSettings(bool listHidden, VFXSettingAttribute.VisibleFlags flags = VFXSettingAttribute.VisibleFlags.All) { return GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Where(f => { var attrArray = f.GetCustomAttributes(typeof(VFXSettingAttribute), true); if (attrArray.Length == 1) { var attr = attrArray[0] as VFXSettingAttribute; if (listHidden) return true; return (attr.visibleFlags & flags) != 0 && !filteredOutSettings.Contains(f.Name); } return false; }); } static public VFXExpression ConvertSpace(VFXExpression input, VFXSlot targetSlot, VFXCoordinateSpace space) { if (targetSlot.spaceable) { if (targetSlot.space != space) { var spaceType = targetSlot.GetSpaceTransformationType(); input = ConvertSpace(input, spaceType, space); } } return input; } static protected VFXExpression ConvertSpace(VFXExpression input, SpaceableType spaceType, VFXCoordinateSpace space) { VFXExpression matrix = null; if (space == VFXCoordinateSpace.Local) { matrix = VFXBuiltInExpression.WorldToLocal; } else if (space == VFXCoordinateSpace.World) { matrix = VFXBuiltInExpression.LocalToWorld; } else { throw new InvalidOperationException("Cannot Convert to unknown space"); } if (spaceType == SpaceableType.Position) { input = new VFXExpressionTransformPosition(matrix, input); } else if (spaceType == SpaceableType.Direction) { input = new VFXExpressionTransformDirection(matrix, input); } else if (spaceType == SpaceableType.Matrix) { input = new VFXExpressionTransformMatrix(matrix, input); } else if (spaceType == SpaceableType.Vector) { input = new VFXExpressionTransformVector(matrix, input); } else { //Not a transformable subSlot } return input; } protected virtual IEnumerable<string> filteredOutSettings { get { return Enumerable.Empty<string>(); } } public VisualEffectResource GetResource() { var graph = GetGraph(); if (graph != null) return graph.visualEffectResource; return null; } public VFXGraph GetGraph() { var graph = this as VFXGraph; if (graph != null) return graph; var parent = GetParent(); if (parent != null) return parent.GetGraph(); return null; } public static void UnlinkModel(VFXModel model, bool notify = true) { if (model is IVFXSlotContainer) { var slotContainer = (IVFXSlotContainer)model; VFXSlot slotToClean = null; do { slotToClean = slotContainer.inputSlots.Concat(slotContainer.outputSlots).FirstOrDefault(o => o.HasLink(true)); if (slotToClean) slotToClean.UnlinkAll(true, notify); } while (slotToClean != null); } } public static void RemoveModel(VFXModel model, bool notify = true) { VFXGraph graph = model.GetGraph(); if (graph != null) graph.UIInfos.Sanitize(graph); // Remove reference from groupInfos UnlinkModel(model); model.Detach(notify); } public static void ReplaceModel(VFXModel dst, VFXModel src, bool notify = true) { // UI dst.m_UIPosition = src.m_UIPosition; dst.m_UICollapsed = src.m_UICollapsed; dst.m_UISuperCollapsed = src.m_UISuperCollapsed; if (notify) dst.Invalidate(InvalidationCause.kUIChanged); VFXGraph graph = src.GetGraph(); if (graph != null && graph.UIInfos != null && graph.UIInfos.groupInfos != null) { // Update group nodes foreach (var groupInfo in graph.UIInfos.groupInfos) if (groupInfo.contents != null) for (int i = 0; i < groupInfo.contents.Length; ++i) if (groupInfo.contents[i].model == src) groupInfo.contents[i].model = dst; } if (dst is VFXBlock && src is VFXBlock) { ((VFXBlock)dst).enabled = ((VFXBlock)src).enabled; } // Unlink everything UnlinkModel(src); // Replace model var parent = src.GetParent(); int index = parent.GetIndex(src); src.Detach(notify); if (parent) parent.AddChild(dst, index, notify); } [SerializeField] protected VFXModel m_Parent; [SerializeField] protected List<VFXModel> m_Children; [SerializeField] protected Vector2 m_UIPosition; [SerializeField] protected bool m_UICollapsed; [SerializeField] protected bool m_UISuperCollapsed; } abstract class VFXModel<ParentType, ChildrenType> : VFXModel where ParentType : VFXModel where ChildrenType : VFXModel { public override bool AcceptChild(VFXModel model, int index = -1) { return index >= -1 && index <= m_Children.Count && model is ChildrenType; } public new ParentType GetParent() { return (ParentType)m_Parent; } public new int GetNbChildren() { return m_Children.Count; } public new ChildrenType this[int index] { get { return m_Children[index] as ChildrenType; } } public new IEnumerable<ChildrenType> children { get { return m_Children.Cast<ChildrenType>(); } } } }
// // Copyright (c) 2004-2017 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if WCF_SUPPORTED namespace NLog.LogReceiverService { using System.ServiceModel.Description; using System; using System.ComponentModel; using System.Net; using System.ServiceModel; using System.ServiceModel.Channels; /// <summary> /// Abstract base class for the WcfLogReceiverXXXWay classes. It can only be /// used internally (see internal constructor). It passes off any Channel usage /// to the inheriting class. /// </summary> /// <typeparam name="TService">Type of the WCF service.</typeparam> public abstract class WcfLogReceiverClientBase<TService> : ClientBase<TService>, IWcfLogReceiverClient where TService : class { /// <summary> /// Initializes a new instance of the <see cref="WcfLogReceiverClientBase{TService}"/> class. /// </summary> protected WcfLogReceiverClientBase() : base() { } /// <summary> /// Initializes a new instance of the <see cref="WcfLogReceiverClientBase{TService}"/> class. /// </summary> /// <param name="endpointConfigurationName">Name of the endpoint configuration.</param> protected WcfLogReceiverClientBase(string endpointConfigurationName) : base(endpointConfigurationName) { } /// <summary> /// Initializes a new instance of the <see cref="WcfLogReceiverClientBase{TService}"/> class. /// </summary> /// <param name="endpointConfigurationName">Name of the endpoint configuration.</param> /// <param name="remoteAddress">The remote address.</param> protected WcfLogReceiverClientBase(string endpointConfigurationName, string remoteAddress) : base(endpointConfigurationName, remoteAddress) { } /// <summary> /// Initializes a new instance of the <see cref="WcfLogReceiverClientBase{TService}"/> class. /// </summary> /// <param name="endpointConfigurationName">Name of the endpoint configuration.</param> /// <param name="remoteAddress">The remote address.</param> protected WcfLogReceiverClientBase(string endpointConfigurationName, EndpointAddress remoteAddress) : base(endpointConfigurationName, remoteAddress) { } /// <summary> /// Initializes a new instance of the <see cref="WcfLogReceiverClientBase{TService}"/> class. /// </summary> /// <param name="binding">The binding.</param> /// <param name="remoteAddress">The remote address.</param> protected WcfLogReceiverClientBase(Binding binding, EndpointAddress remoteAddress) : base(binding, remoteAddress) { } /// <summary> /// Occurs when the log message processing has completed. /// </summary> public event EventHandler<AsyncCompletedEventArgs> ProcessLogMessagesCompleted; /// <summary> /// Occurs when Open operation has completed. /// </summary> public event EventHandler<AsyncCompletedEventArgs> OpenCompleted; /// <summary> /// Occurs when Close operation has completed. /// </summary> public event EventHandler<AsyncCompletedEventArgs> CloseCompleted; #if !NET4_0 && !NET3_5 && !NETSTANDARD /// <summary> /// Gets or sets the cookie container. /// </summary> /// <value>The cookie container.</value> public CookieContainer CookieContainer { get { var httpCookieContainerManager = InnerChannel.GetProperty<IHttpCookieContainerManager>(); return httpCookieContainerManager?.CookieContainer; } set { var httpCookieContainerManager = InnerChannel.GetProperty<IHttpCookieContainerManager>(); if (httpCookieContainerManager != null) { httpCookieContainerManager.CookieContainer = value; } else { throw new InvalidOperationException("Unable to set the CookieContainer. Please make sure the binding contains an HttpCookieContainerBindingElement."); } } } #endif /// <summary> /// Opens the client asynchronously. /// </summary> public void OpenAsync() { OpenAsync(null); } /// <summary> /// Opens the client asynchronously. /// </summary> /// <param name="userState">User-specific state.</param> public void OpenAsync(object userState) { InvokeAsync(OnBeginOpen, null, OnEndOpen, OnOpenCompleted, userState); } /// <summary> /// Closes the client asynchronously. /// </summary> public void CloseAsync() { CloseAsync(null); } /// <summary> /// Closes the client asynchronously. /// </summary> /// <param name="userState">User-specific state.</param> public void CloseAsync(object userState) { InvokeAsync(OnBeginClose, null, OnEndClose, OnCloseCompleted, userState); } /// <summary> /// Processes the log messages asynchronously. /// </summary> /// <param name="events">The events to send.</param> public void ProcessLogMessagesAsync(NLogEvents events) { ProcessLogMessagesAsync(events, null); } /// <summary> /// Processes the log messages asynchronously. /// </summary> /// <param name="events">The events to send.</param> /// <param name="userState">User-specific state.</param> public void ProcessLogMessagesAsync(NLogEvents events, object userState) { InvokeAsync( OnBeginProcessLogMessages, new object[] { events }, OnEndProcessLogMessages, OnProcessLogMessagesCompleted, userState); } /// <summary> /// Begins processing of log messages. /// </summary> /// <param name="events">The events to send.</param> /// <param name="callback">The callback.</param> /// <param name="asyncState">Asynchronous state.</param> /// <returns> /// IAsyncResult value which can be passed to <see cref="ILogReceiverOneWayClient.EndProcessLogMessages"/>. /// </returns> public abstract IAsyncResult BeginProcessLogMessages(NLogEvents events, AsyncCallback callback, object asyncState); /// <summary> /// Ends asynchronous processing of log messages. /// </summary> /// <param name="result">The result.</param> public abstract void EndProcessLogMessages(IAsyncResult result); private IAsyncResult OnBeginProcessLogMessages(object[] inValues, AsyncCallback callback, object asyncState) { var events = (NLogEvents)inValues[0]; return BeginProcessLogMessages(events, callback, asyncState); } private object[] OnEndProcessLogMessages(IAsyncResult result) { EndProcessLogMessages(result); return null; } private void OnProcessLogMessagesCompleted(object state) { if (ProcessLogMessagesCompleted != null) { var e = (InvokeAsyncCompletedEventArgs)state; ProcessLogMessagesCompleted(this, new AsyncCompletedEventArgs(e.Error, e.Cancelled, e.UserState)); } } private IAsyncResult OnBeginOpen(object[] inValues, AsyncCallback callback, object asyncState) { return ((ICommunicationObject)this).BeginOpen(callback, asyncState); } private object[] OnEndOpen(IAsyncResult result) { ((ICommunicationObject)this).EndOpen(result); return null; } private void OnOpenCompleted(object state) { if (OpenCompleted != null) { var e = (InvokeAsyncCompletedEventArgs)state; OpenCompleted(this, new AsyncCompletedEventArgs(e.Error, e.Cancelled, e.UserState)); } } private IAsyncResult OnBeginClose(object[] inValues, AsyncCallback callback, object asyncState) { return ((ICommunicationObject)this).BeginClose(callback, asyncState); } private object[] OnEndClose(IAsyncResult result) { ((ICommunicationObject)this).EndClose(result); return null; } private void OnCloseCompleted(object state) { if (CloseCompleted != null) { var e = (InvokeAsyncCompletedEventArgs)state; CloseCompleted(this, new AsyncCompletedEventArgs(e.Error, e.Cancelled, e.UserState)); } } } } #endif
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; using Cetera.IO; namespace Cetera.Archive { public sealed class SARC : List<SARC.Node> { public SARCHeader sarcHeader; public SimplerSARCHeader ssarcHeader; public SFATHeader sfatHeader; public SFNTHeader sfntHeader; [DebuggerDisplay("{fileName}")] public class Node { public State state; public SFATNode nodeEntry; public SimplerSFATNode sNodeEntry; public String fileName; } public enum State : byte { Normal = 0, Simpler = 1 } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct SimplerSARCHeader { String4 magic; public uint nodeCount; uint unk1; uint unk2; } public class SimplerSFATNode { public SimplerSFATNode(Stream input) { using (BinaryReaderX br = new BinaryReaderX(input, true)) { hash = br.ReadUInt32(); dataStart = br.ReadUInt32(); dataLength = br.ReadUInt32(); unk1 = br.ReadUInt32(); } } public uint hash; public uint dataStart; public uint dataLength; public uint unk1; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct SARCHeader { String4 magic; ushort headerSize; ByteOrder byteOrder; uint fileSize; public uint dataOffset; uint unk1; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct SFATHeader { String4 magic; ushort headerSize; public ushort nodeCount; uint hashMultiplier; } public class SFATNode { public SFATNode(Stream input) { using (BinaryReaderX br = new BinaryReaderX(input, true)) { nameHash = br.ReadUInt32(); SFNTOffset = br.ReadUInt16(); unk1 = br.ReadUInt16(); dataStart = br.ReadUInt32(); dataEnd = br.ReadUInt32(); } } public uint nameHash; public ushort SFNTOffset; public ushort unk1; public uint dataStart; public uint dataEnd; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct SFNTHeader { String4 magic; ushort headerSize; ushort unk1; } public unsafe uint CalcNodeHash(String name, int hashMultiplier) { uint result = 0; for (int i = 0; i < name.Length; i++) { result = (uint)(name[i] + (result * hashMultiplier)); } return result; } public String readASCII(BinaryReaderX br) { String result = ""; Encoding ascii = Encoding.GetEncoding("ascii"); byte[] character = br.ReadBytes(1); while (character[0] != 0x00) { result += ascii.GetString(character); character = br.ReadBytes(1); } br.BaseStream.Position -= 1; return result; } public SARC(Stream input) { using (BinaryReaderX br = new BinaryReaderX(input)) { br.BaseStream.Position = 6; ushort ind = br.ReadUInt16(); if (ind != 0xfeff && ind != 0xfffe) { br.BaseStream.Position = 0; SimplerSARC(br.BaseStream); } else { br.BaseStream.Position = 0; sarcHeader = br.ReadStruct<SARCHeader>(); sfatHeader = br.ReadStruct<SFATHeader>(); for (int i = 0; i < sfatHeader.nodeCount; i++) { Add(new Node()); this[i].state = State.Normal; this[i].nodeEntry = br.ReadStruct<SFATNode>(); } sfntHeader = br.ReadStruct<SFNTHeader>(); for (int i = 0; i < sfatHeader.nodeCount; i++) { this[i].fileName = readASCII(br); byte tmp; do { tmp = br.ReadByte(); } while (tmp == 0x00); br.BaseStream.Position -= 1; } } } } public void SimplerSARC(Stream input) { using (BinaryReaderX br = new BinaryReaderX(input)) { ssarcHeader = br.ReadStruct<SimplerSARCHeader>(); for (int i = 0; i < ssarcHeader.nodeCount; i++) { Add(new Node()); this[i].state = State.Simpler; this[i].sNodeEntry = br.ReadStruct<SimplerSFATNode>(); } for (int i = 0; i < ssarcHeader.nodeCount; i++) { br.BaseStream.Position = this[i].sNodeEntry.dataStart; this[i].fileName = "File" + i.ToString(); } } } public void Save(Stream input) { int t = 0; } } }
//////////////////////////////////////////////////////////////////////////// // // Copyright 2017 Rubius // // 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.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.SignalR; using Newtonsoft.Json; using Realmius.Contracts; using Realmius.Contracts.Models; using Realmius.Contracts.SignalR; using Realmius.Server.Infrastructure; using Realmius.Server.Models; using Realmius.Server.QuickStart; using Realmius.Contracts.Logger; namespace Realmius.Server.Exchange { public class RealmiusPersistentConnection<TUser> : PersistentConnection { protected readonly RealmiusServerProcessor<TUser> Processor; protected static RealmiusServerProcessor<TUser> ProcessorStatic; private static readonly ConcurrentDictionary<string, TUser> Connections = new ConcurrentDictionary<string, TUser>(); private static JsonSerializerSettings SerializerSettings; private static bool _initialized; private ILogger Logger => Processor.Configuration.Logger; protected static T Deserialize<T>(string data) { return JsonConvert.DeserializeObject<T>(data, SerializerSettings); } internal static string Serialize(object obj) { return JsonConvert.SerializeObject(obj, SerializerSettings); } public RealmiusPersistentConnection() : this(new RealmiusServerProcessor<TUser>(RealmiusServer.GetConfiguration<TUser>())) { } protected RealmiusPersistentConnection(RealmiusServerProcessor<TUser> processor) { InitializeIfNeeded(); Processor = processor; if (ProcessorStatic == null) ProcessorStatic = processor; } private void InitializeIfNeeded() { if (_initialized) return; _initialized = true; SerializerSettings = new JsonSerializerSettings() { StringEscapeHandling = StringEscapeHandling.EscapeNonAscii, }; ChangeTrackingDbContext.DataUpdated += (sender, data) => { Task.Factory.StartNew(() => { //await Task.Delay(20); PersistentConnectionUpdatedDataHandler.HandleDataChanges<TUser>(sender, data); }); }; } protected override Task OnReceived(IRequest request, string connectionId, string data) { if (data.Length < MethodConstants.CommandNameLength) return Task.FromResult(true); var command = data.Substring(0, MethodConstants.CommandNameLength); var parameter = data.Substring(MethodConstants.CommandNameLength); switch (command) { case MethodConstants.ServerUploadData: var result = UploadData(Deserialize<UploadDataRequest>(parameter), connectionId); Send(connectionId, MethodConstants.ServerUploadData, result); break; default: Logger.Exception(new InvalidOperationException($"Unknown command {command}")); break; } return Task.FromResult(true); } public UploadDataResponse UploadData(UploadDataRequest request, string connectionId) { if (!Connections.ContainsKey(connectionId)) { Logger.Info($"User with ConnectionId {connectionId} not found in the connections pool (not authorized?)"); return new UploadDataResponse(); } var result = Processor.Upload(request, Connections[connectionId]); return result; } protected override Task OnConnected(IRequest request, string connectionId) { UserConnected(request, connectionId); return base.OnConnected(request, connectionId); } public static void AddUserGroup(Func<TUser, bool> userPredicate, string group) { var connectionIds = Connections.Where(x => userPredicate(x.Value)); var connection = GlobalHost.ConnectionManager.GetConnectionContext<RealmiusPersistentConnection<TUser>>(); foreach (KeyValuePair<string, TUser> connectionId in connectionIds) { connection.Groups.Add(connectionId.Key, group); var tags = ProcessorStatic.GetTagsForUser(connectionId.Value); if (tags.Contains(group)) continue; tags.Add(group); //include data for the tag var changes = ProcessorStatic.Download(new DownloadDataRequest() { LastChangeTime = new Dictionary<string, DateTimeOffset>() { { group, DateTimeOffset.MinValue } }, Types = ProcessorStatic.Configuration.TypesToSync.Select(x => x.Name), OnlyDownloadSpecifiedTags = true, }, connectionId.Value); var downloadData = new DownloadDataResponse() { ChangedObjects = changes.ChangedObjects, LastChange = new Dictionary<string, DateTimeOffset>() { { group, DateTimeOffset.UtcNow } }, LastChangeContainsNewTags = true, }; connection.Connection.Send(connectionId.Key, MethodConstants.ClientDataDownloaded + Serialize(downloadData)); } } protected virtual void UserConnected(IRequest contextRequest, string connectionId) { var user = Processor.Configuration.AuthenticateUser(contextRequest); if (user == null) { CallUnauthorize(connectionId, new UnauthorizedResponse() { Error = "User not authorized" }); return; } Connections[connectionId] = user; var lastDownloadString = contextRequest.QueryString[Constants.LastDownloadParameterName]; Dictionary<string, DateTimeOffset> lastDownload; var userTags = Processor.GetTagsForUser(user); if (string.IsNullOrEmpty(lastDownloadString)) { var lastDownloadOld = contextRequest.QueryString[Constants.LastDownloadParameterNameOld]; if (string.IsNullOrEmpty(lastDownloadOld)) { lastDownload = new Dictionary<string, DateTimeOffset>(); } else { var date = DateTimeOffset.Parse(lastDownloadOld); lastDownload = userTags.ToDictionary(x => x, x => date); } } else { lastDownload = JsonConvert.DeserializeObject<Dictionary<string, DateTimeOffset>>(lastDownloadString); } var types = contextRequest.QueryString[Constants.SyncTypesParameterName]; var data = Processor.Download(new DownloadDataRequest() { LastChangeTime = lastDownload, Types = types.Split(','), }, user); data.LastChangeContainsNewTags = true; CallDataDownloaded(connectionId, data); foreach (var userTag in userTags) { Groups.Add(connectionId, userTag); } } private void CallUnauthorize(string connectionId, UnauthorizedResponse unauthorizedResponse) { Send(connectionId, MethodConstants.ClientUnauthorized, unauthorizedResponse); } private void CallDataDownloaded(string connectionId, DownloadDataResponse data) { Send(connectionId, MethodConstants.ClientDataDownloaded, data); } private void Send(string connectionId, string command, object data) { Connection.Send(connectionId, command + Serialize(data)); } protected override Task OnDisconnected(IRequest request, string connectionId, bool stopCalled) { UserDisconnected(connectionId); return base.OnDisconnected(request, connectionId, stopCalled); } private void UserDisconnected(string connectionId) { TUser user; if (Connections.ContainsKey(connectionId)) Connections.TryRemove(connectionId, out user); } protected override Task OnReconnected(IRequest request, string connectionId) { UserConnected(request, connectionId); return base.OnReconnected(request, connectionId); } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.HSSF.Record { using System; using System.Collections.Generic; using System.Text; using NPOI.HSSF.Record.Cont; using NPOI.Util; /** * Title: Unicode String<p/> * Description: Unicode String - just standard fields that are in several records. * It is considered more desirable then repeating it in all of them.<p/> * This is often called a XLUnicodeRichExtendedString in MS documentation.<p/> * REFERENCE: PG 264 Microsoft Excel 97 Developer's Kit (ISBN: 1-57231-498-2)<p/> * REFERENCE: PG 951 Excel Binary File Format (.xls) Structure Specification v20091214 */ public class UnicodeString : IComparable<UnicodeString> { // TODO - make this when the compatibility version is Removed private static POILogger _logger = POILogFactory.GetLogger(typeof(UnicodeString)); private short field_1_charCount; private byte field_2_optionflags; private String field_3_string; private List<FormatRun> field_4_format_Runs; private ExtRst field_5_ext_rst; private static BitField highByte = BitFieldFactory.GetInstance(0x1); // 0x2 is reserved private static BitField extBit = BitFieldFactory.GetInstance(0x4); private static BitField richText = BitFieldFactory.GetInstance(0x8); public class FormatRun : IComparable<FormatRun> { internal short _character; internal short _fontIndex; public FormatRun(short character, short fontIndex) { this._character = character; this._fontIndex = fontIndex; } public FormatRun(ILittleEndianInput in1) : this(in1.ReadShort(), in1.ReadShort()) { } public short CharacterPos { get { return _character; } } public short FontIndex { get { return _fontIndex; } } public override bool Equals(Object o) { if (!(o is FormatRun)) { return false; } FormatRun other = (FormatRun)o; return _character == other._character && _fontIndex == other._fontIndex; } public override int GetHashCode() { return base.GetHashCode(); } public int CompareTo(FormatRun r) { if (_character == r._character && _fontIndex == r._fontIndex) { return 0; } if (_character == r._character) { return _fontIndex - r._fontIndex; } return _character - r._character; } public override String ToString() { return "character=" + _character + ",fontIndex=" + _fontIndex; } public void Serialize(ILittleEndianOutput out1) { out1.WriteShort(_character); out1.WriteShort(_fontIndex); } } // See page 681 public class ExtRst : IComparable<ExtRst> { private short reserved; // This is a Phs (see page 881) private short formattingFontIndex; private short formattingOptions; // This is a RPHSSub (see page 894) private int numberOfRuns; private String phoneticText; // This is an array of PhRuns (see page 881) private PhRun[] phRuns; // Sometimes there's some cruft at the end private byte[] extraData; private void populateEmpty() { reserved = 1; phoneticText = ""; phRuns = new PhRun[0]; extraData = new byte[0]; } public override int GetHashCode() { int hash = reserved; hash = 31 * hash + formattingFontIndex; hash = 31 * hash + formattingOptions; hash = 31 * hash + numberOfRuns; hash = 31 * hash + phoneticText.GetHashCode(); if (phRuns != null) { foreach (PhRun ph in phRuns) { hash = 31 * hash + ph.phoneticTextFirstCharacterOffset; hash = 31 * hash + ph.realTextFirstCharacterOffset; hash = 31 * hash + ph.realTextLength; } } return hash; } internal ExtRst() { populateEmpty(); } internal ExtRst(ILittleEndianInput in1, int expectedLength) { reserved = in1.ReadShort(); // Old style detection (Reserved = 0xFF) if (reserved == -1) { populateEmpty(); return; } // Spot corrupt records if (reserved != 1) { _logger.Log(POILogger.WARN, "Warning - ExtRst has wrong magic marker, expecting 1 but found " + reserved + " - ignoring"); // Grab all the remaining data, and ignore it for (int i = 0; i < expectedLength - 2; i++) { in1.ReadByte(); } // And make us be empty populateEmpty(); return; } // Carry on Reading in as normal short stringDataSize = in1.ReadShort(); formattingFontIndex = in1.ReadShort(); formattingOptions = in1.ReadShort(); // RPHSSub numberOfRuns = in1.ReadUShort(); short length1 = in1.ReadShort(); // No really. Someone Clearly forgot to read // the docs on their datastructure... short length2 = in1.ReadShort(); // And sometimes they write out garbage :( if (length1 == 0 && length2 > 0) { length2 = 0; } if (length1 != length2) { throw new InvalidOperationException( "The two length fields of the Phonetic Text don't agree! " + length1 + " vs " + length2 ); } phoneticText = StringUtil.ReadUnicodeLE(in1, length1); int RunData = stringDataSize - 4 - 6 - (2 * phoneticText.Length); int numRuns = (RunData / 6); phRuns = new PhRun[numRuns]; for (int i = 0; i < phRuns.Length; i++) { phRuns[i] = new PhRun(in1); } int extraDataLength = RunData - (numRuns * 6); if (extraDataLength < 0) { //System.err.Println("Warning - ExtRst overran by " + (0-extraDataLength) + " bytes"); extraDataLength = 0; } extraData = new byte[extraDataLength]; for (int i = 0; i < extraData.Length; i++) { extraData[i] = (byte)in1.ReadByte(); } } /** * Returns our size, excluding our * 4 byte header */ internal int DataSize { get { return 4 + 6 + (2 * phoneticText.Length) + (6 * phRuns.Length) + extraData.Length; } } internal void Serialize(ContinuableRecordOutput out1) { int dataSize = DataSize; out1.WriteContinueIfRequired(8); out1.WriteShort(reserved); out1.WriteShort(dataSize); out1.WriteShort(formattingFontIndex); out1.WriteShort(formattingOptions); out1.WriteContinueIfRequired(6); out1.WriteShort(numberOfRuns); out1.WriteShort(phoneticText.Length); out1.WriteShort(phoneticText.Length); out1.WriteContinueIfRequired(phoneticText.Length * 2); StringUtil.PutUnicodeLE(phoneticText, out1); for (int i = 0; i < phRuns.Length; i++) { phRuns[i].Serialize(out1); } out1.Write(extraData); } public override bool Equals(Object obj) { if (!(obj is ExtRst)) { return false; } ExtRst other = (ExtRst)obj; return (CompareTo(other) == 0); } public override string ToString() { return base.ToString(); } public int CompareTo(ExtRst o) { int result; result = reserved - o.reserved; if (result != 0) return result; result = formattingFontIndex - o.formattingFontIndex; if (result != 0) return result; result = formattingOptions - o.formattingOptions; if (result != 0) return result; result = numberOfRuns - o.numberOfRuns; if (result != 0) return result; //result = phoneticText.CompareTo(o.phoneticText); result = string.Compare(phoneticText, o.phoneticText, StringComparison.CurrentCulture); if (result != 0) return result; result = phRuns.Length - o.phRuns.Length; if (result != 0) return result; for (int i = 0; i < phRuns.Length; i++) { result = phRuns[i].phoneticTextFirstCharacterOffset - o.phRuns[i].phoneticTextFirstCharacterOffset; if (result != 0) return result; result = phRuns[i].realTextFirstCharacterOffset - o.phRuns[i].realTextFirstCharacterOffset; if (result != 0) return result; result = phRuns[i].realTextLength - o.phRuns[i].realTextLength; if (result != 0) return result; } result = Arrays.HashCode(extraData) - Arrays.HashCode(o.extraData); // If we Get here, it's the same return result; } internal ExtRst Clone() { ExtRst ext = new ExtRst(); ext.reserved = reserved; ext.formattingFontIndex = formattingFontIndex; ext.formattingOptions = formattingOptions; ext.numberOfRuns = numberOfRuns; ext.phoneticText = phoneticText; ext.phRuns = new PhRun[phRuns.Length]; for (int i = 0; i < ext.phRuns.Length; i++) { ext.phRuns[i] = new PhRun( phRuns[i].phoneticTextFirstCharacterOffset, phRuns[i].realTextFirstCharacterOffset, phRuns[i].realTextLength ); } return ext; } public short FormattingFontIndex { get { return formattingFontIndex; } } public short FormattingOptions { get { return formattingOptions; } } public int NumberOfRuns { get { return numberOfRuns; } } public String PhoneticText { get { return phoneticText; } } public PhRun[] PhRuns { get { return phRuns; } } } public class PhRun { internal int phoneticTextFirstCharacterOffset; internal int realTextFirstCharacterOffset; internal int realTextLength; public PhRun(int phoneticTextFirstCharacterOffset, int realTextFirstCharacterOffset, int realTextLength) { this.phoneticTextFirstCharacterOffset = phoneticTextFirstCharacterOffset; this.realTextFirstCharacterOffset = realTextFirstCharacterOffset; this.realTextLength = realTextLength; } internal PhRun(ILittleEndianInput in1) { phoneticTextFirstCharacterOffset = in1.ReadUShort(); realTextFirstCharacterOffset = in1.ReadUShort(); realTextLength = in1.ReadUShort(); } internal void Serialize(ContinuableRecordOutput out1) { out1.WriteContinueIfRequired(6); out1.WriteShort(phoneticTextFirstCharacterOffset); out1.WriteShort(realTextFirstCharacterOffset); out1.WriteShort(realTextLength); } } private UnicodeString() { //Used for clone method. } public UnicodeString(String str) { String = (str); } public override int GetHashCode() { int stringHash = 0; if (field_3_string != null) stringHash = field_3_string.GetHashCode(); return field_1_charCount + stringHash; } /** * Our handling of Equals is inconsistent with CompareTo. The trouble is because we don't truely understand * rich text fields yet it's difficult to make a sound comparison. * * @param o The object to Compare. * @return true if the object is actually Equal. */ public override bool Equals(Object o) { if (!(o is UnicodeString)) { return false; } UnicodeString other = (UnicodeString)o; //OK lets do this in stages to return a quickly, first check the actual string bool eq = ((field_1_charCount == other.field_1_charCount) && (field_2_optionflags == other.field_2_optionflags) && field_3_string.Equals(other.field_3_string)); if (!eq) return false; //OK string appears to be equal but now lets compare formatting Runs if ((field_4_format_Runs == null) && (other.field_4_format_Runs == null)) //Strings are Equal, and there are not formatting Runs. return true; if (((field_4_format_Runs == null) && (other.field_4_format_Runs != null)) || (field_4_format_Runs != null) && (other.field_4_format_Runs == null)) //Strings are Equal, but one or the other has formatting Runs return false; //Strings are Equal, so now compare formatting Runs. int size = field_4_format_Runs.Count; if (size != other.field_4_format_Runs.Count) return false; for (int i = 0; i < size; i++) { FormatRun Run1 = field_4_format_Runs[(i)]; FormatRun run2 = other.field_4_format_Runs[(i)]; if (!Run1.Equals(run2)) return false; } // Well the format Runs are equal as well!, better check the ExtRst data if (field_5_ext_rst == null && other.field_5_ext_rst == null) { // Good } else if (field_5_ext_rst != null && other.field_5_ext_rst != null) { int extCmp = field_5_ext_rst.CompareTo(other.field_5_ext_rst); if (extCmp == 0) { // Good } else { return false; } } else { return false; } //Phew!! After all of that we have finally worked out that the strings //are identical. return true; } /** * construct a unicode string record and fill its fields, ID is ignored * @param in the RecordInputstream to read the record from */ public UnicodeString(RecordInputStream in1) { field_1_charCount = in1.ReadShort(); field_2_optionflags = (byte)in1.ReadByte(); int RunCount = 0; int extensionLength = 0; //Read the number of rich Runs if rich text. if (IsRichText) { RunCount = in1.ReadShort(); } //Read the size of extended data if present. if (IsExtendedText) { extensionLength = in1.ReadInt(); } bool IsCompressed = ((field_2_optionflags & 1) == 0); if (IsCompressed) { field_3_string = in1.ReadCompressedUnicode(CharCount); } else { field_3_string = in1.ReadUnicodeLEString(CharCount); } if (IsRichText && (RunCount > 0)) { field_4_format_Runs = new List<FormatRun>(RunCount); for (int i = 0; i < RunCount; i++) { field_4_format_Runs.Add(new FormatRun(in1)); } } if (IsExtendedText && (extensionLength > 0)) { field_5_ext_rst = new ExtRst(new ContinuableRecordInput(in1), extensionLength); if (field_5_ext_rst.DataSize + 4 != extensionLength) { _logger.Log(POILogger.WARN, "ExtRst was supposed to be " + extensionLength + " bytes long, but seems to actually be " + (field_5_ext_rst.DataSize + 4)); } } } /** * get the number of characters in the string, * as an un-wrapped int * * @return number of characters */ public int CharCount { get { if (field_1_charCount < 0) { return field_1_charCount + 65536; } return field_1_charCount; } set { field_1_charCount = (short)value; } } public short CharCountShort { get { return field_1_charCount; } } /** * Get the option flags which among other things return if this is a 16-bit or * 8 bit string * * @return optionflags bitmask * */ public byte OptionFlags { get { return field_2_optionflags; } set { field_2_optionflags = value; } } /** * @return the actual string this Contains as a java String object */ public String String { get { return field_3_string; } set { field_3_string = value; CharCount = ((short)field_3_string.Length); // scan for characters greater than 255 ... if any are // present, we have to use 16-bit encoding. Otherwise, we // can use 8-bit encoding bool useUTF16 = false; int strlen = value.Length; for (int j = 0; j < strlen; j++) { if (value[j] > 255) { useUTF16 = true; break; } } if (useUTF16) //Set the uncompressed bit field_2_optionflags = highByte.SetByte(field_2_optionflags); else field_2_optionflags = highByte.ClearByte(field_2_optionflags); } } public int FormatRunCount { get { if (field_4_format_Runs == null) return 0; return field_4_format_Runs.Count; } } public FormatRun GetFormatRun(int index) { if (field_4_format_Runs == null) { return null; } if (index < 0 || index >= field_4_format_Runs.Count) { return null; } return field_4_format_Runs[(index)]; } private int FindFormatRunAt(int characterPos) { int size = field_4_format_Runs.Count; for (int i = 0; i < size; i++) { FormatRun r = field_4_format_Runs[(i)]; if (r._character == characterPos) return i; else if (r._character > characterPos) return -1; } return -1; } /** Adds a font run to the formatted string. * * If a font run exists at the current charcter location, then it is * Replaced with the font run to be Added. */ public void AddFormatRun(FormatRun r) { if (field_4_format_Runs == null) { field_4_format_Runs = new List<FormatRun>(); } int index = FindFormatRunAt(r._character); if (index != -1) field_4_format_Runs.RemoveAt(index); field_4_format_Runs.Add(r); //Need to sort the font Runs to ensure that the font Runs appear in //character order //collections.Sort(field_4_format_Runs); field_4_format_Runs.Sort(); //Make sure that we now say that we are a rich string field_2_optionflags = richText.SetByte(field_2_optionflags); } public List<FormatRun> FormatIterator() { if (field_4_format_Runs != null) { return field_4_format_Runs; } return null; } public void RemoveFormatRun(FormatRun r) { field_4_format_Runs.Remove(r); if (field_4_format_Runs.Count == 0) { field_4_format_Runs = null; field_2_optionflags = richText.ClearByte(field_2_optionflags); } } public void ClearFormatting() { field_4_format_Runs = null; field_2_optionflags = richText.ClearByte(field_2_optionflags); } public ExtRst ExtendedRst { get { return this.field_5_ext_rst; } set { if (value != null) { field_2_optionflags = extBit.SetByte(field_2_optionflags); } else { field_2_optionflags = extBit.ClearByte(field_2_optionflags); } this.field_5_ext_rst = value; } } /** * Swaps all use in the string of one font index * for use of a different font index. * Normally only called when fonts have been * Removed / re-ordered */ public void SwapFontUse(short oldFontIndex, short newFontIndex) { foreach (FormatRun run in field_4_format_Runs) { if (run._fontIndex == oldFontIndex) { run._fontIndex = newFontIndex; } } } /** * unlike the real records we return the same as "getString()" rather than debug info * @see #getDebugInfo() * @return String value of the record */ public override String ToString() { return String; } /** * return a character representation of the fields of this record * * * @return String of output for biffviewer etc. * */ public String GetDebugInfo() { StringBuilder buffer = new StringBuilder(); buffer.Append("[UNICODESTRING]\n"); buffer.Append(" .charcount = ") .Append(StringUtil.ToHexString(CharCount)).Append("\n"); buffer.Append(" .optionflags = ") .Append(StringUtil.ToHexString(OptionFlags)).Append("\n"); buffer.Append(" .string = ").Append(String).Append("\n"); if (field_4_format_Runs != null) { for (int i = 0; i < field_4_format_Runs.Count; i++) { FormatRun r = field_4_format_Runs[(i)]; buffer.Append(" .format_Run" + i + " = ").Append(r.ToString()).Append("\n"); } } if (field_5_ext_rst != null) { buffer.Append(" .field_5_ext_rst = ").Append("\n"); buffer.Append(field_5_ext_rst.ToString()).Append("\n"); } buffer.Append("[/UNICODESTRING]\n"); return buffer.ToString(); } /** * Serialises out the String. There are special rules * about where we can and can't split onto * Continue records. */ public void Serialize(ContinuableRecordOutput out1) { int numberOfRichTextRuns = 0; int extendedDataSize = 0; if (IsRichText && field_4_format_Runs != null) { numberOfRichTextRuns = field_4_format_Runs.Count; } if (IsExtendedText && field_5_ext_rst != null) { extendedDataSize = 4 + field_5_ext_rst.DataSize; } // Serialise the bulk of the String // The WriteString handles tricky continue stuff for us out1.WriteString(field_3_string, numberOfRichTextRuns, extendedDataSize); if (numberOfRichTextRuns > 0) { //This will ensure that a run does not split a continue for (int i = 0; i < numberOfRichTextRuns; i++) { if (out1.AvailableSpace < 4) { out1.WriteContinue(); } FormatRun r = field_4_format_Runs[(i)]; r.Serialize(out1); } } if (extendedDataSize > 0) { field_5_ext_rst.Serialize(out1); } } public int CompareTo(UnicodeString str) { //int result = String.CompareTo(str.String); int result = string.Compare(String, str.String, StringComparison.CurrentCulture); //As per the Equals method lets do this in stages if (result != 0) return result; //OK string appears to be equal but now lets compare formatting Runs if ((field_4_format_Runs == null) && (str.field_4_format_Runs == null)) //Strings are Equal, and there are no formatting Runs. return 0; if ((field_4_format_Runs == null) && (str.field_4_format_Runs != null)) //Strings are Equal, but one or the other has formatting Runs return 1; if ((field_4_format_Runs != null) && (str.field_4_format_Runs == null)) //Strings are Equal, but one or the other has formatting Runs return -1; //Strings are Equal, so now compare formatting Runs. int size = field_4_format_Runs.Count; if (size != str.field_4_format_Runs.Count) return size - str.field_4_format_Runs.Count; for (int i = 0; i < size; i++) { FormatRun Run1 = field_4_format_Runs[(i)]; FormatRun run2 = str.field_4_format_Runs[(i)]; result = Run1.CompareTo(run2); if (result != 0) return result; } //Well the format Runs are equal as well!, better check the ExtRst data if ((field_5_ext_rst == null) && (str.field_5_ext_rst == null)) return 0; if ((field_5_ext_rst == null) && (str.field_5_ext_rst != null)) return 1; if ((field_5_ext_rst != null) && (str.field_5_ext_rst == null)) return -1; result = field_5_ext_rst.CompareTo(str.field_5_ext_rst); if (result != 0) return result; //Phew!! After all of that we have finally worked out that the strings //are identical. return 0; } private bool IsRichText { get { return richText.IsSet(OptionFlags); } } private bool IsExtendedText { get { return extBit.IsSet(OptionFlags); } } public Object Clone() { UnicodeString str = new UnicodeString(); str.field_1_charCount = field_1_charCount; str.field_2_optionflags = field_2_optionflags; str.field_3_string = field_3_string; if (field_4_format_Runs != null) { str.field_4_format_Runs = new List<FormatRun>(); foreach (FormatRun r in field_4_format_Runs) { str.field_4_format_Runs.Add(new FormatRun(r._character, r._fontIndex)); } } if (field_5_ext_rst != null) { str.field_5_ext_rst = field_5_ext_rst.Clone(); } return str; } } }
using Loon.Core.Geom; namespace Loon.Core.Input { public class LTouchLocation { protected internal int id; private Vector2f position; private Vector2f previousPosition; private LTouchLocationState state = LTouchLocationState.Invalid; private LTouchLocationState previousState = LTouchLocationState.Invalid; private float pressure; private float previousPressure; public bool IsDrag() { return Touch.IsDrag() && (previousState == LTouchLocationState.Dragged && state == LTouchLocationState.Dragged); } public bool IsDown() { return Touch.IsDown() && (previousState == LTouchLocationState.Pressed && (state == LTouchLocationState.Pressed || state == LTouchLocationState.Dragged)); } public bool IsUp() { return Touch.IsUp() && (previousState == LTouchLocationState.Pressed || previousState == LTouchLocationState.Dragged) && (state == LTouchLocationState.Released); } public int GetId() { return id; } public Vector2f GetPosition() { return position; } public void SetPosition(float x, float y) { previousPosition.Set(position); position.Set(x, y); } public void SetPosition(Vector2f v) { previousPosition.Set(position); position.Set(v); } public float GetPressure() { return pressure; } public float GetPrevPressure() { return previousPressure; } public Vector2f GetPrevPosition() { return previousPosition; } public void SetPrevPosition(Vector2f v) { previousPosition.Set(v); } public LTouchLocationState GetState() { return state; } public void SetState(LTouchLocationState value_ren) { previousState = state; state = value_ren; } public LTouchLocationState GetPrevState() { return previousState; } public void SetPrevState(LTouchLocationState value_ren) { previousState = value_ren; } public LTouchLocation() :this(0, LTouchLocationState.Invalid, new Vector2f(0, 0), LTouchLocationState.Invalid, new Vector2f(0, 0)){ } public LTouchLocation(int aId, LTouchLocationState aState, Vector2f aPosition, LTouchLocationState aPreviousState, Vector2f aPreviousPosition) { id = aId; position = aPosition; previousPosition = aPreviousPosition; state = aState; previousState = aPreviousState; pressure = 0.0f; previousPressure = 0.0f; } public LTouchLocation(int aId, LTouchLocationState aState, Vector2f aPosition) { id = aId; position = aPosition; previousPosition = Vector2f.ZERO(); state = aState; previousState = LTouchLocationState.Invalid; pressure = 0.0f; previousPressure = 0.0f; } public LTouchLocation(int aId, LTouchLocationState aState, float x, float y) { id = aId; position = new Vector2f(x, y); previousPosition = Vector2f.ZERO(); state = aState; previousState = LTouchLocationState.Invalid; pressure = 0.0f; previousPressure = 0.0f; } public LTouchLocation(int aId, LTouchLocationState aState, Vector2f aPosition, float aPressure, LTouchLocationState aPreviousState, Vector2f aPreviousPosition, float aPreviousPressure) { id = aId; position = aPosition; previousPosition = aPreviousPosition; state = aState; previousState = aPreviousState; pressure = aPressure; previousPressure = aPreviousPressure; } public LTouchLocation(int aId, LTouchLocationState aState, Vector2f aPosition, float aPressure) { id = aId; position = aPosition; previousPosition = Vector2f.ZERO(); state = aState; previousState = LTouchLocationState.Invalid; pressure = aPressure; previousPressure = 0.0f; } public bool tryGetPreviousLocation( RefObject<LTouchLocation> aPreviousLocation) { if (aPreviousLocation.argvalue == null) { aPreviousLocation.argvalue = new LTouchLocation(); } if (previousState == LTouchLocationState.Invalid) { aPreviousLocation.argvalue.id = -1; aPreviousLocation.argvalue.state = LTouchLocationState.Invalid; aPreviousLocation.argvalue.position = Vector2f.ZERO(); aPreviousLocation.argvalue.previousState = LTouchLocationState.Invalid; aPreviousLocation.argvalue.previousPosition = Vector2f.ZERO(); aPreviousLocation.argvalue.pressure = 0.0f; aPreviousLocation.argvalue.previousPressure = 0.0f; return false; } else { aPreviousLocation.argvalue.id = this.id; aPreviousLocation.argvalue.state = this.previousState; aPreviousLocation.argvalue.position = this.previousPosition.Cpy(); aPreviousLocation.argvalue.previousState = LTouchLocationState.Invalid; aPreviousLocation.argvalue.previousPosition = Vector2f.ZERO(); aPreviousLocation.argvalue.pressure = this.previousPressure; aPreviousLocation.argvalue.previousPressure = 0.0f; return true; } } public override bool Equals(object obj) { bool result = false; if (obj is LTouchLocation) { result = Equals((LTouchLocation) obj); } return result; } public bool Equals(LTouchLocation other) { return (id == other.id) && (this.GetPosition().Equals(other.GetPosition())) && (this.previousPosition.Equals(other.previousPosition)); } public override int GetHashCode() { return id; } public override string ToString() { return "Touch id:" + id + " state:" + state + " position:" + position + " pressure:" + pressure + " prevState:" + previousState + " prevPosition:" + previousPosition + " previousPressure:" + previousPressure; } public virtual LTouchLocation Clone() { LTouchLocation varCopy = new LTouchLocation(); varCopy.id = this.id; varCopy.position.Set(this.position); varCopy.previousPosition.Set(this.previousPosition); varCopy.state = this.state; varCopy.previousState = this.previousState; varCopy.pressure = this.pressure; varCopy.previousPressure = this.previousPressure; return varCopy; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.Resources; using Microsoft.Azure.Management.Resources.Models; namespace Microsoft.Azure.Management.Resources { public static partial class ResourceOperationsExtensions { /// <summary> /// Begin moving resources.To determine whether the operation has /// finished processing the request, call /// GetLongRunningOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='sourceResourceGroupName'> /// Required. Source resource group name. /// </param> /// <param name='parameters'> /// Required. move resources' parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse BeginMoving(this IResourceOperations operations, string sourceResourceGroupName, ResourcesMoveInfo parameters) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).BeginMovingAsync(sourceResourceGroupName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begin moving resources.To determine whether the operation has /// finished processing the request, call /// GetLongRunningOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='sourceResourceGroupName'> /// Required. Source resource group name. /// </param> /// <param name='parameters'> /// Required. move resources' parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> BeginMovingAsync(this IResourceOperations operations, string sourceResourceGroupName, ResourcesMoveInfo parameters) { return operations.BeginMovingAsync(sourceResourceGroupName, parameters, CancellationToken.None); } /// <summary> /// Checks whether resource exists. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='identity'> /// Required. Resource identity. /// </param> /// <returns> /// Resource group information. /// </returns> public static ResourceExistsResult CheckExistence(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).CheckExistenceAsync(resourceGroupName, identity); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Checks whether resource exists. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='identity'> /// Required. Resource identity. /// </param> /// <returns> /// Resource group information. /// </returns> public static Task<ResourceExistsResult> CheckExistenceAsync(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity) { return operations.CheckExistenceAsync(resourceGroupName, identity, CancellationToken.None); } /// <summary> /// Create a resource. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='identity'> /// Required. Resource identity. /// </param> /// <param name='parameters'> /// Required. Create or update resource parameters. /// </param> /// <returns> /// Resource information. /// </returns> public static ResourceCreateOrUpdateResult CreateOrUpdate(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity, GenericResource parameters) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).CreateOrUpdateAsync(resourceGroupName, identity, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create a resource. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='identity'> /// Required. Resource identity. /// </param> /// <param name='parameters'> /// Required. Create or update resource parameters. /// </param> /// <returns> /// Resource information. /// </returns> public static Task<ResourceCreateOrUpdateResult> CreateOrUpdateAsync(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity, GenericResource parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, identity, parameters, CancellationToken.None); } /// <summary> /// Delete resource and all of its resources. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='identity'> /// Required. Resource identity. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).DeleteAsync(resourceGroupName, identity); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete resource and all of its resources. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='identity'> /// Required. Resource identity. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity) { return operations.DeleteAsync(resourceGroupName, identity, CancellationToken.None); } /// <summary> /// Returns a resource belonging to a resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='identity'> /// Required. Resource identity. /// </param> /// <returns> /// Resource information. /// </returns> public static ResourceGetResult Get(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).GetAsync(resourceGroupName, identity); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns a resource belonging to a resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='identity'> /// Required. Resource identity. /// </param> /// <returns> /// Resource information. /// </returns> public static Task<ResourceGetResult> GetAsync(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity) { return operations.GetAsync(resourceGroupName, identity, CancellationToken.None); } /// <summary> /// Get all of the resources under a subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='parameters'> /// Optional. Query parameters. If null is passed returns all resource /// groups. /// </param> /// <returns> /// List of resource groups. /// </returns> public static ResourceListResult List(this IResourceOperations operations, ResourceListParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).ListAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get all of the resources under a subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='parameters'> /// Optional. Query parameters. If null is passed returns all resource /// groups. /// </param> /// <returns> /// List of resource groups. /// </returns> public static Task<ResourceListResult> ListAsync(this IResourceOperations operations, ResourceListParameters parameters) { return operations.ListAsync(parameters, CancellationToken.None); } /// <summary> /// Get a list of deployments. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <returns> /// List of resource groups. /// </returns> public static ResourceListResult ListNext(this IResourceOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get a list of deployments. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <returns> /// List of resource groups. /// </returns> public static Task<ResourceListResult> ListNextAsync(this IResourceOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } /// <summary> /// Move resources within or across subscriptions. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='sourceResourceGroupName'> /// Required. Source resource group name. /// </param> /// <param name='parameters'> /// Required. move resources' parameters. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse MoveResources(this IResourceOperations operations, string sourceResourceGroupName, ResourcesMoveInfo parameters) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).MoveResourcesAsync(sourceResourceGroupName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Move resources within or across subscriptions. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='sourceResourceGroupName'> /// Required. Source resource group name. /// </param> /// <param name='parameters'> /// Required. move resources' parameters. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> MoveResourcesAsync(this IResourceOperations operations, string sourceResourceGroupName, ResourcesMoveInfo parameters) { return operations.MoveResourcesAsync(sourceResourceGroupName, parameters, CancellationToken.None); } } }
#if NET40 #define CUSTOM_THREADPOOL #endif using System; using System.Collections.Generic; using System.Linq; using System.Text; using Fact.Extensions; #if CUSTOM_THREADPOOL //using Castle.MicroKernel.Registration; #endif using System.Threading; using System.Threading.Tasks; using System.Reflection; namespace Fact.Extensions.Initialization { /// <summary> /// TODO: Consolodate this with the Collections version /// </summary> /// <typeparam name="T"></typeparam> public interface IFactory<T> { T Create(); } } namespace Fact.Extensions.Initialization { /// <summary> /// Collections tend to have an overhead to their internal lookup /// The "CanHandle" call is a specialized version which yields metadata which in turn can /// be used to optimize the next lookup call. /// For property bag stuff, it's like a "Contains" call /// </summary> /// <typeparam name="TKey"></typeparam> /// <remarks> /// Note these are not directly related to IAggregator UI validation interfaces /// </remarks> public interface IAggregateWithMeta<TKey> { bool CanHandle(TKey key, out object meta); } /// <summary> /// TODO: This could use a better name. IAggregate was chosen because aggregates sometimes are iterated over /// and inspected item by item to see which item can be handled /// </summary> /// <typeparam name="TKey"></typeparam> public interface IAggregate<TKey> { /// <summary> /// Returns whether this aggregate key can be processed /// </summary> /// <param name="key"></param> /// <returns></returns> /// <remarks> /// It is up to each aggregate to determine the meaning of processable/handleable /// </remarks> bool CanHandle(TKey key); } public static class IAggregate_Extensions { /// <summary> /// Iterate through can-handle items then execute specialized handler /// when one is found /// </summary> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TAggregateItem"></typeparam> /// <param name="aggregates"></param> /// <param name="key"></param> /// <param name="handler"></param> /// <param name="multi">when false, handles first item where "CanHandle = true". when true, handles all items which are "CanHandle = true"</param> public static bool Execute<TKey, TAggregateItem>(this IEnumerable<TAggregateItem> aggregates, TKey key, Action<TAggregateItem, TKey> handler, bool multi = false) where TAggregateItem: IAggregate<TKey> { bool found = false; foreach(var ai in aggregates) { if(ai.CanHandle(key)) { handler(ai, key); if (!multi) return true; found = true; } } return found; } } public interface IFactory<TInput, TOutput> { bool CanCreate(TInput id); TOutput Create(TInput id); } /// <summary> /// Meta provides an optimization cache area, since often the CanCreate does a lookup operation /// of some kind which then the create may have to repeat /// </summary> /// <typeparam name="TInput"></typeparam> /// <typeparam name="TOutput"></typeparam> public interface IFactoryWithMeta<TInput, TOutput> : IFactory<TInput, TOutput> { bool CanCreate(TInput id, out object meta); TOutput Create(TInput id, object meta); } public class FactoryAggregator<TInput, TOutput> : IFactoryWithMeta<TInput, TOutput> { LinkedList<IFactory<TInput, TOutput>> candidates = new LinkedList<IFactory<TInput, TOutput>>(); public IFactory<TInput, TOutput> GetCandidate(TInput id) { return candidates.FirstOrDefault(c => c.CanCreate(id)); /* foreach (var c in candidates) { if (c.CanCreate(id)) return c; } return null;*/ } internal class Meta { internal IFactory<TInput, TOutput> candidate; internal object meta; // meta associated with the found candidate linked to the ID #if DEBUG internal TInput id; #endif } IFactory<TInput, TOutput> GetCandidate(TInput id, out object meta) { foreach (var c in candidates) { var c_meta = c as IFactoryWithMeta<TInput, TOutput>; if (c_meta != null) { if (c_meta.CanCreate(id, out meta)) return c; } else { if (c.CanCreate(id)) { meta = null; return c; } } } meta = null; return null; } public bool CanCreate(TInput id) { return GetCandidate(id) != null; } public bool CanCreate(TInput id, out object meta) { var c = GetCandidate(id, out meta); if(c != null) { var _meta = new Meta() { meta = meta, candidate = c }; #if DEBUG _meta.id = id; #endif meta = _meta; return true; } return false; } public TOutput Create(TInput id) { var c = GetCandidate(id); if (c != null) return c.Create(id); throw new KeyNotFoundException(); } public TOutput Create(TInput id, object meta) { var _meta = meta as Meta; if(_meta != null) { var c_meta = _meta.candidate as IFactoryWithMeta<TInput, TOutput>; if(c_meta != null) { #if DEBUG if (!Object.Equals(_meta.id, id)) throw new ArgumentOutOfRangeException(); #endif return c_meta.Create(id, _meta.meta); } else { return _meta.candidate.Create(id); } } var c = GetCandidate(id); if (c != null) return c.Create(id); throw new KeyNotFoundException(); } public void Add(IFactory<TInput, TOutput> candidate) { candidates.AddLast(candidate); } } public class DelegateFactory<TInput, TOutput> : IFactory<TInput, TOutput> { readonly Func<TInput, bool> canCreate; readonly Func<TInput, TOutput> create; public DelegateFactory(Func<TInput, bool> canCreate, Func<TInput, TOutput> create) { this.canCreate = canCreate; this.create = create; } public bool CanCreate(TInput id) { return canCreate(id); } public TOutput Create(TInput id) { return create(id); } } #if UNUSED public class FactoryAggregator<TInput, TOutput> : IFactory<TInput, TOutput> { Lookup<TInput, IFactory<TInput, TOutput>> canService; public bool CanCreate(TInput id) { var result = canService[id]; if (result != null && result.CountTo(1) > 0) return true; return true; } public TOutput Create(TInput id) { return canService[id].First().Create(id); } } #endif public abstract class ChildSyncMeta<T> : DependencyBuilderNode<T>.Meta { public ChildSyncMeta(string key, DependencyBuilderNode<T> item) : base(key, item) { // when child is added, register child as something this item depends on // to reach satisfied state item.ChildAdded += Handler; // when dig phase completes, check to see if we can satisfy the dependency // (in this case, check to see that all parents have uninitialized, so that // we can too) item.DigEnded += _item => EvalSatisfy (); } } public abstract class ChildAsyncMeta<T> : DependencyBuilderNode<T>.Meta { public ChildAsyncMeta(string key, DependencyBuilderNode<T> item) : base(key, item) { // when child is added, register child as something this item depends on // to reach satisfied state. However, this is only tracked so that outside // processes know when the entire ChildAsyncMeta tree is done. The tree // item.ChildAdded += _item => EvalSatisfy2(); item.DigEnded += HandleDigEnded; } void HandleDigEnded (DependencyBuilder<T>.Node obj) { } public void EvalSatisfy2 () { satisfyTask = Task.Factory.StartNew (() => { Satisfy(); /* if(Satisfied != null) Satisfied(this);*/ // dependencies work in reverse for async, since we don't know all the proper dendencies // until the end of the dig but don't want to wait until the end of the dig Dependencies.Add(Item); var children = Item.Children as ICollection<DependencyBuilder<T>.Node>; var count = children == null ? Item.Children.Count() : children.Count; // If we reach the same number of dependencies accumulated as children AND we are // finished digging, then do stuff if(Dependencies.Count == count) { } }); } public override void Start () { // begin evaluations immediately EvalSatisfy (); } } #if UNUSED public class AssemblyDependencyBuilder_TEST : DependencyBuilder<Assembly> { internal class InitAsyncMeta : ChildAsyncMeta<Assembly> { internal InitAsyncMeta(Item item) : base("initAsync", item) {} protected override void Satisfy () { var item = (Item)Item; ((ILoaderAsync)item.loader).Load (); } protected override bool ShouldSatisfy { get { return ((Item)Item).loader is ILoaderAsync; } } } internal class InitSyncMeta : ChildSyncMeta<Assembly> { internal InitSyncMeta(Item item) : base("initSync", item) {} protected override void Satisfy () { ((ILoader)((Item)Item).loader).Initialize (); } protected override bool ShouldSatisfy { get { return ((Item)Item).loader is ILoader; } } } public new class Item : _DependencyBuilderItem<Assembly> { public readonly object loader; public Item(Assembly key) { loader = key.CreateInstance("Fact._Global.Loader"); var initAsync = new InitAsyncMeta(this); Add(initAsync); Add(new InitSyncMeta(this)); } public override IEnumerable<Assembly> GetChildren () { // FIX: need to not duplicate this from AssemblyDependencyBuilder._Item return value.GetReferencedAssemblies(). Where(x => Initializer.SkipAssembly.FirstOrDefault(y => x.Name.StartsWith(y)) == null). Where(x => !Initializer.Inspected.Contains(x.Name)). Select(x => System.Reflection.Assembly.Load(x)); } } protected override DependencyBuilder<Assembly>.Item CreateItem (Assembly key) { return new Item (key); } } #endif #if !NETCORE public class AssemblyUninitializeMeta : _DependencyBuilderItem<Assembly>.Meta { public AssemblyUninitializeMeta(_DependencyBuilderItem<Assembly> item) : base("uninitialize", item) { // when parent is added, register parent as something this item depends on // for uninitialization item.ParentAdded += Handler; // when dig phase completes, check to see if we can satisfy the dependency // (in this case, check to see that all parents have uninitialized, so that // we can too) item.DigEnded += _item => EvalSatisfy (); } protected override bool ShouldSatisfy { get { var item = ((AssemblyDependencyBuilder._Item)Item); return item.loader is ILoaderShutdown; } } protected override void Satisfy () { var item = ((AssemblyDependencyBuilder._Item)Item); (( ILoaderShutdown)item.loader).Shutdown(); } } #endif public abstract class UninitializingItem<T> : DependencyBuilderNode<T> { HashSet<UninitializingItem<T>> ParentUninitialized = new HashSet<UninitializingItem<T>>(); public bool IsUninitialized { get; private set; } /// <summary> /// Uninitialize events are still fired, but the actual Uninitialize call is skipped /// if this is false. Events still need to fire because consider parent A, child B, /// then child C of child B. If child B has no uninitialization code but A and C do /// we still need to "skip a generation" so that C properly knows when to uninit. /// </summary> /// <value><c>true</c> if should uninitialize; otherwise, <c>false</c>.</value> protected abstract bool ShouldUninitialize { get; } public class UninitializeMeta : Meta { protected override void Satisfy () { throw new NotImplementedException (); /* var item = Item; var loader = ((AssemblyDependencyBuilder._Item)Item).loader; ((ILoaderShutdown)loader).Shutdown ();*/ } protected override bool ShouldSatisfy { get { throw new NotImplementedException (); /* ((AssemblyDependencyBuilder._Item)Item).loader is ILoaderShutdown; */ } } public UninitializeMeta(string key, DependencyBuilderNode<T> item) : base(key, item) { //item.ParentAdded += Handler; } } public UninitializingItem(T value) : base(value) { // handler for uninitialization is created and registered var uninitializeMeta = new UninitializeMeta ("parent", this); Add (uninitializeMeta); // when parent is added, register parent as something this item depends on // for uninitialization ParentAdded += uninitializeMeta.Handler; // when dig phase completes, check to see if we can satisfy the dependency // (in this case, check to see that all parents have uninitialized, so that // we can too) DigEnded += item => { uninitializeMeta.EvalSatisfy(); }; } public event Action<UninitializingItem<T>> Uninitialized; void EvalUninitialize() { if(ParentUninitialized.Count == 0) { if (ShouldUninitialize) { Uninitialize (); } if (Uninitialized != null) Uninitialized (this); } } protected abstract void Uninitialize (); } #if !NETCORE public class AssemblyUninitializingDependencyBuilder : DependencyBuilder<Assembly> { public class Item : UninitializingItem<Assembly> { object loader = null; protected override bool ShouldUninitialize { get { return loader is ILoaderShutdown; } } protected override void Uninitialize () { ((ILoaderShutdown)loader).Shutdown (); } public override IEnumerable<Assembly> GetChildren () { // FIX: need to not duplicate this from AssemblyDependencyBuilder._Item return value.GetReferencedAssemblies(). Where(x => Initializer.SkipAssembly.FirstOrDefault(y => x.Name.StartsWith(y)) == null). Where(x => !Initializer.Inspected.Contains(x.Name)). Select(x => System.Reflection.Assembly.Load(x)); } } protected override DependencyBuilder<Assembly>.Item CreateItem (Assembly key) { return new Item (); } } #endif }
using System; using System.Collections.Generic; using System.Data; using System.Linq; namespace ImportToSRP3.Models { public abstract class UploadedFileBase { protected List<Individual> Individuals; protected SRP3Entities DbContext; protected DataSet Result; protected long ClusterId; protected long NationalCommunityId; protected abstract Dictionary<string, bool> Columns { get; set; } protected void AddBooks(Individual individual, bool b1, bool b2, bool b31, bool b32, bool b33, bool b4, bool b5, bool b6, bool b7, bool b8, bool b9, bool b10) { individual.ActivityStudyItemIndividuals = new List<ActivityStudyItemIndividual>(); if (b1) { individual.ActivityStudyItemIndividuals.Add(AddBook(1, 1)); } if (b2) { individual.ActivityStudyItemIndividuals.Add(AddBook(2, 2)); } if (b31) { individual.ActivityStudyItemIndividuals.Add(AddBook(3, 3)); } if (b32) { individual.ActivityStudyItemIndividuals.Add(AddBook(3, 4)); } if (b33) { individual.ActivityStudyItemIndividuals.Add(AddBook(3, 5)); } if (b4) { individual.ActivityStudyItemIndividuals.Add(AddBook(4, 6)); } if (b5) { individual.ActivityStudyItemIndividuals.Add(AddBook(5, 7)); } if (b6) { individual.ActivityStudyItemIndividuals.Add(AddBook(6, 8)); } if (b7) { individual.ActivityStudyItemIndividuals.Add(AddBook(7, 9)); } if (b8) { individual.ActivityStudyItemIndividuals.Add(AddBook(8, 10)); } if (b9) { individual.ActivityStudyItemIndividuals.Add(AddBook(9, 11)); } if (b10) { individual.ActivityStudyItemIndividuals.Add(AddBook(10, 12)); } } private ActivityStudyItemIndividual AddBook(int number, int sequence) { var asii = new ActivityStudyItemIndividual() { IndividualType = 1, IndividualRole = 7, IsCurrent = true, IsCompleted = true, StudyItemId = DbContext.StudyItems.First(si => si.ActivityStudyItemType == "Book" && si.Number == number && si.Sequence == sequence).Id, CreatedTimestamp = DateTime.Now, LastUpdatedTimestamp = DateTime.Now, }; return asii; } protected void AddIndividualEmails(Individual individual, string email) { individual.IndividualEmails = new List<IndividualEmail>(); short order = 0; if (!string.IsNullOrEmpty(email)) { ++order; individual.IndividualEmails.Add(new IndividualEmail() { Order = order, LastUpdatedTimestamp = DateTime.Now, CreatedTimestamp = DateTime.Now, Email = email, }); } } protected void AddIndividualPhones(Individual individual, string homeTelephone, string workTelephone, string cellPhone) { individual.IndividualPhones = new List<IndividualPhone>(); short order = 0; if (!string.IsNullOrEmpty(homeTelephone)) { ++order; individual.IndividualPhones.Add(new IndividualPhone() { Order = order, LastUpdatedTimestamp = DateTime.Now, CreatedTimestamp = DateTime.Now, Phone = homeTelephone, }); } if (!string.IsNullOrEmpty(workTelephone)) { ++order; individual.IndividualPhones.Add(new IndividualPhone() { Order = order, LastUpdatedTimestamp = DateTime.Now, CreatedTimestamp = DateTime.Now, Phone = workTelephone, }); } if (!string.IsNullOrEmpty(cellPhone)) { ++order; individual.IndividualPhones.Add(new IndividualPhone() { Order = order, LastUpdatedTimestamp = DateTime.Now, CreatedTimestamp = DateTime.Now, Phone = cellPhone, }); } } protected string GetAddress(string address, string suburb, string code) { var result = string.Empty; if (!string.IsNullOrEmpty(address)) result += address + Environment.NewLine; if (!string.IsNullOrEmpty(suburb)) result += suburb + Environment.NewLine; if (!string.IsNullOrEmpty(code)) result += code + Environment.NewLine; return result; } protected long? GetFocusNeighborhood(long localityId, string focusNeighborhoodName) { if (string.IsNullOrEmpty(focusNeighborhoodName)) return null; var foc = DbContext.Subdivisions.FirstOrDefault(f => f.LocalityId == localityId && f.Name == focusNeighborhoodName); if (foc == null) { foc = new Subdivision() { Name = focusNeighborhoodName, CreatedTimestamp = DateTime.Now, LastUpdatedTimestamp = DateTime.Now, LocalityId = localityId }; DbContext.Subdivisions.Add(foc); DbContext.SaveChanges(); } return foc.Id; } protected long GetLocality(string localityName) { var loc = DbContext.Localities.FirstOrDefault(l => l.ClusterId == ClusterId && l.Name == localityName); if (loc == null) { loc = new Locality() { Name = localityName, CreatedTimestamp = DateTime.Now, LastUpdatedTimestamp = DateTime.Now, ClusterId = ClusterId, GUID = Guid.NewGuid() }; DbContext.Localities.Add(loc); DbContext.SaveChanges(); } return loc.Id; } protected void GetRegistrationDate(Individual i, string registrationDate) { if (!string.IsNullOrEmpty(registrationDate)) { DateTime regDate; if (DateTime.TryParse(registrationDate, out regDate)) { i.RegistrationDate = regDate; i.DisplayRegistrationDate = regDate.ToString("yyyy-MM-dd"); return; } } //i.RegistrationDate = new DateTime(DateTime.Now.Year, 1, 1); //i.DisplayRegistrationDate = i.RegistrationDate.Value.ToString("yyyy-MM-dd"); } protected void GetEstimatedYearOfBirthDate(Individual i, string ageCategory, string estimatedAge, string birthDate) { i.IsSelectedEstimatedYearOfBirthDate = true; if (!string.IsNullOrEmpty(birthDate)) { DateTime dob; if (DateTime.TryParse(birthDate, out dob)) { i.EstimatedYearOfBirthDate = (short)dob.Year; i.BirthDate = dob; i.DisplayBirthDate = dob.ToString("yyyy-MM-dd"); i.IsSelectedEstimatedYearOfBirthDate = false; return; } } if (!string.IsNullOrEmpty(estimatedAge)) { short age; if (Int16.TryParse(estimatedAge, out age)) { i.EstimatedYearOfBirthDate = (short)(DateTime.Now.Year - age); i.BirthDate = new DateTime(i.EstimatedYearOfBirthDate.Value, 1, 1); i.DisplayBirthDate = i.EstimatedYearOfBirthDate.Value.ToString(); return; } } if (!string.IsNullOrEmpty(ageCategory)) { Random r = new Random(); ageCategory = ageCategory.ToLower(); if (ageCategory == "adult") { i.EstimatedYearOfBirthDate = (short)(DateTime.Now.Year - r.Next(21, 60)); } else if (ageCategory == "junior Youth") { i.EstimatedYearOfBirthDate = (short)(DateTime.Now.Year - r.Next(11, 16)); } else if (ageCategory == "youth") { i.EstimatedYearOfBirthDate = (short)(DateTime.Now.Year - r.Next(16, 21)); } else if (ageCategory == "child") { i.EstimatedYearOfBirthDate = (short)(DateTime.Now.Year - r.Next(0, 11)); } else { i.EstimatedYearOfBirthDate = 1900; } i.BirthDate = new DateTime(i.EstimatedYearOfBirthDate.Value, 1, 1); i.DisplayBirthDate = i.EstimatedYearOfBirthDate.Value.ToString(); } } protected long GetCluster(string clusterName,long regionId) { var c = DbContext.Clusters.FirstOrDefault(n => n.Name == clusterName && n.RegionId == regionId); if (c == null) { c = new Cluster() { Name = clusterName, CreatedTimestamp = DateTime.Now, LastUpdatedTimestamp = DateTime.Now, RegionId = regionId, GUID = Guid.NewGuid() }; DbContext.Clusters.Add(c); DbContext.SaveChanges(); return c.Id; } return c.Id; } protected long GetRegion(string regionName,long nationalCommunityId) { var r = DbContext.Regions.FirstOrDefault(n => n.Name == regionName && n.NationalCommunityId == nationalCommunityId); if (r == null) { r = new Region() { Name = regionName, CreatedTimestamp = DateTime.Now, LastUpdatedTimestamp = DateTime.Now, NationalCommunityId = nationalCommunityId, GUID = Guid.NewGuid() }; DbContext.Regions.Add(r); DbContext.SaveChanges(); return r.Id; } return r.Id; } public abstract List<Individual> SerializeIndividuals(); } }
//--------------------------------------------------------------------- // <copyright file="Set.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Linq; namespace System.Data.Common.Utils { // An interface for a set abstraction internal class Set<TElement> : InternalBase, IEnumerable<TElement> { #region Fields /// <summary> /// Instance of set value comparer. /// </summary> internal static readonly IEqualityComparer<Set<TElement>> ValueComparer = new SetValueComparer(); /// <summary> /// Instance of empty set with default comparer. /// </summary> internal static readonly Set<TElement> Empty = new Set<TElement>().MakeReadOnly(); private readonly HashSet<TElement> _values; private bool _isReadOnly; #endregion #region Constructors /// <summary> /// Initialize set with the same values and comparer as other set. /// </summary> internal Set(Set<TElement> other) : this(other._values, other.Comparer) { } /// <summary> /// Initialize empty set with default comparer. /// </summary> internal Set() : this(null, null) { } /// <summary> /// Initialize a set with the given elements and using default comparer. /// </summary> internal Set(IEnumerable<TElement> elements) : this(elements, null) { } /// <summary> /// Initializes an empty set with the given comparer. /// </summary> internal Set(IEqualityComparer<TElement> comparer) : this(null, comparer) { } /// <summary> /// Initialize a set with the given elements and comparer. /// </summary> internal Set(IEnumerable<TElement> elements, IEqualityComparer<TElement> comparer) { _values = new HashSet<TElement>( elements ?? Enumerable.Empty<TElement>(), comparer ?? EqualityComparer<TElement>.Default); } #endregion #region Properties /// <summary> /// Gets the number of elements in this set. /// </summary> internal int Count { get { return _values.Count; } } /// <summary> /// Gets the comparer used to determine equality and hash codes for elements of the set. /// </summary> internal IEqualityComparer<TElement> Comparer { get { return _values.Comparer; } } #endregion #region Methods /// <summary> /// Determines whether the given element exists in the set. /// </summary> internal bool Contains(TElement element) { return _values.Contains(element); } /// <summary> /// Requires: !IsReadOnly /// Adds given element to the set. If the set already contains /// the element, does nothing. /// </summary> internal void Add(TElement element) { AssertReadWrite(); _values.Add(element); } /// <summary> /// Requires: !IsReadOnly /// Adds given elements to the set. If the set already contains /// one of the elements, does nothing. /// </summary> internal void AddRange(IEnumerable<TElement> elements) { AssertReadWrite(); foreach (TElement element in elements) { Add(element); } } /// <summary> /// Requires: !IsReadOnly /// Removes given element from the set. If the set does not contain /// the element, does nothing. /// </summary> internal void Remove(TElement element) { AssertReadWrite(); _values.Remove(element); } /// <summary> /// Requires: !IsReadOnly /// Removes all elements from the set. /// </summary> internal void Clear() { AssertReadWrite(); _values.Clear(); } /// <summary> /// Returns an array containing all elements of the set. Order is arbitrary. /// </summary> internal TElement[] ToArray() { return _values.ToArray(); } /// <summary> /// Requires: other set must not be null and must have the same comparer. /// Returns true if this set contains the same elements as the other set. /// </summary> internal bool SetEquals(Set<TElement> other) { AssertSetCompatible(other); return _values.Count == other._values.Count && _values.IsSubsetOf(other._values); } /// <summary> /// Requires: other set must not be null and must have the same comparer. /// Returns true if all elements in this set are contained in the other set. /// </summary> internal bool IsSubsetOf(Set<TElement> other) { AssertSetCompatible(other); return _values.IsSubsetOf(other._values); } /// <summary> /// Requires: other set must not be null and must have the same comparer. /// Returns true if this set and other set have some elements in common. /// </summary> internal bool Overlaps(Set<TElement> other) { AssertSetCompatible(other); return _values.Overlaps(other._values); } /// <summary> /// Requires: !IsReadOnly /// Requires: other collection must not be null. /// Subtracts other set from this set, leaving the result in this. /// </summary> internal void Subtract(IEnumerable<TElement> other) { AssertReadWrite(); _values.ExceptWith(other); } /// <summary> /// Requires: other collection must not be null. /// Subtracts other set from this set, returning result. /// </summary> internal Set<TElement> Difference(IEnumerable<TElement> other) { Set<TElement> copy = new Set<TElement>(this); copy.Subtract(other); return copy; } /// <summary> /// Requires: !IsReadOnly /// Requires: other collection must not be null. /// Unions other set with this set, leaving the result in this set. /// </summary> internal void Unite(IEnumerable<TElement> other) { AssertReadWrite(); _values.UnionWith(other); } /// <summary> /// Requires: other collection must not be null. /// Unions other set with this set, returning the result. /// </summary> internal Set<TElement> Union(IEnumerable<TElement> other) { Set<TElement> copy = new Set<TElement>(this); copy.Unite(other); return copy; } /// <summary> /// Requires: !IsReadOnly /// Requires: other set must not be null and must have the same comparer. /// Intersects this set and other set, leaving the result in this set. /// </summary> internal void Intersect(Set<TElement> other) { AssertReadWrite(); AssertSetCompatible(other); _values.IntersectWith(other._values); } /// <summary> /// Returns a readonly version of this set. /// </summary> internal Set<TElement> AsReadOnly() { if (_isReadOnly) { // once it's readonly, it's always readonly return this; } Set<TElement> copy = new Set<TElement>(this); copy._isReadOnly = true; return copy; } /// <summary> /// Makes this set readonly and returns this set. /// </summary> internal Set<TElement> MakeReadOnly() { _isReadOnly = true; return this; } /// <summary> /// Returns aggregate hash code of all elements in this set. /// </summary> internal int GetElementsHashCode() { int hashCode = 0; foreach (TElement element in this) { hashCode ^= Comparer.GetHashCode(element); } return hashCode; } /// <summary> /// Returns typed enumerator over elements of the set. /// Uses HashSet&lt;TElement&gt;.Enumerator to avoid boxing struct. /// </summary> public HashSet<TElement>.Enumerator GetEnumerator() { return _values.GetEnumerator(); } [Conditional("DEBUG")] private void AssertReadWrite() { Debug.Assert(!_isReadOnly, "attempting to modify readonly collection"); } [Conditional("DEBUG")] private void AssertSetCompatible(Set<TElement> other) { Debug.Assert(other != null, "other set null"); Debug.Assert(other.Comparer.GetType().Equals(this.Comparer.GetType())); } #endregion #region IEnumerable<TElement> Members public class Enumerator : IEnumerator<TElement> { private Dictionary<TElement, bool>.KeyCollection.Enumerator keys; internal Enumerator(Dictionary<TElement, bool>.KeyCollection.Enumerator keys) { this.keys = keys; } public TElement Current { get { return keys.Current; } } public void Dispose() { keys.Dispose(); } object IEnumerator.Current { get { return ((IEnumerator)keys).Current; } } public bool MoveNext() { return keys.MoveNext(); } void System.Collections.IEnumerator.Reset() { ((System.Collections.IEnumerator)keys).Reset(); } } IEnumerator<TElement> IEnumerable<TElement>.GetEnumerator() { return this.GetEnumerator(); } #endregion #region IEnumerable Members /// <summary> /// Returns an untyped enumeration of elements in the set. /// </summary> /// <returns>Enumeration of set members.</returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion #region InternalBase internal override void ToCompactString(StringBuilder builder) { StringUtil.ToCommaSeparatedStringSorted(builder, this); } #endregion #region Nested types private class SetValueComparer : IEqualityComparer<Set<TElement>> { bool IEqualityComparer<Set<TElement>>.Equals(Set<TElement> x, Set<TElement> y) { Debug.Assert(null != x && null != y, "comparer must be used only in context of Dictionary/HashSet"); return x.SetEquals(y); } int IEqualityComparer<Set<TElement>>.GetHashCode(Set<TElement> obj) { Debug.Assert(null != obj, "comparer must be used only in context of Dictionary/HashSet"); return obj.GetElementsHashCode(); } } #endregion } }
//Copyright (c) ServiceStack, Inc. All Rights Reserved. //License: https://raw.github.com/ServiceStack/ServiceStack/master/license.txt using System; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using ServiceStack.Text.Common; using ServiceStack.Text.Json; namespace ServiceStack.Text.Jsv { public struct JsvTypeSerializer : ITypeSerializer { public static ITypeSerializer Instance = new JsvTypeSerializer(); public ObjectDeserializerDelegate ObjectDeserializer { get; set; } public bool IncludeNullValues => false; public bool IncludeNullValuesInDictionaries => false; public string TypeAttrInObject => JsConfig.JsvTypeAttrInObject; internal static string GetTypeAttrInObject(string typeAttr) => $"{{{typeAttr}:"; public WriteObjectDelegate GetWriteFn<T>() => JsvWriter<T>.WriteFn(); public WriteObjectDelegate GetWriteFn(Type type) => JsvWriter.GetWriteFn(type); static readonly TypeInfo DefaultTypeInfo = new TypeInfo { EncodeMapKey = false }; public TypeInfo GetTypeInfo(Type type) => DefaultTypeInfo; public void WriteRawString(TextWriter writer, string value) { writer.Write(value.EncodeJsv()); } public void WritePropertyName(TextWriter writer, string value) { writer.Write(value); } public void WriteBuiltIn(TextWriter writer, object value) { writer.Write(value); } public void WriteObjectString(TextWriter writer, object value) { if (value != null) { if (value is string strValue) { WriteString(writer, strValue); } else { writer.Write(value.ToString().EncodeJsv()); } } } public void WriteException(TextWriter writer, object value) { writer.Write(((Exception)value).Message.EncodeJsv()); } public void WriteString(TextWriter writer, string value) { if (JsState.QueryStringMode && !string.IsNullOrEmpty(value) && value.StartsWith(JsWriter.QuoteString) && value.EndsWith(JsWriter.QuoteString)) value = String.Concat(JsWriter.QuoteChar, value, JsWriter.QuoteChar); else if (JsState.QueryStringMode && !string.IsNullOrEmpty(value) && value.Contains(JsWriter.ItemSeperatorString)) value = String.Concat(JsWriter.QuoteChar, value, JsWriter.QuoteChar); writer.Write(value == "" ? "\"\"" : value.EncodeJsv()); } public void WriteFormattableObjectString(TextWriter writer, object value) { var f = (IFormattable)value; writer.Write(f.ToString(null, CultureInfo.InvariantCulture).EncodeJsv()); } public void WriteDateTime(TextWriter writer, object oDateTime) { var dateTime = (DateTime)oDateTime; switch (JsConfig.DateHandler) { case DateHandler.UnixTime: writer.Write(dateTime.ToUnixTime()); return; case DateHandler.UnixTimeMs: writer.Write(dateTime.ToUnixTimeMs()); return; } writer.Write(DateTimeSerializer.ToShortestXsdDateTimeString((DateTime)oDateTime)); } public void WriteNullableDateTime(TextWriter writer, object dateTime) { if (dateTime == null) return; WriteDateTime(writer, dateTime); } public void WriteDateTimeOffset(TextWriter writer, object oDateTimeOffset) { writer.Write(((DateTimeOffset)oDateTimeOffset).ToString("o")); } public void WriteNullableDateTimeOffset(TextWriter writer, object dateTimeOffset) { if (dateTimeOffset == null) return; this.WriteDateTimeOffset(writer, dateTimeOffset); } public void WriteTimeSpan(TextWriter writer, object oTimeSpan) { writer.Write(DateTimeSerializer.ToXsdTimeSpanString((TimeSpan)oTimeSpan)); } public void WriteNullableTimeSpan(TextWriter writer, object oTimeSpan) { if (oTimeSpan == null) return; writer.Write(DateTimeSerializer.ToXsdTimeSpanString((TimeSpan?)oTimeSpan)); } public void WriteGuid(TextWriter writer, object oValue) { writer.Write(((Guid)oValue).ToString("N")); } public void WriteNullableGuid(TextWriter writer, object oValue) { if (oValue == null) return; writer.Write(((Guid)oValue).ToString("N")); } public void WriteBytes(TextWriter writer, object oByteValue) { if (oByteValue == null) return; writer.Write(Convert.ToBase64String((byte[])oByteValue)); } public void WriteChar(TextWriter writer, object charValue) { if (charValue == null) return; writer.Write((char)charValue); } public void WriteByte(TextWriter writer, object byteValue) { if (byteValue == null) return; writer.Write((byte)byteValue); } public void WriteSByte(TextWriter writer, object sbyteValue) { if (sbyteValue == null) return; writer.Write((sbyte)sbyteValue); } public void WriteInt16(TextWriter writer, object intValue) { if (intValue == null) return; writer.Write((short)intValue); } public void WriteUInt16(TextWriter writer, object intValue) { if (intValue == null) return; writer.Write((ushort)intValue); } public void WriteInt32(TextWriter writer, object intValue) { if (intValue == null) return; writer.Write((int)intValue); } public void WriteUInt32(TextWriter writer, object uintValue) { if (uintValue == null) return; writer.Write((uint)uintValue); } public void WriteUInt64(TextWriter writer, object ulongValue) { if (ulongValue == null) return; writer.Write((ulong)ulongValue); } public void WriteInt64(TextWriter writer, object longValue) { if (longValue == null) return; writer.Write((long)longValue); } public void WriteBool(TextWriter writer, object boolValue) { if (boolValue == null) return; writer.Write((bool)boolValue); } public void WriteFloat(TextWriter writer, object floatValue) { if (floatValue == null) return; var floatVal = (float)floatValue; var cultureInfo = JsState.IsCsv ? CsvConfig.RealNumberCultureInfo : null; if (Equals(floatVal, float.MaxValue) || Equals(floatVal, float.MinValue)) writer.Write(floatVal.ToString("r", cultureInfo ?? CultureInfo.InvariantCulture)); else writer.Write(floatVal.ToString("r", cultureInfo ?? CultureInfo.InvariantCulture)); } public void WriteDouble(TextWriter writer, object doubleValue) { if (doubleValue == null) return; var doubleVal = (double)doubleValue; var cultureInfo = JsState.IsCsv ? CsvConfig.RealNumberCultureInfo : null; if (Equals(doubleVal, double.MaxValue) || Equals(doubleVal, double.MinValue)) writer.Write(doubleVal.ToString("r", cultureInfo ?? CultureInfo.InvariantCulture)); else writer.Write(doubleVal.ToString(cultureInfo ?? CultureInfo.InvariantCulture)); } public void WriteDecimal(TextWriter writer, object decimalValue) { if (decimalValue == null) return; var cultureInfo = JsState.IsCsv ? CsvConfig.RealNumberCultureInfo : null; writer.Write(((decimal)decimalValue).ToString(cultureInfo ?? CultureInfo.InvariantCulture)); } public void WriteEnum(TextWriter writer, object enumValue) { if (enumValue == null) return; var serializedValue = CachedTypeInfo.Get(enumValue.GetType()).EnumInfo.GetSerializedValue(enumValue); if (serializedValue is string strEnum) writer.Write(strEnum); else JsWriter.WriteEnumFlags(writer, enumValue); } public ParseStringDelegate GetParseFn<T>() => JsvReader.Instance.GetParseFn<T>(); public ParseStringDelegate GetParseFn(Type type) => JsvReader.GetParseFn(type); public ParseStringSpanDelegate GetParseStringSpanFn<T>() => JsvReader.Instance.GetParseStringSpanFn<T>(); public ParseStringSpanDelegate GetParseStringSpanFn(Type type) => JsvReader.GetParseStringSpanFn(type); [MethodImpl(MethodImplOptions.AggressiveInlining)] public object UnescapeStringAsObject(ReadOnlySpan<char> value) { return UnescapeSafeString(value).Value(); } public string UnescapeSafeString(string value) => JsState.IsCsv ? value : value.FromCsvField(); public ReadOnlySpan<char> UnescapeSafeString(ReadOnlySpan<char> value) => JsState.IsCsv ? value // already unescaped in CsvReader.ParseFields() : value.FromCsvField(); public string ParseRawString(string value) => value; public string ParseString(string value) => value.FromCsvField(); public string ParseString(ReadOnlySpan<char> value) => value.ToString().FromCsvField(); public string UnescapeString(string value) => value.FromCsvField(); public ReadOnlySpan<char> UnescapeString(ReadOnlySpan<char> value) => value.FromCsvField(); public string EatTypeValue(string value, ref int i) => EatValue(value, ref i); public ReadOnlySpan<char> EatTypeValue(ReadOnlySpan<char> value, ref int i) => EatValue(value, ref i); public bool EatMapStartChar(string value, ref int i) => EatMapStartChar(value.AsSpan(), ref i); public bool EatMapStartChar(ReadOnlySpan<char> value, ref int i) { var success = value[i] == JsWriter.MapStartChar; if (success) i++; return success; } public string EatMapKey(string value, ref int i) => EatMapKey(value.AsSpan(), ref i).ToString(); public ReadOnlySpan<char> EatMapKey(ReadOnlySpan<char> value, ref int i) { var tokenStartPos = i; var valueLength = value.Length; var valueChar = value[tokenStartPos]; switch (valueChar) { case JsWriter.QuoteChar: while (++i < valueLength) { valueChar = value[i]; if (valueChar != JsWriter.QuoteChar) continue; var isLiteralQuote = i + 1 < valueLength && value[i + 1] == JsWriter.QuoteChar; i++; //skip quote if (!isLiteralQuote) break; } return value.Slice(tokenStartPos, i - tokenStartPos); //Is Type/Map, i.e. {...} case JsWriter.MapStartChar: var endsToEat = 1; var withinQuotes = false; while (++i < valueLength && endsToEat > 0) { valueChar = value[i]; if (valueChar == JsWriter.QuoteChar) withinQuotes = !withinQuotes; if (withinQuotes) continue; if (valueChar == JsWriter.MapStartChar) endsToEat++; if (valueChar == JsWriter.MapEndChar) endsToEat--; } return value.Slice(tokenStartPos, i - tokenStartPos); } while (value[++i] != JsWriter.MapKeySeperator) { } return value.Slice(tokenStartPos, i - tokenStartPos); } public bool EatMapKeySeperator(string value, ref int i) { return value[i++] == JsWriter.MapKeySeperator; } public bool EatMapKeySeperator(ReadOnlySpan<char> value, ref int i) { return value[i++] == JsWriter.MapKeySeperator; } public bool EatItemSeperatorOrMapEndChar(string value, ref int i) { if (i == value.Length) return false; var success = value[i] == JsWriter.ItemSeperator || value[i] == JsWriter.MapEndChar; if (success) i++; else if (Env.StrictMode) throw new Exception( $"Expected '{JsWriter.ItemSeperator}' or '{JsWriter.MapEndChar}'"); return success; } public bool EatItemSeperatorOrMapEndChar(ReadOnlySpan<char> value, ref int i) { if (i == value.Length) return false; var success = value[i] == JsWriter.ItemSeperator || value[i] == JsWriter.MapEndChar; if (success) i++; else if (Env.StrictMode) throw new Exception( $"Expected '{JsWriter.ItemSeperator}' or '{JsWriter.MapEndChar}'"); return success; } public void EatWhitespace(string value, ref int i) {} public void EatWhitespace(ReadOnlySpan<char> value, ref int i) { } public string EatValue(string value, ref int i) { return EatValue(value.AsSpan(), ref i).ToString(); } public ReadOnlySpan<char> EatValue(ReadOnlySpan<char> value, ref int i) { var tokenStartPos = i; var valueLength = value.Length; if (i == valueLength) return default; var valueChar = value[i]; var withinQuotes = false; var endsToEat = 1; switch (valueChar) { //If we are at the end, return. case JsWriter.ItemSeperator: case JsWriter.MapEndChar: return default; //Is Within Quotes, i.e. "..." case JsWriter.QuoteChar: while (++i < valueLength) { valueChar = value[i]; if (valueChar != JsWriter.QuoteChar) continue; var isLiteralQuote = i + 1 < valueLength && value[i + 1] == JsWriter.QuoteChar; i++; //skip quote if (!isLiteralQuote) break; } return value.Slice(tokenStartPos, i - tokenStartPos); //Is Type/Map, i.e. {...} case JsWriter.MapStartChar: while (++i < valueLength && endsToEat > 0) { valueChar = value[i]; if (valueChar == JsWriter.QuoteChar) withinQuotes = !withinQuotes; if (withinQuotes) continue; if (valueChar == JsWriter.MapStartChar) endsToEat++; if (valueChar == JsWriter.MapEndChar) endsToEat--; } return value.Slice(tokenStartPos, i - tokenStartPos); //Is List, i.e. [...] case JsWriter.ListStartChar: while (++i < valueLength && endsToEat > 0) { valueChar = value[i]; if (valueChar == JsWriter.QuoteChar) withinQuotes = !withinQuotes; if (withinQuotes) continue; if (valueChar == JsWriter.ListStartChar) endsToEat++; if (valueChar == JsWriter.ListEndChar) endsToEat--; } return value.Slice(tokenStartPos, i - tokenStartPos); } //Is Value while (++i < valueLength) { valueChar = value[i]; if (valueChar == JsWriter.ItemSeperator || valueChar == JsWriter.MapEndChar) { break; } } return value.Slice(tokenStartPos, i - tokenStartPos); } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Net; using System.Text; using System.Xml.Serialization; namespace WebsitePanel.Providers.Web { public class WebVirtualDirectory : ServiceProviderItem { #region Web Management Service Constants public const string WmSvcAvailable = "WmSvcAvailable"; public const string WmSvcSiteEnabled = "WmSvcSiteEnabled"; public const string WmSvcAccountName = "WmSvcAccountName"; public const string WmSvcAccountPassword = "WmSvcAccountPassword"; public const string WmSvcServiceUrl = "WmSvcServiceUrl"; public const string WmSvcServicePort = "WmSvcServicePort"; public const string WmSvcDefaultPort = "8172"; #endregion private string anonymousUsername; private string anonymousUserPassword; private string contentPath; private bool enableWritePermissions; private bool enableParentPaths; private bool enableDirectoryBrowsing; private bool enableAnonymousAccess; private bool enableWindowsAuthentication; private bool enableBasicAuthentication; private bool enableDynamicCompression; private bool enableStaticCompression; private string defaultDocs; private string httpRedirect; private HttpError[] httpErrors; private HttpErrorsMode errorMode; private HttpErrorsExistingResponse existingResponse; private MimeMap[] mimeMaps; private HttpHeader[] httpHeaders; private bool aspInstalled; private string aspNetInstalled; private string phpInstalled; private bool perlInstalled; private bool pythonInstalled; private bool coldfusionInstalled; private bool cgiBinInstalled; private string applicationPool; private bool dedicatedApplicationPool; private string parentSiteName; private bool redirectExactUrl; private bool redirectDirectoryBelow; private bool redirectPermanent; private bool sharePointInstalled; private bool iis7; private string consoleUrl; private string php5VersionsInstalled; public string AnonymousUsername { get { return anonymousUsername; } set { anonymousUsername = value; } } public string AnonymousUserPassword { get { return anonymousUserPassword; } set { anonymousUserPassword = value; } } public string ContentPath { get { return contentPath; } set { contentPath = value; } } public string HttpRedirect { get { return httpRedirect; } set { httpRedirect = value; } } public string DefaultDocs { get { return defaultDocs; } set { defaultDocs = value; } } public MimeMap[] MimeMaps { get { return mimeMaps; } set { mimeMaps = value; } } public HttpError[] HttpErrors { get { return httpErrors; } set { httpErrors = value; } } public HttpErrorsMode ErrorMode { get { return errorMode; } set { errorMode = value; } } public HttpErrorsExistingResponse ExistingResponse { get { return existingResponse; } set { existingResponse = value; } } public string ApplicationPool { get { return this.applicationPool; } set { this.applicationPool = value; } } public bool EnableParentPaths { get { return this.enableParentPaths; } set { this.enableParentPaths = value; } } public HttpHeader[] HttpHeaders { get { return this.httpHeaders; } set { this.httpHeaders = value; } } public bool EnableWritePermissions { get { return this.enableWritePermissions; } set { this.enableWritePermissions = value; } } public bool EnableDirectoryBrowsing { get { return this.enableDirectoryBrowsing; } set { this.enableDirectoryBrowsing = value; } } public bool EnableAnonymousAccess { get { return this.enableAnonymousAccess; } set { this.enableAnonymousAccess = value; } } public bool EnableWindowsAuthentication { get { return this.enableWindowsAuthentication; } set { this.enableWindowsAuthentication = value; } } public bool EnableBasicAuthentication { get { return this.enableBasicAuthentication; } set { this.enableBasicAuthentication = value; } } public bool EnableDynamicCompression { get { return this.enableDynamicCompression; } set { this.enableDynamicCompression = value; } } public bool EnableStaticCompression { get { return this.enableStaticCompression; } set { this.enableStaticCompression = value; } } public bool AspInstalled { get { return this.aspInstalled; } set { this.aspInstalled = value; } } public string AspNetInstalled { get { return this.aspNetInstalled; } set { this.aspNetInstalled = value; } } public string PhpInstalled { get { return this.phpInstalled; } set { this.phpInstalled = value; } } public bool PerlInstalled { get { return this.perlInstalled; } set { this.perlInstalled = value; } } public bool PythonInstalled { get { return this.pythonInstalled; } set { this.pythonInstalled = value; } } public bool ColdFusionInstalled { get { return this.coldfusionInstalled; } set { this.coldfusionInstalled = value; } } public bool DedicatedApplicationPool { get { return this.dedicatedApplicationPool; } set { this.dedicatedApplicationPool = value; } } public string ParentSiteName { get { return this.parentSiteName; } set { this.parentSiteName = value; } } public bool RedirectExactUrl { get { return this.redirectExactUrl; } set { this.redirectExactUrl = value; } } public bool RedirectDirectoryBelow { get { return this.redirectDirectoryBelow; } set { this.redirectDirectoryBelow = value; } } public bool RedirectPermanent { get { return this.redirectPermanent; } set { this.redirectPermanent = value; } } public bool CgiBinInstalled { get { return this.cgiBinInstalled; } set { this.cgiBinInstalled = value; } } public bool SharePointInstalled { get { return this.sharePointInstalled; } set { this.sharePointInstalled = value; } } public bool IIs7 { get { return this.iis7; } set { this.iis7 = value; } } public string ConsoleUrl { get { return consoleUrl; } set { consoleUrl = value; } } public string Php5VersionsInstalled { get { return php5VersionsInstalled; } set { php5VersionsInstalled = value; } } #region Web Deploy Publishing Properties /// <summary> /// Gets or sets Web Deploy publishing account name /// </summary> [Persistent] public string WebDeployPublishingAccount { get; set; } /// <summary> /// Gets or sets Web Deploy publishing password /// </summary> [Persistent] public string WebDeployPublishingPassword { get; set; } /// <summary> /// Gets or sets whether Web Deploy publishing is enabled on the server /// </summary> public bool WebDeployPublishingAvailable { get; set; } /// <summary> /// Gets or sets whether Web Deploy publishing is enabled for this particular web site /// </summary> [Persistent] public bool WebDeploySitePublishingEnabled { get; set; } /// <summary> /// Gets or sets Web Deploy publishing profile data for this particular web site /// </summary> [Persistent] public string WebDeploySitePublishingProfile { get; set; } #endregion /// <summary> /// Gets fully qualified name which consists of parent website name if present and virtual directory name. /// </summary> [XmlIgnore] public string VirtualPath { get { // virtual path is rooted if (String.IsNullOrEmpty(ParentSiteName)) return "/"; // else if (!Name.StartsWith("/")) return "/" + Name; // return Name; } } /// <summary> /// Gets fully qualified name which consists of parent website name if present and virtual directory name. /// </summary> [XmlIgnore] public string FullQualifiedPath { get { if (String.IsNullOrEmpty(ParentSiteName)) return Name; else if (Name.StartsWith("/")) return ParentSiteName + Name; else return ParentSiteName + "/" + Name; } } } }
/* math.c - Arithmetic, compare and logical opcodes * Copyright (c) 1995-1997 Stefan Jokisch * * This file is part of Frotz. * * Frotz 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. * * Frotz 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 */ using zword = System.UInt16; using zbyte = System.Byte; using Frotz; using Frotz.Constants; namespace Frotz.Generic { internal static class Math { /* * z_add, 16bit addition. * * zargs[0] = first value * zargs[1] = second value * */ internal static void z_add() { Process.store((zword)((short)Process.zargs[0] + (short)Process.zargs[1])); }/* z_add */ /* * z_and, bitwise AND operation. * * zargs[0] = first value * zargs[1] = second value * */ internal static void z_and() { Process.store((zword)(Process.zargs[0] & Process.zargs[1])); }/* z_and */ /* * z_art_shift, arithmetic SHIFT operation. * * zargs[0] = value * zargs[1] = #positions to shift left (positive) or right * */ internal static void z_art_shift() { // TODO This code has never been hit... I need to find something that will hit it if ((short)Process.zargs[1] > 0) Process.store((zword)((short)Process.zargs[0] << (short)Process.zargs[1])); else Process.store((zword)((short)Process.zargs[0] >> -(short)Process.zargs[1])); }/* z_art_shift */ /* * z_div, signed 16bit division. * * zargs[0] = first value * zargs[1] = second value * */ internal static void z_div() { if (Process.zargs[1] == 0) Err.runtime_error(ErrorCodes.ERR_DIV_ZERO); Process.store((zword)((short)Process.zargs[0] / (short)Process.zargs[1])); }/* z_div */ /* * z_je, branch if the first value equals any of the following. * * zargs[0] = first value * zargs[1] = second value (optional) * ... * zargs[3] = fourth value (optional) * */ internal static void z_je() { Process.branch( Process.zargc > 1 && (Process.zargs[0] == Process.zargs[1] || ( Process.zargc > 2 && (Process.zargs[0] == Process.zargs[2] || ( Process.zargc > 3 && (Process.zargs[0] == Process.zargs[3])))))); }/* z_je */ /* * z_jg, branch if the first value is greater than the second. * * zargs[0] = first value * zargs[1] = second value * */ internal static void z_jg() { Process.branch((short)Process.zargs[0] > (short)Process.zargs[1]); }/* z_jg */ /* * z_jl, branch if the first value is less than the second. * * zargs[0] = first value * zargs[1] = second value * */ internal static void z_jl() { Process.branch((short)Process.zargs[0] < (short)Process.zargs[1]); }/* z_jl */ /* * z_jz, branch if value is zero. * * zargs[0] = value * */ internal static void z_jz() { Process.branch((short)Process.zargs[0] == 0); }/* z_jz */ /* * z_log_shift, logical SHIFT operation. * * zargs[0] = value * zargs[1] = #positions to shift left (positive) or right (negative) * */ internal static void z_log_shift() { if ((short)Process.zargs[1] > 0) Process.store((zword)(Process.zargs[0] << (short)Process.zargs[1])); else Process.store((zword)(Process.zargs[0] >> -(short)Process.zargs[1])); }/* z_log_shift */ /* * z_mod, remainder after signed 16bit division. * * zargs[0] = first value * zargs[1] = second value * */ internal static void z_mod() { if (Process.zargs[1] == 0) Err.runtime_error(ErrorCodes.ERR_DIV_ZERO); Process.store((zword)((short)Process.zargs[0] % (short)Process.zargs[1])); }/* z_mod */ /* * z_mul, 16bit multiplication. * * zargs[0] = first value * zargs[1] = second value * */ internal static void z_mul() { Process.store((zword)((short)Process.zargs[0] * (short)Process.zargs[1])); }/* z_mul */ /* * z_not, bitwise NOT operation. * * zargs[0] = value * */ internal static void z_not() { Process.store ((zword) ~Process.zargs[0]); }/* z_not */ /* * z_or, bitwise OR operation. * * zargs[0] = first value * zargs[1] = second value * */ internal static void z_or() { Process.store((zword)(Process.zargs[0] | Process.zargs[1])); }/* z_or */ /* * z_sub, 16bit substraction. * * zargs[0] = first value * zargs[1] = second value * */ internal static void z_sub() { Process.store((zword)((short)Process.zargs[0] - (short)Process.zargs[1])); }/* z_sub */ /* * z_test, branch if all the flags of a bit mask are set in a value. * * zargs[0] = value to be examined * zargs[1] = bit mask * */ internal static void z_test() { Process.branch((Process.zargs[0] & Process.zargs[1]) == Process.zargs[1]); }/* z_test */ } }
// 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.Security; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime { // This is a set of stub methods implementing the support for the IReadOnlyDictionary`2 interface on WinRT // objects that support IMapView`2. Used by the interop mashaling infrastructure. // // The methods on this class must be written VERY carefully to avoid introducing security holes. // That's because they are invoked with special "this"! The "this" object // for all of these methods are not IMapViewToIReadOnlyDictionaryAdapter objects. Rather, they are of type // IMapView<K, V>. No actual IMapViewToIReadOnlyDictionaryAdapter object is ever instantiated. Thus, you will see // a lot of expressions that cast "this" to "IMapView<K, V>". [DebuggerDisplay("Count = {Count}")] internal sealed class IMapViewToIReadOnlyDictionaryAdapter { private IMapViewToIReadOnlyDictionaryAdapter() { Debug.Assert(false, "This class is never instantiated"); } // V this[K key] { get } internal V Indexer_Get<K, V>(K key) { if (key == null) throw new ArgumentNullException(nameof(key)); Contract.EndContractBlock(); IMapView<K, V> _this = JitHelpers.UnsafeCast<IMapView<K, V>>(this); return Lookup(_this, key); } // IEnumerable<K> Keys { get } internal IEnumerable<K> Keys<K, V>() { IMapView<K, V> _this = JitHelpers.UnsafeCast<IMapView<K, V>>(this); IReadOnlyDictionary<K, V> roDictionary = (IReadOnlyDictionary<K, V>)_this; return new ReadOnlyDictionaryKeyCollection<K, V>(roDictionary); } // IEnumerable<V> Values { get } internal IEnumerable<V> Values<K, V>() { IMapView<K, V> _this = JitHelpers.UnsafeCast<IMapView<K, V>>(this); IReadOnlyDictionary<K, V> roDictionary = (IReadOnlyDictionary<K, V>)_this; return new ReadOnlyDictionaryValueCollection<K, V>(roDictionary); } // bool ContainsKey(K key) [Pure] internal bool ContainsKey<K, V>(K key) { if (key == null) throw new ArgumentNullException(nameof(key)); IMapView<K, V> _this = JitHelpers.UnsafeCast<IMapView<K, V>>(this); return _this.HasKey(key); } // bool TryGetValue(TKey key, out TValue value) internal bool TryGetValue<K, V>(K key, out V value) { if (key == null) throw new ArgumentNullException(nameof(key)); IMapView<K, V> _this = JitHelpers.UnsafeCast<IMapView<K, V>>(this); // It may be faster to call HasKey then Lookup. On failure, we would otherwise // throw an exception from Lookup. if (!_this.HasKey(key)) { value = default(V); return false; } try { value = _this.Lookup(key); return true; } catch (Exception ex) // Still may hit this case due to a race condition { if (__HResults.E_BOUNDS == ex._HResult) { value = default(V); return false; } throw; } } #region Helpers private static V Lookup<K, V>(IMapView<K, V> _this, K key) { Contract.Requires(null != key); try { return _this.Lookup(key); } catch (Exception ex) { if (__HResults.E_BOUNDS == ex._HResult) throw new KeyNotFoundException(Environment.GetResourceString("Arg_KeyNotFound")); throw; } } #endregion Helpers } // Note: One day we may make these return IReadOnlyCollection<T> [Serializable] [DebuggerDisplay("Count = {Count}")] internal sealed class ReadOnlyDictionaryKeyCollection<TKey, TValue> : IEnumerable<TKey> { private readonly IReadOnlyDictionary<TKey, TValue> dictionary; public ReadOnlyDictionaryKeyCollection(IReadOnlyDictionary<TKey, TValue> dictionary) { if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); this.dictionary = dictionary; } /* public void CopyTo(TKey[] array, int index) { if (array == null) throw new ArgumentNullException(nameof(array)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); if (array.Length <= index && this.Count > 0) throw new ArgumentException(Environment.GetResourceString("Arg_IndexOutOfRangeException")); if (array.Length - index < dictionary.Count) throw new ArgumentException(Environment.GetResourceString("Argument_InsufficientSpaceToCopyCollection")); int i = index; foreach (KeyValuePair<TKey, TValue> mapping in dictionary) { array[i++] = mapping.Key; } } public int Count { get { return dictionary.Count; } } public bool Contains(TKey item) { return dictionary.ContainsKey(item); } */ IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<TKey>)this).GetEnumerator(); } public IEnumerator<TKey> GetEnumerator() { return new ReadOnlyDictionaryKeyEnumerator<TKey, TValue>(dictionary); } } // public class ReadOnlyDictionaryKeyCollection<TKey, TValue> [Serializable] internal sealed class ReadOnlyDictionaryKeyEnumerator<TKey, TValue> : IEnumerator<TKey> { private readonly IReadOnlyDictionary<TKey, TValue> dictionary; private IEnumerator<KeyValuePair<TKey, TValue>> enumeration; public ReadOnlyDictionaryKeyEnumerator(IReadOnlyDictionary<TKey, TValue> dictionary) { if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); this.dictionary = dictionary; this.enumeration = dictionary.GetEnumerator(); } void IDisposable.Dispose() { enumeration.Dispose(); } public bool MoveNext() { return enumeration.MoveNext(); } Object IEnumerator.Current { get { return ((IEnumerator<TKey>)this).Current; } } public TKey Current { get { return enumeration.Current.Key; } } public void Reset() { enumeration = dictionary.GetEnumerator(); } } // class ReadOnlyDictionaryKeyEnumerator<TKey, TValue> [Serializable] [DebuggerDisplay("Count = {Count}")] internal sealed class ReadOnlyDictionaryValueCollection<TKey, TValue> : IEnumerable<TValue> { private readonly IReadOnlyDictionary<TKey, TValue> dictionary; public ReadOnlyDictionaryValueCollection(IReadOnlyDictionary<TKey, TValue> dictionary) { if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); this.dictionary = dictionary; } /* public void CopyTo(TValue[] array, int index) { if (array == null) throw new ArgumentNullException(nameof(array)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); if (array.Length <= index && this.Count > 0) throw new ArgumentException(Environment.GetResourceString("Arg_IndexOutOfRangeException")); if (array.Length - index < dictionary.Count) throw new ArgumentException(Environment.GetResourceString("Argument_InsufficientSpaceToCopyCollection")); int i = index; foreach (KeyValuePair<TKey, TValue> mapping in dictionary) { array[i++] = mapping.Value; } } public int Count { get { return dictionary.Count; } } public bool Contains(TValue item) { EqualityComparer<TValue> comparer = EqualityComparer<TValue>.Default; foreach (TValue value in this) if (comparer.Equals(item, value)) return true; return false; } */ IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<TValue>)this).GetEnumerator(); } public IEnumerator<TValue> GetEnumerator() { return new ReadOnlyDictionaryValueEnumerator<TKey, TValue>(dictionary); } } // public class ReadOnlyDictionaryValueCollection<TKey, TValue> [Serializable] internal sealed class ReadOnlyDictionaryValueEnumerator<TKey, TValue> : IEnumerator<TValue> { private readonly IReadOnlyDictionary<TKey, TValue> dictionary; private IEnumerator<KeyValuePair<TKey, TValue>> enumeration; public ReadOnlyDictionaryValueEnumerator(IReadOnlyDictionary<TKey, TValue> dictionary) { if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); this.dictionary = dictionary; this.enumeration = dictionary.GetEnumerator(); } void IDisposable.Dispose() { enumeration.Dispose(); } public bool MoveNext() { return enumeration.MoveNext(); } Object IEnumerator.Current { get { return ((IEnumerator<TValue>)this).Current; } } public TValue Current { get { return enumeration.Current.Value; } } public void Reset() { enumeration = dictionary.GetEnumerator(); } } // class ReadOnlyDictionaryValueEnumerator<TKey, TValue> }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This file is generated from the ecs-2014-11-13.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ECS.Model { /// <summary> /// An Amazon EC2 instance that is running the Amazon ECS agent and has been registered /// with a cluster. /// </summary> public partial class ContainerInstance { private bool? _agentConnected; private AgentUpdateStatus _agentUpdateStatus; private string _containerInstanceArn; private string _ec2InstanceId; private int? _pendingTasksCount; private List<Resource> _registeredResources = new List<Resource>(); private List<Resource> _remainingResources = new List<Resource>(); private int? _runningTasksCount; private string _status; private VersionInfo _versionInfo; /// <summary> /// Gets and sets the property AgentConnected. /// <para> /// This parameter returns <code>true</code> if the agent is actually connected to Amazon /// ECS. Registered instances with an agent that may be unhealthy or stopped will return /// <code>false</code>, and instances without a connected agent cannot accept placement /// request. /// </para> /// </summary> public bool AgentConnected { get { return this._agentConnected.GetValueOrDefault(); } set { this._agentConnected = value; } } // Check to see if AgentConnected property is set internal bool IsSetAgentConnected() { return this._agentConnected.HasValue; } /// <summary> /// Gets and sets the property AgentUpdateStatus. /// <para> /// The status of the most recent agent update. If an update has never been requested, /// this value is <code>NULL</code>. /// </para> /// </summary> public AgentUpdateStatus AgentUpdateStatus { get { return this._agentUpdateStatus; } set { this._agentUpdateStatus = value; } } // Check to see if AgentUpdateStatus property is set internal bool IsSetAgentUpdateStatus() { return this._agentUpdateStatus != null; } /// <summary> /// Gets and sets the property ContainerInstanceArn. /// <para> /// The Amazon Resource Name (ARN) of the container instance. The ARN contains the <code>arn:aws:ecs</code> /// namespace, followed by the region of the container instance, the AWS account ID of /// the container instance owner, the <code>container-instance</code> namespace, and then /// the container instance UUID. For example, arn:aws:ecs:<i>region</i>:<i>aws_account_id</i>:container-instance/<i>container_instance_UUID</i>. /// </para> /// </summary> public string ContainerInstanceArn { get { return this._containerInstanceArn; } set { this._containerInstanceArn = value; } } // Check to see if ContainerInstanceArn property is set internal bool IsSetContainerInstanceArn() { return this._containerInstanceArn != null; } /// <summary> /// Gets and sets the property Ec2InstanceId. /// <para> /// The Amazon EC2 instance ID of the container instance. /// </para> /// </summary> public string Ec2InstanceId { get { return this._ec2InstanceId; } set { this._ec2InstanceId = value; } } // Check to see if Ec2InstanceId property is set internal bool IsSetEc2InstanceId() { return this._ec2InstanceId != null; } /// <summary> /// Gets and sets the property PendingTasksCount. /// <para> /// The number of tasks on the container instance that are in the <code>PENDING</code> /// status. /// </para> /// </summary> public int PendingTasksCount { get { return this._pendingTasksCount.GetValueOrDefault(); } set { this._pendingTasksCount = value; } } // Check to see if PendingTasksCount property is set internal bool IsSetPendingTasksCount() { return this._pendingTasksCount.HasValue; } /// <summary> /// Gets and sets the property RegisteredResources. /// <para> /// The registered resources on the container instance that are in use by current tasks. /// </para> /// </summary> public List<Resource> RegisteredResources { get { return this._registeredResources; } set { this._registeredResources = value; } } // Check to see if RegisteredResources property is set internal bool IsSetRegisteredResources() { return this._registeredResources != null && this._registeredResources.Count > 0; } /// <summary> /// Gets and sets the property RemainingResources. /// <para> /// The remaining resources of the container instance that are available for new tasks. /// </para> /// </summary> public List<Resource> RemainingResources { get { return this._remainingResources; } set { this._remainingResources = value; } } // Check to see if RemainingResources property is set internal bool IsSetRemainingResources() { return this._remainingResources != null && this._remainingResources.Count > 0; } /// <summary> /// Gets and sets the property RunningTasksCount. /// <para> /// The number of tasks on the container instance that are in the <code>RUNNING</code> /// status. /// </para> /// </summary> public int RunningTasksCount { get { return this._runningTasksCount.GetValueOrDefault(); } set { this._runningTasksCount = value; } } // Check to see if RunningTasksCount property is set internal bool IsSetRunningTasksCount() { return this._runningTasksCount.HasValue; } /// <summary> /// Gets and sets the property Status. /// <para> /// The status of the container instance. The valid values are <code>ACTIVE</code> or /// <code>INACTIVE</code>. <code>ACTIVE</code> indicates that the container instance can /// accept tasks. /// </para> /// </summary> public string Status { get { return this._status; } set { this._status = value; } } // Check to see if Status property is set internal bool IsSetStatus() { return this._status != null; } /// <summary> /// Gets and sets the property VersionInfo. /// <para> /// The version information for the Amazon ECS container agent and Docker daemon running /// on the container instance. /// </para> /// </summary> public VersionInfo VersionInfo { get { return this._versionInfo; } set { this._versionInfo = value; } } // Check to see if VersionInfo property is set internal bool IsSetVersionInfo() { return this._versionInfo != null; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Web.Script.Serialization; using BoC.Helpers; using BoC.Validation; namespace BoC.Extensions { public static class StringExtensions { static readonly Regex guidRegEx = new Regex(Expressions.Guid, RegexOptions.Compiled); public static bool IsGuid(this string expression) { return !String.IsNullOrEmpty(expression) && expression.Contains("-") && guidRegEx.IsMatch(expression); } private static readonly Regex emailExpression = new Regex(Expressions.Email, RegexOptions.Singleline | RegexOptions.Compiled); public static bool IsEmail(this string target) { return !string.IsNullOrEmpty(target) && emailExpression.IsMatch(target); } private static readonly Regex webUrlExpression = new Regex(Expressions.WebUrl, RegexOptions.Singleline | RegexOptions.Compiled); public static bool IsWebUrl(this string target) { return !string.IsNullOrEmpty(target) && webUrlExpression.IsMatch(target); } public static string NullSafe(this string target) { return (target ?? string.Empty).Trim(); } public static string MD5(this string s) { var provider = new MD5CryptoServiceProvider(); var bytes = Encoding.UTF8.GetBytes(s); var builder = new StringBuilder(); bytes = provider.ComputeHash(bytes); foreach (var b in bytes) builder.Append(b.ToString("x2").ToLower()); return builder.ToString(); } public static string FormatWith(this string target, params object[] args) { Check.Argument.IsNotEmpty(target, "target"); return string.Format(CultureInfo.CurrentCulture, target, args); } public static T ToEnum<T>(this string target, T defaultValue) where T : struct, IComparable, IFormattable { var convertedValue = defaultValue; if (!string.IsNullOrEmpty(target)) { try { convertedValue = (T) Enum.Parse(typeof (T), target.Trim()); } catch (ArgumentException){} } return convertedValue; } public static int LevenshteinDistance(this String value, String compareString) { return LevenshteinDistance(value, compareString, false); } public static int LevenshteinDistance(this String value, String compareString, bool removeSpecialChars) { return value.LevenshteinDistance(compareString, removeSpecialChars, false); } public static int LevenshteinDistancePercentage(this String value, String compareString, bool removeSpecialChars) { return value.LevenshteinDistance(compareString, removeSpecialChars, true); } public static int LevenshteinDistancePercentage(this String value, String compareString) { return value.LevenshteinDistance(compareString, false, true); } ///***************************** /// Compute Levenshtein distance /// Memory efficient version ///***************************** static int LevenshteinDistance(this String value, String compareString, bool removeSpecialChars, bool returnPercentage) { if (value == null) throw new ArgumentNullException("value"); if (compareString == null) throw new ArgumentNullException("compareString"); /// Test string length var maxlen = Math.Pow(2, 31); if (value.Length > maxlen) throw new ArgumentException("\nMaximum string length in Levenshtein.iLD is " +maxlen + ".\nYours is " + value.Length + ".", "value"); if (compareString.Length > maxlen) throw new ArgumentException("\nMaximum string length in Levenshtein.iLD is " + maxlen + ".\nYours is " + compareString.Length + ".", "compareString"); if (removeSpecialChars) { value = Regex.Replace(value.ToLower(), "\\W", ""); compareString = Regex.Replace(compareString.ToLower(), "\\W", ""); } int RowLen = value.Length; // length of sRow int ColLen = compareString.Length; // length of sCol int RowIdx; // iterates through sRow int ColIdx; // iterates through sCol char Row_i; // ith character of sRow char Col_j; // jth character of sCol int cost; // cost // Step 1 if (RowLen == 0 && ColLen == 0) { return 0; } if (ColLen == 0 || RowLen == 0) { return returnPercentage ? 100 : Math.Max(ColLen, RowLen); } /// Create the two vectors int[] v0 = new int[RowLen + 1]; int[] v1 = new int[RowLen + 1]; int[] vTmp; /// Step 2 /// Initialize the first vector for (RowIdx = 1; RowIdx <= RowLen; RowIdx++) { v0[RowIdx] = RowIdx; } // Step 3 /// Fore each column for (ColIdx = 1; ColIdx <= ColLen; ColIdx++) { /// Set the 0'th element to the column number v1[0] = ColIdx; Col_j = compareString[ColIdx - 1]; // Step 4 /// Fore each row for (RowIdx = 1; RowIdx <= RowLen; RowIdx++) { Row_i = value[RowIdx - 1]; // Step 5 if (Row_i == Col_j) { cost = 0; } else { cost = 1; } // Step 6 /// Find minimum int m_min = v0[RowIdx] + 1; int b = v1[RowIdx - 1] + 1; int c = v0[RowIdx - 1] + cost; if (b < m_min) { m_min = b; } if (c < m_min) { m_min = c; } v1[RowIdx] = m_min; } /// Swap the vectors vTmp = v0; v0 = v1; v1 = vTmp; } // Step 7 /// Value between 0 - 100 /// 0==perfect match 100==totaly different /// /// The vectors where swaped one last time at the end of the last loop, /// that is why the result is now in v0 rather than in v1 System.Console.WriteLine("iDist=" + v0[RowLen]); if (returnPercentage) { int max = System.Math.Max(RowLen, ColLen); return ((100*v0[RowLen])/max); } return v0[RowLen]; } } }
using System; using System.Drawing; using System.Collections.Generic; using System.Text; using System.Collections; using Antlr.Runtime; namespace JovianStyle { public enum Model_Type { tyInteger, tyString, tyBitmap } public class Variant { public Model_Type Type; public string data_String; public int data_Integer; public Bitmap data_Bitmap; public Variant() { } public Variant(int x) { Type = Model_Type.tyInteger; data_Integer = x; } public Variant(string x) { Type = Model_Type.tyString; data_String = x.Substring(1,x.Length - 2); } } public class RuleInputs { public string RuleName; public Variant[] Inputs; } public class Environment { public string Rulename; public string ClassName; public static int URLCounter = 0; //public string dirPump; private int LoadCounter; private int Temp = 0; public int GetTemp() { int t = Temp; Temp++; return t; } public Environment(string x) { LoadCounter = 0; if (System.IO.Directory.Exists("c/")) { string[] y = System.IO.Directory.GetFiles("c/"); foreach (string z in y) { if (z.IndexOf(".") > 0) { try { string z2 = z.Substring(z.LastIndexOf("/") + 1); string z3 = z2.Substring(0, z2.IndexOf(".")); int iC = Int32.Parse(z3); LoadCounter = Math.Max(iC + 1, LoadCounter); } catch (Exception crap) { } } } } //dirPump = "/apps/" + x + "/c"; } public int LC() { int lc = LoadCounter; LoadCounter++; return lc; } public SortedList<string, int> UrlMapping = new SortedList<string, int>(); public int getURL(string url) { if (UrlMapping.ContainsKey(url)) { return UrlMapping[url]; } int x = URLCounter; URLCounter++; UrlMapping.Add(url, x); return x; } public SortedList<string, Variant> Env = new SortedList<string, Variant>(); public void MapString(string x, string s) { Variant v = new Variant(); v.Type = Model_Type.tyString; v.data_String = s; Env.Add(x, v); } public Variant Get(string x) { return Env[x]; } public System.IO.TextWriter Dest; } public class Model_TypeWrap { public Model_Type Type; public Model_TypeWrap(Model_Type x) { Type = x; } } public class Model_Parameter { public Model_Type Type; public string Name; public Model_Parameter(Model_Type ty, string n) { Type = ty; Name = n; } } public interface Model_Expression { Variant Eval(Environment E); string str(); } public class Model_Variable : Model_Expression { public string Variable; public Model_Variable(string v) { Variable = v.ToUpper(); } public Variant Eval(Environment E) { if (Variable.Equals("RULENAME")) { Variant v = new Variant(); v.Type = Model_Type.tyString; v.data_String = E.Rulename; return v; } if (Variable.Equals("CLASSNAME")) { Variant v = new Variant(); v.Type = Model_Type.tyString; v.data_String = E.ClassName; return v; } return E.Get(Variable); } public string str() { return Variable; } } public class Model_Constant : Model_Expression { public Variant Constant; public Model_Constant(int x) { Constant = new Variant(); Constant.data_Integer = x; Constant.Type = Model_Type.tyInteger; } public Model_Constant(string x) { Constant = new Variant(); Constant.data_String = x.Substring(1,x.Length - 2); Constant.Type = Model_Type.tyString; } public Variant Eval(Environment E) { return Constant; } public string str() { if(Constant.Type==Model_Type.tyInteger) return ""+Constant.data_Integer; if(Constant.Type==Model_Type.tyString) return "\""+Constant.data_String+"\""; return "?"; } } public class Model_LibraryCall : Model_Expression { public string Name; public ArrayList Parameters; public Model_LibraryCall(string n, ArrayList p) { Name = n; Parameters = p; } public Variant Eval(Environment E) { Variant [] V = new Variant[Parameters.Count]; for(int k = 0; k < Parameters.Count; k++) { V[k] = (Parameters[k] as Model_Expression).Eval(E); } return Library.Eval(Name, V, E); } public string str() { string s = Name + "("; foreach (Model_Expression e in Parameters) { s += "!" + e.str(); } s += ")"; return s; } } public class Model_Operation : Model_Expression { public string Operator; public Model_Expression Left; public Model_Expression Right; public Model_Operation(string op, Model_Expression l, Model_Expression r) { Operator = op; Left = l; Right = r; } public Variant Eval(Environment E) { Variant L = Left.Eval(E); Variant R = Right.Eval(E); Variant V = new Variant(); if (L.Type == Model_Type.tyString || R.Type == Model_Type.tyString) { if (Operator.Equals("+")) { if (L.Type == Model_Type.tyInteger) L.data_String = "" + L.data_Integer; if (R.Type == Model_Type.tyInteger) R.data_String = "" + R.data_Integer; V.Type = Model_Type.tyString; V.data_String = L.data_String + R.data_String; return V; } } if (L.Type == Model_Type.tyInteger && R.Type == Model_Type.tyInteger) { V.Type = Model_Type.tyInteger; if (Operator.Equals("+")) V.data_Integer = L.data_Integer + R.data_Integer; if (Operator.Equals("-")) V.data_Integer = L.data_Integer - R.data_Integer; if (Operator.Equals("*")) V.data_Integer = L.data_Integer * R.data_Integer; if (Operator.Equals("/")) V.data_Integer = L.data_Integer / R.data_Integer; return V; } throw new Exception("+-*/"); } public string str() { return "(" + Left.str() + Operator + Right.str() + ")"; } } public class Model_Dot : Model_Expression { public Model_Expression Base; public string Field; public Model_Dot(Model_Expression b, string f) { Base = b; Field = f.ToUpper(); } public Variant Eval(Environment E) { Variant V = Base.Eval(E); Variant R = new Variant(); R.Type = Model_Type.tyInteger; if (V.Type == Model_Type.tyString) { if (Field.Equals("LENGTH")) { R.data_Integer = V.data_String.Length; return R; } } if (V.Type == Model_Type.tyBitmap) { if (Field.Equals("WIDTH")) { R.data_Integer = V.data_Bitmap.Width; return R; } if (Field.Equals("HEIGHT")) { R.data_Integer = V.data_Bitmap.Height; return R; } if (Field.Equals("URL")) { R.Type = Model_Type.tyString; string ext = ".png"; if (V.data_String.ToLower().Contains(".jpg")) ext = ".jpg"; if (V.data_String.ToLower().Contains(".gif")) ext = ".gif"; int XYZ = E.getURL(V.data_String); R.data_String = "c/" + XYZ + ext; if (!System.IO.Directory.Exists("c")) System.IO.Directory.CreateDirectory("c"); System.IO.File.Copy("temp/" + V.data_String, R.data_String,true); R.data_String = "c/" + XYZ + ext; Console.WriteLine("[Save(" + R.data_String + ")]"); return R; } } throw new Exception("WTF"); } public string str() { return Base.str() + "." + Field; } } public interface Model_Statement { void Execute(Environment E); string str(); } public class Model_Assignment : Model_Statement { public string Variable; public Model_Expression Expression; public Model_Assignment(string l, Model_Expression r) { Variable = l.ToUpper(); Expression = r; } public void Execute(Environment E) { Variant V = Expression.Eval(E); E.Env.Remove(Variable); E.Env.Add(Variable, V); } public string str() { return Variable + "=" + Expression.str() + ";"; } } public class Model_Unit : Model_Statement { public Model_Expression Expression; public Model_Unit(Model_Expression e) { Expression = e; } public void Execute(Environment E) { Variant V = Expression.Eval(E); } public string str() { return Expression.str() + ";"; } } public class Model_Echo : Model_Statement { public Model_Expression Expression; public Model_Echo(Model_Expression e) { Expression = e; } public void Execute(Environment E) { Variant V = Expression.Eval(E); string s = V.data_String; if (V.Type == Model_Type.tyInteger) s = "" + V.data_Integer; E.Dest.Write(s); } public string str() { return "echo " + Expression.str() + ";"; } } public class Model_Block : Model_Statement { public Model_Statement[] Statements; public void Execute(Environment E) { for (int k = 0; k < Statements.Length; k++) { Statements[k].Execute(E); } } public string str() { string s = "{"; foreach (Model_Statement k in Statements) s += k.str(); return s + "}"; } } public class Model_Rule { public string Name; public string[] Parameters; public Model_Block Code; public string str() { string s = Name + "("; foreach (string x in Parameters) s += x+","; return s + ")" + Code.str(); } } public class Model_File { public Model_Rule[] Rules; private SortedList<string, Model_Rule> TRT; private int ClassCounter; public static Model_File Build(string code) { // REMOVE COMMENTS string code2 = Prepare.PrepareFile(code, new IgnoreComments()); string Flat = Special.CompileOuter(code2 + " "); // BUILD TREE JovianStyle.Parser.StyleModelLexer l = new JovianStyle.Parser.StyleModelLexer(new ANTLRStringStream(Flat)); CommonTokenStream tokens = new CommonTokenStream(l); JovianStyle.Parser.StyleModelParser p = new JovianStyle.Parser.StyleModelParser(tokens); // DO IT Model_File model = p.file(); model.Compile(); return model; } private RuleInputs ParseInputs(string code) { JovianStyle.Parser.StyleModelLexer l = new JovianStyle.Parser.StyleModelLexer(new ANTLRStringStream(code)); CommonTokenStream tokens = new CommonTokenStream(l); JovianStyle.Parser.StyleModelParser p = new JovianStyle.Parser.StyleModelParser(tokens); return p.ruleinput(); } private void Compile() { TRT = new SortedList<string, Model_Rule>(); foreach (Model_Rule r in Rules) { r.Name = r.Name.ToUpper().Trim(); TRT.Add(r.Name, r); } ClassCounter = 0; } public string CacheLogic(string style, string app, bool IE) { RuleInputs In = ParseInputs(style); Environment Env = new Environment(app); Env.Dest = new System.IO.StringWriter(); Env.Rulename = In.RuleName.ToUpper().Trim(); if (IE) Env.Rulename += "_IE6"; if (!TRT.ContainsKey(Env.Rulename)) { return "[]"; } Model_Rule Rule = TRT[Env.Rulename]; return Rule.str(); } public string EvalF(string style, string className, int w, int h, string app, bool IE) { RuleInputs In = ParseInputs(style); Environment Env = new Environment(app); Env.Dest = new System.IO.StringWriter(); Env.Rulename = In.RuleName.ToUpper().Trim(); if (IE) Env.Rulename += "_IE6"; Env.ClassName = className; if (!TRT.ContainsKey(Env.Rulename)) { className = "NotFound_"+Env.Rulename; return ".NotFound_"+Env.Rulename+" { color:#ff0000; } "; } Model_Rule Rule = TRT[Env.Rulename]; if (In.Inputs.Length != Rule.Parameters.Length) throw new Exception("Arity MisMatch"); for (int k = 0; k < Rule.Parameters.Length; k++) { Env.Env.Add(Rule.Parameters[k].ToUpper(), In.Inputs[k]); } Env.Env.Add("WIDTH", new Variant(w)); Env.Env.Add("HEIGHT", new Variant(h)); Rule.Code.Execute(Env); return Env.Dest.ToString(); } public string PickClassName() { string className = "clX" + ClassCounter; ClassCounter++; return className; } public string Eval(string style, out string className, int w, int h, string app) { className = PickClassName(); return EvalF(style, className, w, h, app, false); /* JovianStyle.Specification.Environment E = new JovianStyle.Specification.Environment(); E.Dest = System.Console.Out; string[] vIn = inputs.Split(new char[] { '/' }); Console.WriteLine(R.Name + ":"); for (int k = 0; k < R.Parameters.Length; k++) { E.MapString(R.Parameters[k], vIn[k]); } R.Code.Execute(E); //Console.WriteLine(R.Parameters */ } } }
// Copyright (C) 2009-2017 Luca Piccioni // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Diagnostics; namespace OpenGL.Objects.State { /// <summary> /// Blend render state (buffer group, color). /// </summary> [DebuggerDisplay("BlendState: Enabled={Enabled} Src={SrcFactor} Dst={DstFactor} RgbEq={RgbEquation} AlphaEq={AlphaEquation} SrcAlpha={AlphaSrcFactor} DstAlpha={AlphaDstFactor}")] public class BlendState : GraphicsState { #region Constructors /// <summary> /// Construct a default BlendState (blending disabled). /// </summary> public BlendState() { } /// <summary> /// Construct a BlendState with unified RGB/Alpha function. /// </summary> /// <param name="equation"> /// A <see cref="BlendEquationMode"/> flag indicating which equation to used for blending. /// </param> /// <param name="srcFactor"> /// A <see cref="BlendingFactor"/> that specify the scaling factors applied to the source color (including alpha). /// </param> /// <param name="dstFactor"> /// A <see cref="BlendingFactor"/> that specify the scaling factors applied to the destination color (including alpha). /// </param> public BlendState(BlendEquationMode equation, BlendingFactor srcFactor, BlendingFactor dstFactor) : this(equation, equation, srcFactor, srcFactor, dstFactor, dstFactor, new ColorRGBAF()) { } /// <summary> /// Construct a BlendState with unified RGB/Alpha function. /// </summary> /// <param name="equation"> /// A <see cref="BlendEquationMode"/> flag indicating which equation to used for blending. /// </param> /// <param name="srcFactor"> /// A <see cref="BlendingFactor"/> that specify the scaling factors applied to the source color (including alpha). /// </param> /// <param name="dstFactor"> /// A <see cref="BlendingFactor"/> that specify the scaling factors applied to the destination color (including alpha). /// </param> /// <param name="constColor"> /// A <see cref="ColorRGBAF"/> that specify the constant color used in blending functions. /// </param> public BlendState(BlendEquationMode equation, BlendingFactor srcFactor, BlendingFactor dstFactor, ColorRGBAF constColor) : this(equation, equation, srcFactor, srcFactor, dstFactor, dstFactor, constColor) { } /// <summary> /// Construct a BlendState with separated RGB/Alpha functions. /// </summary> /// <param name="rgbEquation"> /// A <see cref="BlendEquationMode"/> flag indicating which equation to used for blending RGB color components. /// </param> /// <param name="alphaEquation"> /// A <see cref="BlendEquationMode"/> flag indicating which equation to used for blending Alpha color component. /// </param> /// <param name="srcRgbFactor"> /// A <see cref="BlendingFactor"/> that specify the scaling factors applied to the source color (alpha component excluded). /// </param> /// <param name="srcAlphaFactor"> /// A <see cref="BlendingFactor"/> that specify the scaling factors applied to only the source alpha component. /// </param> /// <param name="dstRgbFactor"> /// A <see cref="BlendingFactor"/> that specify the scaling factors applied to the destination color (alpha component excluded). /// </param> /// <param name="dstAlphaFactor"> /// A <see cref="BlendingFactor"/> that specify the scaling factors applied to only the destination alpha component. /// </param> public BlendState(BlendEquationMode rgbEquation, BlendEquationMode alphaEquation, BlendingFactor srcRgbFactor, BlendingFactor srcAlphaFactor, BlendingFactor dstRgbFactor, BlendingFactor dstAlphaFactor) : this(rgbEquation, alphaEquation, srcRgbFactor, srcAlphaFactor, dstRgbFactor, dstAlphaFactor, new ColorRGBAF()) { } /// <summary> /// Construct a BlendState with separated RGB/Alpha functions. /// </summary> /// <param name="rgbEquation"> /// A <see cref="BlendEquationMode"/> flag indicating which equation to used for blending RGB color components. /// </param> /// <param name="alphaEquation"> /// A <see cref="BlendEquationMode"/> flag indicating which equation to used for blending Alpha color component. /// </param> /// <param name="srcRgbFactor"> /// A <see cref="BlendingFactor"/> that specify the scaling factors applied to the source color (alpha component excluded). /// </param> /// <param name="srcAlphaFactor"> /// A <see cref="BlendingFactor"/> that specify the scaling factors applied to only the source alpha component. /// </param> /// <param name="dstRgbFactor"> /// A <see cref="BlendingFactor"/> that specify the scaling factors applied to the destination color (alpha component excluded). /// </param> /// <param name="dstAlphaFactor"> /// A <see cref="BlendingFactor"/> that specify the scaling factors applied to only the destination alpha component. /// </param> /// <param name="constColor"> /// A <see cref="ColorRGBAF"/> that specify the constant color used in blending functions. /// </param> public BlendState(BlendEquationMode rgbEquation, BlendEquationMode alphaEquation, BlendingFactor srcRgbFactor, BlendingFactor srcAlphaFactor, BlendingFactor dstRgbFactor, BlendingFactor dstAlphaFactor, ColorRGBAF constColor) { if (IsSupportedEquation(rgbEquation) == false) throw new ArgumentException("not supported blending equation " + srcRgbFactor, "rgbEquation"); if (IsSupportedEquation(alphaEquation) == false) throw new ArgumentException("not supported blending equation " + alphaEquation, "rgbEquation"); if (IsSupportedFunction(srcRgbFactor) == false) throw new ArgumentException("not supported blending function " + srcRgbFactor, "srcRgbFactor"); if (IsSupportedFunction(srcAlphaFactor) == false) throw new ArgumentException("not supported blending function " + srcAlphaFactor, "srcAlphaFactor"); if (IsSupportedFunction(dstRgbFactor) == false) throw new ArgumentException("not supported blending function " + dstRgbFactor, "dstRgbFactor"); if (IsSupportedFunction(dstAlphaFactor) == false) throw new ArgumentException("not supported blending function " + dstAlphaFactor, "dstAlphaFactor"); // Blend enabled _Enabled = true; // Store RGB separate equation _RgbEquation = rgbEquation; // Store alpha separate equation _AlphaEquation = alphaEquation; // Store rgb separate function _RgbSrcFactor = srcRgbFactor; _RgbDstFactor = dstRgbFactor; // Store alpha separate function _AlphaSrcFactor = srcAlphaFactor; _AlphaDstFactor = dstAlphaFactor; // Store blend color _BlendColor = constColor; if (EquationSeparated && !Gl.CurrentExtensions.BlendEquationSeparate_EXT) throw new InvalidOperationException("not supported separated blending equations"); if (FunctionSeparated && !Gl.CurrentExtensions.BlendFuncSeparate_EXT) throw new InvalidOperationException("not supported separated blending functions"); } /// <summary> /// Construct the current BlendState. /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> defining this GraphicsState. /// </param> public BlendState(GraphicsContext ctx) { if (ctx == null) throw new ArgumentNullException("ctx"); int blendRgbEquation, blendAlphaEquation; int blendRgbSrcFunct, blendAlphaSrcFunct; int blendRgbDstFunct, blendAlphaDstFunct; // Blend enabled _Enabled = Gl.IsEnabled(EnableCap.Blend); if (ctx.Extensions.BlendEquationSeparate_EXT) { // Blend equation (RGB) Gl.Get(Gl.BLEND_EQUATION_RGB, out blendRgbEquation); // Blend equation (Alpha) Gl.Get(Gl.BLEND_EQUATION_ALPHA, out blendAlphaEquation); } else { if (ctx.Extensions.BlendMinmax_EXT) { // Blend equation (RGBA) Gl.Get(GetPName.BlendEquationRgb, out blendRgbEquation); // Alpha equation is the same for RGB! blendAlphaEquation = blendRgbEquation; } else { blendRgbEquation = blendAlphaEquation = (int)BlendEquationMode.FuncAdd; } } #if !MONODROID if (ctx.Extensions.BlendFuncSeparate_EXT) { // Blend source function (RGB) Gl.Get(Gl.BLEND_SRC_RGB, out blendRgbSrcFunct); // Blend source function (Alpha) Gl.Get(Gl.BLEND_SRC_ALPHA, out blendAlphaSrcFunct); // Blend destination function (RGB) Gl.Get(Gl.BLEND_DST_RGB, out blendRgbDstFunct); // Blend destination function (Alpha) Gl.Get(Gl.BLEND_DST_ALPHA, out blendAlphaDstFunct); } else { // Blend source function (RGBA) Gl.Get(GetPName.BlendSrc, out blendRgbSrcFunct); blendAlphaSrcFunct = blendRgbSrcFunct; // Blend destination function (RGBA) Gl.Get(GetPName.BlendDst, out blendRgbDstFunct); blendAlphaDstFunct = blendRgbDstFunct; } #else // Blend source function (RGB) Gl.Get(Gl.BLEND_SRC_RGB, out blendRgbSrcFunct); // Blend source function (Alpha) Gl.Get(Gl.BLEND_SRC_ALPHA, out blendAlphaSrcFunct); // Blend destination function (RGB) Gl.Get(Gl.BLEND_DST_RGB, out blendRgbDstFunct); // Blend destination function (Alpha) Gl.Get(Gl.BLEND_DST_ALPHA, out blendAlphaDstFunct); #endif // Store blending equation _RgbEquation = (BlendEquationMode)blendRgbEquation; _AlphaEquation = (BlendEquationMode)blendAlphaEquation; // Store blending function _RgbSrcFactor = (BlendingFactor)blendRgbSrcFunct; _AlphaSrcFactor = (BlendingFactor)blendAlphaSrcFunct; _RgbDstFactor = (BlendingFactor)blendRgbDstFunct; _AlphaDstFactor = (BlendingFactor)blendAlphaDstFunct; // Store blend color if (ctx.Extensions.BlendColor_EXT) { float[] blendColor = new float[4]; Gl.Get(GetPName.BlendColor, blendColor); _BlendColor = new ColorRGBAF(blendColor[0], blendColor[1], blendColor[2], blendColor[3]); } } #endregion #region Information /// <summary> /// Determine whether the blending is enabled. /// </summary> public bool Enabled { get { return (_Enabled); } } /// <summary> /// Determine whether blending equation is separated for RGB and Alpha components. /// </summary> public bool EquationSeparated { get { return (_RgbEquation != _AlphaEquation); } } /// <summary> /// Blend equation for RGB components. /// </summary> public BlendEquationMode RgbEquation { get { return (_RgbEquation); } } /// <summary> /// Blend equation for alpha components. /// </summary> public BlendEquationMode AlphaEquation { get { return (_AlphaEquation); } } /// <summary> /// Determine whether blending function is separated for RGB and Alpha components. /// </summary> public bool FunctionSeparated { get { return ((_RgbSrcFactor != _AlphaSrcFactor) || (_RgbDstFactor != _AlphaDstFactor)); } } /// <summary> /// Source blending factor. /// </summary> public BlendingFactor SrcFactor { get { return (_RgbSrcFactor); } set { _RgbSrcFactor = _AlphaSrcFactor = value; } } /// <summary> /// Destination blending factor. /// </summary> public BlendingFactor DstFactor { get { return (_RgbDstFactor); } set { _RgbDstFactor = _AlphaDstFactor = value; } } /// <summary> /// RGB source blending factor. /// </summary> public BlendingFactor RgbSrcFactor { get { return (_RgbSrcFactor); } set { _RgbSrcFactor = value; } } /// <summary> /// RGB destination blending factor. /// </summary> public BlendingFactor RgbDstFactor { get { return (_RgbDstFactor); } set { _RgbDstFactor = value; } } /// <summary> /// Alpha source blending factor. /// </summary> public BlendingFactor AlphaSrcFactor { get { return (_AlphaSrcFactor); } set { _AlphaSrcFactor = value; } } /// <summary> /// Alpha destination blending factor. /// </summary> public BlendingFactor AlphaDstFactor { get { return (_AlphaDstFactor); } set { _AlphaDstFactor = value; } } /// <summary> /// Constant blending color. /// </summary> public ColorRGBAF BlendColor { get { return (_BlendColor); } set { _BlendColor = value; } } /// <summary> /// Determine whether a blending function is supported. /// </summary> /// <param name="equation"></param> /// <returns></returns> private static bool IsSupportedEquation(BlendEquationMode equation) { switch (equation) { case BlendEquationMode.Min: case BlendEquationMode.Max: return (Gl.CurrentExtensions.BlendMinmax_EXT); // XXX Use GraphicsContext case BlendEquationMode.FuncSubtract: case BlendEquationMode.FuncReverseSubtract: return (Gl.CurrentExtensions.BlendSubtract_EXT); // XXX Use GraphicsContext default: return (true); } } /// <summary> /// Determine whether a blending function is supported. /// </summary> /// <param name="func"></param> /// <returns></returns> private static bool IsSupportedFunction(BlendingFactor func) { switch (func) { case BlendingFactor.ConstantColor: case BlendingFactor.OneMinusConstantColor: case BlendingFactor.ConstantAlpha: case BlendingFactor.OneMinusConstantAlpha: return (Gl.CurrentExtensions.BlendColor_EXT); // XXX Use GraphicsContext default: return (true); } } private static bool RequiresConstColor(BlendingFactor func) { switch (func) { case BlendingFactor.ConstantColor: case BlendingFactor.OneMinusConstantColor: case BlendingFactor.ConstantAlpha: case BlendingFactor.OneMinusConstantAlpha: return (true); default: return (false); } } /// <summary> /// Enabled flag. /// </summary> private bool _Enabled; /// <summary> /// Blend equation for RGB components. /// </summary> private BlendEquationMode _RgbEquation = BlendEquationMode.FuncAdd; /// <summary> /// Blend equation for alpha components. /// </summary> private BlendEquationMode _AlphaEquation = BlendEquationMode.FuncAdd; /// <summary> /// RGB source blending factor. /// </summary> private BlendingFactor _RgbSrcFactor = BlendingFactor.One; /// <summary> /// RGB destination blending factor. /// </summary> private BlendingFactor _RgbDstFactor = BlendingFactor.Zero; /// <summary> /// Alpha source blending factor. /// </summary> private BlendingFactor _AlphaSrcFactor = BlendingFactor.One; /// <summary> /// Alpha destination blending factor. /// </summary> private BlendingFactor _AlphaDstFactor = BlendingFactor.Zero; /// <summary> /// Constant blending color. /// </summary> private ColorRGBAF _BlendColor; #endregion #region Default State /// <summary> /// The system default state for BlendState. /// </summary> public static BlendState DefaultState { get { return (new BlendState()); } } #endregion #region Frequent States /// <summary> /// The default state for alpha blending. /// </summary> public static BlendState AlphaBlending { get { return (new BlendState(BlendEquationMode.FuncAdd, BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha)); } } #endregion #region GraphicsState Overrides /// <summary> /// The identifier of the state. /// </summary> public const string StateId = "OpenGL.Blend"; /// <summary> /// The identifier of this GraphicsState. /// </summary> public override string StateIdentifier { get { return (StateId); } } /// <summary> /// Unique index assigned to this GraphicsState. /// </summary> public static int StateSetIndex { get { return (_StateIndex); } } /// <summary> /// Unique index assigned to this GraphicsState. /// </summary> public override int StateIndex { get { return (_StateIndex); } } /// <summary> /// The index for this GraphicsState. /// </summary> private static int _StateIndex = NextStateIndex(); /// <summary> /// Set ShaderProgram state. /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> which has defined the shader program <paramref name="sProgram"/>. /// </param> /// <param name="program"> /// The <see cref="ShaderProgram"/> which has the state set. /// </param> public override void Apply(GraphicsContext ctx, ShaderProgram program) { if (ctx == null) throw new ArgumentNullException("ctx"); BlendState currentState = (BlendState)ctx.GetCurrentState(StateIndex); if (currentState != null) ApplyStateCore(ctx, program, currentState); else ApplyStateCore(ctx, program); ctx.SetCurrentState(this); } private void ApplyStateCore(GraphicsContext ctx, ShaderProgram program) { if (Enabled) { // Enable blending Gl.Enable(EnableCap.Blend); // Set blending equation if (ctx.Extensions.BlendMinmax_EXT) { if (EquationSeparated) Gl.BlendEquationSeparate(RgbEquation, AlphaEquation); else Gl.BlendEquation(RgbEquation); } // Set blending function if (FunctionSeparated) Gl.BlendFuncSeparate(_RgbSrcFactor, _RgbDstFactor, _AlphaSrcFactor, _AlphaDstFactor); else Gl.BlendFunc(_RgbSrcFactor, _RgbDstFactor); // Set blend color, if required if (RequiresConstColor(_RgbSrcFactor) || RequiresConstColor(_AlphaSrcFactor) || RequiresConstColor(_RgbDstFactor) || RequiresConstColor(_AlphaDstFactor)) { Gl.BlendColor(_BlendColor.r, _BlendColor.g, _BlendColor.b, _BlendColor.a); } } else { // Disable blending Gl.Disable(EnableCap.Blend); } } private void ApplyStateCore(GraphicsContext ctx, ShaderProgram program, BlendState currentState) { if (Enabled) { // Enable blending if (currentState.Enabled == false) Gl.Enable(EnableCap.Blend); // Set blending equation if (ctx.Extensions.BlendMinmax_EXT) { if (EquationSeparated) { if (currentState.RgbEquation != RgbEquation || currentState.AlphaEquation != AlphaEquation) Gl.BlendEquationSeparate(RgbEquation, AlphaEquation); } else { if (currentState.RgbEquation != RgbEquation) Gl.BlendEquation(RgbEquation); } } // Set blending function if (FunctionSeparated) { if (currentState._RgbSrcFactor != _RgbSrcFactor || currentState._RgbDstFactor != _RgbDstFactor || currentState._AlphaSrcFactor != _AlphaSrcFactor || currentState._AlphaDstFactor != _AlphaDstFactor) Gl.BlendFuncSeparate(_RgbSrcFactor, _RgbDstFactor, _AlphaSrcFactor, _AlphaDstFactor); } else { if (currentState._RgbSrcFactor != _RgbSrcFactor || currentState._RgbDstFactor != _RgbDstFactor) Gl.BlendFunc(_RgbSrcFactor, _RgbDstFactor); } // Set blend color, if required if (RequiresConstColor(_RgbSrcFactor) || RequiresConstColor(_AlphaSrcFactor) || RequiresConstColor(_RgbDstFactor) || RequiresConstColor(_AlphaDstFactor)) { Gl.BlendColor(_BlendColor.r, _BlendColor.g, _BlendColor.b, _BlendColor.a); } } else { // Disable blending if (currentState.Enabled == true) Gl.Disable(EnableCap.Blend); } } /// <summary> /// Merge this state with another one. /// </summary> /// <param name="state"> /// A <see cref="IGraphicsState"/> having the same <see cref="StateIdentifier"/> of this state. /// </param> public override void Merge(IGraphicsState state) { if (state == null) throw new ArgumentNullException("state"); BlendState otherState = state as BlendState; if (otherState == null) throw new ArgumentException("not a BlendState", "state"); _Enabled = otherState._Enabled; _RgbEquation = otherState._RgbEquation; _AlphaEquation = otherState._AlphaEquation; _RgbSrcFactor = otherState._RgbSrcFactor; _AlphaSrcFactor = otherState._AlphaSrcFactor; _RgbDstFactor = otherState._RgbDstFactor; _AlphaDstFactor = otherState._AlphaDstFactor; _BlendColor = otherState._BlendColor; } /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other"> /// A <see cref="GraphicsState"/> to compare to this GraphicsState. /// </param> /// <returns> /// It returns true if the current object is equal to <paramref name="other"/>. /// </returns> /// <remarks> /// <para> /// This method test only whether <paramref name="other"/> type equals to this type. /// </para> /// </remarks> /// <exception cref="ArgumentNullException"> /// This exception is thrown if the parameter <paramref name="other"/> is null. /// </exception> public override bool Equals(IGraphicsState other) { if (base.Equals(other) == false) return (false); Debug.Assert(other is BlendState); BlendState otherState = (BlendState) other; if (otherState._Enabled != _Enabled) return (false); if ((otherState.RgbEquation != RgbEquation) || (otherState.AlphaEquation != AlphaEquation)) return (false); if ((otherState.RgbSrcFactor != RgbSrcFactor) || (otherState.RgbDstFactor != RgbDstFactor)) return (false); if ((otherState.AlphaSrcFactor != AlphaSrcFactor) || (otherState.AlphaDstFactor != AlphaDstFactor)) return (false); return (true); } /// <summary> /// Represents the current <see cref="GraphicsState"/> for logging. /// </summary> /// <returns> /// A <see cref="String"/> that represents the current <see cref="GraphicsState"/>. /// </returns> public override string ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (Enabled) { sb.AppendFormat("{0}: ", StateIdentifier); if (EquationSeparated) sb.AppendFormat("RgbEquation={0} AlphaEquation={1} ", RgbEquation, AlphaEquation); else sb.AppendFormat("BlendEquationMode={0} ", RgbEquation); if (FunctionSeparated) sb.AppendFormat("RgbSrcFactor={0} RgbDstFactor={1} AlphaSrcFactor={2} AlphaDstFactor={3} ", RgbSrcFactor, RgbDstFactor, AlphaSrcFactor, AlphaDstFactor); else sb.AppendFormat("RgbSrcFactor={0} RgbDstFactor={1} ", RgbSrcFactor, RgbDstFactor); if (RequiresConstColor(RgbSrcFactor) || RequiresConstColor(RgbDstFactor)) sb.AppendFormat("BlendColor={0} ", BlendColor); sb.Remove(sb.Length - 1, 1); } else sb.AppendFormat("{0}: Enabled=false", StateIdentifier); return (sb.ToString()); } #endregion } }
#region License /* The MIT License Copyright (c) 2008 Sky Morey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System.Collections; namespace System.IO { /// <summary> /// FileArchiver /// </summary> public class FileArchiver { /// <summary> /// ArchiveEveryMode /// </summary> public enum ArchiveEveryMode { /// <summary> /// /// </summary> None, /// <summary> /// /// </summary> Year, /// <summary> /// /// </summary> Month, /// <summary> /// /// </summary> Day, /// <summary> /// /// </summary> Hour, /// <summary> /// /// </summary> Minute } /// <summary> /// ArchiveNumberingMode /// </summary> public enum ArchiveNumberingMode { /// <summary> /// /// </summary> Sequence, /// <summary> /// /// </summary> Rolling } /// <summary> /// Initializes a new instance of the <see cref="FileArchiver"/> class. /// </summary> public FileArchiver() { MaxArchiveFiles = 9; ArchiveAboveSize = -1L; ArchiveNumbering = ArchiveNumberingMode.Rolling; } /// <summary> /// Gets or sets the max archive files. /// </summary> /// <value>The max archive files.</value> public int MaxArchiveFiles { get; set; } /// <summary> /// Gets or sets the archive numbering. /// </summary> /// <value>The archive numbering.</value> public ArchiveNumberingMode ArchiveNumbering { get; set; } /// <summary> /// Gets or sets the size of the archive above. /// </summary> /// <value>The size of the archive above.</value> public long ArchiveAboveSize { get; set; } /// <summary> /// Gets or sets the archive every. /// </summary> /// <value>The archive every.</value> public ArchiveEveryMode ArchiveEvery { get; set; } /// <summary> /// Gets the file info. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="lastWriteTime">The last write time.</param> /// <param name="fileLength">Length of the file.</param> /// <returns></returns> private bool GetFileInfo(string fileName, out DateTime lastWriteTime, out long fileLength) { var info = new FileInfo(fileName); if (info.Exists) { fileLength = info.Length; lastWriteTime = info.LastWriteTime; return true; } fileLength = -1L; lastWriteTime = DateTime.MinValue; return false; } /// <summary> /// Shoulds the auto archive. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="upcomingWriteTime">The upcoming write time.</param> /// <param name="upcomingWriteSize">Size of the upcoming write.</param> /// <returns></returns> public bool ShouldAutoArchive(string fileName, DateTime upcomingWriteTime, int upcomingWriteSize) { DateTime time; long num; string str; if ((ArchiveAboveSize == -1L) && (ArchiveEvery == ArchiveEveryMode.None)) return false; if (!GetFileInfo(fileName, out time, out num)) return false; if ((ArchiveAboveSize != -1L) && ((num + upcomingWriteSize) > ArchiveAboveSize)) return true; switch (ArchiveEvery) { case ArchiveEveryMode.Year: str = "yyyy"; break; case ArchiveEveryMode.Month: str = "yyyyMM"; break; case ArchiveEveryMode.Hour: str = "yyyyMMddHH"; break; case ArchiveEveryMode.Minute: str = "yyyyMMddHHmm"; break; case ArchiveEveryMode.None: return false; default: str = "yyyyMMdd"; break; } string str2 = time.ToString(str); string str3 = upcomingWriteTime.ToString(str); if (str2 != str3) return true; return false; } /// <summary> /// Res the scope path. /// </summary> /// <param name="directory">The directory.</param> /// <param name="path">The path.</param> /// <returns></returns> public static string ReScopePath(string directory, string path) { return Path.GetFullPath(Path.Combine(Path.Combine(Path.GetDirectoryName(path), directory), Path.GetFileName(path))); } /// <summary> /// Does the auto archive. /// </summary> /// <param name="fileName">Name of the file.</param> public void DoAutoArchive(string archiveDirectory, string fileName) { var info = new FileInfo(fileName); if (info.Exists) { string formattedMessage = Path.ChangeExtension(info.FullName, ".{#}" + Path.GetExtension(fileName)); if ((archiveDirectory != null) && (archiveDirectory.Length > 0)) formattedMessage = ReScopePath(archiveDirectory, formattedMessage); switch (ArchiveNumbering) { case ArchiveNumberingMode.Sequence: SequentialArchive(info.FullName, formattedMessage); return; case ArchiveNumberingMode.Rolling: RecursiveRollingRename(info.FullName, formattedMessage, 0); return; } } } /// <summary> /// Recursives the rolling rename. /// </summary> /// <param name="archiveDirectory">The archive directory.</param> /// <param name="fileName">Name of the file.</param> /// <param name="pattern">The pattern.</param> /// <param name="archiveNumber">The archive number.</param> private void RecursiveRollingRename(string fileName, string pattern, int archiveNumber) { if ((MaxArchiveFiles != -1) && (archiveNumber >= MaxArchiveFiles)) File.Delete(fileName); else if (File.Exists(fileName)) { string str = ReplaceNumber(pattern, archiveNumber); if (File.Exists(fileName)) RecursiveRollingRename(str, pattern, archiveNumber + 1); //s_Logger.Trace("Renaming {0} to {1}", fileName, str); try { File.Move(fileName, str); } catch (DirectoryNotFoundException) { Directory.CreateDirectory(Path.GetDirectoryName(str)); File.Move(fileName, str); } } } /// <summary> /// Sequentials the archive. /// </summary> /// <param name="archiveDirectory">The archive directory.</param> /// <param name="fileName">Name of the file.</param> /// <param name="pattern">The pattern.</param> private void SequentialArchive(string fileName, string pattern) { string str = Path.GetFileName(pattern); int index = str.IndexOf("{#"); int startIndex = str.IndexOf("#}") + 2; int num3 = str.Length - startIndex; string searchPattern = str.Substring(0, index) + "*" + str.Substring(startIndex); string directoryName = Path.GetDirectoryName(Path.GetFullPath(pattern)); int num4 = -1; int num5 = -1; var hashtable = new Hashtable(); try { foreach (string str4 in Directory.GetFiles(directoryName, searchPattern)) { int num6; string str5 = Path.GetFileName(str4); string str6 = str5.Substring(index, (str5.Length - num3) - index); try { num6 = Convert.ToInt32(str6); } catch (FormatException) { continue; } num4 = Math.Max(num4, num6); num5 = (num5 != -1 ? Math.Min(num5, num6) : num6); hashtable[num6] = str4; } num4++; } catch (DirectoryNotFoundException) { Directory.CreateDirectory(directoryName); num4 = 0; } if ((MaxArchiveFiles != -1) && (num5 != -1)) { int num7 = (num4 - MaxArchiveFiles) + 1; for (int i = num5; i < num7; i++) { string path = (string)hashtable[i]; if (path != null) File.Delete(path); } } string destFileName = ReplaceNumber(pattern, num4); File.Move(fileName, destFileName); } /// <summary> /// Replaces the number. /// </summary> /// <param name="pattern">The pattern.</param> /// <param name="value">The value.</param> /// <returns></returns> private string ReplaceNumber(string pattern, int value) { int index = pattern.IndexOf("{#"); int startIndex = pattern.IndexOf("#}") + 2; int totalWidth = (startIndex - index) - 2; return (pattern.Substring(0, index) + Convert.ToString(value, 10).PadLeft(totalWidth, '0') + pattern.Substring(startIndex)); } } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Telegram.Bot; using Telegram.Bot.Exceptions; using Telegram.Bot.Extensions.Polling; using Telegram.Bot.Types; namespace MagicNewCardsBot { public class TelegramController { #region Definitions private readonly string _telegramBotApiKey; private readonly Telegram.Bot.TelegramBotClient _botClient; private readonly int MAX_CONCURRENT_MESSAGES = 50; private int _offset; private readonly long? _idUserDebug; #endregion #region Constructors public TelegramController(String apiKey, long? IdUserDebug = null) { _telegramBotApiKey = apiKey; _botClient = new Telegram.Bot.TelegramBotClient(_telegramBotApiKey); _offset = 0; _idUserDebug = IdUserDebug; } #endregion #region Public Methods async public Task InitialUpdateAsync() { await GetInitialUpdateEventsAsync(); } async private Task SendCardToChatsAsync(Card card, IAsyncEnumerable<Chat> chats) { int sendingChats = 0; //goes trough all the chats and send a message for each one await foreach (Chat chat in chats) { Utils.LogInformation($"Sending {card} to {chat.Id}"); _ = SendCardToChatAsync(card, chat); sendingChats++; if (sendingChats >= MAX_CONCURRENT_MESSAGES) { await Task.Delay(1000); sendingChats = 0; } } } async public Task SendImageToAllChatsAsync(Card card) { if (_idUserDebug.HasValue) await SendCardToChatAsync(card, new Chat { Id = _idUserDebug.Value, Type = Telegram.Bot.Types.Enums.ChatType.Private, Title = "test", FirstName = "test" }); else { await SendCardToChatsAsync(card, Database.GetChatsAsync()); } } async public Task SendImageToChatsByRarityAsync(Card card) { await SendCardToChatsAsync(card, Database.GetChatsAsync(card.GetRarityCharacter())); } public void HookUpdateEvent() { var cts = new CancellationTokenSource(); var cancellationToken = cts.Token; _botClient.StartReceiving(HandleUpdateAsync, HandleErrorAsync, null, cancellationToken); } #endregion #region Private Methods private static InputMediaPhoto CreateInputMedia(Card card) { InputMediaPhoto photo = new(new InputMedia(card.ImageUrl)) { Caption = GetMessageText(card), ParseMode = Telegram.Bot.Types.Enums.ParseMode.Html }; return photo; } private static string GetMessageText(Card card) { String messageText; //if the text is to big, we need to send it as a message afterwards Boolean isTextToBig = card.GetFullText().Length >= 1024; if (isTextToBig) { messageText = card.Name?.ToString(); } else { messageText = card.GetTelegramTextFormatted(); } return messageText; } async private Task SendCardToChatAsync(Card card, Chat chat) { try { //if there is a additional image, we must send a album if (card.ExtraSides != null && card.ExtraSides.Count > 0) { List<InputMediaPhoto> lstPhotos = new(); InputMediaPhoto cardPhoto = CreateInputMedia(card); lstPhotos.Add(cardPhoto); foreach (Card extraSide in card.ExtraSides) { var media = CreateInputMedia(extraSide); lstPhotos.Add(media); } await _botClient.SendMediaGroupAsync(chat, lstPhotos); } else { var message = await _botClient.SendPhotoAsync(chatId: chat, photo: card.ImageUrl, caption: GetMessageText(card), parseMode: Telegram.Bot.Types.Enums.ParseMode.Html); } } catch (Exception ex) //sometimes this exception is not a problem, like if the bot was removed from the group { if (ex.Message.Contains("bot was kicked")) { Utils.LogInformation(String.Format("Bot was kicked from group {0}, deleting him from chat table", chat.Id)); await Database.DeleteFromChatAsync(chat); return; } else if (ex.Message.Contains("bot was blocked by the user")) { Utils.LogInformation(String.Format("Bot was blocked by user {0}, deleting him from chat table", chat.Id)); await Database.DeleteFromChatAsync(chat); return; } else if (ex.Message.Contains("user is deactivated")) { Utils.LogInformation(String.Format("User {0} deactivated, deleting him from chat table", chat.Id)); await Database.DeleteFromChatAsync(chat); return; } else if (ex.Message.Contains("chat not found")) { Utils.LogInformation(String.Format("Chat {0} not found, deleting him from chat table", chat.Id)); await Database.DeleteFromChatAsync(chat); return; } else if (ex.Message.Contains("have no rights to send a message")) { Utils.LogInformation(String.Format("Chat {0} not found, deleting him from chat table", chat.Id)); await Database.DeleteFromChatAsync(chat); return; } else { try { await Database.InsertLogAsync($"Telegram send message: {card.FullUrlWebSite} image: {card.ImageUrl}, user: {chat.FirstName} group: {chat.Title}", card.Name, ex.ToString()); Utils.LogInformation(ex.Message); if (!String.IsNullOrEmpty(chat.FirstName)) { Utils.LogInformation("Name: " + chat.FirstName); } if (!String.IsNullOrEmpty(chat.Title)) { Utils.LogInformation("Title: " + chat.Title); } await _botClient.SendTextMessageAsync(23973855, $"Error on {card.FullUrlWebSite} image: {card.ImageUrl} user: {chat.FirstName} group: {chat.Title} id: {chat.Id}"); Utils.LogError(ex.StackTrace); return; } catch { Utils.LogError("Error on SendSpoilToChat catch clause"); } //if there is any error here, we do not want to stop sending the other cards, so just an empty catch } } } async private Task GetInitialUpdateEventsAsync() { try { //get all updates Update[] updates = await _botClient.GetUpdatesAsync(_offset); if (updates.Length > 0) { //check if the chatID is in the list, if it isn't, adds it foreach (Update update in updates) { if (update != null) { //if the offset is equal to the update //and there is only one message in the return //it means that there are no new messages after the offset //so we can stop this and add the hook for the on update event if (updates.Length == 1 && _offset == update.Id) { HookUpdateEvent(); return; } //else we have to continue updating else { _offset = update.Id; } //check if the message is in good state if (update.Message != null && update.Message.Chat != null) { //call the method to see if it is needed to add it to the database await InsertInDbIfNotYetAddedAsync(update.Message.Chat); } } } //recursive call for offset checking await GetInitialUpdateEventsAsync(); } } catch (Exception ex) { Utils.LogError(ex.Message); Utils.LogError(ex.StackTrace); } } async private Task InsertInDbIfNotYetAddedAsync(Chat chat) { //query the list to see if the chat is already in the database bool isInDb = await Database.ChatExistsAsync(chat); if (isInDb == false) { //if it isn't adds it await Database.InsertChatAsync(chat); await _botClient.SendTextMessageAsync(chat, "Bot initialized sucessfully, new cards will be sent when avaliable"); Utils.LogInformation(String.Format("Chat {0} - {1}{2} added", chat.Id, chat.Title, chat.FirstName)); } } #endregion #region Events async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken) { if (update.Message is Message message) { try { Utils.LogInformation(String.Format("Handling event ID:{0} from user {1}{2}", message.MessageId, message.Chat.FirstName, message.Chat.Title)); await InsertInDbIfNotYetAddedAsync(message.Chat); //commands handling if (message.EntityValues != null) { foreach (var entity in message.EntityValues) { if (entity.Contains($"/rarity")) { var value = message.Text.Replace(entity, string.Empty); var validString = Utils.ReturnValidRarityFromCommand(value); if (!string.IsNullOrWhiteSpace(validString)) { await Database.UpdateWantedRaritiesForChatAsync(message.Chat, validString); await _botClient.SendTextMessageAsync(message.Chat, "Updated rarities that will be recieved to: " + validString, cancellationToken: cancellationToken); } } } } } catch (Exception ex) { Utils.LogError(ex.Message); Utils.LogError(ex.StackTrace); } } } async Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken) { if (exception is ApiRequestException apiRequestException) { Utils.LogError(apiRequestException.Message); Utils.LogError(apiRequestException.StackTrace); await Database.InsertLogAsync("HandleErrorAsync", String.Empty, exception.ToString()); } } #endregion } }
using System; using System.Collections.Generic; using System.Xml.Serialization; using SIL.Annotations; namespace SIL.Text { /// <summary> /// A LanguageForm is a unicode string plus the id of its writing system /// </summary> public class LanguageForm : Annotatable, IComparable<LanguageForm> { private string _writingSystemId; private string _form; private readonly List<FormatSpan> _spans = new List<FormatSpan>(); /// <summary> /// See the comment on MultiText._parent for information on /// this field. /// </summary> private MultiTextBase _parent; /// <summary> /// for netreflector /// </summary> public LanguageForm() { } public LanguageForm(string writingSystemId, string form, MultiTextBase parent) { _parent = parent; _writingSystemId = writingSystemId; _form = form; } public LanguageForm(LanguageForm form, MultiTextBase parent) : this(form.WritingSystemId, form.Form, parent) { foreach (var span in form.Spans) AddSpan(span.Index, span.Length, span.Lang, span.Class, span.LinkURL); } [XmlAttribute("ws")] public string WritingSystemId { get { return _writingSystemId; } // needed for depersisting with netreflector set { _writingSystemId = value; } } [XmlText] public string Form { get { return _form; } set { _form = value; } } [XmlIgnore] public List<FormatSpan> Spans { get { return _spans; } } /// <summary> /// See the comment on MultiText._parent for information on /// this field. /// </summary> [XmlIgnore] public MultiTextBase Parent { get { return _parent; } } public override bool Equals(object other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; if (other.GetType() != typeof(LanguageForm)) return false; return Equals((LanguageForm)other); } public bool Equals(LanguageForm other) { if(other == null) return false; if (!IsStarred.Equals(other.IsStarred)) return false; if ((WritingSystemId != null && !WritingSystemId.Equals(other.WritingSystemId)) || (other.WritingSystemId != null && !other.WritingSystemId.Equals(WritingSystemId))) return false; if ((Form != null && !Form.Equals(other.Form)) || (other.Form != null && !other.Form.Equals(Form))) return false; if ((_annotation != null && !_annotation.Equals(other._annotation)) || (other._annotation != null && !other._annotation.Equals(_annotation))) return false; if (_spans != other.Spans) { if (_spans == null || other.Spans == null || _spans.Count != other.Spans.Count) return false; for (int i = 0; i < _spans.Count; ++i) { if (!_spans[i].Equals(other.Spans[i])) return false; } } return true; } public int CompareTo(LanguageForm other) { if(other == null) { return 1; } int writingSystemOrder = this.WritingSystemId.CompareTo(other.WritingSystemId); if (writingSystemOrder != 0) { return writingSystemOrder; } int formOrder = this.Form.CompareTo(other.Form); return formOrder; } public override Annotatable Clone() { var clone = new LanguageForm(); clone._writingSystemId = _writingSystemId; clone._form = _form; clone._annotation = _annotation == null ? null : _annotation.Clone(); foreach (var span in _spans) clone._spans.Add(new FormatSpan{Index=span.Index, Length=span.Length, Class=span.Class, Lang=span.Lang, LinkURL=span.LinkURL}); return clone; } /// <summary> /// Store formatting information for one span of characters in the form. /// (This information is not used, but needs to be maintained for output.) /// </summary> /// <remarks> /// Although the LIFT standard officially allows nested spans, we don't /// bother because FieldWorks doesn't support them. /// </remarks> public class FormatSpan { /// <summary>Store the starting index of the span</summary> public int Index { get; set; } /// <summary>Store the length of the span</summary> public int Length { get; set; } /// <summary>Store the language of the data in the span</summary> public string Lang { get; set; } /// <summary>Store the class (style) applied to the data in the span</summary> public string Class { get; set; } /// <summary>Store the underlying URL link of the span</summary> public string LinkURL { get; set; } public override bool Equals(object other) { var that = other as FormatSpan; if (that == null) return false; if (this.Index != that.Index || this.Length!= that.Length) return false; return (this.Class == that.Class && this.Lang == that.Lang && this.LinkURL == that.LinkURL); } } public void AddSpan(int index, int length, string lang, string style, string url) { var span = new FormatSpan {Index=index, Length=length, Lang=lang, Class=style, LinkURL=url}; _spans.Add(span); } /// <summary> /// Adjusts the spans for the changes from oldText to newText. Assume that only one chunk of /// text has changed between the two strings. /// </summary> public static void AdjustSpansForTextChange(string oldText, string newText, List<FormatSpan> spans) { // Be paranoid and check for null strings... Just convert them to empty strings for our purposes. // (I don't think they'll ever be null, but that fits the category of famous last words...) if (oldText == null) oldText = String.Empty; if (newText == null) newText = String.Empty; // If there are no spans, the text hasn't actually changed, or the text length hasn't changed, // then we'll assume we don't need to do anything. if (spans == null || spans.Count == 0 || newText == oldText || newText.Length == oldText.Length) return; // Get the locations of the first changing character in the old string. // We assume that OnTextChanged gets called for every single change, so that // pinpoints the location, and the change in string length tells us the length // of the change itself. (>0 = insertion, <0 = deletion) int minLength = Math.Min(newText.Length, oldText.Length); int diffLocation = minLength; for (int i = 0; i < minLength; ++i) { if (newText[i] != oldText[i]) { diffLocation = i; break; } } int diffLength = newText.Length - oldText.Length; foreach (var span in spans) AdjustSpan(span, diffLocation, diffLength); } private static void AdjustSpan(FormatSpan span, int location, int length) { if (span.Length <= 0) return; // we've already deleted all the characters in the span. if (location > span.Index + span.Length || length == 0) return; // the change doesn't affect the span. // Adding characters to the end of the span is probably desireable if they differ. if (length > 0) { // Inserting characters is fairly easy to deal with. if (location <= span.Index) span.Index += length; else span.Length += length; } // The span changes only if the deletion starts before the end of the span. else if (location < span.Index + span.Length) { // Deleting characters has a number of cases to deal with. // Remember, length is a negative number here! if (location < span.Index) { if (span.Index + length >= location) { span.Index += length; } else { int before = span.Index - location; span.Index = location; span.Length += (before + length); } } else { span.Length += length; if (span.Length < location - span.Index) span.Length = location - span.Index; } } } } }
// 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.Globalization; using System.IO; using System.Linq; using System.Reflection.Tests; using System.Runtime.CompilerServices; using System.Security; using Xunit; [assembly: Attr(77, name = "AttrSimple"), Int32Attr(77, name = "Int32AttrSimple"), Int64Attr(77, name = "Int64AttrSimple"), StringAttr("hello", name = "StringAttrSimple"), EnumAttr(PublicEnum.Case1, name = "EnumAttrSimple"), TypeAttr(typeof(object), name = "TypeAttrSimple")] [assembly: CompilationRelaxations(8)] [assembly: Debuggable((DebuggableAttribute.DebuggingModes)263)] [assembly: CLSCompliant(false)] namespace System.Reflection.Tests { public class AssemblyTests : FileCleanupTestBase { private string SourceTestAssemblyPath { get; } = Path.Combine(Environment.CurrentDirectory, "TestAssembly.dll"); private string DestTestAssemblyPath { get; } private string LoadFromTestPath { get; } public AssemblyTests() { // Assembly.Location does not return the file path for single-file deployment targets. DestTestAssemblyPath = Path.Combine(base.TestDirectory, "TestAssembly.dll"); LoadFromTestPath = Path.Combine(base.TestDirectory, "System.Reflection.Tests.dll"); File.Copy(SourceTestAssemblyPath, DestTestAssemblyPath); string currAssemblyPath = Path.Combine(Environment.CurrentDirectory, "System.Reflection.Tests.dll"); File.Copy(currAssemblyPath, LoadFromTestPath, true); } [Theory] [InlineData(typeof(Int32Attr))] [InlineData(typeof(Int64Attr))] [InlineData(typeof(StringAttr))] [InlineData(typeof(EnumAttr))] [InlineData(typeof(TypeAttr))] [InlineData(typeof(CompilationRelaxationsAttribute))] [InlineData(typeof(AssemblyTitleAttribute))] [InlineData(typeof(AssemblyDescriptionAttribute))] [InlineData(typeof(AssemblyCompanyAttribute))] [InlineData(typeof(CLSCompliantAttribute))] [InlineData(typeof(DebuggableAttribute))] [InlineData(typeof(Attr))] public void CustomAttributes(Type type) { Assembly assembly = Helpers.ExecutingAssembly; IEnumerable<Type> attributesData = assembly.CustomAttributes.Select(customAttribute => customAttribute.AttributeType); Assert.Contains(type, attributesData); ICustomAttributeProvider attributeProvider = assembly; Assert.Single(attributeProvider.GetCustomAttributes(type, false)); Assert.True(attributeProvider.IsDefined(type, false)); IEnumerable<Type> customAttributes = attributeProvider.GetCustomAttributes(false).Select(attribute => attribute.GetType()); Assert.Contains(type, customAttributes); } [Theory] [InlineData(typeof(int), false)] [InlineData(typeof(Attr), true)] [InlineData(typeof(Int32Attr), true)] [InlineData(typeof(Int64Attr), true)] [InlineData(typeof(StringAttr), true)] [InlineData(typeof(EnumAttr), true)] [InlineData(typeof(TypeAttr), true)] [InlineData(typeof(ObjectAttr), true)] [InlineData(typeof(NullAttr), true)] public void DefinedTypes(Type type, bool expected) { IEnumerable<Type> customAttrs = Helpers.ExecutingAssembly.DefinedTypes.Select(typeInfo => typeInfo.AsType()); Assert.Equal(expected, customAttrs.Contains(type)); } [Theory] [InlineData("EmbeddedImage.png", true)] [InlineData("EmbeddedTextFile.txt", true)] [InlineData("NoSuchFile", false)] public void EmbeddedFiles(string resource, bool exists) { string[] resources = Helpers.ExecutingAssembly.GetManifestResourceNames(); Stream resourceStream = Helpers.ExecutingAssembly.GetManifestResourceStream(resource); Assert.Equal(exists, resources.Contains(resource)); Assert.Equal(exists, resourceStream != null); } [Theory] [InlineData("EmbeddedImage1.png", true)] [InlineData("EmbeddedTextFile1.txt", true)] [InlineData("NoSuchFile", false)] public void GetManifestResourceStream(string resource, bool exists) { Type assemblyType = typeof(AssemblyTests); Stream resourceStream = assemblyType.Assembly.GetManifestResourceStream(assemblyType, resource); Assert.Equal(exists, resourceStream != null); } public static IEnumerable<object[]> Equals_TestData() { yield return new object[] { Assembly.Load(new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName)), Assembly.Load(new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName)), true }; yield return new object[] { Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), true }; yield return new object[] { Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), Helpers.ExecutingAssembly, false }; } [Theory] [MemberData(nameof(Equals_TestData))] public void Equals(Assembly assembly1, Assembly assembly2, bool expected) { Assert.Equal(expected, assembly1.Equals(assembly2)); } [Theory] [InlineData(typeof(AssemblyPublicClass), true)] [InlineData(typeof(AssemblyTests), true)] [InlineData(typeof(AssemblyPublicClass.PublicNestedClass), true)] [InlineData(typeof(PublicEnum), true)] [InlineData(typeof(AssemblyGenericPublicClass<>), true)] [InlineData(typeof(AssemblyInternalClass), false)] public void ExportedTypes(Type type, bool expected) { Assembly assembly = Helpers.ExecutingAssembly; Assert.Equal(assembly.GetExportedTypes(), assembly.ExportedTypes); Assert.Equal(expected, assembly.ExportedTypes.Contains(type)); } [Fact] public void GetEntryAssembly() { Assert.NotNull(Assembly.GetEntryAssembly()); string assembly = Assembly.GetEntryAssembly().ToString(); bool correct = assembly.IndexOf("xunit.console", StringComparison.OrdinalIgnoreCase) != -1 || assembly.IndexOf("Microsoft.DotNet.XUnitRunnerUap", StringComparison.OrdinalIgnoreCase) != -1; Assert.True(correct, $"Unexpected assembly name {assembly}"); } [Fact] public void GetFile() { Assert.Throws<ArgumentNullException>(() => typeof(AssemblyTests).Assembly.GetFile(null)); AssertExtensions.Throws<ArgumentException>(null, () => typeof(AssemblyTests).Assembly.GetFile("")); Assert.Null(typeof(AssemblyTests).Assembly.GetFile("NonExistentfile.dll")); Assert.NotNull(typeof(AssemblyTests).Assembly.GetFile("System.Reflection.Tests.dll")); Assert.Equal(typeof(AssemblyTests).Assembly.GetFile("System.Reflection.Tests.dll").Name, typeof(AssemblyTests).Assembly.Location); } [Fact] public void GetFiles() { Assert.NotNull(typeof(AssemblyTests).Assembly.GetFiles()); Assert.Equal(typeof(AssemblyTests).Assembly.GetFiles().Length, 1); Assert.Equal(typeof(AssemblyTests).Assembly.GetFiles()[0].Name, typeof(AssemblyTests).Assembly.Location); } public static IEnumerable<object[]> GetHashCode_TestData() { yield return new object[] { LoadSystemRuntimeAssembly() }; yield return new object[] { LoadSystemCollectionsAssembly() }; yield return new object[] { LoadSystemReflectionAssembly() }; yield return new object[] { typeof(AssemblyTests).GetTypeInfo().Assembly }; } [Theory] [MemberData(nameof(GetHashCode_TestData))] public void GetHashCode(Assembly assembly) { int hashCode = assembly.GetHashCode(); Assert.NotEqual(-1, hashCode); Assert.NotEqual(0, hashCode); } [Theory] [InlineData("System.Reflection.Tests.AssemblyPublicClass", true)] [InlineData("System.Reflection.Tests.AssemblyInternalClass", true)] [InlineData("System.Reflection.Tests.PublicEnum", true)] [InlineData("System.Reflection.Tests.PublicStruct", true)] [InlineData("AssemblyPublicClass", false)] [InlineData("NoSuchType", false)] public void GetType(string name, bool exists) { Type type = Helpers.ExecutingAssembly.GetType(name); if (exists) { Assert.Equal(name, type.FullName); } else { Assert.Null(type); } } [Fact] public void GetType_NoQualifierAllowed() { Assembly a = typeof(G<int>).Assembly; string s = typeof(G<int>).AssemblyQualifiedName; AssertExtensions.Throws<ArgumentException>(null, () => a.GetType(s, throwOnError: true, ignoreCase: false)); } [Fact] public void GetType_DoesntSearchMscorlib() { Assembly a = typeof(AssemblyTests).Assembly; Assert.Throws<TypeLoadException>(() => a.GetType("System.Object", throwOnError: true, ignoreCase: false)); Assert.Throws<TypeLoadException>(() => a.GetType("G`1[[System.Object]]", throwOnError: true, ignoreCase: false)); } [Fact] public void GetType_DefaultsToItself() { Assembly a = typeof(AssemblyTests).Assembly; Type t = a.GetType("G`1[[G`1[[System.Int32, mscorlib]]]]", throwOnError: true, ignoreCase: false); Assert.Equal(typeof(G<G<int>>), t); } [Fact] public void GlobalAssemblyCache() { Assert.False(typeof(AssemblyTests).Assembly.GlobalAssemblyCache); } [Fact] public void HostContext() { Assert.Equal(0, typeof(AssemblyTests).Assembly.HostContext); } public static IEnumerable<object[]> IsDynamic_TestData() { yield return new object[] { Helpers.ExecutingAssembly, false }; yield return new object[] { LoadSystemCollectionsAssembly(), false }; } [Theory] [MemberData(nameof(IsDynamic_TestData))] public void IsDynamic(Assembly assembly, bool expected) { Assert.Equal(expected, assembly.IsDynamic); } public static IEnumerable<object[]> Load_TestData() { yield return new object[] { new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName) }; yield return new object[] { new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName) }; yield return new object[] { new AssemblyName(typeof(AssemblyName).GetTypeInfo().Assembly.FullName) }; } [Fact] public void IsFullyTrusted() { Assert.True(typeof(AssemblyTests).Assembly.IsFullyTrusted); } [Fact] public void SecurityRuleSet_Netcore() { Assert.Equal(SecurityRuleSet.None, typeof(AssemblyTests).Assembly.SecurityRuleSet); } [Theory] [MemberData(nameof(Load_TestData))] public void Load(AssemblyName assemblyRef) { Assert.NotNull(Assembly.Load(assemblyRef)); } [Fact] public void Load_Invalid() { Assert.Throws<ArgumentNullException>(() => Assembly.Load((AssemblyName)null)); // AssemblyRef is null Assert.Throws<FileNotFoundException>(() => Assembly.Load(new AssemblyName("no such assembly"))); // No such assembly } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Assembly.LoadFile() not supported on UWP")] public void LoadFile() { Assembly currentAssembly = typeof(AssemblyTests).Assembly; const string RuntimeTestsDll = "System.Reflection.Tests.dll"; string fullRuntimeTestsPath = Path.GetFullPath(RuntimeTestsDll); var loadedAssembly1 = Assembly.LoadFile(fullRuntimeTestsPath); Assert.NotEqual(currentAssembly, loadedAssembly1); #if netcoreapp System.Runtime.Loader.AssemblyLoadContext alc = System.Runtime.Loader.AssemblyLoadContext.GetLoadContext(loadedAssembly1); string expectedName = string.Format("Assembly.LoadFile({0})", fullRuntimeTestsPath); Assert.Equal(expectedName, alc.Name); Assert.Contains(fullRuntimeTestsPath, alc.Name); Assert.Contains(expectedName, alc.ToString()); Assert.Contains("System.Runtime.Loader.IndividualAssemblyLoadContext", alc.ToString()); #endif string dir = Path.GetDirectoryName(fullRuntimeTestsPath); fullRuntimeTestsPath = Path.Combine(dir, ".", RuntimeTestsDll); Assembly loadedAssembly2 = Assembly.LoadFile(fullRuntimeTestsPath); Assert.Equal(loadedAssembly1, loadedAssembly2); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap)] public void LoadFile_NullPath_Netcore_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("path", () => Assembly.LoadFile(null)); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Assembly.LoadFile() not supported on UWP")] public void LoadFile_NoSuchPath_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>("path", null, () => Assembly.LoadFile("System.Runtime.Tests.dll")); } [Fact] public void LoadFromUsingHashValue_Netcore() { Assert.Throws<NotSupportedException>(() => Assembly.LoadFrom("abc", null, System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA1)); } [Fact] public void LoadFrom_SamePath_ReturnsEqualAssemblies() { Assembly assembly1 = Assembly.LoadFrom(DestTestAssemblyPath); Assembly assembly2 = Assembly.LoadFrom(DestTestAssemblyPath); Assert.Equal(assembly1, assembly2); } [Fact] public void LoadFrom_SameIdentityAsAssemblyWithDifferentPath_ReturnsEqualAssemblies() { Assembly assembly1 = Assembly.LoadFrom(typeof(AssemblyTests).Assembly.Location); Assert.Equal(assembly1, typeof(AssemblyTests).Assembly); Assembly assembly2 = Assembly.LoadFrom(LoadFromTestPath); Assert.Equal(assembly1, assembly2); } [Fact] public void LoadFrom_NullAssemblyFile_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("assemblyFile", () => Assembly.LoadFrom(null)); AssertExtensions.Throws<ArgumentNullException>("assemblyFile", () => Assembly.UnsafeLoadFrom(null)); } [Fact] public void LoadFrom_EmptyAssemblyFile_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>("path", null, (() => Assembly.LoadFrom(""))); AssertExtensions.Throws<ArgumentException>("path", null, (() => Assembly.UnsafeLoadFrom(""))); } [Fact] public void LoadFrom_NoSuchFile_ThrowsFileNotFoundException() { Assert.Throws<FileNotFoundException>(() => Assembly.LoadFrom("NoSuchPath")); Assert.Throws<FileNotFoundException>(() => Assembly.UnsafeLoadFrom("NoSuchPath")); } [Fact] public void UnsafeLoadFrom_SamePath_ReturnsEqualAssemblies() { Assembly assembly1 = Assembly.UnsafeLoadFrom(DestTestAssemblyPath); Assembly assembly2 = Assembly.UnsafeLoadFrom(DestTestAssemblyPath); Assert.Equal(assembly1, assembly2); } [Fact] public void LoadFrom_WithHashValue_NetCoreCore_ThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => Assembly.LoadFrom(DestTestAssemblyPath, new byte[0], Configuration.Assemblies.AssemblyHashAlgorithm.None)); } [Fact] public void LoadModule_Netcore() { Assembly assembly = typeof(AssemblyTests).Assembly; Assert.Throws<NotImplementedException>(() => assembly.LoadModule("abc", null)); Assert.Throws<NotImplementedException>(() => assembly.LoadModule("abc", null, null)); } #pragma warning disable 618 [Fact] public void LoadWithPartialName() { string simpleName = typeof(AssemblyTests).Assembly.GetName().Name; var assembly = Assembly.LoadWithPartialName(simpleName); Assert.Equal(typeof(AssemblyTests).Assembly, assembly); } [Fact] public void LoadWithPartialName_Neg() { AssertExtensions.Throws<ArgumentNullException>("partialName", () => Assembly.LoadWithPartialName(null)); AssertExtensions.Throws<ArgumentException>("partialName", () => Assembly.LoadWithPartialName("")); Assert.Null(Assembly.LoadWithPartialName("no such assembly")); } #pragma warning restore 618 [Fact] public void Location_ExecutingAssembly_IsNotNull() { // This test applies on all platforms including .NET Native. Location must at least be non-null (it can be empty). // System.Reflection.CoreCLR.Tests adds tests that expect more than that. Assert.NotNull(Helpers.ExecutingAssembly.Location); } [Fact] public void CodeBase() { Assert.NotEmpty(Helpers.ExecutingAssembly.CodeBase); } [Fact] public void ImageRuntimeVersion() { Assert.NotEmpty(Helpers.ExecutingAssembly.ImageRuntimeVersion); } public static IEnumerable<object[]> CreateInstance_TestData() { yield return new object[] { Helpers.ExecutingAssembly, typeof(AssemblyPublicClass).FullName, typeof(AssemblyPublicClass) }; yield return new object[] { typeof(int).GetTypeInfo().Assembly, typeof(int).FullName, typeof(int) }; yield return new object[] { typeof(int).GetTypeInfo().Assembly, typeof(Dictionary<int, string>).FullName, typeof(Dictionary<int, string>) }; } [Theory] [MemberData(nameof(CreateInstance_TestData))] public void CreateInstance(Assembly assembly, string typeName, Type expectedType) { Assert.IsType(expectedType, assembly.CreateInstance(typeName)); Assert.IsType(expectedType, assembly.CreateInstance(typeName, false)); Assert.IsType(expectedType, assembly.CreateInstance(typeName, true)); Assert.IsType(expectedType, assembly.CreateInstance(typeName.ToUpper(), true)); Assert.IsType(expectedType, assembly.CreateInstance(typeName.ToLower(), true)); } public static IEnumerable<object[]> CreateInstanceWithBindingFlags_TestData() { yield return new object[] { typeof(AssemblyTests).Assembly, typeof(AssemblyPublicClass).FullName, BindingFlags.CreateInstance, typeof(AssemblyPublicClass) }; yield return new object[] { typeof(int).Assembly, typeof(int).FullName, BindingFlags.Default, typeof(int) }; yield return new object[] { typeof(int).Assembly, typeof(Dictionary<int, string>).FullName, BindingFlags.Default, typeof(Dictionary<int, string>) }; } [Theory] [MemberData(nameof(CreateInstanceWithBindingFlags_TestData))] public void CreateInstanceWithBindingFlags(Assembly assembly, string typeName, BindingFlags bindingFlags, Type expectedType) { Assert.IsType(expectedType, assembly.CreateInstance(typeName, true, bindingFlags, null, null, null, null)); Assert.IsType(expectedType, assembly.CreateInstance(typeName, false, bindingFlags, null, null, null, null)); } public static IEnumerable<object[]> CreateInstance_Invalid_TestData() { yield return new object[] { "", typeof(ArgumentException) }; yield return new object[] { null, typeof(ArgumentNullException) }; yield return new object[] { typeof(AssemblyClassWithPrivateCtor).FullName, typeof(MissingMethodException) }; yield return new object[] { typeof(AssemblyClassWithNoDefaultCtor).FullName, typeof(MissingMethodException) }; } [Theory] [MemberData(nameof(CreateInstance_Invalid_TestData))] public void CreateInstance_Invalid(string typeName, Type exceptionType) { Assembly assembly = Helpers.ExecutingAssembly; Assert.Throws(exceptionType, () => Helpers.ExecutingAssembly.CreateInstance(typeName)); Assert.Throws(exceptionType, () => Helpers.ExecutingAssembly.CreateInstance(typeName, true)); Assert.Throws(exceptionType, () => Helpers.ExecutingAssembly.CreateInstance(typeName, false)); assembly = typeof(AssemblyTests).Assembly; Assert.Throws(exceptionType, () => assembly.CreateInstance(typeName, true, BindingFlags.Public, null, null, null, null)); Assert.Throws(exceptionType, () => assembly.CreateInstance(typeName, false, BindingFlags.Public, null, null, null, null)); } [Fact] public void CreateQualifiedName() { string assemblyName = Helpers.ExecutingAssembly.ToString(); Assert.Equal(typeof(AssemblyTests).FullName + ", " + assemblyName, Assembly.CreateQualifiedName(assemblyName, typeof(AssemblyTests).FullName)); } [Fact] public void GetReferencedAssemblies() { // It is too brittle to depend on the assembly references so we just call the method and check that it does not throw. AssemblyName[] assemblies = Helpers.ExecutingAssembly.GetReferencedAssemblies(); Assert.NotEmpty(assemblies); } public static IEnumerable<object[]> Modules_TestData() { yield return new object[] { LoadSystemCollectionsAssembly() }; yield return new object[] { LoadSystemReflectionAssembly() }; } [Theory] [MemberData(nameof(Modules_TestData))] public void Modules(Assembly assembly) { Assert.NotEmpty(assembly.Modules); foreach (Module module in assembly.Modules) { Assert.NotNull(module); } } public static IEnumerable<object[]> Equality_TestData() { yield return new object[] { Assembly.Load(new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName)), Assembly.Load(new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName)), true }; yield return new object[] { Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), true }; yield return new object[] { Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), typeof(AssemblyTests).Assembly, false }; } [Theory] [MemberData(nameof(Equality_TestData))] public void Equality(Assembly assembly1, Assembly assembly2, bool expected) { Assert.Equal(expected, assembly1 == assembly2); Assert.NotEqual(expected, assembly1 != assembly2); } [Fact] public void GetAssembly_Nullery() { AssertExtensions.Throws<ArgumentNullException>("type", () => Assembly.GetAssembly(null)); } public static IEnumerable<object[]> GetAssembly_TestData() { yield return new object[] { Assembly.Load(new AssemblyName(typeof(HashSet<int>).GetTypeInfo().Assembly.FullName)), Assembly.GetAssembly(typeof(HashSet<int>)), true }; yield return new object[] { Assembly.Load(new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName)), Assembly.GetAssembly(typeof(int)), true }; yield return new object[] { typeof(AssemblyTests).Assembly, Assembly.GetAssembly(typeof(AssemblyTests)), true }; } [Theory] [MemberData(nameof(GetAssembly_TestData))] public void GetAssembly(Assembly assembly1, Assembly assembly2, bool expected) { Assert.Equal(expected, assembly1.Equals(assembly2)); } public static IEnumerable<object[]> GetCallingAssembly_TestData() { yield return new object[] { typeof(AssemblyTests).Assembly, GetGetCallingAssembly(), true }; yield return new object[] { Assembly.GetCallingAssembly(), GetGetCallingAssembly(), false }; } [Theory] [MemberData(nameof(GetCallingAssembly_TestData))] public void GetCallingAssembly(Assembly assembly1, Assembly assembly2, bool expected) { Assert.Equal(expected, assembly1.Equals(assembly2)); } [Fact] public void GetExecutingAssembly() { Assert.True(typeof(AssemblyTests).Assembly.Equals(Assembly.GetExecutingAssembly())); } [Fact] public void GetSatelliteAssemblyNeg() { Assert.Throws<ArgumentNullException>(() => (typeof(AssemblyTests).Assembly.GetSatelliteAssembly(null))); Assert.Throws<System.IO.FileNotFoundException>(() => (typeof(AssemblyTests).Assembly.GetSatelliteAssembly(CultureInfo.InvariantCulture))); } [Fact] public void AssemblyLoadFromString() { AssemblyName an = typeof(AssemblyTests).Assembly.GetName(); string fullName = an.FullName; string simpleName = an.Name; Assembly a1 = Assembly.Load(fullName); Assert.NotNull(a1); Assert.Equal(fullName, a1.GetName().FullName); Assembly a2 = Assembly.Load(simpleName); Assert.NotNull(a2); Assert.Equal(fullName, a2.GetName().FullName); } [Fact] public void AssemblyLoadFromStringNeg() { Assert.Throws<ArgumentNullException>(() => Assembly.Load((string)null)); AssertExtensions.Throws<ArgumentException>(null, () => Assembly.Load(string.Empty)); string emptyCName = new string('\0', 1); AssertExtensions.Throws<ArgumentException>(null, () => Assembly.Load(emptyCName)); Assert.Throws<FileNotFoundException>(() => Assembly.Load("no such assembly")); // No such assembly } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Assembly.Load(byte[]) not supported on UWP")] public void AssemblyLoadFromBytes() { Assembly assembly = typeof(AssemblyTests).Assembly; byte[] aBytes = System.IO.File.ReadAllBytes(assembly.Location); Assembly loadedAssembly = Assembly.Load(aBytes); Assert.NotNull(loadedAssembly); Assert.Equal(assembly.FullName, loadedAssembly.FullName); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Assembly.Load(byte[]) not supported on UWP")] public void AssemblyLoadFromBytesNeg() { Assert.Throws<ArgumentNullException>(() => Assembly.Load((byte[])null)); Assert.Throws<BadImageFormatException>(() => Assembly.Load(new byte[0])); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Assembly.Load(byte[]) not supported on UWP")] public void AssemblyLoadFromBytesWithSymbols() { Assembly assembly = typeof(AssemblyTests).Assembly; byte[] aBytes = System.IO.File.ReadAllBytes(assembly.Location); byte[] symbols = System.IO.File.ReadAllBytes((System.IO.Path.ChangeExtension(assembly.Location, ".pdb"))); Assembly loadedAssembly = Assembly.Load(aBytes, symbols); Assert.NotNull(loadedAssembly); Assert.Equal(assembly.FullName, loadedAssembly.FullName); } [Fact] public void AssemblyReflectionOnlyLoadFromString() { AssemblyName an = typeof(AssemblyTests).Assembly.GetName(); Assert.Throws<PlatformNotSupportedException>(() => Assembly.ReflectionOnlyLoad(an.FullName)); } [Fact] public void AssemblyReflectionOnlyLoadFromBytes() { Assembly assembly = typeof(AssemblyTests).Assembly; byte[] aBytes = System.IO.File.ReadAllBytes(assembly.Location); Assert.Throws<PlatformNotSupportedException>(() => Assembly.ReflectionOnlyLoad(aBytes)); } [Fact] public void AssemblyReflectionOnlyLoadFromNeg() { Assert.Throws<PlatformNotSupportedException>(() => Assembly.ReflectionOnlyLoad((string)null)); Assert.Throws<PlatformNotSupportedException>(() => Assembly.ReflectionOnlyLoad(string.Empty)); Assert.Throws<PlatformNotSupportedException>(() => Assembly.ReflectionOnlyLoad((byte[])null)); } public static IEnumerable<object[]> GetModules_TestData() { yield return new object[] { LoadSystemCollectionsAssembly() }; yield return new object[] { LoadSystemReflectionAssembly() }; } [Theory] [MemberData(nameof(GetModules_TestData))] public void GetModules_GetModule(Assembly assembly) { Assert.NotEmpty(assembly.GetModules()); foreach (Module module in assembly.GetModules()) { Assert.Equal(module, assembly.GetModule(module.ToString())); } } [Fact] public void GetLoadedModules() { Assembly assembly = typeof(AssemblyTests).Assembly; Assert.NotEmpty(assembly.GetLoadedModules()); foreach (Module module in assembly.GetLoadedModules()) { Assert.NotNull(module); Assert.Equal(module, assembly.GetModule(module.ToString())); } } [Theory] [InlineData(typeof(Int32Attr))] [InlineData(typeof(Int64Attr))] [InlineData(typeof(StringAttr))] [InlineData(typeof(EnumAttr))] [InlineData(typeof(TypeAttr))] [InlineData(typeof(CompilationRelaxationsAttribute))] [InlineData(typeof(AssemblyTitleAttribute))] [InlineData(typeof(AssemblyDescriptionAttribute))] [InlineData(typeof(AssemblyCompanyAttribute))] [InlineData(typeof(CLSCompliantAttribute))] [InlineData(typeof(DebuggableAttribute))] [InlineData(typeof(Attr))] public void GetCustomAttributesData(Type attrType) { IEnumerable<CustomAttributeData> customAttributesData = typeof(AssemblyTests).Assembly.GetCustomAttributesData().Where(cad => cad.AttributeType == attrType); Assert.True(customAttributesData.Count() > 0, $"Did not find custom attribute of type {attrType}"); } private static Assembly LoadSystemCollectionsAssembly() { // Force System.collections to be linked statically List<int> li = new List<int>(); li.Add(1); return Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)); } private static Assembly LoadSystemReflectionAssembly() { // Force System.Reflection to be linked statically return Assembly.Load(new AssemblyName(typeof(AssemblyName).GetTypeInfo().Assembly.FullName)); } private static Assembly LoadSystemRuntimeAssembly() { // Load System.Runtime return Assembly.Load(new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName)); ; } private static Assembly GetGetCallingAssembly() { return Assembly.GetCallingAssembly(); } } public struct PublicStruct { } public class AssemblyPublicClass { public class PublicNestedClass { } } public class AssemblyGenericPublicClass<T> { } internal class AssemblyInternalClass { } public class AssemblyClassWithPrivateCtor { private AssemblyClassWithPrivateCtor() { } } public class AssemblyClassWithNoDefaultCtor { public AssemblyClassWithNoDefaultCtor(int x) { } } } internal class G<T> { }
// ReSharper disable All using System.Collections.Generic; using System.Data; using System.Dynamic; using System.Linq; using Frapid.Configuration; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Frapid.DbPolicy; using Frapid.Framework.Extensions; using Npgsql; using Frapid.NPoco; using Serilog; namespace Frapid.Config.DataAccess { /// <summary> /// Provides simplified data access features to perform SCRUD operation on the database table "config.flag_types". /// </summary> public class FlagType : DbAccess, IFlagTypeRepository { /// <summary> /// The schema of this table. Returns literal "config". /// </summary> public override string _ObjectNamespace => "config"; /// <summary> /// The schema unqualified name of this table. Returns literal "flag_types". /// </summary> public override string _ObjectName => "flag_types"; /// <summary> /// Login id of application user accessing this table. /// </summary> public long _LoginId { get; set; } /// <summary> /// User id of application user accessing this table. /// </summary> public int _UserId { get; set; } /// <summary> /// The name of the database on which queries are being executed to. /// </summary> public string _Catalog { get; set; } /// <summary> /// Performs SQL count on the table "config.flag_types". /// </summary> /// <returns>Returns the number of rows of the table "config.flag_types".</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long Count() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"FlagType\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT COUNT(*) FROM config.flag_types;"; return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Executes a select query on the table "config.flag_types" to return all instances of the "FlagType" class. /// </summary> /// <returns>Returns a non-live, non-mapped instances of "FlagType" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.FlagType> GetAll() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the export entity \"FlagType\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.flag_types ORDER BY flag_type_id;"; return Factory.Get<Frapid.Config.Entities.FlagType>(this._Catalog, sql); } /// <summary> /// Executes a select query on the table "config.flag_types" to return all instances of the "FlagType" class to export. /// </summary> /// <returns>Returns a non-live, non-mapped instances of "FlagType" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<dynamic> Export() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the export entity \"FlagType\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.flag_types ORDER BY flag_type_id;"; return Factory.Get<dynamic>(this._Catalog, sql); } /// <summary> /// Executes a select query on the table "config.flag_types" with a where filter on the column "flag_type_id" to return a single instance of the "FlagType" class. /// </summary> /// <param name="flagTypeId">The column "flag_type_id" parameter used on where filter.</param> /// <returns>Returns a non-live, non-mapped instance of "FlagType" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.FlagType Get(int flagTypeId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get entity \"FlagType\" filtered by \"FlagTypeId\" with value {FlagTypeId} was denied to the user with Login ID {_LoginId}", flagTypeId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.flag_types WHERE flag_type_id=@0;"; return Factory.Get<Frapid.Config.Entities.FlagType>(this._Catalog, sql, flagTypeId).FirstOrDefault(); } /// <summary> /// Gets the first record of the table "config.flag_types". /// </summary> /// <returns>Returns a non-live, non-mapped instance of "FlagType" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.FlagType GetFirst() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the first record of entity \"FlagType\" was denied to the user with Login ID {_LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.flag_types ORDER BY flag_type_id LIMIT 1;"; return Factory.Get<Frapid.Config.Entities.FlagType>(this._Catalog, sql).FirstOrDefault(); } /// <summary> /// Gets the previous record of the table "config.flag_types" sorted by flagTypeId. /// </summary> /// <param name="flagTypeId">The column "flag_type_id" parameter used to find the next record.</param> /// <returns>Returns a non-live, non-mapped instance of "FlagType" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.FlagType GetPrevious(int flagTypeId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the previous entity of \"FlagType\" by \"FlagTypeId\" with value {FlagTypeId} was denied to the user with Login ID {_LoginId}", flagTypeId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.flag_types WHERE flag_type_id < @0 ORDER BY flag_type_id DESC LIMIT 1;"; return Factory.Get<Frapid.Config.Entities.FlagType>(this._Catalog, sql, flagTypeId).FirstOrDefault(); } /// <summary> /// Gets the next record of the table "config.flag_types" sorted by flagTypeId. /// </summary> /// <param name="flagTypeId">The column "flag_type_id" parameter used to find the next record.</param> /// <returns>Returns a non-live, non-mapped instance of "FlagType" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.FlagType GetNext(int flagTypeId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the next entity of \"FlagType\" by \"FlagTypeId\" with value {FlagTypeId} was denied to the user with Login ID {_LoginId}", flagTypeId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.flag_types WHERE flag_type_id > @0 ORDER BY flag_type_id LIMIT 1;"; return Factory.Get<Frapid.Config.Entities.FlagType>(this._Catalog, sql, flagTypeId).FirstOrDefault(); } /// <summary> /// Gets the last record of the table "config.flag_types". /// </summary> /// <returns>Returns a non-live, non-mapped instance of "FlagType" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.FlagType GetLast() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the last record of entity \"FlagType\" was denied to the user with Login ID {_LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.flag_types ORDER BY flag_type_id DESC LIMIT 1;"; return Factory.Get<Frapid.Config.Entities.FlagType>(this._Catalog, sql).FirstOrDefault(); } /// <summary> /// Executes a select query on the table "config.flag_types" with a where filter on the column "flag_type_id" to return a multiple instances of the "FlagType" class. /// </summary> /// <param name="flagTypeIds">Array of column "flag_type_id" parameter used on where filter.</param> /// <returns>Returns a non-live, non-mapped collection of "FlagType" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.FlagType> Get(int[] flagTypeIds) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to entity \"FlagType\" was denied to the user with Login ID {LoginId}. flagTypeIds: {flagTypeIds}.", this._LoginId, flagTypeIds); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.flag_types WHERE flag_type_id IN (@0);"; return Factory.Get<Frapid.Config.Entities.FlagType>(this._Catalog, sql, flagTypeIds); } /// <summary> /// Custom fields are user defined form elements for config.flag_types. /// </summary> /// <returns>Returns an enumerable custom field collection for the table config.flag_types</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to get custom fields for entity \"FlagType\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } string sql; if (string.IsNullOrWhiteSpace(resourceId)) { sql = "SELECT * FROM config.custom_field_definition_view WHERE table_name='config.flag_types' ORDER BY field_order;"; return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql); } sql = "SELECT * from config.get_custom_field_definition('config.flag_types'::text, @0::text) ORDER BY field_order;"; return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql, resourceId); } /// <summary> /// Displayfields provide a minimal name/value context for data binding the row collection of config.flag_types. /// </summary> /// <returns>Returns an enumerable name and value collection for the table config.flag_types</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields() { List<Frapid.DataAccess.Models.DisplayField> displayFields = new List<Frapid.DataAccess.Models.DisplayField>(); if (string.IsNullOrWhiteSpace(this._Catalog)) { return displayFields; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to get display field for entity \"FlagType\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT flag_type_id AS key, flag_type_name as value FROM config.flag_types;"; using (NpgsqlCommand command = new NpgsqlCommand(sql)) { using (DataTable table = DbOperation.GetDataTable(this._Catalog, command)) { if (table?.Rows == null || table.Rows.Count == 0) { return displayFields; } foreach (DataRow row in table.Rows) { if (row != null) { DisplayField displayField = new DisplayField { Key = row["key"].ToString(), Value = row["value"].ToString() }; displayFields.Add(displayField); } } } } return displayFields; } /// <summary> /// Inserts or updates the instance of FlagType class on the database table "config.flag_types". /// </summary> /// <param name="flagType">The instance of "FlagType" class to insert or update.</param> /// <param name="customFields">The custom field collection.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public object AddOrEdit(dynamic flagType, List<Frapid.DataAccess.Models.CustomField> customFields) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } flagType.audit_user_id = this._UserId; flagType.audit_ts = System.DateTime.UtcNow; object primaryKeyValue = flagType.flag_type_id; if (Cast.To<int>(primaryKeyValue) > 0) { this.Update(flagType, Cast.To<int>(primaryKeyValue)); } else { primaryKeyValue = this.Add(flagType); } string sql = "DELETE FROM config.custom_fields WHERE custom_field_setup_id IN(" + "SELECT custom_field_setup_id " + "FROM config.custom_field_setup " + "WHERE form_name=config.get_custom_field_form_name('config.flag_types')" + ");"; Factory.NonQuery(this._Catalog, sql); if (customFields == null) { return primaryKeyValue; } foreach (var field in customFields) { sql = "INSERT INTO config.custom_fields(custom_field_setup_id, resource_id, value) " + "SELECT config.get_custom_field_setup_id_by_table_name('config.flag_types', @0::character varying(100)), " + "@1, @2;"; Factory.NonQuery(this._Catalog, sql, field.FieldName, primaryKeyValue, field.Value); } return primaryKeyValue; } /// <summary> /// Inserts the instance of FlagType class on the database table "config.flag_types". /// </summary> /// <param name="flagType">The instance of "FlagType" class to insert.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public object Add(dynamic flagType) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Create, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to add entity \"FlagType\" was denied to the user with Login ID {LoginId}. {FlagType}", this._LoginId, flagType); throw new UnauthorizedException("Access is denied."); } } return Factory.Insert(this._Catalog, flagType, "config.flag_types", "flag_type_id"); } /// <summary> /// Inserts or updates multiple instances of FlagType class on the database table "config.flag_types"; /// </summary> /// <param name="flagTypes">List of "FlagType" class to import.</param> /// <returns></returns> public List<object> BulkImport(List<ExpandoObject> flagTypes) { if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.ImportData, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to import entity \"FlagType\" was denied to the user with Login ID {LoginId}. {flagTypes}", this._LoginId, flagTypes); throw new UnauthorizedException("Access is denied."); } } var result = new List<object>(); int line = 0; try { using (Database db = new Database(ConnectionString.GetConnectionString(this._Catalog), Factory.ProviderName)) { using (ITransaction transaction = db.GetTransaction()) { foreach (dynamic flagType in flagTypes) { line++; flagType.audit_user_id = this._UserId; flagType.audit_ts = System.DateTime.UtcNow; object primaryKeyValue = flagType.flag_type_id; if (Cast.To<int>(primaryKeyValue) > 0) { result.Add(flagType.flag_type_id); db.Update("config.flag_types", "flag_type_id", flagType, flagType.flag_type_id); } else { result.Add(db.Insert("config.flag_types", "flag_type_id", flagType)); } } transaction.Complete(); } return result; } } catch (NpgsqlException ex) { string errorMessage = $"Error on line {line} "; if (ex.Code.StartsWith("P")) { errorMessage += Factory.GetDbErrorResource(ex); throw new DataAccessException(errorMessage, ex); } errorMessage += ex.Message; throw new DataAccessException(errorMessage, ex); } catch (System.Exception ex) { string errorMessage = $"Error on line {line} "; throw new DataAccessException(errorMessage, ex); } } /// <summary> /// Updates the row of the table "config.flag_types" with an instance of "FlagType" class against the primary key value. /// </summary> /// <param name="flagType">The instance of "FlagType" class to update.</param> /// <param name="flagTypeId">The value of the column "flag_type_id" which will be updated.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public void Update(dynamic flagType, int flagTypeId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Edit, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to edit entity \"FlagType\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}. {FlagType}", flagTypeId, this._LoginId, flagType); throw new UnauthorizedException("Access is denied."); } } Factory.Update(this._Catalog, flagType, flagTypeId, "config.flag_types", "flag_type_id"); } /// <summary> /// Deletes the row of the table "config.flag_types" against the primary key value. /// </summary> /// <param name="flagTypeId">The value of the column "flag_type_id" which will be deleted.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public void Delete(int flagTypeId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Delete, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to delete entity \"FlagType\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}.", flagTypeId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "DELETE FROM config.flag_types WHERE flag_type_id=@0;"; Factory.NonQuery(this._Catalog, sql, flagTypeId); } /// <summary> /// Performs a select statement on table "config.flag_types" producing a paginated result of 10. /// </summary> /// <returns>Returns the first page of collection of "FlagType" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.FlagType> GetPaginatedResult() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the first page of the entity \"FlagType\" was denied to the user with Login ID {LoginId}.", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.flag_types ORDER BY flag_type_id LIMIT 10 OFFSET 0;"; return Factory.Get<Frapid.Config.Entities.FlagType>(this._Catalog, sql); } /// <summary> /// Performs a select statement on table "config.flag_types" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result.</param> /// <returns>Returns collection of "FlagType" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.FlagType> GetPaginatedResult(long pageNumber) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the entity \"FlagType\" was denied to the user with Login ID {LoginId}.", pageNumber, this._LoginId); throw new UnauthorizedException("Access is denied."); } } long offset = (pageNumber - 1) * 10; const string sql = "SELECT * FROM config.flag_types ORDER BY flag_type_id LIMIT 10 OFFSET @0;"; return Factory.Get<Frapid.Config.Entities.FlagType>(this._Catalog, sql, offset); } public List<Frapid.DataAccess.Models.Filter> GetFilters(string catalog, string filterName) { const string sql = "SELECT * FROM config.filters WHERE object_name='config.flag_types' AND lower(filter_name)=lower(@0);"; return Factory.Get<Frapid.DataAccess.Models.Filter>(catalog, sql, filterName).ToList(); } /// <summary> /// Performs a filtered count on table "config.flag_types". /// </summary> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns number of rows of "FlagType" class using the filter.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long CountWhere(List<Frapid.DataAccess.Models.Filter> filters) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"FlagType\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", this._LoginId, filters); throw new UnauthorizedException("Access is denied."); } } Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM config.flag_types WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.FlagType(), filters); return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Performs a filtered select statement on table "config.flag_types" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns collection of "FlagType" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.FlagType> GetWhere(long pageNumber, List<Frapid.DataAccess.Models.Filter> filters) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the filtered entity \"FlagType\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", pageNumber, this._LoginId, filters); throw new UnauthorizedException("Access is denied."); } } long offset = (pageNumber - 1) * 10; Sql sql = Sql.Builder.Append("SELECT * FROM config.flag_types WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.FlagType(), filters); sql.OrderBy("flag_type_id"); if (pageNumber > 0) { sql.Append("LIMIT @0", 10); sql.Append("OFFSET @0", offset); } return Factory.Get<Frapid.Config.Entities.FlagType>(this._Catalog, sql); } /// <summary> /// Performs a filtered count on table "config.flag_types". /// </summary> /// <param name="filterName">The named filter.</param> /// <returns>Returns number of rows of "FlagType" class using the filter.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long CountFiltered(string filterName) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"FlagType\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", this._LoginId, filterName); throw new UnauthorizedException("Access is denied."); } } List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName); Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM config.flag_types WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.FlagType(), filters); return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Performs a filtered select statement on table "config.flag_types" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param> /// <param name="filterName">The named filter.</param> /// <returns>Returns collection of "FlagType" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.FlagType> GetFiltered(long pageNumber, string filterName) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the filtered entity \"FlagType\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", pageNumber, this._LoginId, filterName); throw new UnauthorizedException("Access is denied."); } } List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName); long offset = (pageNumber - 1) * 10; Sql sql = Sql.Builder.Append("SELECT * FROM config.flag_types WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.FlagType(), filters); sql.OrderBy("flag_type_id"); if (pageNumber > 0) { sql.Append("LIMIT @0", 10); sql.Append("OFFSET @0", offset); } return Factory.Get<Frapid.Config.Entities.FlagType>(this._Catalog, sql); } } }
/******************************************************************************* * Copyright (c) 2013, Daniel Murphy * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ using System; using System.Diagnostics; using SharpBox2D.Callbacks; using SharpBox2D.Collision; using SharpBox2D.Collision.Shapes; using SharpBox2D.Common; using SharpBox2D.Dynamics; using SharpBox2D.Dynamics.Contacts; using SharpBox2D.Dynamics.Joints; using SharpBox2D.TestBed.Framework; namespace SharpBox2D.TestBed.Tests { public class RayCastTest : TestbedTest { public static int e_maxBodies = 256; private enum Mode { e_closest, e_any, e_multiple }; private int m_bodyIndex; private Body[] m_bodies; private int[] m_userData; private PolygonShape[] m_polygons; private CircleShape m_circle; private EdgeShape m_edge; private float m_angle; private Mode m_mode; public override string getTestName() { return "Raycast"; } public override void initTest(bool deserialized) { m_bodies = new Body[e_maxBodies]; m_userData = new int[e_maxBodies]; m_polygons = new PolygonShape[4]; { BodyDef bd = new BodyDef(); Body ground = getWorld().createBody(bd); EdgeShape shape = new EdgeShape(); shape.set(new Vec2(-40.0f, 0.0f), new Vec2(40.0f, 0.0f)); ground.createFixture(shape, 0.0f); } { Vec2[] vertices = new Vec2[3]; vertices[0] = new Vec2(-0.5f, 0.0f); vertices[1] = new Vec2(0.5f, 0.0f); vertices[2] = new Vec2(0.0f, 1.5f); m_polygons[0] = new PolygonShape(); m_polygons[0].set(vertices, 3); } { Vec2[] vertices = new Vec2[3]; vertices[0] = new Vec2(-0.1f, 0.0f); vertices[1] = new Vec2(0.1f, 0.0f); vertices[2] = new Vec2(0.0f, 1.5f); m_polygons[1] = new PolygonShape(); m_polygons[1].set(vertices, 3); } { float w = 1.0f; float b = w/(2.0f + MathUtils.sqrt(2.0f)); float s = MathUtils.sqrt(2.0f)*b; Vec2[] vertices = new Vec2[8]; vertices[0] = new Vec2(0.5f*s, 0.0f); vertices[1] = new Vec2(0.5f*w, b); vertices[2] = new Vec2(0.5f*w, b + s); vertices[3] = new Vec2(0.5f*s, w); vertices[4] = new Vec2(-0.5f*s, w); vertices[5] = new Vec2(-0.5f*w, b + s); vertices[6] = new Vec2(-0.5f*w, b); vertices[7] = new Vec2(-0.5f*s, 0.0f); m_polygons[2] = new PolygonShape(); m_polygons[2].set(vertices, 8); } { m_polygons[3] = new PolygonShape(); m_polygons[3].setAsBox(0.5f, 0.5f); } { m_circle = new CircleShape(); m_circle.m_radius = 0.5f; } { m_edge = new EdgeShape(); m_edge.set(new Vec2(-1.0f, 0.0f), new Vec2(1.0f, 0.0f)); } m_bodyIndex = 0; m_angle = 0.0f; m_mode = Mode.e_closest; } private RayCastClosestCallback ccallback = new RayCastClosestCallback(); private RayCastAnyCallback acallback = new RayCastAnyCallback(); private RayCastMultipleCallback mcallback = new RayCastMultipleCallback(); // pooling private Vec2 point1 = new Vec2(); private Vec2 d = new Vec2(); private Vec2 pooledHead = new Vec2(); private Vec2 point2 = new Vec2(); public override void step(TestbedSettings settings) { bool advanceRay = settings.pause == false || settings.singleStep; base.step(settings); addTextLine("Press 1-6 to drop stuff, m to change the mode"); addTextLine("Polygon 1 is filtered"); addTextLine("Mode = " + m_mode); float L = 11.0f; point1.set(0.0f, 10.0f); d.set(L*MathUtils.cos(m_angle), L*MathUtils.sin(m_angle)); point2.set(point1); point2.addLocal(d); if (m_mode == Mode.e_closest) { ccallback.init(); getWorld().raycast(ccallback, point1, point2); if (ccallback.m_hit) { getDebugDraw().drawPoint(ccallback.m_point, 5.0f, new Color4f(0.4f, 0.9f, 0.4f)); getDebugDraw().drawSegment(point1, ccallback.m_point, new Color4f(0.8f, 0.8f, 0.8f)); pooledHead.set(ccallback.m_normal); pooledHead.mulLocal(.5f); pooledHead.addLocal(ccallback.m_point); getDebugDraw().drawSegment(ccallback.m_point, pooledHead, new Color4f(0.9f, 0.9f, 0.4f)); } else { getDebugDraw().drawSegment(point1, point2, new Color4f(0.8f, 0.8f, 0.8f)); } } else if (m_mode == Mode.e_any) { acallback.init(); getWorld().raycast(acallback, point1, point2); if (acallback.m_hit) { getDebugDraw().drawPoint(acallback.m_point, 5.0f, new Color4f(0.4f, 0.9f, 0.4f)); getDebugDraw().drawSegment(point1, acallback.m_point, new Color4f(0.8f, 0.8f, 0.8f)); pooledHead.set(acallback.m_normal); pooledHead.mulLocal(.5f); pooledHead.addLocal(acallback.m_point); getDebugDraw().drawSegment(acallback.m_point, pooledHead, new Color4f(0.9f, 0.9f, 0.4f)); } else { getDebugDraw().drawSegment(point1, point2, new Color4f(0.8f, 0.8f, 0.8f)); } } else if (m_mode == Mode.e_multiple) { mcallback.init(); getWorld().raycast(mcallback, point1, point2); getDebugDraw().drawSegment(point1, point2, new Color4f(0.8f, 0.8f, 0.8f)); for (int i = 0; i < mcallback.m_count; ++i) { Vec2 p = mcallback.m_points[i]; Vec2 n = mcallback.m_normals[i]; getDebugDraw().drawPoint(p, 5.0f, new Color4f(0.4f, 0.9f, 0.4f)); getDebugDraw().drawSegment(point1, p, new Color4f(0.8f, 0.8f, 0.8f)); pooledHead.set(n); pooledHead.mulLocal(.5f); pooledHead.addLocal(p); getDebugDraw().drawSegment(p, pooledHead, new Color4f(0.9f, 0.9f, 0.4f)); } } if (advanceRay) { m_angle += 0.25f*MathUtils.PI/180.0f; } } private Random _random = new Random(); private void Create(int index) { if (m_bodies[m_bodyIndex] != null) { getWorld().destroyBody(m_bodies[m_bodyIndex]); m_bodies[m_bodyIndex] = null; } BodyDef bd = new BodyDef(); float x = (float) _random.NextDouble()*20 - 10; float y = (float) _random.NextDouble()*20; bd.position.set(x, y); bd.angle = (float) _random.NextDouble()*MathUtils.TWOPI - MathUtils.PI; m_userData[m_bodyIndex] = index; bd.userData = m_userData[m_bodyIndex]; if (index == 4) { bd.angularDamping = 0.02f; } m_bodies[m_bodyIndex] = getWorld().createBody(bd); if (index < 4) { FixtureDef fd = new FixtureDef(); fd.shape = m_polygons[index]; fd.friction = 0.3f; m_bodies[m_bodyIndex].createFixture(fd); } else if (index < 5) { FixtureDef fd = new FixtureDef(); fd.shape = m_circle; fd.friction = 0.3f; m_bodies[m_bodyIndex].createFixture(fd); } else { FixtureDef fd = new FixtureDef(); fd.shape = m_edge; fd.friction = 0.3f; m_bodies[m_bodyIndex].createFixture(fd); } m_bodyIndex = (m_bodyIndex + 1)%e_maxBodies; } private void DestroyBody() { for (int i = 0; i < e_maxBodies; ++i) { if (m_bodies[i] != null) { getWorld().destroyBody(m_bodies[i]); m_bodies[i] = null; return; } } } public override void keyPressed(char argKeyChar, int argKeyCode) { switch (argKeyChar) { case '1': case '2': case '3': case '4': case '5': case '6': Create(argKeyChar - '1'); break; case 'd': DestroyBody(); break; case 'm': if (m_mode == Mode.e_closest) { m_mode = Mode.e_any; } else if (m_mode == Mode.e_any) { m_mode = Mode.e_multiple; } else if (m_mode == Mode.e_multiple) { m_mode = Mode.e_closest; } break; } } } // This test demonstrates how to use the world ray-cast feature. // NOTE: we are intentionally filtering one of the polygons, therefore // the ray will always miss one type of polygon. // This callback finds the closest hit. Polygon 0 is filtered. internal class RayCastClosestCallback : RayCastCallback { internal bool m_hit; internal Vec2 m_point; internal Vec2 m_normal; public void init() { m_hit = false; } public float reportFixture(Fixture fixture, Vec2 point, Vec2 normal, float fraction) { Body body = fixture.getBody(); Object userData = body.getUserData(); if (userData != null) { int index = (int) userData; if (index == 0) { // filter return -1f; } } m_hit = true; m_point = point; m_normal = normal; return fraction; } }; // This callback finds any hit. Polygon 0 is filtered. internal class RayCastAnyCallback : RayCastCallback { public void init() { m_hit = false; } public float reportFixture(Fixture fixture, Vec2 point, Vec2 normal, float fraction) { Body body = fixture.getBody(); Object userData = body.getUserData(); if (userData != null) { int index = (int) userData; if (index == 0) { // filter return -1f; } } m_hit = true; m_point = point; m_normal = normal; return 0f; } internal bool m_hit; internal Vec2 m_point; internal Vec2 m_normal; }; // This ray cast collects multiple hits along the ray. Polygon 0 is filtered. internal class RayCastMultipleCallback : RayCastCallback { public const int e_maxCount = 30; internal Vec2[] m_points = new Vec2[e_maxCount]; internal Vec2[] m_normals = new Vec2[e_maxCount]; internal int m_count; public void init() { for (int i = 0; i < e_maxCount; i++) { m_points[i] = new Vec2(); m_normals[i] = new Vec2(); } m_count = 0; } public float reportFixture(Fixture fixture, Vec2 point, Vec2 normal, float fraction) { Body body = fixture.getBody(); int index = 0; Object userData = body.getUserData(); if (userData != null) { index = (int) userData; if (index == 0) { // filter return -1f; } } Debug.Assert(m_count < e_maxCount); m_points[m_count].set(point); m_normals[m_count].set(normal); ++m_count; if (m_count == e_maxCount) { return 0f; } return 1f; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Reflection.Internal; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; namespace System.Reflection.Metadata { [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] public partial class BlobBuilder { // The implementation is akin to StringBuilder. // The differences: // - BlobBuilder allows efficient sequential write of the built content to a stream. // - BlobBuilder allows for chunk allocation customization. A custom allocator can use pooling strategy, for example. internal const int DefaultChunkSize = 256; // Must be at least the size of the largest primitive type we write atomically (Guid). internal const int MinChunkSize = 16; // Builders are linked like so: // // [1:first]->[2]->[3:last]<-[4:head] // ^_______________| // // In this case the content represented is a sequence (1,2,3,4). // This structure optimizes for append write operations and sequential enumeration from the start of the chain. // Data can only be written to the head node. Other nodes are "frozen". private BlobBuilder _nextOrPrevious; private BlobBuilder FirstChunk => _nextOrPrevious._nextOrPrevious; // The sum of lengths of all preceding chunks (not including the current chunk), // or a difference between original buffer length of a builder that was linked as a suffix to another builder, // and the current length of the buffer (not that the buffers are swapped when suffix linking). private int _previousLengthOrFrozenSuffixLengthDelta; private byte[] _buffer; // The length of data in the buffer in lower 31 bits. // Head: highest bit is 0, length may be 0. // Non-head: highest bit is 1, lower 31 bits are not all 0. private uint _length; private const uint IsFrozenMask = 0x80000000; private bool IsHead => (_length & IsFrozenMask) == 0; private int Length => (int)(_length & ~IsFrozenMask); private uint FrozenLength => _length | IsFrozenMask; public BlobBuilder(int capacity = DefaultChunkSize) { if (capacity < 0) { Throw.ArgumentOutOfRange(nameof(capacity)); } _nextOrPrevious = this; _buffer = new byte[Math.Max(MinChunkSize, capacity)]; } protected virtual BlobBuilder AllocateChunk(int minimalSize) { return new BlobBuilder(Math.Max(_buffer.Length, minimalSize)); } protected virtual void FreeChunk() { // nop } public void Clear() { if (!IsHead) { Throw.InvalidOperationBuilderAlreadyLinked(); } // Swap buffer with the first chunk. // Note that we need to keep holding on all allocated buffers, // so that builders with custom allocator can release them. var first = FirstChunk; if (first != this) { var firstBuffer = first._buffer; first._length = FrozenLength; first._buffer = _buffer; _buffer = firstBuffer; } // free all chunks except for the current one foreach (BlobBuilder chunk in GetChunks()) { if (chunk != this) { chunk.ClearChunk(); chunk.FreeChunk(); } } ClearChunk(); } protected void Free() { Clear(); FreeChunk(); } // internal for testing internal void ClearChunk() { _length = 0; _previousLengthOrFrozenSuffixLengthDelta = 0; _nextOrPrevious = this; } private void CheckInvariants() { #if DEBUG Debug.Assert(_buffer != null); Debug.Assert(Length >= 0 && Length <= _buffer.Length); Debug.Assert(_nextOrPrevious != null); if (IsHead) { Debug.Assert(_previousLengthOrFrozenSuffixLengthDelta >= 0); // last chunk: int totalLength = 0; foreach (var chunk in GetChunks()) { Debug.Assert(chunk.IsHead || chunk.Length > 0); totalLength += chunk.Length; } Debug.Assert(totalLength == Count); } #endif } public int Count => _previousLengthOrFrozenSuffixLengthDelta + Length; private int PreviousLength { get { Debug.Assert(IsHead); return _previousLengthOrFrozenSuffixLengthDelta; } set { Debug.Assert(IsHead); _previousLengthOrFrozenSuffixLengthDelta = value; } } protected int FreeBytes => _buffer.Length - Length; // internal for testing protected internal int ChunkCapacity => _buffer.Length; // internal for testing internal Chunks GetChunks() { if (!IsHead) { Throw.InvalidOperationBuilderAlreadyLinked(); } return new Chunks(this); } /// <summary> /// Returns a sequence of all blobs that represent the content of the builder. /// </summary> /// <exception cref="InvalidOperationException">Content is not available, the builder has been linked with another one.</exception> public Blobs GetBlobs() { if (!IsHead) { Throw.InvalidOperationBuilderAlreadyLinked(); } return new Blobs(this); } /// <summary> /// Compares the current content of this writer with another one. /// </summary> /// <exception cref="InvalidOperationException">Content is not available, the builder has been linked with another one.</exception> public bool ContentEquals(BlobBuilder other) { if (!IsHead) { Throw.InvalidOperationBuilderAlreadyLinked(); } if (ReferenceEquals(this, other)) { return true; } if (other == null) { return false; } if (!other.IsHead) { Throw.InvalidOperationBuilderAlreadyLinked(); } if (Count != other.Count) { return false; } var leftEnumerator = GetChunks(); var rightEnumerator = other.GetChunks(); int leftStart = 0; int rightStart = 0; bool leftContinues = leftEnumerator.MoveNext(); bool rightContinues = rightEnumerator.MoveNext(); while (leftContinues && rightContinues) { Debug.Assert(leftStart == 0 || rightStart == 0); var left = leftEnumerator.Current; var right = rightEnumerator.Current; int minLength = Math.Min(left.Length - leftStart, right.Length - rightStart); if (!ByteSequenceComparer.Equals(left._buffer, leftStart, right._buffer, rightStart, minLength)) { return false; } leftStart += minLength; rightStart += minLength; // nothing remains in left chunk to compare: if (leftStart == left.Length) { leftContinues = leftEnumerator.MoveNext(); leftStart = 0; } // nothing remains in left chunk to compare: if (rightStart == right.Length) { rightContinues = rightEnumerator.MoveNext(); rightStart = 0; } } return leftContinues == rightContinues; } /// <exception cref="InvalidOperationException">Content is not available, the builder has been linked with another one.</exception> public byte[] ToArray() { return ToArray(0, Count); } /// <exception cref="ArgumentOutOfRangeException">Range specified by <paramref name="start"/> and <paramref name="byteCount"/> falls outside of the bounds of the buffer content.</exception> /// <exception cref="InvalidOperationException">Content is not available, the builder has been linked with another one.</exception> public byte[] ToArray(int start, int byteCount) { BlobUtilities.ValidateRange(Count, start, byteCount, nameof(byteCount)); var result = new byte[byteCount]; int chunkStart = 0; int bufferStart = start; int bufferEnd = start + byteCount; foreach (var chunk in GetChunks()) { int chunkEnd = chunkStart + chunk.Length; Debug.Assert(bufferStart >= chunkStart); if (chunkEnd > bufferStart) { int bytesToCopy = Math.Min(bufferEnd, chunkEnd) - bufferStart; Debug.Assert(bytesToCopy >= 0); Array.Copy(chunk._buffer, bufferStart - chunkStart, result, bufferStart - start, bytesToCopy); bufferStart += bytesToCopy; if (bufferStart == bufferEnd) { break; } } chunkStart = chunkEnd; } Debug.Assert(bufferStart == bufferEnd); return result; } /// <exception cref="InvalidOperationException">Content is not available, the builder has been linked with another one.</exception> public ImmutableArray<byte> ToImmutableArray() { return ToImmutableArray(0, Count); } /// <exception cref="ArgumentOutOfRangeException">Range specified by <paramref name="start"/> and <paramref name="byteCount"/> falls outside of the bounds of the buffer content.</exception> /// <exception cref="InvalidOperationException">Content is not available, the builder has been linked with another one.</exception> public ImmutableArray<byte> ToImmutableArray(int start, int byteCount) { var array = ToArray(start, byteCount); return ImmutableByteArrayInterop.DangerousCreateFromUnderlyingArray(ref array); } /// <exception cref="ArgumentNullException"><paramref name="destination"/> is null.</exception> /// <exception cref="InvalidOperationException">Content is not available, the builder has been linked with another one.</exception> public void WriteContentTo(Stream destination) { if (destination == null) { Throw.ArgumentNull(nameof(destination)); } foreach (var chunk in GetChunks()) { destination.Write(chunk._buffer, 0, chunk.Length); } } /// <exception cref="ArgumentNullException"><paramref name="destination"/> is default(<see cref="BlobWriter"/>).</exception> /// <exception cref="InvalidOperationException">Content is not available, the builder has been linked with another one.</exception> public void WriteContentTo(ref BlobWriter destination) { if (destination.IsDefault) { Throw.ArgumentNull(nameof(destination)); } foreach (var chunk in GetChunks()) { destination.WriteBytes(chunk._buffer, 0, chunk.Length); } } /// <exception cref="ArgumentNullException"><paramref name="destination"/> is null.</exception> /// <exception cref="InvalidOperationException">Content is not available, the builder has been linked with another one.</exception> public void WriteContentTo(BlobBuilder destination) { if (destination == null) { Throw.ArgumentNull(nameof(destination)); } foreach (var chunk in GetChunks()) { destination.WriteBytes(chunk._buffer, 0, chunk.Length); } } /// <exception cref="ArgumentNullException"><paramref name="prefix"/> is null.</exception> /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void LinkPrefix(BlobBuilder prefix) { if (prefix == null) { Throw.ArgumentNull(nameof(prefix)); } // TODO: consider copying data from right to left while there is space if (!prefix.IsHead || !IsHead) { Throw.InvalidOperationBuilderAlreadyLinked(); } // avoid chaining empty chunks: if (prefix.Count == 0) { return; } PreviousLength += prefix.Count; // prefix is not a head anymore: prefix._length = prefix.FrozenLength; // First and last chunks: // // [PrefixFirst]->[]->[PrefixLast] <- [prefix] [First]->[]->[Last] <- [this] // ^_________________| ^___________| // // Degenerate cases: // this == First == Last and/or prefix == PrefixFirst == PrefixLast. var first = FirstChunk; var prefixFirst = prefix.FirstChunk; var last = _nextOrPrevious; var prefixLast = prefix._nextOrPrevious; // Relink like so: // [PrefixFirst]->[]->[PrefixLast] -> [prefix] -> [First]->[]->[Last] <- [this] // ^________________________________________________________| _nextOrPrevious = (last != this) ? last : prefix; prefix._nextOrPrevious = (first != this) ? first : (prefixFirst != prefix) ? prefixFirst : prefix; if (last != this) { last._nextOrPrevious = (prefixFirst != prefix) ? prefixFirst : prefix; } if (prefixLast != prefix) { prefixLast._nextOrPrevious = prefix; } prefix.CheckInvariants(); CheckInvariants(); } /// <exception cref="ArgumentNullException"><paramref name="suffix"/> is null.</exception> /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void LinkSuffix(BlobBuilder suffix) { if (suffix == null) { throw new ArgumentNullException(nameof(suffix)); } // TODO: consider copying data from right to left while there is space if (!IsHead || !suffix.IsHead) { Throw.InvalidOperationBuilderAlreadyLinked(); } // avoid chaining empty chunks: if (suffix.Count == 0) { return; } bool isEmpty = Count == 0; // swap buffers of the heads: var suffixBuffer = suffix._buffer; uint suffixLength = suffix._length; int suffixPreviousLength = suffix.PreviousLength; int oldSuffixLength = suffix.Length; suffix._buffer = _buffer; suffix._length = FrozenLength; // suffix is not a head anymore _buffer = suffixBuffer; _length = suffixLength; PreviousLength += suffix.Length + suffixPreviousLength; // Update the _previousLength of the suffix so that suffix.Count = suffix._previousLength + suffix.Length doesn't change. // Note that the resulting previous length might be negative. // The value is not used, other than for calculating the value of Count property. suffix._previousLengthOrFrozenSuffixLengthDelta = suffixPreviousLength + oldSuffixLength - suffix.Length; if (!isEmpty) { // First and last chunks: // // [First]->[]->[Last] <- [this] [SuffixFirst]->[]->[SuffixLast] <- [suffix] // ^___________| ^_________________| // // Degenerate cases: // this == First == Last and/or suffix == SuffixFirst == SuffixLast. var first = FirstChunk; var suffixFirst = suffix.FirstChunk; var last = _nextOrPrevious; var suffixLast = suffix._nextOrPrevious; // Relink like so: // [First]->[]->[Last] -> [suffix] -> [SuffixFirst]->[]->[SuffixLast] <- [this] // ^_______________________________________________________| _nextOrPrevious = suffixLast; suffix._nextOrPrevious = (suffixFirst != suffix) ? suffixFirst : (first != this) ? first : suffix; if (last != this) { last._nextOrPrevious = suffix; } if (suffixLast != suffix) { suffixLast._nextOrPrevious = (first != this) ? first : suffix; } } CheckInvariants(); suffix.CheckInvariants(); } private void AddLength(int value) { _length += (uint)value; } [MethodImpl(MethodImplOptions.NoInlining)] private void Expand(int newLength) { // TODO: consider converting the last chunk to a smaller one if there is too much empty space left // May happen only if the derived class attempts to write to a builder that is not last, // or if a builder prepended to another one is not discarded. if (!IsHead) { Throw.InvalidOperationBuilderAlreadyLinked(); } var newChunk = AllocateChunk(Math.Max(newLength, MinChunkSize)); if (newChunk.ChunkCapacity < newLength) { // The overridden allocator didn't provide large enough buffer: throw new InvalidOperationException(SR.Format(SR.ReturnedBuilderSizeTooSmall, GetType(), nameof(AllocateChunk))); } var newBuffer = newChunk._buffer; if (_length == 0) { // If the first write into an empty buffer needs more space than the buffer provides, swap the buffers. newChunk._buffer = _buffer; _buffer = newBuffer; } else { // Otherwise append the new buffer. var last = _nextOrPrevious; var first = FirstChunk; if (last == this) { // single chunk in the chain _nextOrPrevious = newChunk; } else { newChunk._nextOrPrevious = first; last._nextOrPrevious = newChunk; _nextOrPrevious = newChunk; } newChunk._buffer = _buffer; newChunk._length = FrozenLength; newChunk._previousLengthOrFrozenSuffixLengthDelta = PreviousLength; _buffer = newBuffer; PreviousLength += Length; _length = 0; } CheckInvariants(); } /// <summary> /// Reserves a contiguous block of bytes. /// </summary> /// <exception cref="ArgumentOutOfRangeException"><paramref name="byteCount"/> is negative.</exception> /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public Blob ReserveBytes(int byteCount) { if (byteCount < 0) { Throw.ArgumentOutOfRange(nameof(byteCount)); } int start = ReserveBytesImpl(byteCount); return new Blob(_buffer, start, byteCount); } private int ReserveBytesImpl(int byteCount) { Debug.Assert(byteCount >= 0); // If write is attempted to a frozen builder we fall back // to expand where an exception is thrown: uint result = _length; if (result > _buffer.Length - byteCount) { Expand(byteCount); result = 0; } _length = result + (uint)byteCount; return (int)result; } private int ReserveBytesPrimitive(int byteCount) { // If the primitive doesn't fit to the current chuck we'll allocate a new chunk that is at least MinChunkSize. // That chunk has to fit the primitive otherwise we might keep allocating new chunks and never end up with one that fits. Debug.Assert(byteCount <= MinChunkSize); return ReserveBytesImpl(byteCount); } /// <exception cref="ArgumentOutOfRangeException"><paramref name="byteCount"/> is negative.</exception> /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteBytes(byte value, int byteCount) { if (byteCount < 0) { Throw.ArgumentOutOfRange(nameof(byteCount)); } if (!IsHead) { Throw.InvalidOperationBuilderAlreadyLinked(); } int bytesToCurrent = Math.Min(FreeBytes, byteCount); _buffer.WriteBytes(Length, value, bytesToCurrent); AddLength(bytesToCurrent); int remaining = byteCount - bytesToCurrent; if (remaining > 0) { Expand(remaining); _buffer.WriteBytes(0, value, remaining); AddLength(remaining); } } /// <exception cref="ArgumentNullException"><paramref name="buffer"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="byteCount"/> is negative.</exception> /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public unsafe void WriteBytes(byte* buffer, int byteCount) { if (buffer == null) { Throw.ArgumentNull(nameof(buffer)); } if (byteCount < 0) { Throw.ArgumentOutOfRange(nameof(byteCount)); } if (!IsHead) { Throw.InvalidOperationBuilderAlreadyLinked(); } WriteBytesUnchecked(buffer, byteCount); } private unsafe void WriteBytesUnchecked(byte* buffer, int byteCount) { int bytesToCurrent = Math.Min(FreeBytes, byteCount); Marshal.Copy((IntPtr)buffer, _buffer, Length, bytesToCurrent); AddLength(bytesToCurrent); int remaining = byteCount - bytesToCurrent; if (remaining > 0) { Expand(remaining); Marshal.Copy((IntPtr)(buffer + bytesToCurrent), _buffer, 0, remaining); AddLength(remaining); } } /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="byteCount"/> is negative.</exception> /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> /// <returns>Bytes successfully written from the <paramref name="source" />.</returns> public int TryWriteBytes(Stream source, int byteCount) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (byteCount < 0) { throw new ArgumentOutOfRangeException(nameof(byteCount)); } if (byteCount == 0) { return 0; } int bytesRead = 0; int bytesToCurrent = Math.Min(FreeBytes, byteCount); if (bytesToCurrent > 0) { bytesRead = source.TryReadAll(_buffer, Length, bytesToCurrent); AddLength(bytesRead); if (bytesRead != bytesToCurrent) { return bytesRead; } } int remaining = byteCount - bytesToCurrent; if (remaining > 0) { Expand(remaining); bytesRead = source.TryReadAll(_buffer, 0, remaining); AddLength(bytesRead); bytesRead += bytesToCurrent; } return bytesRead; } /// <exception cref="ArgumentNullException"><paramref name="buffer"/> is null.</exception> /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteBytes(ImmutableArray<byte> buffer) { WriteBytes(buffer, 0, buffer.IsDefault ? 0 : buffer.Length); } /// <exception cref="ArgumentNullException"><paramref name="buffer"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException">Range specified by <paramref name="start"/> and <paramref name="byteCount"/> falls outside of the bounds of the <paramref name="buffer"/>.</exception> /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteBytes(ImmutableArray<byte> buffer, int start, int byteCount) { WriteBytes(ImmutableByteArrayInterop.DangerousGetUnderlyingArray(buffer), start, byteCount); } /// <exception cref="ArgumentNullException"><paramref name="buffer"/> is null.</exception> /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteBytes(byte[] buffer) { WriteBytes(buffer, 0, buffer?.Length ?? 0); } /// <exception cref="ArgumentNullException"><paramref name="buffer"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException">Range specified by <paramref name="start"/> and <paramref name="byteCount"/> falls outside of the bounds of the <paramref name="buffer"/>.</exception> /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public unsafe void WriteBytes(byte[] buffer, int start, int byteCount) { if (buffer == null) { Throw.ArgumentNull(nameof(buffer)); } BlobUtilities.ValidateRange(buffer.Length, start, byteCount, nameof(byteCount)); if (!IsHead) { Throw.InvalidOperationBuilderAlreadyLinked(); } // an empty array has no element pointer: if (buffer.Length == 0) { return; } fixed (byte* ptr = &buffer[0]) { WriteBytesUnchecked(ptr + start, byteCount); } } /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void PadTo(int position) { WriteBytes(0, position - Count); } /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void Align(int alignment) { int position = Count; WriteBytes(0, BitArithmetic.Align(position, alignment) - position); } /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteBoolean(bool value) { WriteByte((byte)(value ? 1 : 0)); } /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteByte(byte value) { int start = ReserveBytesPrimitive(sizeof(byte)); _buffer.WriteByte(start, value); } /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteSByte(sbyte value) { WriteByte(unchecked((byte)value)); } /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteDouble(double value) { int start = ReserveBytesPrimitive(sizeof(double)); _buffer.WriteDouble(start, value); } /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteSingle(float value) { int start = ReserveBytesPrimitive(sizeof(float)); _buffer.WriteSingle(start, value); } /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteInt16(short value) { WriteUInt16(unchecked((ushort)value)); } /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteUInt16(ushort value) { int start = ReserveBytesPrimitive(sizeof(ushort)); _buffer.WriteUInt16(start, value); } /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteInt16BE(short value) { WriteUInt16BE(unchecked((ushort)value)); } /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteUInt16BE(ushort value) { int start = ReserveBytesPrimitive(sizeof(ushort)); _buffer.WriteUInt16BE(start, value); } /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteInt32BE(int value) { WriteUInt32BE(unchecked((uint)value)); } /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteUInt32BE(uint value) { int start = ReserveBytesPrimitive(sizeof(uint)); _buffer.WriteUInt32BE(start, value); } /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteInt32(int value) { WriteUInt32(unchecked((uint)value)); } /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteUInt32(uint value) { int start = ReserveBytesPrimitive(sizeof(uint)); _buffer.WriteUInt32(start, value); } /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteInt64(long value) { WriteUInt64(unchecked((ulong)value)); } /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteUInt64(ulong value) { int start = ReserveBytesPrimitive(sizeof(ulong)); _buffer.WriteUInt64(start, value); } /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteDecimal(decimal value) { int start = ReserveBytesPrimitive(BlobUtilities.SizeOfSerializedDecimal); _buffer.WriteDecimal(start, value); } /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteGuid(Guid value) { int start = ReserveBytesPrimitive(BlobUtilities.SizeOfGuid); _buffer.WriteGuid(start, value); } /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteDateTime(DateTime value) { WriteInt64(value.Ticks); } /// <summary> /// Writes a reference to a heap (heap offset) or a table (row number). /// </summary> /// <param name="reference">Heap offset or table row number.</param> /// <param name="isSmall">True to encode the reference as 16-bit integer, false to encode as 32-bit integer.</param> /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteReference(int reference, bool isSmall) { // This code is a very hot path, hence we don't check if the reference actually fits 2B. if (isSmall) { Debug.Assert(unchecked((ushort)reference) == reference); WriteUInt16((ushort)reference); } else { WriteInt32(reference); } } /// <summary> /// Writes UTF16 (little-endian) encoded string at the current position. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="value"/> is null.</exception> /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public unsafe void WriteUTF16(char[] value) { if (value == null) { Throw.ArgumentNull(nameof(value)); } if (!IsHead) { Throw.InvalidOperationBuilderAlreadyLinked(); } if (value.Length == 0) { return; } if (BitConverter.IsLittleEndian) { fixed (char* ptr = &value[0]) { WriteBytesUnchecked((byte*)ptr, value.Length * sizeof(char)); } } else { byte[] bytes = Encoding.Unicode.GetBytes(value); fixed (byte* ptr = &bytes[0]) { WriteBytesUnchecked((byte*)ptr, bytes.Length); } } } /// <summary> /// Writes UTF16 (little-endian) encoded string at the current position. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="value"/> is null.</exception> /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public unsafe void WriteUTF16(string value) { if (value == null) { Throw.ArgumentNull(nameof(value)); } if (!IsHead) { Throw.InvalidOperationBuilderAlreadyLinked(); } if (BitConverter.IsLittleEndian) { fixed (char* ptr = value) { WriteBytesUnchecked((byte*)ptr, value.Length * sizeof(char)); } } else { byte[] bytes = Encoding.Unicode.GetBytes(value); fixed (byte* ptr = bytes) { WriteBytesUnchecked((byte*)ptr, bytes.Length); } } } /// <summary> /// Writes string in SerString format (see ECMA-335-II 23.3 Custom attributes). /// </summary> /// <remarks> /// The string is UTF8 encoded and prefixed by the its size in bytes. /// Null string is represented as a single byte 0xFF. /// </remarks> /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteSerializedString(string value) { if (value == null) { WriteByte(0xff); return; } WriteUTF8(value, 0, value.Length, allowUnpairedSurrogates: true, prependSize: true); } /// <summary> /// Writes string in User String (#US) heap format (see ECMA-335-II 24.2.4 #US and #Blob heaps): /// </summary> /// <remarks> /// The string is UTF16 encoded and prefixed by the its size in bytes. /// /// This final byte holds the value 1 if and only if any UTF16 character within the string has any bit set in its top byte, /// or its low byte is any of the following: 0x01-0x08, 0x0E-0x1F, 0x27, 0x2D, 0x7F. Otherwise, it holds 0. /// The 1 signifies Unicode characters that require handling beyond that normally provided for 8-bit encoding sets. /// </remarks> /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteUserString(string value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } WriteCompressedInteger(BlobUtilities.GetUserStringByteLength(value.Length)); WriteUTF16(value); WriteByte(BlobUtilities.GetUserStringTrailingByte(value)); } /// <summary> /// Writes UTF8 encoded string at the current position. /// </summary> /// <param name="value">Constant value.</param> /// <param name="allowUnpairedSurrogates"> /// True to encode unpaired surrogates as specified, otherwise replace them with U+FFFD character. /// </param> /// <exception cref="ArgumentNullException"><paramref name="value"/> is null.</exception> /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteUTF8(string value, bool allowUnpairedSurrogates = true) { if (value == null) { Throw.ArgumentNull(nameof(value)); } WriteUTF8(value, 0, value.Length, allowUnpairedSurrogates, prependSize: false); } internal unsafe void WriteUTF8(string str, int start, int length, bool allowUnpairedSurrogates, bool prependSize) { Debug.Assert(start >= 0); Debug.Assert(length >= 0); Debug.Assert(start + length <= str.Length); if (!IsHead) { Throw.InvalidOperationBuilderAlreadyLinked(); } fixed (char* strPtr = str) { char* currentPtr = strPtr + start; char* nextPtr; // the max size of compressed int is 4B: int byteLimit = FreeBytes - (prependSize ? sizeof(uint) : 0); int bytesToCurrent = BlobUtilities.GetUTF8ByteCount(currentPtr, length, byteLimit, out nextPtr); int charsToCurrent = (int)(nextPtr - currentPtr); int charsToNext = length - charsToCurrent; int bytesToNext = BlobUtilities.GetUTF8ByteCount(nextPtr, charsToNext); if (prependSize) { WriteCompressedInteger(bytesToCurrent + bytesToNext); } _buffer.WriteUTF8(Length, currentPtr, charsToCurrent, bytesToCurrent, allowUnpairedSurrogates); AddLength(bytesToCurrent); if (bytesToNext > 0) { Expand(bytesToNext); _buffer.WriteUTF8(0, nextPtr, charsToNext, bytesToNext, allowUnpairedSurrogates); AddLength(bytesToNext); } } } /// <summary> /// Implements compressed signed integer encoding as defined by ECMA-335-II chapter 23.2: Blobs and signatures. /// </summary> /// <remarks> /// If the value lies between -64 (0xFFFFFFC0) and 63 (0x3F), inclusive, encode as a one-byte integer: /// bit 7 clear, value bits 5 through 0 held in bits 6 through 1, sign bit (value bit 31) in bit 0. /// /// If the value lies between -8192 (0xFFFFE000) and 8191 (0x1FFF), inclusive, encode as a two-byte integer: /// 15 set, bit 14 clear, value bits 12 through 0 held in bits 13 through 1, sign bit(value bit 31) in bit 0. /// /// If the value lies between -268435456 (0xF000000) and 268435455 (0x0FFFFFFF), inclusive, encode as a four-byte integer: /// 31 set, 30 set, bit 29 clear, value bits 27 through 0 held in bits 28 through 1, sign bit(value bit 31) in bit 0. /// </remarks> /// <exception cref="ArgumentOutOfRangeException"><paramref name="value"/> can't be represented as a compressed signed integer.</exception> /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteCompressedSignedInteger(int value) { BlobWriterImpl.WriteCompressedSignedInteger(this, value); } /// <summary> /// Implements compressed unsigned integer encoding as defined by ECMA-335-II chapter 23.2: Blobs and signatures. /// </summary> /// <remarks> /// If the value lies between 0 (0x00) and 127 (0x7F), inclusive, /// encode as a one-byte integer (bit 7 is clear, value held in bits 6 through 0). /// /// If the value lies between 28 (0x80) and 214 - 1 (0x3FFF), inclusive, /// encode as a 2-byte integer with bit 15 set, bit 14 clear (value held in bits 13 through 0). /// /// Otherwise, encode as a 4-byte integer, with bit 31 set, bit 30 set, bit 29 clear (value held in bits 28 through 0). /// </remarks> /// <exception cref="ArgumentOutOfRangeException"><paramref name="value"/> can't be represented as a compressed unsigned integer.</exception> /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteCompressedInteger(int value) { BlobWriterImpl.WriteCompressedInteger(this, unchecked((uint)value)); } /// <summary> /// Writes a constant value (see ECMA-335 Partition II section 22.9) at the current position. /// </summary> /// <exception cref="ArgumentException"><paramref name="value"/> is not of a constant type.</exception> /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> public void WriteConstant(object value) { BlobWriterImpl.WriteConstant(this, value); } internal string GetDebuggerDisplay() { return IsHead ? string.Join("->", GetChunks().Select(chunk => $"[{Display(chunk._buffer, chunk.Length)}]")) : $"<{Display(_buffer, Length)}>"; } private static string Display(byte[] bytes, int length) { const int MaxDisplaySize = 64; return (length <= MaxDisplaySize) ? BitConverter.ToString(bytes, 0, length) : BitConverter.ToString(bytes, 0, MaxDisplaySize / 2) + "-...-" + BitConverter.ToString(bytes, length - MaxDisplaySize / 2, MaxDisplaySize / 2); } } }
using UnityEngine; using UnityEditor; using System; using System.Linq; using System.IO; using System.Collections.Generic; using System.Reflection; using Model=UnityEngine.AssetGraph.DataModel.Version2; namespace UnityEngine.AssetGraph { /// <summary> /// IAssetGenerator is an interface to generate new asset from incoming asset. /// Subclass of IAssetGenerator must have CustomAssetGenerator attribute. /// </summary> public interface IAssetGenerator { /// <summary> /// Called when validating this prefabBuilder. /// NodeException should be thrown if this modifier is not ready to be used for building. /// </summary> void OnValidate (); /// <summary> /// Gets the asset extension of generating asset. /// </summary> /// <returns>The extension in string format (e.g. ".png").</returns> /// <param name="asset">The source asset to generate from.</param> string GetAssetExtension (AssetReference asset); /// <summary> /// Gets the type of the asset. /// For type of assets that have associated importers, return type of Importer. /// Textures = TextureImporter, Audio = AudioImporter, Video = VideoClipImporter /// </summary> /// <returns>The asset type.</returns> /// <param name="asset">The source asset to generate from.</param> Type GetAssetType(AssetReference asset); /// <summary> /// Test if generator can generate new asset with given asset. /// NodeException should be thrown if there is any error that user should know about. /// </summary> /// <returns><c>true</c> if this instance can generate asset; otherwise, <c>false</c>.</returns> /// <param name="asset">Asset to examine if derivertive asset can be generated.</param> bool CanGenerateAsset (AssetReference asset); /// <summary> /// Generates the asset. /// </summary> /// <returns><c>true</c>, if asset was generated, <c>false</c> otherwise.</returns> /// <param name="asset">Asset to generate derivertive asset from.</param> /// <param name="generateAssetPath">Path to save generated derivertive asset.</param> bool GenerateAsset (AssetReference asset, string generateAssetPath); /// <summary> /// Draw Inspector GUI for this AssetGenerator. /// Make sure to call <c>onValueChanged</c>() when inspector values are modified. /// It will save state of AssetGenerator object. /// </summary> /// <param name="onValueChanged">Action to call when inspector value changed.</param> void OnInspectorGUI (Action onValueChanged); } /// <summary> /// Attribute for Custom Asset Generator. /// </summary> [AttributeUsage(AttributeTargets.Class)] public class CustomAssetGenerator : Attribute { private string m_name; private string m_version; private const int kDEFAULT_ASSET_THRES = 10; /// <summary> /// GUI name of the generator. /// </summary> /// <value>The GUI name of the generator.</value> public string Name { get { return m_name; } } /// <summary> /// Version string of the generator. /// Version string is useful to force update all generated assets /// when generator have catastrophic changes. /// </summary> /// <value>The version string.</value> public string Version { get { return m_version; } } public CustomAssetGenerator (string name) { m_name = name; m_version = string.Empty; } public CustomAssetGenerator (string name, string version) { m_name = name; m_version = version; } public CustomAssetGenerator (string name, string version, int itemThreashold) { m_name = name; m_version = version; } } public class AssetGeneratorUtility { private static Dictionary<string, string> s_attributeAssemblyQualifiedNameMap; public static Dictionary<string, string> GetAttributeAssemblyQualifiedNameMap () { if(s_attributeAssemblyQualifiedNameMap == null) { // attribute name or class name : class name s_attributeAssemblyQualifiedNameMap = new Dictionary<string, string>(); var allBuilders = new List<Type>(); foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { var builders = assembly.GetTypes() .Where(t => !t.IsInterface) .Where(t => typeof(IAssetGenerator).IsAssignableFrom(t)); allBuilders.AddRange (builders); } foreach (var type in allBuilders) { // set attribute-name as key of dict if atribute is exist. CustomAssetGenerator attr = type.GetCustomAttributes(typeof(CustomAssetGenerator), true).FirstOrDefault() as CustomAssetGenerator; var typename = type.AssemblyQualifiedName; if (attr != null) { if (!s_attributeAssemblyQualifiedNameMap.ContainsKey(attr.Name)) { s_attributeAssemblyQualifiedNameMap[attr.Name] = typename; } } else { s_attributeAssemblyQualifiedNameMap[typename] = typename; } } } return s_attributeAssemblyQualifiedNameMap; } public static string GetGUIName(IAssetGenerator generator) { CustomAssetGenerator attr = generator.GetType().GetCustomAttributes(typeof(CustomAssetGenerator), false).FirstOrDefault() as CustomAssetGenerator; return attr.Name; } public static bool HasValidAttribute(Type t) { CustomAssetGenerator attr = t.GetCustomAttributes(typeof(CustomAssetGenerator), false).FirstOrDefault() as CustomAssetGenerator; return attr != null && !string.IsNullOrEmpty(attr.Name); } public static string GetGUIName(string className) { if(className != null) { var type = Type.GetType(className); if(type != null) { CustomAssetGenerator attr = type.GetCustomAttributes(typeof(CustomAssetGenerator), false).FirstOrDefault() as CustomAssetGenerator; if(attr != null) { return attr.Name; } } } return string.Empty; } public static string GetVersion(string className) { var type = Type.GetType(className); if(type != null) { CustomAssetGenerator attr = type.GetCustomAttributes(typeof(CustomAssetGenerator), false).FirstOrDefault() as CustomAssetGenerator; if(attr != null) { return attr.Version; } } return string.Empty; } public static string GUINameToAssemblyQualifiedName(string guiName) { var map = GetAttributeAssemblyQualifiedNameMap(); if(map.ContainsKey(guiName)) { return map[guiName]; } return null; } public static IAssetGenerator CreateGenerator(string guiName) { var className = GUINameToAssemblyQualifiedName(guiName); if(className != null) { var type = Type.GetType(className); if (type == null) { return null; } return (IAssetGenerator) type.Assembly.CreateInstance(type.FullName); } return null; } public static IAssetGenerator CreateByAssemblyQualifiedName(string assemblyQualifiedName) { if(assemblyQualifiedName == null) { return null; } Type t = Type.GetType(assemblyQualifiedName); if(t == null) { return null; } if(!HasValidAttribute(t)) { return null; } return (IAssetGenerator) t.Assembly.CreateInstance(t.FullName); } } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Revit.SDK.Samples.ViewPrinter.CS { public partial class viewSheetSetForm : System.Windows.Forms.Form { public viewSheetSetForm(ViewSheets viewSheets) { InitializeComponent(); m_viewSheets = viewSheets; } private ViewSheets m_viewSheets; private bool m_stopUpdateFlag; private void ViewSheetSetForm_Load(object sender, EventArgs e) { viewSheetSetNameComboBox.DataSource = m_viewSheets.ViewSheetSetNames; this.viewSheetSetNameComboBox.SelectedValueChanged += new System.EventHandler(this.viewSheetSetNameComboBox_SelectedValueChanged); viewSheetSetNameComboBox.SelectedItem = m_viewSheets.SettingName; showSheetsCheckBox.Checked = true; showViewsCheckBox.Checked = true; ListViewSheetSet(); this.viewSheetSetListView.ItemChecked += new System.Windows.Forms.ItemCheckedEventHandler(this.viewSheetSetListView_ItemChecked); } private void ListViewSheetSet() { VisibleType vt; if (showSheetsCheckBox.Checked && showViewsCheckBox.Checked) { vt = VisibleType.VT_BothViewAndSheet; } else if (showSheetsCheckBox.Checked && !showViewsCheckBox.Checked) { vt = VisibleType.VT_SheetOnly; } else if (!showSheetsCheckBox.Checked && showViewsCheckBox.Checked) { vt = VisibleType.VT_ViewOnly; } else { vt = VisibleType.VT_None; } List<Autodesk.Revit.DB.View> views = m_viewSheets.AvailableViewSheetSet(vt); viewSheetSetListView.Items.Clear(); foreach (Autodesk.Revit.DB.View view in views) { ListViewItem item = new ListViewItem(view.ViewType.ToString() + ": " + view.ViewName); item.Checked = m_viewSheets.IsSelected(item.Text); viewSheetSetListView.Items.Add(item); } } private void viewSheetSetNameComboBox_SelectedValueChanged(object sender, EventArgs e) { if (m_stopUpdateFlag) return; m_viewSheets.SettingName = viewSheetSetNameComboBox.SelectedItem as string; ListViewSheetSet(); saveButton.Enabled = revertButton.Enabled = false; reNameButton.Enabled = deleteButton.Enabled = m_viewSheets.SettingName.Equals("<In-Session>") ? false : true; } private void showSheetsCheckBox_CheckedChanged(object sender, EventArgs e) { ListViewSheetSet(); } private void showViewsCheckBox_CheckedChanged(object sender, EventArgs e) { ListViewSheetSet(); } private void saveButton_Click(object sender, EventArgs e) { List<string> names = new List<string>(); foreach (ListViewItem item in viewSheetSetListView.Items) { if (item.Checked) { names.Add(item.Text); } } m_viewSheets.ChangeCurrentViewSheetSet(names); m_viewSheets.Save(); } private void saveAsButton_Click(object sender, EventArgs e) { using (SaveAsForm dlg = new SaveAsForm(m_viewSheets)) { dlg.ShowDialog(); } m_stopUpdateFlag = true; viewSheetSetNameComboBox.DataSource = m_viewSheets.ViewSheetSetNames; viewSheetSetNameComboBox.Update(); m_stopUpdateFlag = false; viewSheetSetNameComboBox.SelectedItem = m_viewSheets.SettingName; } private void revertButton_Click(object sender, EventArgs e) { m_viewSheets.Revert(); ViewSheetSetForm_Load(null, null); } private void reNameButton_Click(object sender, EventArgs e) { using (ReNameForm dlg = new ReNameForm(m_viewSheets)) { dlg.ShowDialog(); } m_stopUpdateFlag = true; viewSheetSetNameComboBox.DataSource = m_viewSheets.ViewSheetSetNames; viewSheetSetNameComboBox.Update(); m_stopUpdateFlag = false; viewSheetSetNameComboBox.SelectedItem = m_viewSheets.SettingName; } private void deleteButton_Click(object sender, EventArgs e) { m_viewSheets.Delete(); m_stopUpdateFlag = true; viewSheetSetNameComboBox.DataSource = m_viewSheets.ViewSheetSetNames; viewSheetSetNameComboBox.Update(); m_stopUpdateFlag = false; viewSheetSetNameComboBox.SelectedItem = m_viewSheets.SettingName; } private void checkAllButton_Click(object sender, EventArgs e) { foreach (ListViewItem item in viewSheetSetListView.Items) { item.Checked = true; } } private void checkNoneButton_Click(object sender, EventArgs e) { foreach (ListViewItem item in viewSheetSetListView.Items) { item.Checked = false; } } private void viewSheetSetListView_ItemChecked(object sender, ItemCheckedEventArgs e) { if (!m_viewSheets.SettingName.Equals("<In-Session>") && !saveButton.Enabled) { saveButton.Enabled = revertButton.Enabled = reNameButton.Enabled = true; } } } }
namespace Epi.Windows.MakeView.Dialogs { partial class ImportCheckCodeDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ImportCheckCodeDialog)); this.btnCancel = new System.Windows.Forms.Button(); this.Button3 = new System.Windows.Forms.Button(); this.CheckBox3 = new System.Windows.Forms.CheckBox(); this.CheckBox2 = new System.Windows.Forms.CheckBox(); this.CheckBox1 = new System.Windows.Forms.CheckBox(); this.Button2 = new System.Windows.Forms.Button(); this.TextBox2 = new System.Windows.Forms.TextBox(); this.Label2 = new System.Windows.Forms.Label(); this.Button1 = new System.Windows.Forms.Button(); this.TextBox1 = new System.Windows.Forms.TextBox(); this.Label1 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // baseImageList // this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream"))); this.baseImageList.Images.SetKeyName(0, ""); this.baseImageList.Images.SetKeyName(1, ""); this.baseImageList.Images.SetKeyName(2, ""); this.baseImageList.Images.SetKeyName(3, ""); this.baseImageList.Images.SetKeyName(4, ""); this.baseImageList.Images.SetKeyName(5, ""); this.baseImageList.Images.SetKeyName(6, ""); this.baseImageList.Images.SetKeyName(7, ""); this.baseImageList.Images.SetKeyName(8, ""); this.baseImageList.Images.SetKeyName(9, ""); this.baseImageList.Images.SetKeyName(10, ""); this.baseImageList.Images.SetKeyName(11, ""); this.baseImageList.Images.SetKeyName(12, ""); this.baseImageList.Images.SetKeyName(13, ""); this.baseImageList.Images.SetKeyName(14, ""); this.baseImageList.Images.SetKeyName(15, ""); this.baseImageList.Images.SetKeyName(16, ""); this.baseImageList.Images.SetKeyName(17, ""); this.baseImageList.Images.SetKeyName(18, ""); this.baseImageList.Images.SetKeyName(19, ""); this.baseImageList.Images.SetKeyName(20, ""); this.baseImageList.Images.SetKeyName(21, ""); this.baseImageList.Images.SetKeyName(22, ""); this.baseImageList.Images.SetKeyName(23, ""); this.baseImageList.Images.SetKeyName(24, ""); this.baseImageList.Images.SetKeyName(25, ""); this.baseImageList.Images.SetKeyName(26, ""); this.baseImageList.Images.SetKeyName(27, ""); this.baseImageList.Images.SetKeyName(28, ""); this.baseImageList.Images.SetKeyName(29, ""); this.baseImageList.Images.SetKeyName(30, ""); this.baseImageList.Images.SetKeyName(31, ""); this.baseImageList.Images.SetKeyName(32, ""); this.baseImageList.Images.SetKeyName(33, ""); this.baseImageList.Images.SetKeyName(34, ""); this.baseImageList.Images.SetKeyName(35, ""); this.baseImageList.Images.SetKeyName(36, ""); this.baseImageList.Images.SetKeyName(37, ""); this.baseImageList.Images.SetKeyName(38, ""); this.baseImageList.Images.SetKeyName(39, ""); this.baseImageList.Images.SetKeyName(40, ""); this.baseImageList.Images.SetKeyName(41, ""); this.baseImageList.Images.SetKeyName(42, ""); this.baseImageList.Images.SetKeyName(43, ""); this.baseImageList.Images.SetKeyName(44, ""); this.baseImageList.Images.SetKeyName(45, ""); this.baseImageList.Images.SetKeyName(46, ""); this.baseImageList.Images.SetKeyName(47, ""); this.baseImageList.Images.SetKeyName(48, ""); this.baseImageList.Images.SetKeyName(49, ""); this.baseImageList.Images.SetKeyName(50, ""); this.baseImageList.Images.SetKeyName(51, ""); this.baseImageList.Images.SetKeyName(52, ""); this.baseImageList.Images.SetKeyName(53, ""); this.baseImageList.Images.SetKeyName(54, ""); this.baseImageList.Images.SetKeyName(55, ""); this.baseImageList.Images.SetKeyName(56, ""); this.baseImageList.Images.SetKeyName(57, ""); this.baseImageList.Images.SetKeyName(58, ""); this.baseImageList.Images.SetKeyName(59, ""); this.baseImageList.Images.SetKeyName(60, ""); this.baseImageList.Images.SetKeyName(61, ""); this.baseImageList.Images.SetKeyName(62, ""); this.baseImageList.Images.SetKeyName(63, ""); this.baseImageList.Images.SetKeyName(64, ""); this.baseImageList.Images.SetKeyName(65, ""); this.baseImageList.Images.SetKeyName(66, ""); this.baseImageList.Images.SetKeyName(67, ""); this.baseImageList.Images.SetKeyName(68, ""); this.baseImageList.Images.SetKeyName(69, ""); // // btnCancel // resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.Name = "btnCancel"; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // Button3 // resources.ApplyResources(this.Button3, "Button3"); this.Button3.Name = "Button3"; // // CheckBox3 // resources.ApplyResources(this.CheckBox3, "CheckBox3"); this.CheckBox3.Name = "CheckBox3"; // // CheckBox2 // resources.ApplyResources(this.CheckBox2, "CheckBox2"); this.CheckBox2.Name = "CheckBox2"; // // CheckBox1 // resources.ApplyResources(this.CheckBox1, "CheckBox1"); this.CheckBox1.Name = "CheckBox1"; // // Button2 // resources.ApplyResources(this.Button2, "Button2"); this.Button2.Name = "Button2"; // // TextBox2 // resources.ApplyResources(this.TextBox2, "TextBox2"); this.TextBox2.Name = "TextBox2"; // // Label2 // this.Label2.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.Label2, "Label2"); this.Label2.Name = "Label2"; // // Button1 // resources.ApplyResources(this.Button1, "Button1"); this.Button1.Name = "Button1"; // // TextBox1 // resources.ApplyResources(this.TextBox1, "TextBox1"); this.TextBox1.Name = "TextBox1"; // // Label1 // this.Label1.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.Label1, "Label1"); this.Label1.Name = "Label1"; // // ImportCheckCodeDialog // resources.ApplyResources(this, "$this"); this.Controls.Add(this.btnCancel); this.Controls.Add(this.Button3); this.Controls.Add(this.CheckBox3); this.Controls.Add(this.CheckBox2); this.Controls.Add(this.CheckBox1); this.Controls.Add(this.Button2); this.Controls.Add(this.TextBox2); this.Controls.Add(this.Label2); this.Controls.Add(this.Button1); this.Controls.Add(this.TextBox1); this.Controls.Add(this.Label1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ImportCheckCodeDialog"; this.ShowInTaskbar = false; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button Button3; private System.Windows.Forms.CheckBox CheckBox3; private System.Windows.Forms.CheckBox CheckBox2; private System.Windows.Forms.CheckBox CheckBox1; private System.Windows.Forms.Button Button2; private System.Windows.Forms.TextBox TextBox2; private System.Windows.Forms.Label Label2; private System.Windows.Forms.Button Button1; private System.Windows.Forms.TextBox TextBox1; private System.Windows.Forms.Label Label1; private System.Windows.Forms.Button btnCancel; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Text.Utf16; using Xunit; using Xunit.Abstractions; namespace System.Text.Utf8.Tests { public class Utf8StringTests { #region Helpers - useful only when debugging or generating test cases ITestOutputHelper output; public Utf8StringTests(ITestOutputHelper output) { this.output = output; } private static string GetStringLiteral(string s) { if (s == null) { return "null"; } Utf16LittleEndianCodePointEnumerable codePoints = new Utf16LittleEndianCodePointEnumerable(s); StringBuilder sb = new StringBuilder(); sb.Append('"'); foreach (uint codePoint in codePoints) { if (codePoint >= 32 && codePoint < 127) { sb.Append(char.ConvertFromUtf32(unchecked((int)codePoint))); } else if (codePoint == (uint)'\n') { sb.Append("\\n"); } else if (codePoint == (uint)'\r') { sb.Append("\\r"); } else if (codePoint == (uint)'\t') { sb.Append("\\t"); } else { sb.Append(string.Format("\\u{0:X04}", codePoint)); } } sb.Append('"'); return sb.ToString(); } #endregion public static object[][] LengthTestCases = { new object[] { 0, ""}, new object[] { 4, "1258"}, new object[] { 3, "\uABCD"}, new object[] { 4, "a\uABEE"}, new object[] { 5, "a\uABEEa"}, new object[] { 8, "a\uABEE\uABCDa"} }; [Theory, MemberData("LengthTestCases")] public void Length(int expectedLength, string str) { Utf8String s = new Utf8String(str); Assert.Equal(expectedLength, s.Length); } public static object[][] LengthInCodePointsTestCases = { new object[] { 0, ""}, new object[] { 4, "1258"}, new object[] { 1, "\uABCD"}, new object[] { 2, "a\uABEE"}, new object[] { 3, "a\uABEEa"}, new object[] { 4, "a\uABEE\uABCDa"} }; //[Theory(Skip = "System.InvalidProgramException : Common Language Runtime detected an invalid program."), MemberData("LengthInCodePointsTestCases")] public void LengthInCodePoints(int expectedLength, string str) { Utf8String s = new Utf8String(str); Assert.Equal(expectedLength, s.CodePoints.Count()); } public static object[][] ToStringTestCases = { new object[] { "", ""}, new object[] { "1258", "1258"}, new object[] { "\uABCD", "\uABCD"}, new object[] { "a\uABEE", "a\uABEE"}, new object[] { "a\uABEEa", "a\uABEEa"}, new object[] { "a\uABEE\uABCDa", "a\uABEE\uABCDa"} }; [Theory, MemberData("ToStringTestCases")] public void ToString(string expected, string str) { Utf8String s = new Utf8String(str); Assert.Equal(expected, s.ToString()); } public static object[][] StringEqualsTestCases_EmptyStrings = new object[][] { new object[] { true, "", ""}, new object[] { false, "", " "}, new object[] { false, "", "a"}, new object[] { false, "", "\uABCD"}, new object[] { false, "", "abc"}, new object[] { false, "", "a\uABCD"}, new object[] { false, "", "\uABCDa"} }; public static object[][] StringEqualsTestCases_SimpleStrings = new object[][] { new object[] { true, "a", "a"}, new object[] { true, "\uABCD", "\uABCD"}, new object[] { true, "abc", "abc"}, new object[] { true, "a\uABCDbc", "a\uABCDbc"}, new object[] { false, "a", "b"}, new object[] { false, "aaaaa", "aaaab"}, new object[] { false, "aaaaa", "baaaa"}, new object[] { false, "ababab", "bababa"}, new object[] { false, "abbbba", "abbba"}, new object[] { false, "aabcaa", "aacbaa"}, new object[] { false, "\uABCD", "\uABCE"}, new object[] { false, "abc", "abcd"}, new object[] { false, "abc", "dabc"}, new object[] { false, "ab\uABCDc", "ab\uABCEc"} }; // TODO: add cases for different lengths [Theory] [MemberData("StringEqualsTestCases_EmptyStrings")] [MemberData("StringEqualsTestCases_SimpleStrings")] public unsafe void StringEqualsWithThreeArgs(bool expected, string str1, string str2) { // TODO: investigate why the tests fail if we have two methods with the same name StringEquals Utf8String s1 = new Utf8String(str1); Utf8String s2 = new Utf8String(str2); Assert.Equal(expected, s1.Equals(s2)); Assert.Equal(expected, s2.Equals(s1)); } [Theory] [MemberData("StringEqualsTestCases_EmptyStrings")] [MemberData("StringEqualsTestCases_SimpleStrings")] public unsafe void StringEqualsConvertedToUtf16String(bool expected, string str1, string str2) { Utf8String s1 = new Utf8String(str1); Utf8String s2 = new Utf8String(str2); Assert.Equal(expected, s1.Equals(s2.ToString())); Assert.Equal(expected, s2.Equals(s1.ToString())); } public static object[][] StartsWithCodeUnitTestCases = new object[][] { new object[] { false, "", (byte)'a' }, new object[] { false, "a", (byte)'a' }, new object[] { false, "abc", (byte)'a' }, new object[] { false, "b", (byte)'a' }, new object[] { false, "ba", (byte)'a' } }; [Theory] [InlineData("", 'a')] [InlineData("abc", 'a')] [InlineData("v", 'v')] [InlineData("1", 'a')] [InlineData("1a", 'a')] public void StartsWithCodeUnit(string s, char c) { Utf8String u8s = new Utf8String(s); byte codeUnit = (byte)c; Assert.Equal(s.StartsWith(c.ToString()), u8s.StartsWith(codeUnit)); } [Theory] [InlineData("", 'a')] [InlineData("cba", 'a')] [InlineData("v", 'v')] [InlineData("1", 'a')] [InlineData("a1", 'a')] public void EndsWithCodeUnit(string s, char c) { Utf8String u8s = new Utf8String(s); byte codeUnit = (byte)c; Assert.Equal(s.EndsWith(c.ToString()), u8s.EndsWith(codeUnit)); } [Theory] [InlineData("", "a")] [InlineData("abc", "a")] [InlineData("v", "v")] [InlineData("1", "a")] [InlineData("1a", "a")] [InlineData("abc", "abc")] [InlineData("abcd", "abc")] [InlineData("abc", "abcd")] public void StartsWithUtf8String(string s, string pattern) { Utf8String u8s = new Utf8String(s); Utf8String u8pattern = new Utf8String(pattern); Assert.Equal(s.StartsWith(pattern), u8s.StartsWith(u8pattern)); } [Theory] [InlineData("", "a")] [InlineData("cba", "a")] [InlineData("v", "v")] [InlineData("1", "a")] [InlineData("a1", "a")] [InlineData("abc", "abc")] [InlineData("abcd", "bcd")] [InlineData("abc", "abcd")] public void EndsWithUtf8String(string s, string pattern) { Utf8String u8s = new Utf8String(s); Utf8String u8pattern = new Utf8String(pattern); Assert.Equal(s.EndsWith(pattern), u8s.EndsWith(u8pattern)); } [Theory] [InlineData("", 'a')] [InlineData("abc", 'a')] [InlineData("abc", 'b')] [InlineData("abc", 'c')] [InlineData("abc", 'd')] public void SubstringFromCodeUnit(string s, char c) { Utf8String u8s = new Utf8String(s); byte codeUnit = (byte)(c); Utf8String u8result; int idx = s.IndexOf(c); bool expectedToFind = idx != -1; Assert.Equal(expectedToFind, u8s.TrySubstringFrom(codeUnit, out u8result)); if (expectedToFind) { string expected = s.Substring(idx); TestHelper.Validate(new Utf8String(expected), u8result); Assert.Equal(expected, u8result.ToString()); } } [Theory] [InlineData("", 'a')] [InlineData("abc", 'a')] [InlineData("abc", 'b')] [InlineData("abc", 'c')] [InlineData("abc", 'd')] public void SubstringToCodeUnit(string s, char c) { Utf8String u8s = new Utf8String(s); byte codeUnit = (byte)(c); Utf8String u8result; int idx = s.IndexOf(c); bool expectedToFind = idx != -1; Assert.Equal(expectedToFind, u8s.TrySubstringTo(codeUnit, out u8result)); if (expectedToFind) { string expected = s.Substring(0, idx); TestHelper.Validate(new Utf8String(expected), u8result); Assert.Equal(expected, u8result.ToString()); } } [Theory] [InlineData("")] [InlineData("a")] [InlineData("ab")] [InlineData("abcdefghijklmnopqrstuvwxyz")] [InlineData("ABCDEFGHIJKLMNOPQRSTUVWXYZ")] [InlineData("0123456789")] [InlineData(" ,.\r\n[]<>()")] [InlineData("1258")] [InlineData("1258Hello")] [InlineData("\uABCD")] [InlineData("\uABEE")] [InlineData("a\uABEE")] [InlineData("a\uABEEa")] [InlineData("a\uABEE\uABCDa")] public void CodePointEnumeratorsTests(string s) { Utf8String u8s = new Utf8String(s); TestCodePointForwardEnumerator(s, u8s); TestCodePointReverseEnumerator(s, u8s); byte[] bytes = u8s.CopyBytes(); unsafe { fixed (byte* pinnedBytes = bytes) { Utf8String u8sFromBytePointer = new Utf8String(new Span<byte>(pinnedBytes, u8s.Length)); TestCodePointForwardEnumerator(s, u8sFromBytePointer); TestCodePointReverseEnumerator(s, u8sFromBytePointer); } } } // Implementations are intentionally split to avoid boxing private void TestCodePointForwardEnumerator(string s, Utf8String u8s) { List<uint> codePoints = new List<uint>(); Utf8String.CodePointEnumerator it = u8s.CodePoints.GetEnumerator(); while (it.MoveNext()) { codePoints.Add(it.Current); } Utf16LittleEndianCodePointEnumerable utf16CodePoints = new Utf16LittleEndianCodePointEnumerable(s); Assert.Equal(utf16CodePoints, codePoints); Utf8String u8s2 = new Utf8String(GetUtf8BytesFromCodePoints(codePoints)); TestHelper.Validate(u8s, u8s2); Assert.Equal(s, u8s2.ToString()); } private void TestCodePointReverseEnumerator(string s, Utf8String u8s) { List<uint> codePoints = new List<uint>(); Utf8String.CodePointReverseEnumerator it = u8s.CodePoints.GetReverseEnumerator(); while (it.MoveNext()) { codePoints.Add(it.Current); } codePoints.Reverse(); Utf16LittleEndianCodePointEnumerable utf16CodePoints = new Utf16LittleEndianCodePointEnumerable(s); Assert.Equal(utf16CodePoints, codePoints); Utf8String u8s2 = new Utf8String(GetUtf8BytesFromCodePoints(codePoints)); TestHelper.Validate(u8s, u8s2); Assert.Equal(s, u8s2.ToString()); } private byte[] GetUtf8BytesFromCodePoints(List<uint> codePoints) { ReadOnlySpan<byte> utf32 = codePoints.ToArray().AsSpan().AsBytes(); Assert.Equal(Buffers.TransformationStatus.Done, Encoders.Utf8.ComputeEncodedBytesFromUtf32(utf32, out int needed)); byte[] utf8 = new byte[needed]; Assert.Equal(Buffers.TransformationStatus.Done, Encoders.Utf8.ConvertFromUtf32(utf32, utf8, out int consumed, out int written)); Assert.Equal(needed, written); return utf8; } [Theory] [InlineData(" ")] [InlineData("")] [InlineData("a")] [InlineData("a ")] [InlineData("ab")] [InlineData("abcdefghijklmnopqrstuvwxyz ")] [InlineData("ABCDEFGHIJKLMNOPQRSTUVWXYZ")] [InlineData("0123456789")] [InlineData(",.\r\n[]<>()")] [InlineData("1258")] [InlineData("1258Hello")] [InlineData("\uABCD")] [InlineData("\uABEE ")] [InlineData("a\uABEE ")] [InlineData("a\uABEEa")] [InlineData("a\uABEE\uABCDa")] [InlineData(" ")] [InlineData(" a")] [InlineData(" ab")] [InlineData(" abcdefghijklmnopqrstuvwxyz")] [InlineData(" ABCDEFGHIJKL MNOPQRSTUVWXYZ ")] [InlineData(" 0123456789 ")] [InlineData(" ,.\r\n[]<>()")] [InlineData(" 1258")] [InlineData(" 1258He llo")] [InlineData(" \uABCD")] [InlineData(" \uABEE")] [InlineData(" a\uABEE")] [InlineData(" a\uABEEa")] [InlineData(" a\uABEE\uABCDa")] [InlineData(" ")] [InlineData(" a ")] [InlineData(" a ")] [InlineData(" a a a ")] [InlineData(" a a a ")] public void TrimTests(string s) { TrimStartTest(s); TrimEndTest(s); TrimTest(s); char[] utf16codeUnits = s.ToCharArray(); Array.Reverse(utf16codeUnits); s = new string(utf16codeUnits); TrimStartTest(s); TrimEndTest(s); TrimTest(s); } public void TrimStartTest(string s) { Utf8String u8s = new Utf8String(s); string expected = s.TrimStart(); Utf8String u8expected = new Utf8String(expected); Utf8String u8trimmed = u8s.TrimStart(); TestHelper.Validate(u8expected, u8trimmed); string trimmed = u8trimmed.ToString(); Assert.Equal(expected, trimmed); } public void TrimEndTest(string s) { Utf8String u8s = new Utf8String(s); string expected = s.TrimEnd(); Utf8String u8expected = new Utf8String(expected); Utf8String u8trimmed = u8s.TrimEnd(); TestHelper.Validate(u8expected, u8trimmed); string trimmed = u8trimmed.ToString(); Assert.Equal(expected, trimmed); } public void TrimTest(string s) { Utf8String u8s = new Utf8String(s); string expected = s.Trim(); Utf8String u8expected = new Utf8String(expected); Utf8String u8trimmed = u8s.Trim(); TestHelper.Validate(u8expected, u8trimmed); string trimmed = u8trimmed.ToString(); Assert.Equal(expected, trimmed); } [Theory] [InlineData("")] [InlineData("test124")] public unsafe void StringEquals(string text) { byte[] textArray = Text.Encoding.UTF8.GetBytes(text); byte[] buffer = new byte[textArray.Length]; fixed (byte* p = textArray) fixed (byte* pBuffer = buffer) { Span<byte> byteSpan = new Span<byte>(pBuffer, buffer.Length); Utf8String strFromArray = new Utf8String(textArray); Utf8String strFromPointer = new Utf8String(new Span<byte>(p, textArray.Length)); TestHelper.Validate(strFromArray, strFromPointer); Array.Clear(buffer, 0, buffer.Length); strFromArray.CopyTo(byteSpan); Assert.Equal(textArray, buffer); Array.Clear(buffer, 0, buffer.Length); strFromPointer.CopyTo(byteSpan); Assert.Equal(textArray, buffer); Array.Clear(buffer, 0, buffer.Length); strFromArray.CopyTo(buffer); Assert.Equal(textArray, buffer); Array.Clear(buffer, 0, buffer.Length); strFromPointer.CopyTo(buffer); Assert.Equal(textArray, buffer); } } [Fact] public void HashesSameForTheSameSubstrings() { const int len = 50; // two copies of the same string byte[] bytes = new byte[len * 2]; for (int i = 0; i < len; i++) { // 0x20 is a spacebar, writing explicitly so // the value is more predictable bytes[i] = unchecked((byte)(0x20 + i)); bytes[i + len] = bytes[i]; } Utf8String sFromBytes = new Utf8String(bytes); Utf8String s1FromBytes = sFromBytes.Substring(0, len); Utf8String s2FromBytes = sFromBytes.Substring(len, len); unsafe { fixed (byte* pinnedBytes = bytes) { Utf8String sFromSpan = new Utf8String(new Span<byte>(pinnedBytes, len * 2)); Utf8String s1FromSpan = sFromSpan.Substring(0, len); Utf8String s2FromSpan = sFromSpan.Substring(len, len); TestHashesSameForEquivalentString(s1FromBytes, s2FromBytes); TestHashesSameForEquivalentString(s1FromSpan, s2FromSpan); TestHashesSameForEquivalentString(s1FromSpan, s2FromBytes); } } } private void TestHashesSameForEquivalentString(Utf8String a, Utf8String b) { // for sanity Assert.Equal(a.Length, b.Length); TestHelper.Validate(a, b); for (int i = 0; i < a.Length; i++) { Utf8String prefixOfA = a.Substring(i, a.Length - i); Utf8String prefixOfB = b.Substring(i, b.Length - i); // sanity TestHelper.Validate(prefixOfA, prefixOfB); Assert.Equal(prefixOfA.GetHashCode(), prefixOfB.GetHashCode()); // for all suffixes Utf8String suffixOfA = a.Substring(a.Length - i, i); Utf8String suffixOfB = b.Substring(b.Length - i, i); TestHelper.Validate(suffixOfA, suffixOfB); } } [Theory] [InlineData(0, "", "")] [InlineData(0, "abc", "")] [InlineData(-1, "", "a")] [InlineData(-1, "", "abc")] [InlineData(0, "a", "a")] [InlineData(-1, "a", "b")] [InlineData(0, "abc", "a")] [InlineData(0, "abc", "ab")] [InlineData(0, "abc", "abc")] [InlineData(1, "abc", "b")] [InlineData(1, "abc", "bc")] [InlineData(2, "abc", "c")] [InlineData(34, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", "aaaaaaaab")] [InlineData(0, "abbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "abbbbbbbb")] [InlineData(-1, "aaabaaa", "aabaaaa")] [InlineData(-1, "aaabaaa", "aadaaaa")] [InlineData(1, "abababab", "bababa")] [InlineData(-1, "abababab", "bbababa")] [InlineData(-1, "abababab", "bababaa")] [InlineData(7, "aaabaacaaac", "aaac")] [InlineData(7, "baabaaabaaaa", "baaaa")] public void IndexOfTests(int expected, string s, string substring) { Utf8String utf8s = new Utf8String(s); Utf8String utf8substring = new Utf8String(substring); Assert.Equal(expected, utf8s.IndexOf(utf8substring)); } [Theory] [InlineData("", "", "")] [InlineData("abc", "abc", "")] [InlineData(null, "", "a")] [InlineData(null, "", "abc")] [InlineData("a", "a", "a")] [InlineData(null, "a", "b")] [InlineData("abc", "abc", "a")] [InlineData("abc", "abc", "ab")] [InlineData("abc", "abc", "abc")] [InlineData("bc", "abc", "b")] [InlineData("bc", "abc", "bc")] [InlineData("c", "abc", "c")] [InlineData("aaaaaaaab", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", "aaaaaaaab")] [InlineData("abbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "abbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "abbbbbbbb")] [InlineData(null, "aaabaaa", "aabaaaa")] [InlineData(null, "aaabaaa", "aadaaaa")] [InlineData("bababab", "abababab", "bababa")] [InlineData(null, "abababab", "bbababa")] [InlineData(null, "abababab", "bababaa")] [InlineData("aaac", "aaabaacaaac", "aaac")] [InlineData("baaaa", "baabaaabaaaa", "baaaa")] public void SubstringFromTests(string expected, string s, string substring) { Utf8String utf8s = new Utf8String(s); Utf8String utf8substring = new Utf8String(substring); Utf8String result; Assert.Equal(expected != null, utf8s.TrySubstringFrom(utf8substring, out result)); if (expected != null) { Utf8String utf8expected = new Utf8String(expected); Assert.Equal(expected, result.ToString()); TestHelper.Validate(utf8expected, result); } } [Theory] [InlineData("", "", "")] [InlineData("", "abc", "")] [InlineData(null, "", "a")] [InlineData(null, "", "abc")] [InlineData("", "a", "a")] [InlineData(null, "a", "b")] [InlineData("", "abc", "a")] [InlineData("", "abc", "ab")] [InlineData("", "abc", "abc")] [InlineData("a", "abc", "b")] [InlineData("a", "abc", "bc")] [InlineData("ab", "abc", "c")] [InlineData("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", "aaaaaaaab")] [InlineData("", "abbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "abbbbbbbb")] [InlineData(null, "aaabaaa", "aabaaaa")] [InlineData(null, "aaabaaa", "aadaaaa")] [InlineData("a", "abababab", "bababa")] [InlineData(null, "abababab", "bbababa")] [InlineData(null, "abababab", "bababaa")] [InlineData("aaabaac", "aaabaacaaac", "aaac")] [InlineData("baabaaa", "baabaaabaaaa", "baaaa")] public void SubstringToTests(string expected, string s, string substring) { Utf8String utf8s = new Utf8String(s); Utf8String utf8substring = new Utf8String(substring); Utf8String result; Assert.Equal(expected != null, utf8s.TrySubstringTo(utf8substring, out result)); if (expected != null) { Utf8String utf8expected = new Utf8String(expected); Assert.Equal(expected, result.ToString()); TestHelper.Validate(utf8expected, result); } } [Theory] [InlineData("abc", 'a')] [InlineData("", 'a')] [InlineData("abc", 'c')] [InlineData("a", 'c')] [InlineData("c", 'c')] [InlineData("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", 'b')] [InlineData("abbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", 'a')] [InlineData("aaabaaa", 'b')] [InlineData("aaabaaa", 'a')] [InlineData("abababab", 'a')] [InlineData("abababab", 'b')] public void IndexOfUtf8CharacterTest(string s, char character) { int expected = s.IndexOf(character); Utf8String u8s = new Utf8String(s); byte u8codeUnit = (byte)(character); Assert.Equal(expected, u8s.IndexOf(u8codeUnit)); } [Theory] [InlineData(true, 0, "a", "a")] [InlineData(true, 0, "abc", "a")] [InlineData(true, 0, "abc", "ab")] [InlineData(true, 0, "abc", "abc")] [InlineData(true, 1, "abc", "b")] [InlineData(true, 1, "abc", "bc")] [InlineData(true, 2, "abc", "c")] [InlineData(false, -1, "a", "a")] [InlineData(false, 1, "a", "a")] [InlineData(false, 1, "abc", "a")] [InlineData(false, 1, "abc", "ab")] [InlineData(false, 1, "abc", "abc")] [InlineData(false, 0, "abc", "b")] [InlineData(false, 2, "abc", "b")] [InlineData(false, 0, "abc", "bc")] [InlineData(false, 1, "abc", "c")] public void IsSubstringAtTest(bool expected, int position, string s, string substring) { Utf8String u8s = new Utf8String(s); Utf8String u8substring = new Utf8String(substring); Assert.Equal(expected, u8s.IsSubstringAt(position, u8substring)); } [Theory] [InlineData(-1, "", 0)] [InlineData(0, "a", (uint)'a')] [InlineData(-1, "a", (uint)'b')] [InlineData(0, "\uABCD", 0xABCD)] [InlineData(-1, "\uABCD", 0xABCE)] [InlineData(0, "abc", (uint)'a')] [InlineData(1, "abc", (uint)'b')] [InlineData(2, "abc", (uint)'c')] [InlineData(-1, "abc", (uint)'d')] [InlineData(0, "\uABC0\uABC1\uABC2", 0xABC0)] [InlineData(3, "\uABC0\uABC1\uABC2", 0xABC1)] [InlineData(6, "\uABC0\uABC1\uABC2", 0xABC2)] [InlineData(-1, "\uABC0\uABC1\uABC2", 0xABC3)] [InlineData(0, "\uABC0bc", 0xABC0)] [InlineData(1, "a\uABC1c", 0xABC1)] [InlineData(2, "ab\uABC2", 0xABC2)] [InlineData(-1, "\uABC0\uABC1\uABC2", (uint)'d')] public void IndexOfUnicodeCodePoint(int expected, string s, uint codePointValue) { Utf8String u8s = new Utf8String(s); Assert.Equal(expected, u8s.IndexOf(codePointValue)); } [Fact] public void ReferenceEquals() { Utf8String s1 = new Utf8String("asd"); Assert.True(s1.ReferenceEquals(s1)); Utf8String s2 = new Utf8String("asd"); Assert.True(s2.ReferenceEquals(s2)); Assert.False(s1.ReferenceEquals(s2)); Assert.False(s2.ReferenceEquals(s1)); } [Fact] public void ConstructingFromUtf16StringWithNullValueThrowsArgumentException() { Assert.Throws<ArgumentNullException>(() => { Utf8String utf8String = new Utf8String((string)null); }); } [Fact] public void ConstructingFromUtf16StringWithEmptyStringDoesNotAllocate() { Assert.True((new Utf8String("")).ReferenceEquals(Utf8String.Empty)); Assert.True((new Utf8String(string.Empty)).ReferenceEquals(Utf8String.Empty)); } public static IEnumerable<object[]> TryComputeEncodedBytesShouldMatchEncoding_Strings() { string[] data = { "", "abc", "def", "\uABCD", "\uABC0bc", "a\uABC1c", "ab\uABC2", "\uABC0\uABC1\uABC2", Text.Encoding.UTF8.GetString(new byte[] { 0xF0, 0x9F, 0x92, 0xA9}) }; return data.Select(s => new object[] { s }); } public static object[][] EnsureCodeUnitsOfStringTestCases = { // empty new object[] { new byte[0],""}, // ascii new object[] { new byte[] { 0x61 }, "a"}, new object[] { new byte[] { 0x61, 0x62, 0x63 }, "abc"}, new object[] { new byte[] { 0x41, 0x42, 0x43, 0x44 }, "ABCD"}, new object[] { new byte[] { 0x30, 0x31, 0x32, 0x33, 0x34 }, "01234"}, new object[] { new byte[] { 0x20, 0x2c, 0x2e, 0x0d, 0x0a, 0x5b, 0x5d, 0x3c, 0x3e, 0x28, 0x29 }, " ,.\r\n[]<>()"}, // edge cases for multibyte characters new object[] { new byte[] { 0x7f }, "\u007f"}, new object[] { new byte[] { 0xc2, 0x80 }, "\u0080"}, new object[] { new byte[] { 0xdf, 0xbf }, "\u07ff"}, new object[] { new byte[] { 0xe0, 0xa0, 0x80 }, "\u0800"}, new object[] { new byte[] { 0xef, 0xbf, 0xbf }, "\uffff"}, // ascii mixed with multibyte characters // 1 code unit + 2 code units new object[] { new byte[] { 0x61, 0xc2, 0x80 }, "a\u0080"}, // 2 code units + 1 code unit new object[] { new byte[] { 0xc2, 0x80, 0x61 }, "\u0080a"}, // 1 code unit + 2 code units + 1 code unit new object[] { new byte[] { 0x61, 0xc2, 0x80, 0x61 }, "a\u0080a"}, // 3 code units + 2 code units new object[] { new byte[] { 0xe0, 0xa0, 0x80, 0xc2, 0x80 }, "\u0800\u0080"}, // 2 code units + 3 code units new object[] { new byte[] { 0xc2, 0x80, 0xe0, 0xa0, 0x80 }, "\u0080\u0800"}, // 2 code units + 3 code units new object[] { new byte[] { 0xc2, 0x80, 0x61, 0xef, 0xbf, 0xbf }, "\u0080a\uffff"}, // 1 code unit + 2 code units + 3 code units new object[] { new byte[] { 0x61, 0xc2, 0x80, 0xef, 0xbf, 0xbf }, "a\u0080\uffff"}, // 2 code units + 3 code units + 1 code unit new object[] { new byte[] { 0xc2, 0x80, 0xef, 0xbf, 0xbf, 0x61 }, "\u0080\uffffa"}, // 1 code unit + 2 code units + 3 code units new object[] { new byte[] { 0x61, 0xc2, 0x80, 0x61, 0xef, 0xbf, 0xbf, 0x61 }, "a\u0080a\uffffa"} // TODO: Add case with 4 byte character - it is impossible to do using string literals, need to create it using code point }; [Theory, MemberData("EnsureCodeUnitsOfStringTestCases")] public void EnsureCodeUnitsOfStringByEnumeratingBytes(byte[] expectedBytes, string str) { var utf8String = new Utf8String(str); Assert.Equal(expectedBytes.Length, utf8String.Length); Utf8String.Enumerator e = utf8String.GetEnumerator(); int i = 0; while (e.MoveNext()) { Assert.True(i < expectedBytes.Length); Assert.Equal(expectedBytes[i], (byte)e.Current); i++; } Assert.Equal(expectedBytes.Length, i); } [Theory, MemberData("EnsureCodeUnitsOfStringTestCases")] public void EnsureCodeUnitsOfStringByIndexingBytes(byte[] expectedBytes, string str) { var utf8String = new Utf8String(str); Assert.Equal(expectedBytes.Length, utf8String.Length); for (int i = 0; i < utf8String.Length; i++) { Assert.Equal(expectedBytes[i], (byte)utf8String[i]); } } } }
using System; using System.Collections.Generic; using ModernMoleculeViewer.Rendering; using SharpDX; using SharpDX.Toolkit.Graphics; namespace ModernMoleculeViewer.Model { /// <summary> /// Creates the 3D model for a particular residue when being displayed in cartoon mode. /// </summary> internal class Cartoon { private const int RadialSegmentCount = 10; private const float TurnWidth = 0.2f; private const float HelixWidth = 1.4f; private const float HelixHeight = 0.25f; private const float SheetWidth = 1.2f; private const float SheetHeight = 0.25f; private const float ArrowWidth = 1.6f; private readonly Residue _residue; private readonly List<Vector3> _ribbonPoints; private readonly List<Vector3> _torsionVectors; private readonly List<Vector3> _normalVectors; private readonly List<VertexPositionNormalTexture> _vertices = new List<VertexPositionNormalTexture>(); private readonly List<int> _indices = new List<int>(); private readonly GeometricPrimitiveAdv<VertexPositionNormalTexture> _mesh; /// <summary> /// Builds the 3D model for the cartoon view a the given residue. /// </summary> /// <param name="residue">A residue.</param> /// <param name="initialColor">The residue's current color.</param> /// <param name="graphicsDevice"></param> internal Cartoon(Residue residue, Color initialColor, GraphicsDevice graphicsDevice) { _residue = residue; _residue.Ribbon.GetResidueSpline(_residue, out _ribbonPoints, out _torsionVectors, out _normalVectors); if (_residue.IsHelix) { AddTube(HelixWidth, HelixHeight); if (_residue.IsStructureStart) AddTubeCap(HelixWidth, HelixHeight); if (_residue.IsStructureEnd) AddTubeCap(HelixWidth, HelixHeight); } else if (_residue.IsSheet) { AddSheet(); if (_residue.IsStructureStart || _residue.IsStructureEnd) AddSheetCap(); } else { AddTube(TurnWidth, TurnWidth); if (_residue.IsStructureStart) AddTubeCap(TurnWidth, TurnWidth); if (_residue.IsStructureEnd) AddTubeCap(TurnWidth, TurnWidth); } if (_vertices.Count > 0 && _indices.Count > 0) _mesh = new GeometricPrimitiveAdv<VertexPositionNormalTexture>(graphicsDevice, _vertices.ToArray(), _indices.ToArray()); } public GeometricPrimitiveAdv<VertexPositionNormalTexture> Mesh => _mesh; /* /// <summary> /// Gets and sets the color of the model. /// </summary> internal Color Color { get { return ((SolidColorBrush)diffuseMaterial.Brush).Color; } set { ((SolidColorBrush)diffuseMaterial.Brush).Color = value; } }*/ /* /// <summary> /// Performs hit testing for this cartoon mesh. /// </summary> /// <param name="rayHitTestResult">A 3D mesh hit test result from the WPF visual tree hit /// testing framework</param> /// <returns> /// True if the mesh hit belongs to this residue, otherwise false. /// </returns> internal bool HoverHitTest(RayMeshGeometry3DHitTestResult rayHitTestResult) { return model.Children.Contains(rayHitTestResult.ModelHit); }*/ /// <summary> /// Creates a cylindrical tube along the spline path. /// </summary> /// <param name="width">The x-radius of the extrusion ellipse.</param> /// <param name="height">The y-radius of the extrusion ellipse.</param> private void AddTube(float width, float height) { // store first index int io = _vertices.Count; for (int i = 0; i < _ribbonPoints.Count; i++) { for (int j = 0; j < RadialSegmentCount; j++) { float t = 2 * (float)Math.PI * j / RadialSegmentCount; Vector3 radialVector = width * (float)Math.Cos(t) * _torsionVectors[i] + height * (float)Math.Sin(t) * _normalVectors[i]; Vector3 normalVector = height * (float)Math.Cos(t) * _torsionVectors[i] + width * (float)Math.Sin(t) * _normalVectors[i]; normalVector.Normalize(); _vertices.Add(new VertexPositionNormalTexture(_ribbonPoints[i] + radialVector, normalVector, new Vector2())); } } int rsc = RadialSegmentCount; for (int i = 0; i < _ribbonPoints.Count - 1; i++) { for (int j = 0; j < RadialSegmentCount; j++) { _indices.Add(io + i * rsc + j); _indices.Add(io + i * rsc + (j + 1) % rsc); _indices.Add(io + (i + 1) * rsc + (j + 1) % rsc); _indices.Add(io + i * rsc + j); _indices.Add(io + (i + 1) * rsc + (j + 1) % rsc); _indices.Add(io + (i + 1) * rsc + j); } } } /// <summary> /// Creates an elliptical cap for a tube along the spline path. /// </summary> /// <param name="width">The x-radius of the cap ellipse.</param> /// <param name="height">The y-radius of the cap ellipse.</param> private void AddTubeCap(float width, float height) { int io = _vertices.Count; Vector3 normalVector = Vector3.Cross(_torsionVectors[0], _normalVectors[0]); if (_residue.IsStructureEnd) normalVector = Vector3.Negate(normalVector); int offset = _residue.IsStructureStart ? 0 : _ribbonPoints.Count - 1; _vertices.Add(new VertexPositionNormalTexture(_ribbonPoints[offset], normalVector, new Vector2())); for (int i = 0; i < RadialSegmentCount; i++) { float t = 2 * (float)Math.PI * i / RadialSegmentCount; Vector3 radialVector = width * (float)Math.Cos(t) * _torsionVectors[offset] + height * (float)Math.Sin(t) * _normalVectors[offset]; _vertices.Add(new VertexPositionNormalTexture(_ribbonPoints[offset] + radialVector, normalVector, new Vector2())); _indices.Add(io); if (_residue.IsStructureStart) { _indices.Add(io + (i + 1) % RadialSegmentCount + 1); _indices.Add(io + i + 1); } else { _indices.Add(io + i + 1); _indices.Add(io + (i + 1) % RadialSegmentCount + 1); } } } /// <summary> /// Creates a rectangular solid sheet along the spline path. /// </summary> private void AddSheet() { int io = _vertices.Count; float offsetLength = 0; if (_residue.IsStructureEnd) { Vector3 lengthVector = _ribbonPoints[_ribbonPoints.Count - 1] - _ribbonPoints[0]; offsetLength = ArrowWidth / lengthVector.Length(); } for (int i = 0; i < _ribbonPoints.Count; i++) { float actualWidth = !_residue.IsStructureEnd ? SheetWidth : ArrowWidth * (1 - (float)i / (_ribbonPoints.Count - 1)); Vector3 horizontalVector = actualWidth * _torsionVectors[i]; Vector3 verticalVector = SheetHeight * _normalVectors[i]; Vector3 normalOffset = new Vector3(); if (_residue.IsStructureEnd) { normalOffset = offsetLength * Vector3.Cross(_normalVectors[i], _torsionVectors[i]); } _vertices.Add(new VertexPositionNormalTexture(_ribbonPoints[i] + horizontalVector + verticalVector, _normalVectors[i], new Vector2())); _vertices.Add(new VertexPositionNormalTexture(_ribbonPoints[i] - horizontalVector + verticalVector, _normalVectors[i], new Vector2())); _vertices.Add(new VertexPositionNormalTexture(_ribbonPoints[i] - horizontalVector + verticalVector, -_torsionVectors[i] + normalOffset, new Vector2())); _vertices.Add(new VertexPositionNormalTexture(_ribbonPoints[i] - horizontalVector - verticalVector, -_torsionVectors[i] + normalOffset, new Vector2())); _vertices.Add(new VertexPositionNormalTexture(_ribbonPoints[i] - horizontalVector - verticalVector, -_normalVectors[i], new Vector2())); _vertices.Add(new VertexPositionNormalTexture(_ribbonPoints[i] + horizontalVector - verticalVector, -_normalVectors[i], new Vector2())); _vertices.Add(new VertexPositionNormalTexture(_ribbonPoints[i] + horizontalVector - verticalVector, _torsionVectors[i] + normalOffset, new Vector2())); _vertices.Add(new VertexPositionNormalTexture(_ribbonPoints[i] + horizontalVector + verticalVector, _torsionVectors[i] + normalOffset, new Vector2())); } for (int i = 0; i < _ribbonPoints.Count - 1; i++) { for (int j = 0; j < 4; j++) { _indices.Add(io + i * 8 + 2 * j); _indices.Add(io + i * 8 + 2 * j + 1); _indices.Add(io + (i + 1) * 8 + 2 * j + 1); _indices.Add(io + i * 8 + 2 * j); _indices.Add(io + (i + 1) * 8 + 2 * j + 1); _indices.Add(io + (i + 1) * 8 + 2 * j); } } } /// <summary> /// Creates a flat cap or an arrow head cap for a sheet. /// </summary> private void AddSheetCap() { Vector3 horizontalVector = SheetWidth * _torsionVectors[0]; Vector3 verticalVector = SheetHeight * _normalVectors[0]; Vector3 p1 = _ribbonPoints[0] + horizontalVector + verticalVector; Vector3 p2 = _ribbonPoints[0] - horizontalVector + verticalVector; Vector3 p3 = _ribbonPoints[0] - horizontalVector - verticalVector; Vector3 p4 = _ribbonPoints[0] + horizontalVector - verticalVector; if (_residue.IsStructureStart) { AddSheetCapSection(p1, p2, p3, p4); } else { Vector3 arrowHorizontalVector = ArrowWidth * _torsionVectors[0]; Vector3 p5 = _ribbonPoints[0] + arrowHorizontalVector + verticalVector; Vector3 p6 = _ribbonPoints[0] - arrowHorizontalVector + verticalVector; Vector3 p7 = _ribbonPoints[0] - arrowHorizontalVector - verticalVector; Vector3 p8 = _ribbonPoints[0] + arrowHorizontalVector - verticalVector; AddSheetCapSection(p5, p1, p4, p8); AddSheetCapSection(p2, p6, p7, p3); } } /// <summary> /// Helper method to add a quadrilateral surface for a sheet cap. /// </summary> /// <param name="p1">Point 1.</param> /// <param name="p2">Point 2.</param> /// <param name="p3">Point 3.</param> /// <param name="p4">Point 4.</param> private void AddSheetCapSection(Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4) { int indexOffset = _vertices.Count; Vector3 normalVector = Vector3.Cross(p2 - p1, p4 - p1); normalVector.Normalize(); _vertices.Add(new VertexPositionNormalTexture(p1, normalVector, new Vector2())); _vertices.Add(new VertexPositionNormalTexture(p2, normalVector, new Vector2())); _vertices.Add(new VertexPositionNormalTexture(p3, normalVector, new Vector2())); _vertices.Add(new VertexPositionNormalTexture(p4, normalVector, new Vector2())); _indices.Add(indexOffset + 0); _indices.Add(indexOffset + 2); _indices.Add(indexOffset + 1); _indices.Add(indexOffset + 2); _indices.Add(indexOffset + 0); _indices.Add(indexOffset + 3); } } }
// 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 ga = Google.Api; using gaxgrpc = Google.Api.Gax.Grpc; using gagr = Google.Api.Gax.ResourceNames; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Monitoring.V3.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedMetricServiceClientTest { [xunit::FactAttribute] public void GetMonitoredResourceDescriptorRequestObject() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); GetMonitoredResourceDescriptorRequest request = new GetMonitoredResourceDescriptorRequest { MonitoredResourceDescriptorName = MonitoredResourceDescriptorName.FromProjectMonitoredResourceDescriptor("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"), }; ga::MonitoredResourceDescriptor expectedResponse = new ga::MonitoredResourceDescriptor { Type = "typee2cc9d59", DisplayName = "display_name137f65c2", Description = "description2cf9da67", Labels = { new ga::LabelDescriptor(), }, Name = "name1c9368b0", LaunchStage = ga::LaunchStage.Unspecified, }; mockGrpcClient.Setup(x => x.GetMonitoredResourceDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ga::MonitoredResourceDescriptor response = client.GetMonitoredResourceDescriptor(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetMonitoredResourceDescriptorRequestObjectAsync() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); GetMonitoredResourceDescriptorRequest request = new GetMonitoredResourceDescriptorRequest { MonitoredResourceDescriptorName = MonitoredResourceDescriptorName.FromProjectMonitoredResourceDescriptor("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"), }; ga::MonitoredResourceDescriptor expectedResponse = new ga::MonitoredResourceDescriptor { Type = "typee2cc9d59", DisplayName = "display_name137f65c2", Description = "description2cf9da67", Labels = { new ga::LabelDescriptor(), }, Name = "name1c9368b0", LaunchStage = ga::LaunchStage.Unspecified, }; mockGrpcClient.Setup(x => x.GetMonitoredResourceDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::MonitoredResourceDescriptor>(stt::Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ga::MonitoredResourceDescriptor responseCallSettings = await client.GetMonitoredResourceDescriptorAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ga::MonitoredResourceDescriptor responseCancellationToken = await client.GetMonitoredResourceDescriptorAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetMonitoredResourceDescriptor() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); GetMonitoredResourceDescriptorRequest request = new GetMonitoredResourceDescriptorRequest { MonitoredResourceDescriptorName = MonitoredResourceDescriptorName.FromProjectMonitoredResourceDescriptor("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"), }; ga::MonitoredResourceDescriptor expectedResponse = new ga::MonitoredResourceDescriptor { Type = "typee2cc9d59", DisplayName = "display_name137f65c2", Description = "description2cf9da67", Labels = { new ga::LabelDescriptor(), }, Name = "name1c9368b0", LaunchStage = ga::LaunchStage.Unspecified, }; mockGrpcClient.Setup(x => x.GetMonitoredResourceDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ga::MonitoredResourceDescriptor response = client.GetMonitoredResourceDescriptor(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetMonitoredResourceDescriptorAsync() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); GetMonitoredResourceDescriptorRequest request = new GetMonitoredResourceDescriptorRequest { MonitoredResourceDescriptorName = MonitoredResourceDescriptorName.FromProjectMonitoredResourceDescriptor("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"), }; ga::MonitoredResourceDescriptor expectedResponse = new ga::MonitoredResourceDescriptor { Type = "typee2cc9d59", DisplayName = "display_name137f65c2", Description = "description2cf9da67", Labels = { new ga::LabelDescriptor(), }, Name = "name1c9368b0", LaunchStage = ga::LaunchStage.Unspecified, }; mockGrpcClient.Setup(x => x.GetMonitoredResourceDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::MonitoredResourceDescriptor>(stt::Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ga::MonitoredResourceDescriptor responseCallSettings = await client.GetMonitoredResourceDescriptorAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ga::MonitoredResourceDescriptor responseCancellationToken = await client.GetMonitoredResourceDescriptorAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetMonitoredResourceDescriptorResourceNames1() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); GetMonitoredResourceDescriptorRequest request = new GetMonitoredResourceDescriptorRequest { MonitoredResourceDescriptorName = MonitoredResourceDescriptorName.FromProjectMonitoredResourceDescriptor("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"), }; ga::MonitoredResourceDescriptor expectedResponse = new ga::MonitoredResourceDescriptor { Type = "typee2cc9d59", DisplayName = "display_name137f65c2", Description = "description2cf9da67", Labels = { new ga::LabelDescriptor(), }, Name = "name1c9368b0", LaunchStage = ga::LaunchStage.Unspecified, }; mockGrpcClient.Setup(x => x.GetMonitoredResourceDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ga::MonitoredResourceDescriptor response = client.GetMonitoredResourceDescriptor(request.MonitoredResourceDescriptorName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetMonitoredResourceDescriptorResourceNames1Async() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); GetMonitoredResourceDescriptorRequest request = new GetMonitoredResourceDescriptorRequest { MonitoredResourceDescriptorName = MonitoredResourceDescriptorName.FromProjectMonitoredResourceDescriptor("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"), }; ga::MonitoredResourceDescriptor expectedResponse = new ga::MonitoredResourceDescriptor { Type = "typee2cc9d59", DisplayName = "display_name137f65c2", Description = "description2cf9da67", Labels = { new ga::LabelDescriptor(), }, Name = "name1c9368b0", LaunchStage = ga::LaunchStage.Unspecified, }; mockGrpcClient.Setup(x => x.GetMonitoredResourceDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::MonitoredResourceDescriptor>(stt::Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ga::MonitoredResourceDescriptor responseCallSettings = await client.GetMonitoredResourceDescriptorAsync(request.MonitoredResourceDescriptorName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ga::MonitoredResourceDescriptor responseCancellationToken = await client.GetMonitoredResourceDescriptorAsync(request.MonitoredResourceDescriptorName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetMonitoredResourceDescriptorResourceNames2() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); GetMonitoredResourceDescriptorRequest request = new GetMonitoredResourceDescriptorRequest { MonitoredResourceDescriptorName = MonitoredResourceDescriptorName.FromProjectMonitoredResourceDescriptor("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"), }; ga::MonitoredResourceDescriptor expectedResponse = new ga::MonitoredResourceDescriptor { Type = "typee2cc9d59", DisplayName = "display_name137f65c2", Description = "description2cf9da67", Labels = { new ga::LabelDescriptor(), }, Name = "name1c9368b0", LaunchStage = ga::LaunchStage.Unspecified, }; mockGrpcClient.Setup(x => x.GetMonitoredResourceDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ga::MonitoredResourceDescriptor response = client.GetMonitoredResourceDescriptor(request.ResourceName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetMonitoredResourceDescriptorResourceNames2Async() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); GetMonitoredResourceDescriptorRequest request = new GetMonitoredResourceDescriptorRequest { MonitoredResourceDescriptorName = MonitoredResourceDescriptorName.FromProjectMonitoredResourceDescriptor("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"), }; ga::MonitoredResourceDescriptor expectedResponse = new ga::MonitoredResourceDescriptor { Type = "typee2cc9d59", DisplayName = "display_name137f65c2", Description = "description2cf9da67", Labels = { new ga::LabelDescriptor(), }, Name = "name1c9368b0", LaunchStage = ga::LaunchStage.Unspecified, }; mockGrpcClient.Setup(x => x.GetMonitoredResourceDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::MonitoredResourceDescriptor>(stt::Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ga::MonitoredResourceDescriptor responseCallSettings = await client.GetMonitoredResourceDescriptorAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ga::MonitoredResourceDescriptor responseCancellationToken = await client.GetMonitoredResourceDescriptorAsync(request.ResourceName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetMetricDescriptorRequestObject() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); GetMetricDescriptorRequest request = new GetMetricDescriptorRequest { MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"), }; ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor { Name = "name1c9368b0", Labels = { new ga::LabelDescriptor(), }, MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge, ValueType = ga::MetricDescriptor.Types.ValueType.Money, Unit = "unitebbd343e", Description = "description2cf9da67", DisplayName = "display_name137f65c2", Type = "typee2cc9d59", Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(), LaunchStage = ga::LaunchStage.Unspecified, MonitoredResourceTypes = { "monitored_resource_typesc49bdc0a", }, }; mockGrpcClient.Setup(x => x.GetMetricDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ga::MetricDescriptor response = client.GetMetricDescriptor(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetMetricDescriptorRequestObjectAsync() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); GetMetricDescriptorRequest request = new GetMetricDescriptorRequest { MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"), }; ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor { Name = "name1c9368b0", Labels = { new ga::LabelDescriptor(), }, MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge, ValueType = ga::MetricDescriptor.Types.ValueType.Money, Unit = "unitebbd343e", Description = "description2cf9da67", DisplayName = "display_name137f65c2", Type = "typee2cc9d59", Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(), LaunchStage = ga::LaunchStage.Unspecified, MonitoredResourceTypes = { "monitored_resource_typesc49bdc0a", }, }; mockGrpcClient.Setup(x => x.GetMetricDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::MetricDescriptor>(stt::Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ga::MetricDescriptor responseCallSettings = await client.GetMetricDescriptorAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ga::MetricDescriptor responseCancellationToken = await client.GetMetricDescriptorAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetMetricDescriptor() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); GetMetricDescriptorRequest request = new GetMetricDescriptorRequest { MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"), }; ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor { Name = "name1c9368b0", Labels = { new ga::LabelDescriptor(), }, MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge, ValueType = ga::MetricDescriptor.Types.ValueType.Money, Unit = "unitebbd343e", Description = "description2cf9da67", DisplayName = "display_name137f65c2", Type = "typee2cc9d59", Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(), LaunchStage = ga::LaunchStage.Unspecified, MonitoredResourceTypes = { "monitored_resource_typesc49bdc0a", }, }; mockGrpcClient.Setup(x => x.GetMetricDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ga::MetricDescriptor response = client.GetMetricDescriptor(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetMetricDescriptorAsync() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); GetMetricDescriptorRequest request = new GetMetricDescriptorRequest { MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"), }; ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor { Name = "name1c9368b0", Labels = { new ga::LabelDescriptor(), }, MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge, ValueType = ga::MetricDescriptor.Types.ValueType.Money, Unit = "unitebbd343e", Description = "description2cf9da67", DisplayName = "display_name137f65c2", Type = "typee2cc9d59", Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(), LaunchStage = ga::LaunchStage.Unspecified, MonitoredResourceTypes = { "monitored_resource_typesc49bdc0a", }, }; mockGrpcClient.Setup(x => x.GetMetricDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::MetricDescriptor>(stt::Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ga::MetricDescriptor responseCallSettings = await client.GetMetricDescriptorAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ga::MetricDescriptor responseCancellationToken = await client.GetMetricDescriptorAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetMetricDescriptorResourceNames1() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); GetMetricDescriptorRequest request = new GetMetricDescriptorRequest { MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"), }; ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor { Name = "name1c9368b0", Labels = { new ga::LabelDescriptor(), }, MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge, ValueType = ga::MetricDescriptor.Types.ValueType.Money, Unit = "unitebbd343e", Description = "description2cf9da67", DisplayName = "display_name137f65c2", Type = "typee2cc9d59", Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(), LaunchStage = ga::LaunchStage.Unspecified, MonitoredResourceTypes = { "monitored_resource_typesc49bdc0a", }, }; mockGrpcClient.Setup(x => x.GetMetricDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ga::MetricDescriptor response = client.GetMetricDescriptor(request.MetricDescriptorName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetMetricDescriptorResourceNames1Async() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); GetMetricDescriptorRequest request = new GetMetricDescriptorRequest { MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"), }; ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor { Name = "name1c9368b0", Labels = { new ga::LabelDescriptor(), }, MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge, ValueType = ga::MetricDescriptor.Types.ValueType.Money, Unit = "unitebbd343e", Description = "description2cf9da67", DisplayName = "display_name137f65c2", Type = "typee2cc9d59", Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(), LaunchStage = ga::LaunchStage.Unspecified, MonitoredResourceTypes = { "monitored_resource_typesc49bdc0a", }, }; mockGrpcClient.Setup(x => x.GetMetricDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::MetricDescriptor>(stt::Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ga::MetricDescriptor responseCallSettings = await client.GetMetricDescriptorAsync(request.MetricDescriptorName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ga::MetricDescriptor responseCancellationToken = await client.GetMetricDescriptorAsync(request.MetricDescriptorName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetMetricDescriptorResourceNames2() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); GetMetricDescriptorRequest request = new GetMetricDescriptorRequest { MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"), }; ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor { Name = "name1c9368b0", Labels = { new ga::LabelDescriptor(), }, MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge, ValueType = ga::MetricDescriptor.Types.ValueType.Money, Unit = "unitebbd343e", Description = "description2cf9da67", DisplayName = "display_name137f65c2", Type = "typee2cc9d59", Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(), LaunchStage = ga::LaunchStage.Unspecified, MonitoredResourceTypes = { "monitored_resource_typesc49bdc0a", }, }; mockGrpcClient.Setup(x => x.GetMetricDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ga::MetricDescriptor response = client.GetMetricDescriptor(request.ResourceName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetMetricDescriptorResourceNames2Async() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); GetMetricDescriptorRequest request = new GetMetricDescriptorRequest { MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"), }; ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor { Name = "name1c9368b0", Labels = { new ga::LabelDescriptor(), }, MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge, ValueType = ga::MetricDescriptor.Types.ValueType.Money, Unit = "unitebbd343e", Description = "description2cf9da67", DisplayName = "display_name137f65c2", Type = "typee2cc9d59", Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(), LaunchStage = ga::LaunchStage.Unspecified, MonitoredResourceTypes = { "monitored_resource_typesc49bdc0a", }, }; mockGrpcClient.Setup(x => x.GetMetricDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::MetricDescriptor>(stt::Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ga::MetricDescriptor responseCallSettings = await client.GetMetricDescriptorAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ga::MetricDescriptor responseCancellationToken = await client.GetMetricDescriptorAsync(request.ResourceName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateMetricDescriptorRequestObject() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest { MetricDescriptor = new ga::MetricDescriptor(), ProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor { Name = "name1c9368b0", Labels = { new ga::LabelDescriptor(), }, MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge, ValueType = ga::MetricDescriptor.Types.ValueType.Money, Unit = "unitebbd343e", Description = "description2cf9da67", DisplayName = "display_name137f65c2", Type = "typee2cc9d59", Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(), LaunchStage = ga::LaunchStage.Unspecified, MonitoredResourceTypes = { "monitored_resource_typesc49bdc0a", }, }; mockGrpcClient.Setup(x => x.CreateMetricDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ga::MetricDescriptor response = client.CreateMetricDescriptor(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateMetricDescriptorRequestObjectAsync() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest { MetricDescriptor = new ga::MetricDescriptor(), ProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor { Name = "name1c9368b0", Labels = { new ga::LabelDescriptor(), }, MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge, ValueType = ga::MetricDescriptor.Types.ValueType.Money, Unit = "unitebbd343e", Description = "description2cf9da67", DisplayName = "display_name137f65c2", Type = "typee2cc9d59", Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(), LaunchStage = ga::LaunchStage.Unspecified, MonitoredResourceTypes = { "monitored_resource_typesc49bdc0a", }, }; mockGrpcClient.Setup(x => x.CreateMetricDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::MetricDescriptor>(stt::Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ga::MetricDescriptor responseCallSettings = await client.CreateMetricDescriptorAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ga::MetricDescriptor responseCancellationToken = await client.CreateMetricDescriptorAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateMetricDescriptor() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest { MetricDescriptor = new ga::MetricDescriptor(), ProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor { Name = "name1c9368b0", Labels = { new ga::LabelDescriptor(), }, MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge, ValueType = ga::MetricDescriptor.Types.ValueType.Money, Unit = "unitebbd343e", Description = "description2cf9da67", DisplayName = "display_name137f65c2", Type = "typee2cc9d59", Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(), LaunchStage = ga::LaunchStage.Unspecified, MonitoredResourceTypes = { "monitored_resource_typesc49bdc0a", }, }; mockGrpcClient.Setup(x => x.CreateMetricDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ga::MetricDescriptor response = client.CreateMetricDescriptor(request.Name, request.MetricDescriptor); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateMetricDescriptorAsync() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest { MetricDescriptor = new ga::MetricDescriptor(), ProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor { Name = "name1c9368b0", Labels = { new ga::LabelDescriptor(), }, MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge, ValueType = ga::MetricDescriptor.Types.ValueType.Money, Unit = "unitebbd343e", Description = "description2cf9da67", DisplayName = "display_name137f65c2", Type = "typee2cc9d59", Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(), LaunchStage = ga::LaunchStage.Unspecified, MonitoredResourceTypes = { "monitored_resource_typesc49bdc0a", }, }; mockGrpcClient.Setup(x => x.CreateMetricDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::MetricDescriptor>(stt::Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ga::MetricDescriptor responseCallSettings = await client.CreateMetricDescriptorAsync(request.Name, request.MetricDescriptor, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ga::MetricDescriptor responseCancellationToken = await client.CreateMetricDescriptorAsync(request.Name, request.MetricDescriptor, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateMetricDescriptorResourceNames1() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest { MetricDescriptor = new ga::MetricDescriptor(), ProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor { Name = "name1c9368b0", Labels = { new ga::LabelDescriptor(), }, MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge, ValueType = ga::MetricDescriptor.Types.ValueType.Money, Unit = "unitebbd343e", Description = "description2cf9da67", DisplayName = "display_name137f65c2", Type = "typee2cc9d59", Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(), LaunchStage = ga::LaunchStage.Unspecified, MonitoredResourceTypes = { "monitored_resource_typesc49bdc0a", }, }; mockGrpcClient.Setup(x => x.CreateMetricDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ga::MetricDescriptor response = client.CreateMetricDescriptor(request.ProjectName, request.MetricDescriptor); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateMetricDescriptorResourceNames1Async() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest { MetricDescriptor = new ga::MetricDescriptor(), ProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor { Name = "name1c9368b0", Labels = { new ga::LabelDescriptor(), }, MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge, ValueType = ga::MetricDescriptor.Types.ValueType.Money, Unit = "unitebbd343e", Description = "description2cf9da67", DisplayName = "display_name137f65c2", Type = "typee2cc9d59", Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(), LaunchStage = ga::LaunchStage.Unspecified, MonitoredResourceTypes = { "monitored_resource_typesc49bdc0a", }, }; mockGrpcClient.Setup(x => x.CreateMetricDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::MetricDescriptor>(stt::Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ga::MetricDescriptor responseCallSettings = await client.CreateMetricDescriptorAsync(request.ProjectName, request.MetricDescriptor, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ga::MetricDescriptor responseCancellationToken = await client.CreateMetricDescriptorAsync(request.ProjectName, request.MetricDescriptor, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateMetricDescriptorResourceNames2() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest { MetricDescriptor = new ga::MetricDescriptor(), ProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor { Name = "name1c9368b0", Labels = { new ga::LabelDescriptor(), }, MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge, ValueType = ga::MetricDescriptor.Types.ValueType.Money, Unit = "unitebbd343e", Description = "description2cf9da67", DisplayName = "display_name137f65c2", Type = "typee2cc9d59", Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(), LaunchStage = ga::LaunchStage.Unspecified, MonitoredResourceTypes = { "monitored_resource_typesc49bdc0a", }, }; mockGrpcClient.Setup(x => x.CreateMetricDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ga::MetricDescriptor response = client.CreateMetricDescriptor(request.OrganizationName, request.MetricDescriptor); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateMetricDescriptorResourceNames2Async() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest { MetricDescriptor = new ga::MetricDescriptor(), ProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor { Name = "name1c9368b0", Labels = { new ga::LabelDescriptor(), }, MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge, ValueType = ga::MetricDescriptor.Types.ValueType.Money, Unit = "unitebbd343e", Description = "description2cf9da67", DisplayName = "display_name137f65c2", Type = "typee2cc9d59", Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(), LaunchStage = ga::LaunchStage.Unspecified, MonitoredResourceTypes = { "monitored_resource_typesc49bdc0a", }, }; mockGrpcClient.Setup(x => x.CreateMetricDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::MetricDescriptor>(stt::Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ga::MetricDescriptor responseCallSettings = await client.CreateMetricDescriptorAsync(request.OrganizationName, request.MetricDescriptor, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ga::MetricDescriptor responseCancellationToken = await client.CreateMetricDescriptorAsync(request.OrganizationName, request.MetricDescriptor, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateMetricDescriptorResourceNames3() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest { MetricDescriptor = new ga::MetricDescriptor(), ProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor { Name = "name1c9368b0", Labels = { new ga::LabelDescriptor(), }, MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge, ValueType = ga::MetricDescriptor.Types.ValueType.Money, Unit = "unitebbd343e", Description = "description2cf9da67", DisplayName = "display_name137f65c2", Type = "typee2cc9d59", Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(), LaunchStage = ga::LaunchStage.Unspecified, MonitoredResourceTypes = { "monitored_resource_typesc49bdc0a", }, }; mockGrpcClient.Setup(x => x.CreateMetricDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ga::MetricDescriptor response = client.CreateMetricDescriptor(request.FolderName, request.MetricDescriptor); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateMetricDescriptorResourceNames3Async() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest { MetricDescriptor = new ga::MetricDescriptor(), ProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor { Name = "name1c9368b0", Labels = { new ga::LabelDescriptor(), }, MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge, ValueType = ga::MetricDescriptor.Types.ValueType.Money, Unit = "unitebbd343e", Description = "description2cf9da67", DisplayName = "display_name137f65c2", Type = "typee2cc9d59", Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(), LaunchStage = ga::LaunchStage.Unspecified, MonitoredResourceTypes = { "monitored_resource_typesc49bdc0a", }, }; mockGrpcClient.Setup(x => x.CreateMetricDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::MetricDescriptor>(stt::Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ga::MetricDescriptor responseCallSettings = await client.CreateMetricDescriptorAsync(request.FolderName, request.MetricDescriptor, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ga::MetricDescriptor responseCancellationToken = await client.CreateMetricDescriptorAsync(request.FolderName, request.MetricDescriptor, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateMetricDescriptorResourceNames4() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest { MetricDescriptor = new ga::MetricDescriptor(), ProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor { Name = "name1c9368b0", Labels = { new ga::LabelDescriptor(), }, MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge, ValueType = ga::MetricDescriptor.Types.ValueType.Money, Unit = "unitebbd343e", Description = "description2cf9da67", DisplayName = "display_name137f65c2", Type = "typee2cc9d59", Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(), LaunchStage = ga::LaunchStage.Unspecified, MonitoredResourceTypes = { "monitored_resource_typesc49bdc0a", }, }; mockGrpcClient.Setup(x => x.CreateMetricDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ga::MetricDescriptor response = client.CreateMetricDescriptor(request.ResourceName, request.MetricDescriptor); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateMetricDescriptorResourceNames4Async() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest { MetricDescriptor = new ga::MetricDescriptor(), ProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor { Name = "name1c9368b0", Labels = { new ga::LabelDescriptor(), }, MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge, ValueType = ga::MetricDescriptor.Types.ValueType.Money, Unit = "unitebbd343e", Description = "description2cf9da67", DisplayName = "display_name137f65c2", Type = "typee2cc9d59", Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(), LaunchStage = ga::LaunchStage.Unspecified, MonitoredResourceTypes = { "monitored_resource_typesc49bdc0a", }, }; mockGrpcClient.Setup(x => x.CreateMetricDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::MetricDescriptor>(stt::Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ga::MetricDescriptor responseCallSettings = await client.CreateMetricDescriptorAsync(request.ResourceName, request.MetricDescriptor, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ga::MetricDescriptor responseCancellationToken = await client.CreateMetricDescriptorAsync(request.ResourceName, request.MetricDescriptor, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteMetricDescriptorRequestObject() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); DeleteMetricDescriptorRequest request = new DeleteMetricDescriptorRequest { MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteMetricDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); client.DeleteMetricDescriptor(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteMetricDescriptorRequestObjectAsync() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); DeleteMetricDescriptorRequest request = new DeleteMetricDescriptorRequest { MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteMetricDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteMetricDescriptorAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteMetricDescriptorAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteMetricDescriptor() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); DeleteMetricDescriptorRequest request = new DeleteMetricDescriptorRequest { MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteMetricDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); client.DeleteMetricDescriptor(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteMetricDescriptorAsync() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); DeleteMetricDescriptorRequest request = new DeleteMetricDescriptorRequest { MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteMetricDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteMetricDescriptorAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteMetricDescriptorAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteMetricDescriptorResourceNames1() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); DeleteMetricDescriptorRequest request = new DeleteMetricDescriptorRequest { MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteMetricDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); client.DeleteMetricDescriptor(request.MetricDescriptorName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteMetricDescriptorResourceNames1Async() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); DeleteMetricDescriptorRequest request = new DeleteMetricDescriptorRequest { MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteMetricDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteMetricDescriptorAsync(request.MetricDescriptorName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteMetricDescriptorAsync(request.MetricDescriptorName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteMetricDescriptorResourceNames2() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); DeleteMetricDescriptorRequest request = new DeleteMetricDescriptorRequest { MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteMetricDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); client.DeleteMetricDescriptor(request.ResourceName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteMetricDescriptorResourceNames2Async() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); DeleteMetricDescriptorRequest request = new DeleteMetricDescriptorRequest { MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteMetricDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteMetricDescriptorAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteMetricDescriptorAsync(request.ResourceName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateTimeSeriesRequestObject() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); CreateTimeSeriesRequest request = new CreateTimeSeriesRequest { TimeSeries = { new TimeSeries(), }, ProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.CreateTimeSeries(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); client.CreateTimeSeries(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateTimeSeriesRequestObjectAsync() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); CreateTimeSeriesRequest request = new CreateTimeSeriesRequest { TimeSeries = { new TimeSeries(), }, ProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.CreateTimeSeriesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); await client.CreateTimeSeriesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.CreateTimeSeriesAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateTimeSeries() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); CreateTimeSeriesRequest request = new CreateTimeSeriesRequest { TimeSeries = { new TimeSeries(), }, ProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.CreateTimeSeries(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); client.CreateTimeSeries(request.Name, request.TimeSeries); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateTimeSeriesAsync() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); CreateTimeSeriesRequest request = new CreateTimeSeriesRequest { TimeSeries = { new TimeSeries(), }, ProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.CreateTimeSeriesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); await client.CreateTimeSeriesAsync(request.Name, request.TimeSeries, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.CreateTimeSeriesAsync(request.Name, request.TimeSeries, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateTimeSeriesResourceNames() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); CreateTimeSeriesRequest request = new CreateTimeSeriesRequest { TimeSeries = { new TimeSeries(), }, ProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.CreateTimeSeries(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); client.CreateTimeSeries(request.ProjectName, request.TimeSeries); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateTimeSeriesResourceNamesAsync() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); CreateTimeSeriesRequest request = new CreateTimeSeriesRequest { TimeSeries = { new TimeSeries(), }, ProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.CreateTimeSeriesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); await client.CreateTimeSeriesAsync(request.ProjectName, request.TimeSeries, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.CreateTimeSeriesAsync(request.ProjectName, request.TimeSeries, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateServiceTimeSeriesRequestObject() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); CreateTimeSeriesRequest request = new CreateTimeSeriesRequest { TimeSeries = { new TimeSeries(), }, ProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.CreateServiceTimeSeries(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); client.CreateServiceTimeSeries(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateServiceTimeSeriesRequestObjectAsync() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); CreateTimeSeriesRequest request = new CreateTimeSeriesRequest { TimeSeries = { new TimeSeries(), }, ProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.CreateServiceTimeSeriesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); await client.CreateServiceTimeSeriesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.CreateServiceTimeSeriesAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateServiceTimeSeries() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); CreateTimeSeriesRequest request = new CreateTimeSeriesRequest { TimeSeries = { new TimeSeries(), }, ProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.CreateServiceTimeSeries(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); client.CreateServiceTimeSeries(request.Name, request.TimeSeries); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateServiceTimeSeriesAsync() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); CreateTimeSeriesRequest request = new CreateTimeSeriesRequest { TimeSeries = { new TimeSeries(), }, ProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.CreateServiceTimeSeriesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); await client.CreateServiceTimeSeriesAsync(request.Name, request.TimeSeries, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.CreateServiceTimeSeriesAsync(request.Name, request.TimeSeries, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateServiceTimeSeriesResourceNames() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); CreateTimeSeriesRequest request = new CreateTimeSeriesRequest { TimeSeries = { new TimeSeries(), }, ProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.CreateServiceTimeSeries(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); client.CreateServiceTimeSeries(request.ProjectName, request.TimeSeries); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateServiceTimeSeriesResourceNamesAsync() { moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict); CreateTimeSeriesRequest request = new CreateTimeSeriesRequest { TimeSeries = { new TimeSeries(), }, ProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.CreateServiceTimeSeriesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); await client.CreateServiceTimeSeriesAsync(request.ProjectName, request.TimeSeries, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.CreateServiceTimeSeriesAsync(request.ProjectName, request.TimeSeries, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Compute { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for SnapshotsOperations. /// </summary> public static partial class SnapshotsOperationsExtensions { /// <summary> /// Creates or updates a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='snapshot'> /// Snapshot object supplied in the body of the Put disk operation. /// </param> public static Snapshot CreateOrUpdate(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, Snapshot snapshot) { return operations.CreateOrUpdateAsync(resourceGroupName, snapshotName, snapshot).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='snapshot'> /// Snapshot object supplied in the body of the Put disk operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Snapshot> CreateOrUpdateAsync(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, Snapshot snapshot, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, snapshotName, snapshot, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates (patches) a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='snapshot'> /// Snapshot object supplied in the body of the Patch snapshot operation. /// </param> public static Snapshot Update(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, SnapshotUpdate snapshot) { return operations.UpdateAsync(resourceGroupName, snapshotName, snapshot).GetAwaiter().GetResult(); } /// <summary> /// Updates (patches) a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='snapshot'> /// Snapshot object supplied in the body of the Patch snapshot operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Snapshot> UpdateAsync(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, SnapshotUpdate snapshot, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, snapshotName, snapshot, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets information about a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> public static Snapshot Get(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName) { return operations.GetAsync(resourceGroupName, snapshotName).GetAwaiter().GetResult(); } /// <summary> /// Gets information about a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Snapshot> GetAsync(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, snapshotName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> public static OperationStatusResponse Delete(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName) { return operations.DeleteAsync(resourceGroupName, snapshotName).GetAwaiter().GetResult(); } /// <summary> /// Deletes a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<OperationStatusResponse> DeleteAsync(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DeleteWithHttpMessagesAsync(resourceGroupName, snapshotName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists snapshots under a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> public static IPage<Snapshot> ListByResourceGroup(this ISnapshotsOperations operations, string resourceGroupName) { return operations.ListByResourceGroupAsync(resourceGroupName).GetAwaiter().GetResult(); } /// <summary> /// Lists snapshots under a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Snapshot>> ListByResourceGroupAsync(this ISnapshotsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists snapshots under a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<Snapshot> List(this ISnapshotsOperations operations) { return operations.ListAsync().GetAwaiter().GetResult(); } /// <summary> /// Lists snapshots under a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Snapshot>> ListAsync(this ISnapshotsOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Grants access to a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='grantAccessData'> /// Access data object supplied in the body of the get snapshot access /// operation. /// </param> public static AccessUri GrantAccess(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, GrantAccessData grantAccessData) { return operations.GrantAccessAsync(resourceGroupName, snapshotName, grantAccessData).GetAwaiter().GetResult(); } /// <summary> /// Grants access to a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='grantAccessData'> /// Access data object supplied in the body of the get snapshot access /// operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<AccessUri> GrantAccessAsync(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, GrantAccessData grantAccessData, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GrantAccessWithHttpMessagesAsync(resourceGroupName, snapshotName, grantAccessData, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Revokes access to a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> public static OperationStatusResponse RevokeAccess(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName) { return operations.RevokeAccessAsync(resourceGroupName, snapshotName).GetAwaiter().GetResult(); } /// <summary> /// Revokes access to a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<OperationStatusResponse> RevokeAccessAsync(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.RevokeAccessWithHttpMessagesAsync(resourceGroupName, snapshotName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='snapshot'> /// Snapshot object supplied in the body of the Put disk operation. /// </param> public static Snapshot BeginCreateOrUpdate(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, Snapshot snapshot) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, snapshotName, snapshot).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='snapshot'> /// Snapshot object supplied in the body of the Put disk operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Snapshot> BeginCreateOrUpdateAsync(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, Snapshot snapshot, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, snapshotName, snapshot, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates (patches) a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='snapshot'> /// Snapshot object supplied in the body of the Patch snapshot operation. /// </param> public static Snapshot BeginUpdate(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, SnapshotUpdate snapshot) { return operations.BeginUpdateAsync(resourceGroupName, snapshotName, snapshot).GetAwaiter().GetResult(); } /// <summary> /// Updates (patches) a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='snapshot'> /// Snapshot object supplied in the body of the Patch snapshot operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Snapshot> BeginUpdateAsync(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, SnapshotUpdate snapshot, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, snapshotName, snapshot, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> public static OperationStatusResponse BeginDelete(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName) { return operations.BeginDeleteAsync(resourceGroupName, snapshotName).GetAwaiter().GetResult(); } /// <summary> /// Deletes a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<OperationStatusResponse> BeginDeleteAsync(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, snapshotName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Grants access to a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='grantAccessData'> /// Access data object supplied in the body of the get snapshot access /// operation. /// </param> public static AccessUri BeginGrantAccess(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, GrantAccessData grantAccessData) { return operations.BeginGrantAccessAsync(resourceGroupName, snapshotName, grantAccessData).GetAwaiter().GetResult(); } /// <summary> /// Grants access to a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='grantAccessData'> /// Access data object supplied in the body of the get snapshot access /// operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<AccessUri> BeginGrantAccessAsync(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, GrantAccessData grantAccessData, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginGrantAccessWithHttpMessagesAsync(resourceGroupName, snapshotName, grantAccessData, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Revokes access to a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> public static OperationStatusResponse BeginRevokeAccess(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName) { return operations.BeginRevokeAccessAsync(resourceGroupName, snapshotName).GetAwaiter().GetResult(); } /// <summary> /// Revokes access to a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<OperationStatusResponse> BeginRevokeAccessAsync(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginRevokeAccessWithHttpMessagesAsync(resourceGroupName, snapshotName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists snapshots under a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<Snapshot> ListByResourceGroupNext(this ISnapshotsOperations operations, string nextPageLink) { return operations.ListByResourceGroupNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Lists snapshots under a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Snapshot>> ListByResourceGroupNextAsync(this ISnapshotsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists snapshots under a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<Snapshot> ListNext(this ISnapshotsOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Lists snapshots under a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Snapshot>> ListNextAsync(this ISnapshotsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// ReSharper disable All using System.Collections.Generic; using System.Dynamic; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Controllers; using Frapid.ApplicationState.Cache; using Frapid.ApplicationState.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Frapid.Config.DataAccess; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Frapid.Framework; using Frapid.Framework.Extensions; using Frapid.WebApi; namespace Frapid.Config.Api { /// <summary> /// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Flags. /// </summary> [RoutePrefix("api/v1.0/config/flag")] public class FlagController : FrapidApiController { /// <summary> /// The Flag repository. /// </summary> private IFlagRepository FlagRepository; public FlagController() { } public FlagController(IFlagRepository repository) { this.FlagRepository = repository; } protected override void Initialize(HttpControllerContext context) { base.Initialize(context); if (this.FlagRepository == null) { this.FlagRepository = new Frapid.Config.DataAccess.Flag { _Catalog = this.MetaUser.Catalog, _LoginId = this.MetaUser.LoginId, _UserId = this.MetaUser.UserId }; } } /// <summary> /// Creates meta information of "flag" entity. /// </summary> /// <returns>Returns the "flag" meta information to perform CRUD operation.</returns> [AcceptVerbs("GET", "HEAD")] [Route("meta")] [Route("~/api/config/flag/meta")] [RestAuthorize] public EntityView GetEntityView() { return new EntityView { PrimaryKey = "flag_id", Columns = new List<EntityColumn>() { new EntityColumn { ColumnName = "flag_id", PropertyName = "FlagId", DataType = "long", DbDataType = "int8", IsNullable = false, IsPrimaryKey = true, IsSerial = true, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "user_id", PropertyName = "UserId", DataType = "int", DbDataType = "int4", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "flag_type_id", PropertyName = "FlagTypeId", DataType = "int", DbDataType = "int4", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "resource", PropertyName = "Resource", DataType = "string", DbDataType = "text", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "resource_key", PropertyName = "ResourceKey", DataType = "string", DbDataType = "text", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "resource_id", PropertyName = "ResourceId", DataType = "string", DbDataType = "text", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "flagged_on", PropertyName = "FlaggedOn", DataType = "DateTime", DbDataType = "timestamptz", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 } } }; } /// <summary> /// Counts the number of flags. /// </summary> /// <returns>Returns the count of the flags.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count")] [Route("~/api/config/flag/count")] [RestAuthorize] public long Count() { try { return this.FlagRepository.Count(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns all collection of flag. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("all")] [Route("~/api/config/flag/all")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.Flag> GetAll() { try { return this.FlagRepository.GetAll(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns collection of flag for export. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("export")] [Route("~/api/config/flag/export")] [RestAuthorize] public IEnumerable<dynamic> Export() { try { return this.FlagRepository.Export(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns an instance of flag. /// </summary> /// <param name="flagId">Enter FlagId to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("{flagId}")] [Route("~/api/config/flag/{flagId}")] [RestAuthorize] public Frapid.Config.Entities.Flag Get(long flagId) { try { return this.FlagRepository.Get(flagId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } [AcceptVerbs("GET", "HEAD")] [Route("get")] [Route("~/api/config/flag/get")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.Flag> Get([FromUri] long[] flagIds) { try { return this.FlagRepository.Get(flagIds); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the first instance of flag. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("first")] [Route("~/api/config/flag/first")] [RestAuthorize] public Frapid.Config.Entities.Flag GetFirst() { try { return this.FlagRepository.GetFirst(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the previous instance of flag. /// </summary> /// <param name="flagId">Enter FlagId to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("previous/{flagId}")] [Route("~/api/config/flag/previous/{flagId}")] [RestAuthorize] public Frapid.Config.Entities.Flag GetPrevious(long flagId) { try { return this.FlagRepository.GetPrevious(flagId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the next instance of flag. /// </summary> /// <param name="flagId">Enter FlagId to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("next/{flagId}")] [Route("~/api/config/flag/next/{flagId}")] [RestAuthorize] public Frapid.Config.Entities.Flag GetNext(long flagId) { try { return this.FlagRepository.GetNext(flagId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the last instance of flag. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("last")] [Route("~/api/config/flag/last")] [RestAuthorize] public Frapid.Config.Entities.Flag GetLast() { try { return this.FlagRepository.GetLast(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a paginated collection containing 10 flags on each page, sorted by the property FlagId. /// </summary> /// <returns>Returns the first page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("")] [Route("~/api/config/flag")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.Flag> GetPaginatedResult() { try { return this.FlagRepository.GetPaginatedResult(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a paginated collection containing 10 flags on each page, sorted by the property FlagId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset.</param> /// <returns>Returns the requested page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("page/{pageNumber}")] [Route("~/api/config/flag/page/{pageNumber}")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.Flag> GetPaginatedResult(long pageNumber) { try { return this.FlagRepository.GetPaginatedResult(pageNumber); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Counts the number of flags using the supplied filter(s). /// </summary> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the count of filtered flags.</returns> [AcceptVerbs("POST")] [Route("count-where")] [Route("~/api/config/flag/count-where")] [RestAuthorize] public long CountWhere([FromBody]JArray filters) { try { List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer()); return this.FlagRepository.CountWhere(f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a filtered and paginated collection containing 10 flags on each page, sorted by the property FlagId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("POST")] [Route("get-where/{pageNumber}")] [Route("~/api/config/flag/get-where/{pageNumber}")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.Flag> GetWhere(long pageNumber, [FromBody]JArray filters) { try { List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer()); return this.FlagRepository.GetWhere(pageNumber, f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Counts the number of flags using the supplied filter name. /// </summary> /// <param name="filterName">The named filter.</param> /// <returns>Returns the count of filtered flags.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count-filtered/{filterName}")] [Route("~/api/config/flag/count-filtered/{filterName}")] [RestAuthorize] public long CountFiltered(string filterName) { try { return this.FlagRepository.CountFiltered(filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a filtered and paginated collection containing 10 flags on each page, sorted by the property FlagId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param> /// <param name="filterName">The named filter.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("GET", "HEAD")] [Route("get-filtered/{pageNumber}/{filterName}")] [Route("~/api/config/flag/get-filtered/{pageNumber}/{filterName}")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.Flag> GetFiltered(long pageNumber, string filterName) { try { return this.FlagRepository.GetFiltered(pageNumber, filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Displayfield is a lightweight key/value collection of flags. /// </summary> /// <returns>Returns an enumerable key/value collection of flags.</returns> [AcceptVerbs("GET", "HEAD")] [Route("display-fields")] [Route("~/api/config/flag/display-fields")] [RestAuthorize] public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields() { try { return this.FlagRepository.GetDisplayFields(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// A custom field is a user defined field for flags. /// </summary> /// <returns>Returns an enumerable custom field collection of flags.</returns> [AcceptVerbs("GET", "HEAD")] [Route("custom-fields")] [Route("~/api/config/flag/custom-fields")] [RestAuthorize] public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields() { try { return this.FlagRepository.GetCustomFields(null); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// A custom field is a user defined field for flags. /// </summary> /// <returns>Returns an enumerable custom field collection of flags.</returns> [AcceptVerbs("GET", "HEAD")] [Route("custom-fields/{resourceId}")] [Route("~/api/config/flag/custom-fields/{resourceId}")] [RestAuthorize] public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId) { try { return this.FlagRepository.GetCustomFields(resourceId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } private List<ExpandoObject> ParseCollection(JArray collection) { return JsonConvert.DeserializeObject<List<ExpandoObject>>(collection.ToString(), JsonHelper.GetJsonSerializerSettings()); } /// <summary> /// Adds or edits multiple instances of Flag class. /// </summary> /// <param name="collection">Your collection of Flag class to bulk import.</param> /// <returns>Returns list of imported flagIds.</returns> /// <exception cref="DataAccessException">Thrown when your any Flag class in the collection is invalid or malformed.</exception> [AcceptVerbs("POST")] [Route("bulk-import")] [Route("~/api/config/flag/bulk-import")] [RestAuthorize] public List<object> BulkImport([FromBody]JArray collection) { List<ExpandoObject> flagCollection = this.ParseCollection(collection); if (flagCollection == null || flagCollection.Count.Equals(0)) { return null; } try { return this.FlagRepository.BulkImport(flagCollection); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Deletes an existing instance of Flag class via FlagId. /// </summary> /// <param name="flagId">Enter the value for FlagId in order to find and delete the existing record.</param> [AcceptVerbs("DELETE")] [Route("delete/{flagId}")] [Route("~/api/config/flag/delete/{flagId}")] [RestAuthorize] public void Delete(long flagId) { try { this.FlagRepository.Delete(flagId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Adds or edits your instance of Flag class. /// </summary> /// <param name="flag">Your instance of flags class to add or edit.</param> [AcceptVerbs("POST")] [Route("add-or-edit")] [Route("~/api/config/flag/add-or-edit")] public object AddOrEdit([FromBody]Newtonsoft.Json.Linq.JArray form) { dynamic flag = form[0].ToObject<ExpandoObject>(JsonHelper.GetJsonSerializer()); List<Frapid.DataAccess.Models.CustomField> customFields = form[1].ToObject<List<Frapid.DataAccess.Models.CustomField>>(JsonHelper.GetJsonSerializer()); if (flag == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { flag.user_id = this.MetaUser.UserId; flag.flagged_on = System.DateTime.UtcNow; return this.FlagRepository.AddOrEdit(flag, customFields); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// Adds your instance of Account class. /// </summary> /// <param name="flag">Your instance of flags class to add.</param> [AcceptVerbs("POST")] [Route("add/{flag}")] [Route("~/api/config/flag/add/{flag}")] public void Add(Frapid.Config.Entities.Flag flag) { if (flag == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { flag.UserId = this.MetaUser.UserId; flag.FlaggedOn = System.DateTime.UtcNow; this.FlagRepository.Add(flag); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// Edits existing record with your instance of Account class. /// </summary> /// <param name="flag">Your instance of Account class to edit.</param> /// <param name="flagId">Enter the value for FlagId in order to find and edit the existing record.</param> [AcceptVerbs("PUT")] [Route("edit/{flagId}")] [Route("~/api/config/flag/edit/{flagId}")] public void Edit(long flagId, [FromBody] Frapid.Config.Entities.Flag flag) { if (flag == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { flag.UserId = this.MetaUser.UserId; flag.FlaggedOn = System.DateTime.UtcNow; this.FlagRepository.Update(flag, flagId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } } }
using Microsoft.Xna.Framework.Graphics; using System; namespace CocosSharp { public class CCLabelTtf : CCSprite, ICCTextContainer { private float m_fFontSize; private CCTextAlignment m_hAlignment; private string m_pFontName; protected string m_pString = String.Empty; private CCSize m_tDimensions; private CCVerticalTextAlignment m_vAlignment; public string FontName { get { return m_pFontName; } set { if (m_pFontName != value) { m_pFontName = value; if (m_pString.Length > 0) { Refresh(); } } } } public float FontSize { get { return m_fFontSize; } set { if (m_fFontSize != value) { m_fFontSize = value; if (m_pString.Length > 0) { Refresh(); } } } } public CCSize Dimensions { get { return m_tDimensions; } set { if (!m_tDimensions.Equals(value)) { m_tDimensions = value; if (m_pString.Length > 0) { Refresh(); } } } } public CCVerticalTextAlignment VerticalAlignment { get { return m_vAlignment; } set { if (m_vAlignment != value) { m_vAlignment = value; if (m_pString.Length > 0) { Refresh(); } } } } public CCTextAlignment HorizontalAlignment { get { return m_hAlignment; } set { if (m_hAlignment != value) { m_hAlignment = value; if (m_pString.Length > 0) { Refresh(); } } } } #region Constructors public CCLabelTtf () : this("", "Helvetica", 12.0f) { } public CCLabelTtf (string text, string fontName, float fontSize) : this (text, fontName, fontSize, CCSize.Zero, CCTextAlignment.Center, CCVerticalTextAlignment.Top) { } public CCLabelTtf (string text, string fontName, float fontSize, CCSize dimensions, CCTextAlignment hAlignment) : this (text, fontName, fontSize, dimensions, hAlignment, CCVerticalTextAlignment.Top) { } public CCLabelTtf (string text, string fontName, float fontSize, CCSize dimensions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment) { InitCCLabelTTF(text, fontName, fontSize, dimensions, hAlignment, vAlignment); } private void InitCCLabelTTF(string text, string fontName, float fontSize, CCSize dimensions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment) { // shader program //this->setShaderProgram(CCShaderCache::sharedShaderCache()->programForKey(SHADER_PROGRAM)); m_tDimensions = new CCSize(dimensions.Width, dimensions.Height); m_hAlignment = hAlignment; m_vAlignment = vAlignment; if (fontName == null) fontName = "arial"; m_pFontName = (!string.IsNullOrEmpty(fontName.Trim())) ? fontName : "arial"; m_fFontSize = fontSize; this.Text = text; } #endregion Constructors internal void Refresh() { // // This can only happen when the frame buffer is ready... // try { updateTexture(); } catch (Exception) { } } #region ICCLabelProtocol Members /* * This is where the texture should be created, but it messes with the drawing * of the object tree * public override void Draw() { if (Dirty) { updateTexture(); Dirty = false; } base.Draw(); } */ public string Text { get { return m_pString; } set { // This is called in the update() call, so it should not do any drawing ... if (m_pString != value) { m_pString = value; updateTexture(); } } } #endregion public override string ToString() { return string.Format("FontName:{0}, FontSize:{1}", m_pFontName, m_fFontSize); } private void updateTexture() { CCTexture2D tex; // Dump the old one if (Texture != null) { Texture.Dispose(); } // let system compute label's width or height when its value is 0 // refer to cocos2d-x issue #1430 tex = new CCTexture2D( m_pString, m_tDimensions, m_hAlignment, m_vAlignment, m_pFontName, m_fFontSize); //#if MACOS || IPHONE || IOS // // There was a problem loading the text for some reason or another if result is not true // // For MonoMac and IOS Applications we will try to create a Native Label automatically // // If the font is not found then a default font will be selected by the device and used. // if (!result && !string.IsNullOrEmpty(m_pString)) // { // tex = CCLabelUtilities.CreateLabelTexture (m_pString, // CCMacros.CCSizePointsToPixels (m_tDimensions), // m_hAlignment, // m_vAlignment, // m_pFontName, // m_fFontSize * CCMacros.CCContentScaleFactor (), // new CCColor4B(Microsoft.Xna.Framework.Color.White) ); // } //#endif Texture = tex; CCRect rect = CCRect.Zero; rect.Size = Texture.ContentSizeInPixels; TextureRectInPixels = rect; if (ContentSize == CCSize.Zero) ContentSize = rect.Size; } } }
using System; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.Security.Cryptography; using System.Text; using System.Xml; using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.ReportAppServer.ClientDoc; using CrystalDecisions.ReportAppServer.Controllers; using CrystalDecisions.Shared; using CRDataDefModel = CrystalDecisions.ReportAppServer.DataDefModel; using CRReportDefModel = CrystalDecisions.ReportAppServer.ReportDefModel; using OpenMcdf; namespace RptToXml { public partial class RptDefinitionWriter : IDisposable { private const FormatTypes ShowFormatTypes = FormatTypes.AreaFormat | FormatTypes.SectionFormat | FormatTypes.Color; private ReportDocument _report; private ISCDReportClientDocument _rcd; private CompoundFile _oleCompoundFile; private readonly bool _createdReport; public RptDefinitionWriter(string filename) { _createdReport = true; _report = new ReportDocument(); _report.Load(filename, OpenReportMethod.OpenReportByTempCopy); _rcd = _report.ReportClientDocument; _oleCompoundFile = new CompoundFile(filename); Trace.WriteLine("Loaded report"); } public RptDefinitionWriter(ReportDocument value) { _report = value; _rcd = _report.ReportClientDocument; } public void WriteToXml(System.IO.Stream output) { using (XmlTextWriter writer = new XmlTextWriter(output, Encoding.UTF8) { Formatting = Formatting.Indented }) { WriteToXml(writer); } } public void WriteToXml(string targetXmlPath) { using (XmlTextWriter writer = new XmlTextWriter(targetXmlPath, Encoding.UTF8) {Formatting = Formatting.Indented }) { WriteToXml(writer); } } public void WriteToXml(XmlWriter writer) { Trace.WriteLine("Writing to XML"); writer.WriteStartDocument(); ProcessReport(_report, writer); writer.WriteEndDocument(); writer.Flush(); } //This is a recursive method. GetSubreports() calls it. private void ProcessReport(ReportDocument report, XmlWriter writer) { writer.WriteStartElement("Report"); writer.WriteAttributeString("Name", report.Name); Trace.WriteLine("Writing report " + report.Name); if (!report.IsSubreport) { Trace.WriteLine("Writing header info"); writer.WriteAttributeString("FileName", report.FileName.Replace("rassdk://", "")); writer.WriteAttributeString("HasSavedData", report.HasSavedData.ToString()); if (_oleCompoundFile != null) { writer.WriteStartElement("Embedinfo"); _oleCompoundFile.RootStorage.VisitEntries(fileItem => { if (fileItem.Name.Contains("Ole")) { writer.WriteStartElement("Embed"); writer.WriteAttributeString("Name", fileItem.Name); var cfStream = fileItem as CFStream; if (cfStream != null) { var streamBytes = cfStream.GetData(); writer.WriteAttributeString("Size", cfStream.Size.ToString("0")); using (var md5Provider = new MD5CryptoServiceProvider()) { byte[] md5Hash = md5Provider.ComputeHash(streamBytes); writer.WriteAttributeString("MD5Hash", Convert.ToBase64String(md5Hash)); } } writer.WriteEndElement(); } }, true); writer.WriteEndElement(); } GetSummaryinfo(report, writer); GetReportOptions(report, writer); GetPrintOptions(report, writer); GetSubreports(report, writer); //recursion happens here. } GetDatabase(report, writer); GetDataDefinition(report, writer); GetReportDefinition(report, writer); writer.WriteEndElement(); } private static void GetSummaryinfo(ReportDocument report, XmlWriter writer) { writer.WriteStartElement("Summaryinfo"); writer.WriteAttributeString("KeywordsinReport", report.SummaryInfo.KeywordsInReport); writer.WriteAttributeString("ReportAuthor", report.SummaryInfo.ReportAuthor); writer.WriteAttributeString("ReportComments", report.SummaryInfo.ReportComments); writer.WriteAttributeString("ReportSubject", report.SummaryInfo.ReportSubject); writer.WriteAttributeString("ReportTitle", report.SummaryInfo.ReportTitle); writer.WriteEndElement(); } private static void GetReportOptions(ReportDocument report, XmlWriter writer) { writer.WriteStartElement("ReportOptions"); writer.WriteAttributeString("EnableSaveDataWithReport", report.ReportOptions.EnableSaveDataWithReport.ToString()); writer.WriteAttributeString("EnableSavePreviewPicture", report.ReportOptions.EnableSavePreviewPicture.ToString()); writer.WriteAttributeString("EnableSaveSummariesWithReport", report.ReportOptions.EnableSaveSummariesWithReport.ToString()); writer.WriteAttributeString("EnableUseDummyData", report.ReportOptions.EnableUseDummyData.ToString()); writer.WriteAttributeString("initialDataContext", report.ReportOptions.InitialDataContext); writer.WriteAttributeString("initialReportPartName", report.ReportOptions.InitialReportPartName); writer.WriteEndElement(); } private void GetPrintOptions(ReportDocument report, XmlWriter writer) { writer.WriteStartElement("PrintOptions"); writer.WriteAttributeString("PageContentHeight", report.PrintOptions.PageContentHeight.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("PageContentWidth", report.PrintOptions.PageContentWidth.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("PaperOrientation", report.PrintOptions.PaperOrientation.ToString()); writer.WriteAttributeString("PaperSize", report.PrintOptions.PaperSize.ToString()); writer.WriteAttributeString("PaperSource", report.PrintOptions.PaperSource.ToString()); writer.WriteAttributeString("PrinterDuplex", report.PrintOptions.PrinterDuplex.ToString()); writer.WriteAttributeString("PrinterName", report.PrintOptions.PrinterName); writer.WriteStartElement("PageMargins"); writer.WriteAttributeString("bottomMargin", report.PrintOptions.PageMargins.bottomMargin.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("leftMargin", report.PrintOptions.PageMargins.leftMargin.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("rightMargin", report.PrintOptions.PageMargins.rightMargin.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("topMargin", report.PrintOptions.PageMargins.topMargin.ToString(CultureInfo.InvariantCulture)); writer.WriteEndElement(); CRReportDefModel.PrintOptions rdmPrintOptions = GetRASRDMPrintOptionsObject(report.Name, report); if (rdmPrintOptions != null) GetPageMarginConditionFormulas(rdmPrintOptions, writer); writer.WriteEndElement(); } private void GetSubreports(ReportDocument report, XmlWriter writer) { writer.WriteStartElement("SubReports"); foreach (ReportDocument subreport in report.Subreports) ProcessReport(subreport, writer); writer.WriteEndElement(); } private void GetDatabase(ReportDocument report, XmlWriter writer) { writer.WriteStartElement("Database"); GetTableLinks(report, writer); if (!report.IsSubreport) { var reportClientDocument = report.ReportClientDocument; GetReportClientTables(reportClientDocument, writer); } else { var subrptClientDoc = _report.ReportClientDocument.SubreportController.GetSubreport(report.Name); GetSubreportClientTables(subrptClientDoc, writer); } writer.WriteEndElement(); } private static void GetTableLinks(ReportDocument report, XmlWriter writer) { writer.WriteStartElement("TableLinks"); foreach (TableLink tl in report.Database.Links) { writer.WriteStartElement("TableLink"); writer.WriteAttributeString("JoinType", tl.JoinType.ToString()); writer.WriteStartElement("SourceFields"); foreach (FieldDefinition fd in tl.SourceFields) GetFieldDefinition(fd, writer); writer.WriteEndElement(); writer.WriteStartElement("DestinationFields"); foreach (FieldDefinition fd in tl.DestinationFields) GetFieldDefinition(fd, writer); writer.WriteEndElement(); writer.WriteEndElement(); } writer.WriteEndElement(); } private void GetReportClientTables(ISCDReportClientDocument reportClientDocument, XmlWriter writer) { writer.WriteStartElement("Tables"); foreach (CrystalDecisions.ReportAppServer.DataDefModel.Table table in reportClientDocument.DatabaseController.Database.Tables) { GetTable(table, writer); } writer.WriteEndElement(); } private void GetSubreportClientTables(SubreportClientDocument subrptClientDocument, XmlWriter writer) { writer.WriteStartElement("Tables"); foreach (CrystalDecisions.ReportAppServer.DataDefModel.Table table in subrptClientDocument.DatabaseController.Database.Tables) { GetTable(table, writer); } writer.WriteEndElement(); } private void GetTable(CrystalDecisions.ReportAppServer.DataDefModel.Table table, XmlWriter writer) { writer.WriteStartElement("Table"); writer.WriteAttributeString("Alias", table.Alias); writer.WriteAttributeString("ClassName", table.ClassName); writer.WriteAttributeString("Name", table.Name); writer.WriteStartElement("ConnectionInfo"); foreach (string propertyId in table.ConnectionInfo.Attributes.PropertyIDs) { // make attribute name safe for XML string attributeName = propertyId.Replace(" ", "_"); writer.WriteAttributeString(attributeName, table.ConnectionInfo.Attributes[propertyId].ToString()); } writer.WriteAttributeString("UserName", table.ConnectionInfo.UserName); writer.WriteAttributeString("Password", table.ConnectionInfo.Password); writer.WriteEndElement(); var commandTable = table as CRDataDefModel.CommandTable; if (commandTable != null) { var cmdTable = commandTable; writer.WriteStartElement("Command"); writer.WriteString(cmdTable.CommandText); writer.WriteEndElement(); } writer.WriteStartElement("Fields"); foreach (CrystalDecisions.ReportAppServer.DataDefModel.Field fd in table.DataFields) { GetFieldDefinition(fd, writer); } writer.WriteEndElement(); writer.WriteEndElement(); } private static void GetFieldDefinition(FieldDefinition fd, XmlWriter writer) { writer.WriteStartElement("Field"); writer.WriteAttributeString("FormulaName", fd.FormulaName); writer.WriteAttributeString("Kind", fd.Kind.ToString()); writer.WriteAttributeString("Name", fd.Name); writer.WriteAttributeString("NumberOfBytes", fd.NumberOfBytes.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("ValueType", fd.ValueType.ToString()); writer.WriteEndElement(); } private static void GetFieldDefinition(CrystalDecisions.ReportAppServer.DataDefModel.Field fd, XmlWriter writer) { writer.WriteStartElement("Field"); writer.WriteAttributeString("Description", fd.Description); writer.WriteAttributeString("FormulaForm", fd.FormulaForm); writer.WriteAttributeString("HeadingText", fd.HeadingText); writer.WriteAttributeString("IsRecurring", fd.IsRecurring.ToString()); writer.WriteAttributeString("Kind", fd.Kind.ToString()); writer.WriteAttributeString("Length", fd.Length.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("LongName", fd.LongName); writer.WriteAttributeString("Name", fd.Name); writer.WriteAttributeString("ShortName", fd.ShortName); writer.WriteAttributeString("Type", fd.Type.ToString()); writer.WriteAttributeString("UseCount", fd.UseCount.ToString(CultureInfo.InvariantCulture)); writer.WriteEndElement(); } private void GetDataDefinition(ReportDocument report, XmlWriter writer) { writer.WriteStartElement("DataDefinition"); writer.WriteElementString("GroupSelectionFormula", report.DataDefinition.GroupSelectionFormula); writer.WriteElementString("RecordSelectionFormula", report.DataDefinition.RecordSelectionFormula); writer.WriteStartElement("Groups"); foreach (Group group in report.DataDefinition.Groups) { writer.WriteStartElement("Group"); writer.WriteAttributeString("ConditionField", group.ConditionField.FormulaName); writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteStartElement("SortFields"); foreach (SortField sortField in report.DataDefinition.SortFields) { writer.WriteStartElement("SortField"); writer.WriteAttributeString("Field", sortField.Field.FormulaName); try { string sortDirection = sortField.SortDirection.ToString(); writer.WriteAttributeString("SortDirection", sortDirection); } catch (NotSupportedException) { } writer.WriteAttributeString("SortType", sortField.SortType.ToString()); writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteStartElement("FormulaFieldDefinitions"); foreach (var field in report.DataDefinition.FormulaFields) GetFieldObject(field, report, writer); writer.WriteEndElement(); writer.WriteStartElement("GroupNameFieldDefinitions"); foreach (var field in report.DataDefinition.GroupNameFields) GetFieldObject(field, report, writer); writer.WriteEndElement(); writer.WriteStartElement("ParameterFieldDefinitions"); foreach (var field in report.DataDefinition.ParameterFields) GetFieldObject(field, report, writer); writer.WriteEndElement(); writer.WriteStartElement("RunningTotalFieldDefinitions"); foreach (var field in report.DataDefinition.RunningTotalFields) GetFieldObject(field, report, writer); writer.WriteEndElement(); writer.WriteStartElement("SQLExpressionFields"); foreach (var field in report.DataDefinition.SQLExpressionFields) GetFieldObject(field, report, writer); writer.WriteEndElement(); writer.WriteStartElement("SummaryFields"); foreach (var field in report.DataDefinition.SummaryFields) GetFieldObject(field, report, writer); writer.WriteEndElement(); writer.WriteEndElement(); } private void GetFieldObject(Object fo, ReportDocument report, XmlWriter writer) { if (fo is DatabaseFieldDefinition) { var df = (DatabaseFieldDefinition)fo; writer.WriteStartElement("DatabaseFieldDefinition"); writer.WriteAttributeString("FormulaName", df.FormulaName); writer.WriteAttributeString("Kind", df.Kind.ToString()); writer.WriteAttributeString("Name", df.Name); writer.WriteAttributeString("NumberOfBytes", df.NumberOfBytes.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("TableName", df.TableName); writer.WriteAttributeString("ValueType", df.ValueType.ToString()); } else if (fo is FormulaFieldDefinition) { var ff = (FormulaFieldDefinition)fo; writer.WriteStartElement("FormulaFieldDefinition"); writer.WriteAttributeString("FormulaName", ff.FormulaName); writer.WriteAttributeString("Kind", ff.Kind.ToString()); writer.WriteAttributeString("Name", ff.Name); writer.WriteAttributeString("NumberOfBytes", ff.NumberOfBytes.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("ValueType", ff.ValueType.ToString()); writer.WriteString(ff.Text); } else if (fo is GroupNameFieldDefinition) { var gnf = (GroupNameFieldDefinition)fo; writer.WriteStartElement("GroupNameFieldDefinition"); writer.WriteAttributeString("FormulaName", gnf.FormulaName); writer.WriteAttributeString("Group", gnf.Group.ToString()); writer.WriteAttributeString("GroupNameFieldName", gnf.GroupNameFieldName); writer.WriteAttributeString("Kind", gnf.Kind.ToString()); writer.WriteAttributeString("Name", gnf.Name); writer.WriteAttributeString("NumberOfBytes", gnf.NumberOfBytes.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("ValueType", gnf.ValueType.ToString()); } else if (fo is ParameterFieldDefinition) { var pf = (ParameterFieldDefinition)fo; // if it is a linked parameter, it is passed into a subreport. Just record the actual linkage in the main report. // The parameter will be reported in full when the subreport is exported. var parameterIsLinked = (!report.IsSubreport && pf.IsLinked()); writer.WriteStartElement("ParameterFieldDefinition"); if (parameterIsLinked) { writer.WriteAttributeString("Name", pf.Name); writer.WriteAttributeString("IsLinkedToSubreport", pf.IsLinked().ToString()); writer.WriteAttributeString("ReportName", pf.ReportName); } else { var ddm_pf = GetRASDDMParameterFieldObject(pf.Name, report); writer.WriteAttributeString("AllowCustomCurrentValues", ddm_pf.AllowCustomCurrentValues.ToString()); writer.WriteAttributeString("EditMask", pf.EditMask); writer.WriteAttributeString("EnableAllowEditingDefaultValue", pf.EnableAllowEditingDefaultValue.ToString()); writer.WriteAttributeString("EnableAllowMultipleValue", pf.EnableAllowMultipleValue.ToString()); writer.WriteAttributeString("EnableNullValue", pf.EnableNullValue.ToString()); writer.WriteAttributeString("FormulaName", pf.FormulaName); writer.WriteAttributeString("HasCurrentValue", pf.HasCurrentValue.ToString()); writer.WriteAttributeString("IsOptionalPrompt", pf.IsOptionalPrompt.ToString()); writer.WriteAttributeString("Kind", pf.Kind.ToString()); //writer.WriteAttributeString("MaximumValue", (string) pf.MaximumValue); //writer.WriteAttributeString("MinimumValue", (string) pf.MinimumValue); writer.WriteAttributeString("Name", pf.Name); writer.WriteAttributeString("NumberOfBytes", pf.NumberOfBytes.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("ParameterFieldName", pf.ParameterFieldName); writer.WriteAttributeString("ParameterFieldUsage", pf.ParameterFieldUsage2.ToString()); writer.WriteAttributeString("ParameterType", pf.ParameterType.ToString()); writer.WriteAttributeString("ParameterValueKind", pf.ParameterValueKind.ToString()); writer.WriteAttributeString("PromptText", pf.PromptText); writer.WriteAttributeString("ReportName", pf.ReportName); writer.WriteAttributeString("ValueType", pf.ValueType.ToString()); writer.WriteStartElement("ParameterDefaultValues"); if (pf.DefaultValues.Count > 0) { foreach (ParameterValue pv in pf.DefaultValues) { writer.WriteStartElement("ParameterDefaultValue"); writer.WriteAttributeString("Description", pv.Description); // TODO: document dynamic parameters if (!pv.IsRange) { ParameterDiscreteValue pdv = (ParameterDiscreteValue)pv; writer.WriteAttributeString("Value", pdv.Value.ToString()); } writer.WriteEndElement(); } } writer.WriteEndElement(); writer.WriteStartElement("ParameterInitialValues"); if (ddm_pf.InitialValues.Count > 0) { foreach (CRDataDefModel.ParameterFieldValue pv in ddm_pf.InitialValues) { writer.WriteStartElement("ParameterInitialValue"); CRDataDefModel.ParameterFieldDiscreteValue pdv = (CRDataDefModel.ParameterFieldDiscreteValue)pv; writer.WriteAttributeString("Value", pdv.Value.ToString()); writer.WriteEndElement(); } } writer.WriteEndElement(); writer.WriteStartElement("ParameterCurrentValues"); if (pf.CurrentValues.Count > 0) { foreach (ParameterValue pv in pf.CurrentValues) { writer.WriteStartElement("ParameterCurrentValue"); writer.WriteAttributeString("Description", pv.Description); // TODO: document dynamic parameters if (!pv.IsRange) { ParameterDiscreteValue pdv = (ParameterDiscreteValue)pv; writer.WriteAttributeString("Value", pdv.Value.ToString()); } writer.WriteEndElement(); } } writer.WriteEndElement(); } } else if (fo is RunningTotalFieldDefinition) { var rtf = (RunningTotalFieldDefinition)fo; writer.WriteStartElement("RunningTotalFieldDefinition"); //writer.WriteAttributeString("EvaluationConditionType", rtf.EvaluationCondition); writer.WriteAttributeString("EvaluationConditionType", rtf.EvaluationConditionType.ToString()); writer.WriteAttributeString("FormulaName", rtf.FormulaName); if (rtf.Group != null) writer.WriteAttributeString("Group", rtf.Group.ToString()); writer.WriteAttributeString("Kind", rtf.Kind.ToString()); writer.WriteAttributeString("Name", rtf.Name); writer.WriteAttributeString("NumberOfBytes", rtf.NumberOfBytes.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("Operation", rtf.Operation.ToString()); writer.WriteAttributeString("OperationParameter", rtf.OperationParameter.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("ResetConditionType", rtf.ResetConditionType.ToString()); if (rtf.SecondarySummarizedField != null) writer.WriteAttributeString("SecondarySummarizedField", rtf.SecondarySummarizedField.FormulaName); writer.WriteAttributeString("SummarizedField", rtf.SummarizedField.FormulaName); writer.WriteAttributeString("ValueType", rtf.ValueType.ToString()); } else if (fo is SpecialVarFieldDefinition) { writer.WriteStartElement("SpecialVarFieldDefinition"); var svf = (SpecialVarFieldDefinition)fo; writer.WriteAttributeString("FormulaName", svf.FormulaName); writer.WriteAttributeString("Kind", svf.Kind.ToString()); writer.WriteAttributeString("Name", svf.Name); writer.WriteAttributeString("NumberOfBytes", svf.NumberOfBytes.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("SpecialVarType", svf.SpecialVarType.ToString()); writer.WriteAttributeString("ValueType", svf.ValueType.ToString()); } else if (fo is SQLExpressionFieldDefinition) { writer.WriteStartElement("SQLExpressionFieldDefinition"); var sef = (SQLExpressionFieldDefinition)fo; writer.WriteAttributeString("FormulaName", sef.FormulaName); writer.WriteAttributeString("Kind", sef.Kind.ToString()); writer.WriteAttributeString("Name", sef.Name); writer.WriteAttributeString("NumberOfBytes", sef.NumberOfBytes.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("Text", sef.Text); writer.WriteAttributeString("ValueType", sef.ValueType.ToString()); } else if (fo is SummaryFieldDefinition) { writer.WriteStartElement("SummaryFieldDefinition"); var sf = (SummaryFieldDefinition)fo; writer.WriteAttributeString("FormulaName", sf.FormulaName); if (sf.Group != null) writer.WriteAttributeString("Group", sf.Group.ToString()); writer.WriteAttributeString("Kind", sf.Kind.ToString()); writer.WriteAttributeString("Name", sf.Name); writer.WriteAttributeString("NumberOfBytes", sf.NumberOfBytes.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("Operation", sf.Operation.ToString()); writer.WriteAttributeString("OperationParameter", sf.OperationParameter.ToString(CultureInfo.InvariantCulture)); if (sf.SecondarySummarizedField != null) writer.WriteAttributeString("SecondarySummarizedField", sf.SecondarySummarizedField.ToString()); writer.WriteAttributeString("SummarizedField", sf.SummarizedField.ToString()); writer.WriteAttributeString("ValueType", sf.ValueType.ToString()); } writer.WriteEndElement(); } private CRDataDefModel.ParameterField GetRASDDMParameterFieldObject(string fieldName, ReportDocument report) { CRDataDefModel.ParameterField rdm; if (report.IsSubreport) { var subrptClientDoc = _report.ReportClientDocument.SubreportController.GetSubreport(report.Name); rdm = subrptClientDoc.DataDefController.DataDefinition.ParameterFields.FindField(fieldName, CRDataDefModel.CrFieldDisplayNameTypeEnum.crFieldDisplayNameName) as CRDataDefModel.ParameterField; } else { rdm = _rcd.DataDefController.DataDefinition.ParameterFields.FindField(fieldName, CRDataDefModel.CrFieldDisplayNameTypeEnum.crFieldDisplayNameName) as CRDataDefModel.ParameterField; } return rdm; } private void GetAreaFormat(Area area, ReportDocument report, XmlWriter writer) { writer.WriteStartElement("AreaFormat"); writer.WriteAttributeString("EnableHideForDrillDown", area.AreaFormat.EnableHideForDrillDown.ToString()); writer.WriteAttributeString("EnableKeepTogether", area.AreaFormat.EnableKeepTogether.ToString()); writer.WriteAttributeString("EnableNewPageAfter", area.AreaFormat.EnableNewPageAfter.ToString()); writer.WriteAttributeString("EnableNewPageBefore", area.AreaFormat.EnableNewPageBefore.ToString()); writer.WriteAttributeString("EnablePrintAtBottomOfPage", area.AreaFormat.EnablePrintAtBottomOfPage.ToString()); writer.WriteAttributeString("EnableResetPageNumberAfter", area.AreaFormat.EnableResetPageNumberAfter.ToString()); writer.WriteAttributeString("EnableSuppress", area.AreaFormat.EnableSuppress.ToString()); if (area.Kind == AreaSectionKind.GroupHeader) { GroupAreaFormat gaf = (GroupAreaFormat)area.AreaFormat; writer.WriteStartElement("GroupAreaFormat"); writer.WriteAttributeString("EnableKeepGroupTogether", gaf.EnableKeepGroupTogether.ToString()); writer.WriteAttributeString("EnableRepeatGroupHeader", gaf.EnableRepeatGroupHeader.ToString()); writer.WriteAttributeString("VisibleGroupNumberPerPage", gaf.VisibleGroupNumberPerPage.ToString()); writer.WriteEndElement(); } writer.WriteEndElement(); } private void GetBorderFormat(ReportObject ro, ReportDocument report, XmlWriter writer) { writer.WriteStartElement("Border"); var border = ro.Border; writer.WriteAttributeString("BottomLineStyle", border.BottomLineStyle.ToString()); writer.WriteAttributeString("HasDropShadow", border.HasDropShadow.ToString()); writer.WriteAttributeString("LeftLineStyle", border.LeftLineStyle.ToString()); writer.WriteAttributeString("RightLineStyle", border.RightLineStyle.ToString()); writer.WriteAttributeString("TopLineStyle", border.TopLineStyle.ToString()); CRReportDefModel.ISCRReportObject rdm_ro = GetRASRDMReportObject(ro.Name, report); if (rdm_ro != null) GetBorderConditionFormulas(rdm_ro, writer); if ((ShowFormatTypes & FormatTypes.Color) == FormatTypes.Color) GetColorFormat(border.BackgroundColor, writer, "BackgroundColor"); if ((ShowFormatTypes & FormatTypes.Color) == FormatTypes.Color) GetColorFormat(border.BorderColor, writer, "BorderColor"); writer.WriteEndElement(); } private static void GetColorFormat(Color color, XmlWriter writer, String elementName = "Color") { writer.WriteStartElement(elementName); writer.WriteAttributeString("Name", color.Name); writer.WriteAttributeString("A", color.A.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("R", color.R.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("G", color.G.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("B", color.B.ToString(CultureInfo.InvariantCulture)); writer.WriteEndElement(); } private void GetFontFormat(Font font, ReportDocument report, XmlWriter writer) { writer.WriteStartElement("Font"); writer.WriteAttributeString("Bold", font.Bold.ToString()); writer.WriteAttributeString("FontFamily", font.FontFamily.Name); writer.WriteAttributeString("GdiCharSet", font.GdiCharSet.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("GdiVerticalFont", font.GdiVerticalFont.ToString()); writer.WriteAttributeString("Height", font.Height.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("IsSystemFont", font.IsSystemFont.ToString()); writer.WriteAttributeString("Italic", font.Italic.ToString()); writer.WriteAttributeString("Name", font.Name); writer.WriteAttributeString("OriginalFontName", font.OriginalFontName); writer.WriteAttributeString("Size", font.Size.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("SizeinPoints", font.SizeInPoints.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("Strikeout", font.Strikeout.ToString()); writer.WriteAttributeString("Style", font.Style.ToString()); writer.WriteAttributeString("SystemFontName", font.SystemFontName); writer.WriteAttributeString("Underline", font.Underline.ToString()); writer.WriteAttributeString("Unit", font.Unit.ToString()); // TODO: not yet implemented //if ((ShowFormatTypes & FormatTypes.Color) == FormatTypes.Color) // GetFontColorConditionFormulas(); writer.WriteEndElement(); } private void GetObjectFormat(ReportObject ro, ReportDocument report, XmlWriter writer) { writer.WriteStartElement("ObjectFormat"); writer.WriteAttributeString("CssClass", ro.ObjectFormat.CssClass); writer.WriteAttributeString("EnableCanGrow", ro.ObjectFormat.EnableCanGrow.ToString()); writer.WriteAttributeString("EnableCloseAtPageBreak", ro.ObjectFormat.EnableCloseAtPageBreak.ToString()); writer.WriteAttributeString("EnableKeepTogether", ro.ObjectFormat.EnableKeepTogether.ToString()); writer.WriteAttributeString("EnableSuppress", ro.ObjectFormat.EnableSuppress.ToString()); writer.WriteAttributeString("HorizontalAlignment", ro.ObjectFormat.HorizontalAlignment.ToString()); writer.WriteEndElement(); } private void GetSectionFormat(Section section, ReportDocument report, XmlWriter writer) { writer.WriteStartElement("SectionFormat"); writer.WriteAttributeString("CssClass", section.SectionFormat.CssClass); writer.WriteAttributeString("EnableKeepTogether", section.SectionFormat.EnableKeepTogether.ToString()); writer.WriteAttributeString("EnableNewPageAfter", section.SectionFormat.EnableNewPageAfter.ToString()); writer.WriteAttributeString("EnableNewPageBefore", section.SectionFormat.EnableNewPageBefore.ToString()); writer.WriteAttributeString("EnablePrintAtBottomOfPage", section.SectionFormat.EnablePrintAtBottomOfPage.ToString()); writer.WriteAttributeString("EnableResetPageNumberAfter", section.SectionFormat.EnableResetPageNumberAfter.ToString()); writer.WriteAttributeString("EnableSuppress", section.SectionFormat.EnableSuppress.ToString()); writer.WriteAttributeString("EnableSuppressIfBlank", section.SectionFormat.EnableSuppressIfBlank.ToString()); writer.WriteAttributeString("EnableUnderlaySection", section.SectionFormat.EnableUnderlaySection.ToString()); CRReportDefModel.Section rdm_ro = GetRASRDMSectionObjectFromCRENGSectionObject(section.Name, report); if (rdm_ro != null) GetSectionAreaFormatConditionFormulas(rdm_ro, writer); if ((ShowFormatTypes & FormatTypes.Color) == FormatTypes.Color) GetColorFormat(section.SectionFormat.BackgroundColor, writer, "BackgroundColor"); writer.WriteEndElement(); } private void GetReportDefinition(ReportDocument report, XmlWriter writer) { writer.WriteStartElement("ReportDefinition"); GetAreas(report, writer); writer.WriteEndElement(); } private void GetAreas(ReportDocument report, XmlWriter writer) { writer.WriteStartElement("Areas"); foreach (Area area in report.ReportDefinition.Areas) { writer.WriteStartElement("Area"); writer.WriteAttributeString("Kind", area.Kind.ToString()); writer.WriteAttributeString("Name", area.Name); if ((ShowFormatTypes & FormatTypes.AreaFormat) == FormatTypes.AreaFormat) GetAreaFormat(area, report, writer); GetSections(area, report, writer); writer.WriteEndElement(); } writer.WriteEndElement(); } private void GetSections(Area area, ReportDocument report, XmlWriter writer) { writer.WriteStartElement("Sections"); foreach (Section section in area.Sections) { writer.WriteStartElement("Section"); writer.WriteAttributeString("Height", section.Height.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("Kind", section.Kind.ToString()); writer.WriteAttributeString("Name", section.Name); if ((ShowFormatTypes & FormatTypes.SectionFormat) == FormatTypes.SectionFormat) GetSectionFormat(section, report, writer); GetReportObjects(section, report, writer); writer.WriteEndElement(); } writer.WriteEndElement(); } private void GetReportObjects(Section section, ReportDocument report, XmlWriter writer) { writer.WriteStartElement("ReportObjects"); foreach (ReportObject reportObject in section.ReportObjects) { writer.WriteStartElement(reportObject.GetType().Name); CRReportDefModel.ISCRReportObject rasrdm_ro = GetRASRDMReportObject(reportObject.Name, report); writer.WriteAttributeString("Name", reportObject.Name); writer.WriteAttributeString("Kind", reportObject.Kind.ToString()); writer.WriteAttributeString("Top", reportObject.Top.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("Left", reportObject.Left.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("Width", reportObject.Width.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("Height", reportObject.Height.ToString(CultureInfo.InvariantCulture)); if (reportObject is BoxObject) { var bo = (BoxObject)reportObject; writer.WriteAttributeString("Bottom", bo.Bottom.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("EnableExtendToBottomOfSection", bo.EnableExtendToBottomOfSection.ToString()); writer.WriteAttributeString("EndSectionName", bo.EndSectionName); writer.WriteAttributeString("LineStyle", bo.LineStyle.ToString()); writer.WriteAttributeString("LineThickness", bo.LineThickness.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("Right", bo.Right.ToString(CultureInfo.InvariantCulture)); if ((ShowFormatTypes & FormatTypes.Color) == FormatTypes.Color) GetColorFormat(bo.LineColor, writer, "LineColor"); } else if (reportObject is DrawingObject) { var dobj = (DrawingObject)reportObject; writer.WriteAttributeString("Bottom", dobj.Bottom.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("EnableExtendToBottomOfSection", dobj.EnableExtendToBottomOfSection.ToString()); writer.WriteAttributeString("EndSectionName", dobj.EndSectionName); writer.WriteAttributeString("LineStyle", dobj.LineStyle.ToString()); writer.WriteAttributeString("LineThickness", dobj.LineThickness.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("Right", dobj.Right.ToString(CultureInfo.InvariantCulture)); if ((ShowFormatTypes & FormatTypes.Color) == FormatTypes.Color) GetColorFormat(dobj.LineColor, writer, "LineColor"); } else if (reportObject is FieldHeadingObject) { var fh = (FieldHeadingObject)reportObject; var rasrdm_fh = (CRReportDefModel.FieldHeadingObject)rasrdm_ro; writer.WriteAttributeString("FieldObjectName", fh.FieldObjectName); writer.WriteAttributeString("MaxNumberOfLines", rasrdm_fh.MaxNumberOfLines.ToString()); writer.WriteElementString("Text", fh.Text); } else if (reportObject is FieldObject) { var fo = (FieldObject)reportObject; if (fo.DataSource != null) writer.WriteAttributeString("DataSource", fo.DataSource.FormulaName); if ((ShowFormatTypes & FormatTypes.Color) == FormatTypes.Color) GetColorFormat(fo.Color, writer); if ((ShowFormatTypes & FormatTypes.Font) == FormatTypes.Font) GetFontFormat(fo.Font, report, writer); } else if (reportObject is TextObject) { var tobj = (TextObject)reportObject; var rasrdm_tobj = (CRReportDefModel.TextObject)rasrdm_ro; writer.WriteAttributeString("MaxNumberOfLines", rasrdm_tobj.MaxNumberOfLines.ToString()); writer.WriteElementString("Text", tobj.Text); if ((ShowFormatTypes & FormatTypes.Color) == FormatTypes.Color) GetColorFormat(tobj.Color, writer); if ((ShowFormatTypes & FormatTypes.Font) == FormatTypes.Font) GetFontFormat(tobj.Font, report, writer); } if ((ShowFormatTypes & FormatTypes.Border) == FormatTypes.Border) GetBorderFormat(reportObject, report, writer); if ((ShowFormatTypes & FormatTypes.ObjectFormat) == FormatTypes.ObjectFormat) GetObjectFormat(reportObject, report, writer); if (rasrdm_ro != null) GetObjectFormatConditionFormulas(rasrdm_ro, writer); writer.WriteEndElement(); } writer.WriteEndElement(); } // pretty much straight from api docs private CommonFieldFormat GetCommonFieldFormat(string reportObjectName, ReportDocument report) { FieldObject field = report.ReportDefinition.ReportObjects[reportObjectName] as FieldObject; if (field != null) { return field.FieldFormat.CommonFormat; } return null; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { if (_report != null && _createdReport) _report.Dispose(); _report = null; _rcd = null; if (_oleCompoundFile != null) { ((IDisposable)_oleCompoundFile).Dispose(); _oleCompoundFile = null; } } } } }
// Copyright 2016, 2015, 2014 Matthias Koch // // 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.Globalization; using System.Linq; using System.Text; // ReSharper disable All namespace TestFx.Console.TeamCity { /// <summary> /// Writes specially formatted service messages for TeamCity. /// These messages are interpreted by TeamCity to perform some task. /// See also: http://www.jetbrains.net/confluence/display/TCD3/Build+Script+Interaction+with+TeamCity /// </summary> internal class TeamCityServiceMessageWriter { private readonly Action<string> writer; public TeamCityServiceMessageWriter (Action<string> writer) { if (writer == null) throw new ArgumentNullException("writer"); this.writer = writer; } public void WriteProgressMessage (string message) { if (message == null) throw new ArgumentNullException("message"); WriteMessage( builder => { builder.Append("progressMessage '"); AppendEscapedString(builder, message); builder.Append('\''); }); } public void WriteProgressStart (string message) { if (message == null) throw new ArgumentNullException("message"); WriteMessage( builder => { builder.Append("progressStart '"); AppendEscapedString(builder, message); builder.Append('\''); }); } public void WriteProgressFinish (string message) { if (message == null) throw new ArgumentNullException("message"); WriteMessage( builder => { builder.Append("progressFinish '"); AppendEscapedString(builder, message); builder.Append('\''); }); } public void WriteTestSuiteStarted (string name) { if (name == null) throw new ArgumentNullException("name"); WriteMessage( builder => { builder.Append("testSuiteStarted name='"); AppendEscapedString(builder, name); builder.Append('\''); }); } public void WriteTestSuiteFinished (string name) { if (name == null) throw new ArgumentNullException("name"); WriteMessage( builder => { builder.Append("testSuiteFinished name='"); AppendEscapedString(builder, name); builder.Append('\''); }); } public void WriteTestStarted (string name, bool captureStandardOutput) { if (name == null) throw new ArgumentNullException("name"); WriteMessage( builder => { builder.Append("testStarted name='"); AppendEscapedString(builder, name); builder.Append("' captureStandardOutput='"); AppendEscapedString(builder, captureStandardOutput ? @"true" : @"false"); builder.Append('\''); }); } public void WriteTestFinished (string name, TimeSpan duration) { if (name == null) throw new ArgumentNullException("name"); WriteMessage( builder => { builder.Append("testFinished name='"); AppendEscapedString(builder, name); builder.Append("' duration='"); builder.Append(((int) duration.TotalMilliseconds).ToString(CultureInfo.InvariantCulture)); builder.Append('\''); }); } public void WriteTestIgnored (string name, string message) { if (name == null) throw new ArgumentNullException("name"); if (message == null) throw new ArgumentNullException("message"); WriteMessage( builder => { builder.Append("testIgnored name='"); AppendEscapedString(builder, name); builder.Append("' message='"); AppendEscapedString(builder, message); builder.Append('\''); }); } public void WriteTestStdOut (string name, string text) { if (name == null) throw new ArgumentNullException("name"); if (text == null) throw new ArgumentNullException("text"); WriteMessage( builder => { builder.Append("testStdOut name='"); AppendEscapedString(builder, name); builder.Append("' out='"); AppendEscapedString(builder, text); builder.Append('\''); }); } public void WriteTestStdErr (string name, string text) { if (name == null) throw new ArgumentNullException("name"); if (text == null) throw new ArgumentNullException("text"); WriteMessage( builder => { builder.Append("testStdErr name='"); AppendEscapedString(builder, name); builder.Append("' out='"); AppendEscapedString(builder, text); builder.Append('\''); }); } public void WriteTestFailed (string name, string message, string details) { if (name == null) throw new ArgumentNullException("name"); if (message == null) throw new ArgumentNullException("message"); if (details == null) throw new ArgumentNullException("details"); WriteMessage( builder => { builder.Append("testFailed name='"); AppendEscapedString(builder, name); builder.Append("' message='"); AppendEscapedString(builder, message); builder.Append("' details='"); AppendEscapedString(builder, details); builder.Append('\''); }); } public void WriteTestFailedWithComparisonFailure (string name, string message, string details, string expected, string actual) { if (name == null) throw new ArgumentNullException("name"); if (message == null) throw new ArgumentNullException("message"); if (details == null) throw new ArgumentNullException("details"); if (expected == null) throw new ArgumentNullException("expected"); if (actual == null) throw new ArgumentNullException("actual"); WriteMessage( builder => { builder.Append("testFailed name='"); AppendEscapedString(builder, name); builder.Append("' type='comparisonFailure' message='"); AppendEscapedString(builder, message); builder.Append("' details='"); AppendEscapedString(builder, details); builder.Append("' expected='"); AppendEscapedString(builder, expected); builder.Append("' actual='"); AppendEscapedString(builder, actual); builder.Append('\''); }); } public void WriteError (string message, string details) { WriteMessage( builder => { builder.Append("message test='"); AppendEscapedString(builder, message); builder.Append("' errorDetails='"); AppendEscapedString(builder, details); builder.Append("' status='ERROR'"); }); } private void WriteMessage (Action<StringBuilder> formatter) { var builder = new StringBuilder(); builder.Append("##teamcity["); formatter(builder); builder.Append(']'); writer(builder.ToString()); } private static void AppendEscapedString (StringBuilder builder, string rawString) { if (rawString == null) return; foreach (var c in rawString) { switch (c) { case '\n': builder.Append("|n"); break; case '\'': builder.Append("|'"); break; case '\r': builder.Append("|r"); break; case '|': builder.Append("||"); break; case ']': builder.Append("|]"); break; case '\u0085': // \u0085 (next line) => |x builder.Append("|x"); break; case '\u2028': // \u2028 (line separator) => |l builder.Append("|l"); break; case '\u2029': builder.Append("|p"); break; default: builder.Append(c); break; } } } } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010-2015 FUJIWARA, Yusuke // // 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 -- License Terms -- using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Globalization; using System.Reflection; using MsgPack.Serialization.AbstractSerializers; namespace MsgPack.Serialization.EmittingSerializers { /// <summary> /// Implements common features for IL emitter based serializer builders. /// </summary> /// <typeparam name="TContext">The type of the code generation context.</typeparam> /// <typeparam name="TObject">The type of the serialization target object.</typeparam> internal abstract class ILEmittingSerializerBuilder<TContext, TObject> : SerializerBuilder<TContext, ILConstruct, TObject> where TContext : ILEmittingContext { /// <summary> /// Initializes a new instance of the <see cref="ILEmittingSerializerBuilder{TContext, TObject}"/> class. /// </summary> protected ILEmittingSerializerBuilder() { } protected override void EmitMethodPrologue( TContext context, SerializerMethod method ) { switch ( method ) { case SerializerMethod.PackToCore: { context.IL = context.Emitter.GetPackToMethodILGenerator(); break; } case SerializerMethod.UnpackFromCore: { context.IL = context.Emitter.GetUnpackFromMethodILGenerator(); break; } case SerializerMethod.UnpackToCore: { context.IL = context.Emitter.GetUnpackToMethodILGenerator(); break; } default: { throw new ArgumentOutOfRangeException( "method", method.ToString() ); } } } protected override void EmitMethodPrologue( TContext context, EnumSerializerMethod method ) { switch ( method ) { case EnumSerializerMethod.PackUnderlyingValueTo: { context.IL = context.EnumEmitter.GetPackUnderyingValueToMethodILGenerator(); break; } case EnumSerializerMethod.UnpackFromUnderlyingValue: { context.IL = context.EnumEmitter.GetUnpackFromUnderlyingValueMethodILGenerator(); break; } default: { throw new ArgumentOutOfRangeException( "method", method.ToString() ); } } } protected override void EmitMethodPrologue( TContext context, CollectionSerializerMethod method, MethodInfo declaration ) { switch ( method ) { case CollectionSerializerMethod.AddItem: { context.IL = context.Emitter.GetAddItemMethodILGenerator( declaration ); break; } case CollectionSerializerMethod.CreateInstance: { context.IL = context.Emitter.GetCreateInstanceMethodILGenerator( declaration ); break; } case CollectionSerializerMethod.RestoreSchema: { context.IL = context.Emitter.GetRestoreSchemaMethodILGenerator(); break; } default: { throw new ArgumentOutOfRangeException( "method", method.ToString() ); } } } protected override void EmitMethodEpilogue( TContext context, SerializerMethod method, ILConstruct construct ) { EmitMethodEpilogue( context, construct ); } protected override void EmitMethodEpilogue( TContext context, EnumSerializerMethod method, ILConstruct construct ) { EmitMethodEpilogue( context, construct ); } protected override void EmitMethodEpilogue( TContext context, CollectionSerializerMethod method, ILConstruct construct ) { EmitMethodEpilogue( context, construct ); } private static void EmitMethodEpilogue( TContext context, ILConstruct construct ) { try { if ( construct != null ) { construct.Evaluate( context.IL ); } context.IL.EmitRet(); } finally { context.IL.FlushTrace(); SerializerDebugging.FlushTraceData(); } } protected override ILConstruct EmitSequentialStatements( TContext context, Type contextType, IEnumerable<ILConstruct> statements ) { return ILConstruct.Sequence( contextType, statements ); } protected override ILConstruct MakeNullLiteral( TContext context, Type contextType ) { return ILConstruct.Literal( contextType, default( object ), il => il.EmitLdnull() ); } protected override ILConstruct MakeByteLiteral( TContext context, byte constant ) { return MakeIntegerLiteral( typeof( byte ), constant ); } protected override ILConstruct MakeSByteLiteral( TContext context, sbyte constant ) { return MakeIntegerLiteral( typeof( sbyte ), constant ); } protected override ILConstruct MakeInt16Literal( TContext context, short constant ) { return MakeIntegerLiteral( typeof( short ), constant ); } protected override ILConstruct MakeUInt16Literal( TContext context, ushort constant ) { return MakeIntegerLiteral( typeof( ushort ), constant ); } protected override ILConstruct MakeInt32Literal( TContext context, int constant ) { return MakeIntegerLiteral( typeof( int ), constant ); } protected override ILConstruct MakeUInt32Literal( TContext context, uint constant ) { return MakeIntegerLiteral( typeof( uint ), unchecked( ( int )constant ) ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Many case switch" )] private static ILConstruct MakeIntegerLiteral( Type contextType, int constant ) { switch ( constant ) { case 0: { return ILConstruct.Literal( contextType, constant, il => il.EmitLdc_I4_0() ); } case 1: { return ILConstruct.Literal( contextType, constant, il => il.EmitLdc_I4_1() ); } case 2: { return ILConstruct.Literal( contextType, constant, il => il.EmitLdc_I4_2() ); } case 3: { return ILConstruct.Literal( contextType, constant, il => il.EmitLdc_I4_3() ); } case 4: { return ILConstruct.Literal( contextType, constant, il => il.EmitLdc_I4_4() ); } case 5: { return ILConstruct.Literal( contextType, constant, il => il.EmitLdc_I4_5() ); } case 6: { return ILConstruct.Literal( contextType, constant, il => il.EmitLdc_I4_6() ); } case 7: { return ILConstruct.Literal( contextType, constant, il => il.EmitLdc_I4_7() ); } case 8: { return ILConstruct.Literal( contextType, constant, il => il.EmitLdc_I4_8() ); } case -1: { return ILConstruct.Literal( contextType, constant, il => il.EmitLdc_I4_M1() ); } default: { if ( SByte.MinValue <= constant && constant <= SByte.MaxValue ) { return ILConstruct.Literal( contextType, constant, il => il.EmitLdc_I4_S( unchecked( ( byte )constant ) ) ); } else { return ILConstruct.Literal( contextType, constant, il => il.EmitLdc_I4( constant ) ); } } } } protected override ILConstruct MakeInt64Literal( TContext context, long constant ) { return ILConstruct.Literal( typeof( long ), constant, il => il.EmitLdc_I8( constant ) ); } protected override ILConstruct MakeUInt64Literal( TContext context, ulong constant ) { return ILConstruct.Literal( typeof( ulong ), constant, il => il.EmitLdc_I8( unchecked( ( long )constant ) ) ); } protected override ILConstruct MakeReal32Literal( TContext context, float constant ) { return ILConstruct.Literal( typeof( float ), constant, il => il.EmitLdc_R4( constant ) ); } protected override ILConstruct MakeReal64Literal( TContext context, double constant ) { return ILConstruct.Literal( typeof( double ), constant, il => il.EmitLdc_R8( constant ) ); } protected override ILConstruct MakeBooleanLiteral( TContext context, bool constant ) { return MakeIntegerLiteral( typeof( bool ), constant ? 1 : 0 ); } protected override ILConstruct MakeCharLiteral( TContext context, char constant ) { return MakeIntegerLiteral( typeof( char ), constant ); } protected override ILConstruct MakeStringLiteral( TContext context, string constant ) { return ILConstruct.Literal( typeof( string ), constant, il => il.EmitLdstr( constant ) ); } protected override ILConstruct MakeEnumLiteral( TContext context, Type type, object constant ) { var underyingType = Enum.GetUnderlyingType( type ); switch ( Type.GetTypeCode( underyingType ) ) { case TypeCode.Byte: { // tiny integrals are represented as int32 in IL operands. return this.MakeInt32Literal( context, ( byte )constant ); } case TypeCode.SByte: { // tiny integrals are represented as int32 in IL operands. return this.MakeInt32Literal( context, ( sbyte )constant ); } case TypeCode.Int16: { // tiny integrals are represented as int32 in IL operands. return this.MakeInt32Literal( context, ( short )constant ); } case TypeCode.UInt16: { // tiny integrals are represented as int32 in IL operands. return this.MakeInt32Literal( context, ( ushort )constant ); } case TypeCode.Int32: { return this.MakeInt32Literal( context, ( int )constant ); } case TypeCode.UInt32: { // signeds and unsigneds are identical in IL operands. return this.MakeInt32Literal( context, unchecked( ( int )( uint )constant ) ); } case TypeCode.Int64: { return this.MakeInt64Literal( context, ( long )constant ); } case TypeCode.UInt64: { // signeds and unsigneds are identical in IL operands. return this.MakeInt64Literal( context, unchecked( ( long )( ulong )constant ) ); } default: { // bool and char are not supported. // Of course these are very rare, and bool is not supported in ExpressionTree (it hurts portability), // and char is not supported by MsgPack protocol itself. throw new NotSupportedException( String.Format( CultureInfo.CurrentCulture, "Underying type '{0}' is not supported.", underyingType ) ); } } } protected override ILConstruct MakeDefaultLiteral( TContext context, Type type ) { return ILConstruct.Literal( type, "default(" + type + ")", il => { var temp = il.DeclareLocal( type ); il.EmitAnyLdloca( temp ); il.EmitInitobj( type ); il.EmitAnyLdloc( temp ); } ); } protected override ILConstruct EmitThisReferenceExpression( TContext context ) { return ILConstruct.Literal( context.GetSerializerType( typeof( TObject ) ), "(this)", il => il.EmitLdarg_0() ); } protected override ILConstruct EmitBoxExpression( TContext context, Type valueType, ILConstruct value ) { return ILConstruct.UnaryOperator( "box", value, ( il, val ) => { val.LoadValue( il, false ); il.EmitBox( valueType ); } ); } protected override ILConstruct EmitUnboxAnyExpression( TContext context, Type targetType, ILConstruct value ) { return ILConstruct.UnaryOperator( "unbox.any", value, ( il, val ) => { val.LoadValue( il, false ); il.EmitUnbox_Any( targetType ); } ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] protected override ILConstruct EmitNotExpression( TContext context, ILConstruct booleanExpression ) { if ( booleanExpression.ContextType != typeof( bool ) ) { throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, "Not expression must be Boolean elementType, but actual is '{0}'.", booleanExpression.ContextType ), "booleanExpression" ); } return ILConstruct.UnaryOperator( "!", booleanExpression, ( il, val ) => { val.LoadValue( il, false ); il.EmitLdc_I4_0(); il.EmitCeq(); }, ( il, val, @else ) => { val.LoadValue( il, false ); il.EmitBrtrue( @else ); } ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] protected override ILConstruct EmitEqualsExpression( TContext context, ILConstruct left, ILConstruct right ) { var equality = left.ContextType.GetMethod( "op_Equality" ); return ILConstruct.BinaryOperator( "==", typeof( bool ), left, right, ( il, l, r ) => { l.LoadValue( il, false ); r.LoadValue( il, false ); if ( equality == null ) { il.EmitCeq(); } else { il.EmitAnyCall( equality ); } }, ( il, l, r, @else ) => { l.LoadValue( il, false ); r.LoadValue( il, false ); if ( equality == null ) { il.EmitCeq(); } else { il.EmitAnyCall( equality ); } il.EmitBrfalse( @else ); } ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] protected override ILConstruct EmitGreaterThanExpression( TContext context, ILConstruct left, ILConstruct right ) { #if DEBUG Contract.Assert( left.ContextType.IsPrimitive && left.ContextType != typeof( string ) ); #endif var greaterThan = left.ContextType.GetMethod( "op_GreaterThan" ); return ILConstruct.BinaryOperator( ">", typeof( bool ), left, right, ( il, l, r ) => { l.LoadValue( il, false ); r.LoadValue( il, false ); if ( greaterThan == null ) { il.EmitCgt(); } else { il.EmitAnyCall( greaterThan ); } }, ( il, l, r, @else ) => { l.LoadValue( il, false ); r.LoadValue( il, false ); if ( greaterThan == null ) { il.EmitCgt(); } else { il.EmitAnyCall( greaterThan ); } il.EmitBrfalse( @else ); } ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] protected override ILConstruct EmitLessThanExpression( TContext context, ILConstruct left, ILConstruct right ) { #if DEBUG Contract.Assert( left.ContextType.IsPrimitive && left.ContextType != typeof( string ) ); #endif var lessThan = left.ContextType.GetMethod( "op_LessThan" ); return ILConstruct.BinaryOperator( "<", typeof( bool ), left, right, ( il, l, r ) => { l.LoadValue( il, false ); r.LoadValue( il, false ); if ( lessThan == null ) { il.EmitClt(); } else { il.EmitAnyCall( lessThan ); } }, ( il, l, r, @else ) => { l.LoadValue( il, false ); r.LoadValue( il, false ); if ( lessThan == null ) { il.EmitClt(); } else { il.EmitAnyCall( lessThan ); } il.EmitBrfalse( @else ); } ); } protected override ILConstruct EmitIncrement( TContext context, ILConstruct int32Value ) { return ILConstruct.UnaryOperator( "++", int32Value, ( il, variable ) => { variable.LoadValue( il, false ); il.EmitLdc_I4_1(); il.EmitAdd(); variable.StoreValue( il ); } ); } protected override ILConstruct EmitTypeOfExpression( TContext context, Type type ) { return ILConstruct.Literal( typeof( Type ), type, il => il.EmitTypeOf( type ) ); } protected override ILConstruct EmitMethodOfExpression( TContext context, MethodBase method ) { return ILConstruct.Literal( typeof( MethodInfo ), method, il => { il.EmitLdtoken( method ); il.EmitLdtoken( method.DeclaringType ); il.EmitCall( Metadata._MethodBase.GetMethodFromHandle ); } ); } protected override ILConstruct EmitFieldOfExpression( TContext context, FieldInfo field ) { return ILConstruct.Literal( typeof( MethodInfo ), field, il => { il.EmitLdtoken( field ); il.EmitLdtoken( field.DeclaringType ); il.EmitCall( Metadata._FieldInfo.GetFieldFromHandle ); } ); } protected override ILConstruct DeclareLocal( TContext context, Type type, string name ) { return ILConstruct.Variable( type, name ); } protected override ILConstruct ReferArgument( TContext context, Type type, string name, int index ) { return ILConstruct.Argument( index, type, name ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] protected override ILConstruct EmitInvokeVoidMethod( TContext context, ILConstruct instance, MethodInfo method, params ILConstruct[] arguments ) { return method.ReturnType == typeof( void ) ? ILConstruct.Invoke( instance, method, arguments ) : ILConstruct.Sequence( typeof( void ), new[] { ILConstruct.Invoke( instance, method, arguments ), ILConstruct.Instruction( "pop", typeof( void ), false, il => il.EmitPop() ) } ); } protected override ILConstruct EmitCreateNewObjectExpression( TContext context, ILConstruct variable, ConstructorInfo constructor, params ILConstruct[] arguments ) { return ILConstruct.NewObject( variable, constructor, arguments ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "3", Justification = "Asserted internally" )] protected override ILConstruct EmitCreateNewArrayExpression( TContext context, Type elementType, int length ) { var array = ILConstruct.Variable( elementType.MakeArrayType(), "array" ); return ILConstruct.Composite( ILConstruct.Sequence( array.ContextType, new[] { array, ILConstruct.Instruction( "NewArray", array.ContextType, false, il => { il.EmitNewarr( elementType, length ); array.StoreValue( il ); } ) } ), array ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "3", Justification = "Asserted internally" )] protected override ILConstruct EmitCreateNewArrayExpression( TContext context, Type elementType, int length, IEnumerable<ILConstruct> initialElements ) { var array = ILConstruct.Variable( elementType.MakeArrayType(), "array" ); return ILConstruct.Composite( ILConstruct.Sequence( array.ContextType, new[] { array, ILConstruct.Instruction( "CreateArray", array.ContextType, false, il => { il.EmitNewarr( elementType, length ); array.StoreValue( il ); var index = 0; foreach ( var initialElement in initialElements ) { array.LoadValue( il, false ); this.MakeInt32Literal( context, index ).LoadValue( il, false ); initialElement.LoadValue( il, false ); il.EmitStelem( elementType ); index++; } } ) } ), array ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] protected override ILConstruct EmitSetArrayElementStatement( TContext context, ILConstruct array, ILConstruct index, ILConstruct value ) { return ILConstruct.Instruction( "SetArrayElement", array.ContextType, false, il => { il.EmitAnyStelem( value.ContextType, il0 => { array.LoadValue( il0, false ); }, il0 => { index.LoadValue( il0, false ); }, il0 => { value.LoadValue( il0, true ); } ); } ); } protected override ILConstruct EmitInvokeMethodExpression( TContext context, ILConstruct instance, MethodInfo method, IEnumerable<ILConstruct> arguments ) { return ILConstruct.Invoke( instance, method, arguments ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] protected override ILConstruct EmitGetPropertyExpression( TContext context, ILConstruct instance, PropertyInfo property ) { return ILConstruct.Invoke( instance, property.GetGetMethod( true ), ILConstruct.NoArguments ); } protected override ILConstruct EmitGetFieldExpression( TContext context, ILConstruct instance, FieldInfo field ) { return ILConstruct.LoadField( instance, field ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] protected override ILConstruct EmitSetProperty( TContext context, ILConstruct instance, PropertyInfo property, ILConstruct value ) { #if DEBUG // ReSharper disable PossibleNullReferenceException Contract.Assert( property.GetSetMethod( true ) != null, property.DeclaringType.FullName + "::" + property.Name + ".set != null" ); // ReSharper restore PossibleNullReferenceException #endif return ILConstruct.Invoke( instance, property.GetSetMethod( true ), new[] { value } ); } protected override ILConstruct EmitSetField( TContext context, ILConstruct instance, FieldInfo field, ILConstruct value ) { return ILConstruct.StoreField( instance, field, value ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] protected override ILConstruct EmitLoadVariableExpression( TContext context, ILConstruct variable ) { return ILConstruct.Instruction( "load", variable.ContextType, false, il => variable.LoadValue( il, false ) ); } protected override ILConstruct EmitStoreVariableStatement( TContext context, ILConstruct variable, ILConstruct value ) { return ILConstruct.StoreLocal( variable, value ); } protected override ILConstruct EmitThrowExpression( TContext context, Type expressionType, ILConstruct exceptionExpression ) { return ILConstruct.Instruction( "throw", expressionType, true, il => { exceptionExpression.LoadValue( il, false ); il.EmitThrow(); } ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] protected override ILConstruct EmitTryFinally( TContext context, ILConstruct tryStatement, ILConstruct finallyStatement ) { return ILConstruct.Instruction( "try-finally", tryStatement.ContextType, false, il => { il.BeginExceptionBlock(); tryStatement.Evaluate( il ); il.BeginFinallyBlock(); finallyStatement.Evaluate( il ); il.EndExceptionBlock(); } ); } protected override ILConstruct EmitConditionalExpression( TContext context, ILConstruct conditionExpression, ILConstruct thenExpression, ILConstruct elseExpression ) { return ILConstruct.IfThenElse( conditionExpression, thenExpression, elseExpression ); } protected override ILConstruct EmitAndConditionalExpression( TContext context, IList<ILConstruct> conditionExpressions, ILConstruct thenExpression, ILConstruct elseExpression ) { return ILConstruct.IfThenElse( ILConstruct.AndCondition( conditionExpressions ), thenExpression, elseExpression ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] protected override ILConstruct EmitStringSwitchStatement( TContext context, ILConstruct target, IDictionary<string, ILConstruct> cases, ILConstruct defaultCase ) { // Simple if statements ILConstruct @else = defaultCase; foreach ( var @case in cases ) { @else = this.EmitConditionalExpression( context, this.EmitInvokeMethodExpression( context, null, Metadata._String.op_Equality, target, this.MakeStringLiteral( context, @case.Key ) ), @case.Value, @else ); } return @else; } protected override ILConstruct EmitForLoop( TContext context, ILConstruct count, Func<ForLoopContext, ILConstruct> loopBodyEmitter ) { var i = this.DeclareLocal( context, typeof( int ), "i" ); var loopContext = new ForLoopContext( i ); return this.EmitSequentialStatements( context, i.ContextType, i, ILConstruct.Instruction( "for", typeof( void ), false, il => { var forCond = il.DefineLabel( "FOR_COND" ); il.EmitBr( forCond ); var body = il.DefineLabel( "BODY" ); il.MarkLabel( body ); loopBodyEmitter( loopContext ).Evaluate( il ); // increment i.LoadValue( il, false ); il.EmitLdc_I4_1(); il.EmitAdd(); i.StoreValue( il ); // cond il.MarkLabel( forCond ); i.LoadValue( il, false ); count.LoadValue( il, false ); il.EmitBlt( body ); } ) ); } protected override ILConstruct EmitForEachLoop( TContext context, CollectionTraits traits, ILConstruct collection, Func<ILConstruct, ILConstruct> loopBodyEmitter ) { return ILConstruct.Instruction( "foreach", typeof( void ), false, il => { var enumerator = il.DeclareLocal( traits.GetEnumeratorMethod.ReturnType, "enumerator" ); var currentItem = this.DeclareLocal( context, traits.ElementType, "item" ); // gets enumerator collection.LoadValue( il, true ); il.EmitAnyCall( traits.GetEnumeratorMethod ); il.EmitAnyStloc( enumerator ); if ( typeof( IDisposable ).IsAssignableFrom( traits.GetEnumeratorMethod.ReturnType ) ) { il.BeginExceptionBlock(); } var startLoop = il.DefineLabel( "START_LOOP" ); il.MarkLabel( startLoop ); currentItem.Evaluate( il ); var endLoop = il.DefineLabel( "END_LOOP" ); var enumeratorType = traits.GetEnumeratorMethod.ReturnType; var moveNextMethod = Metadata._IEnumerator.FindEnumeratorMoveNextMethod( enumeratorType ); var currentProperty = Metadata._IEnumerator.FindEnumeratorCurrentProperty( enumeratorType, traits ); Contract.Assert( currentProperty != null, enumeratorType.ToString() ); // iterates if ( traits.GetEnumeratorMethod.ReturnType.IsValueType ) { il.EmitAnyLdloca( enumerator ); } else { il.EmitAnyLdloc( enumerator ); } il.EmitAnyCall( moveNextMethod ); il.EmitBrfalse( endLoop ); // get current item if ( traits.GetEnumeratorMethod.ReturnType.IsValueType ) { il.EmitAnyLdloca( enumerator ); } else { il.EmitAnyLdloc( enumerator ); } il.EmitGetProperty( currentProperty ); currentItem.StoreValue( il ); // body loopBodyEmitter( currentItem ).Evaluate( il ); // end loop il.EmitBr( startLoop ); il.MarkLabel( endLoop ); // Dispose if ( typeof( IDisposable ).IsAssignableFrom( traits.GetEnumeratorMethod.ReturnType ) ) { il.BeginFinallyBlock(); if ( traits.GetEnumeratorMethod.ReturnType.IsValueType ) { var disposeMethod = traits.GetEnumeratorMethod.ReturnType.GetMethod( "Dispose" ); if ( disposeMethod != null && disposeMethod.GetParameters().Length == 0 && disposeMethod.ReturnType == typeof( void ) ) { il.EmitAnyLdloca( enumerator ); il.EmitAnyCall( disposeMethod ); } else { il.EmitAnyLdloc( enumerator ); il.EmitBox( traits.GetEnumeratorMethod.ReturnType ); il.EmitAnyCall( Metadata._IDisposable.Dispose ); } } else { il.EmitAnyLdloc( enumerator ); il.EmitAnyCall( Metadata._IDisposable.Dispose ); } il.EndExceptionBlock(); } } ); } protected override ILConstruct EmitEnumFromUnderlyingCastExpression( TContext context, Type enumType, ILConstruct underlyingValue ) { // No operations are needed in IL level. return underlyingValue; } protected override ILConstruct EmitEnumToUnderlyingCastExpression( TContext context, Type underlyingType, ILConstruct enumValue ) { // No operations are needed in IL level. return enumValue; } protected override Func<SerializationContext, MessagePackSerializer<TObject>> CreateSerializerConstructor( TContext codeGenerationContext, PolymorphismSchema schema ) { return context => codeGenerationContext.Emitter.CreateInstance<TObject>( context, schema ); } protected override Func<SerializationContext, MessagePackSerializer<TObject>> CreateEnumSerializerConstructor( TContext codeGenerationContext ) { return context => codeGenerationContext.EnumEmitter.CreateInstance<TObject>( context, EnumMessagePackSerializerHelpers.DetermineEnumSerializationMethod( context, typeof( TObject ), EnumMemberSerializationMethod.Default ) ); } } }
using System; using System.Diagnostics; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.IO; using System.IO.IsolatedStorage; using System.Threading; using System.ComponentModel; using System.Windows.Forms; using System.Windows.Forms.Design; using System.Drawing; using System.Drawing.Design; using System.Globalization; using NetSpell.SpellChecker; using NetSpell.SpellChecker.Dictionary.Affix; using NetSpell.SpellChecker.Dictionary.Phonetic; namespace NetSpell.SpellChecker.Dictionary { /// <summary> /// The WordDictionary class contains all the logic for managing the word list. /// </summary> [ToolboxBitmap(typeof(NetSpell.SpellChecker.Dictionary.WordDictionary), "Dictionary.bmp")] public class WordDictionary : System.ComponentModel.Component { private Hashtable _baseWords = new Hashtable(); private string _copyright = ""; private string _dictionaryFile = Thread.CurrentThread.CurrentCulture.Name + ".dic"; private string _dictionaryFolder = ""; private bool _enableUserFile = true; private bool _initialized = false; private PhoneticRuleCollection _phoneticRules = new PhoneticRuleCollection(); private ArrayList _possibleBaseWords = new ArrayList(); private AffixRuleCollection _prefixRules = new AffixRuleCollection(); private ArrayList _replaceCharacters = new ArrayList(); private AffixRuleCollection _suffixRules = new AffixRuleCollection(); private string _tryCharacters = ""; private string _userFile = "user.dic"; private Hashtable _userWords = new Hashtable(); private System.ComponentModel.Container components = null; /// <summary> /// Initializes a new instance of the class /// </summary> public WordDictionary() { InitializeComponent(); } /// <summary> /// Initializes a new instance of the class /// </summary> public WordDictionary(System.ComponentModel.IContainer container) { container.Add(this); InitializeComponent(); } /// <summary> /// Loads the user dictionary file /// </summary> private void LoadUserFile() { // load user words _userWords.Clear(); // quit if user file is disabled if(!this.EnableUserFile) return; string userPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData), "NetSpell"); string filePath = Path.Combine(userPath, _userFile); if (File.Exists(filePath)) { TraceWriter.TraceInfo("Loading User Dictionary:{0}", filePath); //IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForAssembly(); //fs = new IsolatedStorageFileStream(_UserFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, isf); FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite); StreamReader sr = new StreamReader(fs, Encoding.UTF8); // read line by line while (sr.Peek() >= 0) { string tempLine = sr.ReadLine().Trim(); if (tempLine.Length > 0) { _userWords.Add(tempLine, tempLine); } } fs.Close(); sr.Close(); //isf.Close(); TraceWriter.TraceInfo("Loaded User Dictionary; Words:{0}", _userWords.Count); } } /// <summary> /// Saves the user dictionary file /// </summary> /// <remarks> /// If the file does not exist, it will be created /// </remarks> private void SaveUserFile() { // quit if user file is disabled if(!this.EnableUserFile) return; string userPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData), "NetSpell"); if (!Directory.Exists(userPath)) Directory.CreateDirectory(userPath); string filePath = Path.Combine(userPath, _userFile); TraceWriter.TraceInfo("Saving User Dictionary:{0}", filePath); //IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForAssembly(); //FileStream fs = new IsolatedStorageFileStream(_UserFile, FileMode.Create, FileAccess.Write, isf); FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write); StreamWriter sw = new StreamWriter(fs, Encoding.UTF8); sw.NewLine = "\n"; foreach (string tempWord in _userWords.Keys) { sw.WriteLine(tempWord); } sw.Close(); fs.Close(); //isf.Close(); TraceWriter.TraceInfo("Saved User Dictionary; Words:{0}", _userWords.Count); } /// <summary> /// Verifies the base word has the affix key /// </summary> /// <param name="word" type="string"> /// <para> /// Base word to check /// </para> /// </param> /// <param name="affixKey" type="string"> /// <para> /// Affix key to check /// </para> /// </param> /// <returns> /// True if word contains affix key /// </returns> private bool VerifyAffixKey(string word, char affixKey) { // make sure base word has this affix key Word baseWord = (Word)this.BaseWords[word]; ArrayList keys = new ArrayList(baseWord.AffixKeys.ToCharArray()); return keys.Contains(affixKey); } /// <summary> /// Adds a word to the user list /// </summary> /// <param name="word" type="string"> /// <para> /// The word to add /// </para> /// </param> /// <remarks> /// This method is only affects the user word list /// </remarks> public void Add(string word) { _userWords.Add(word, word); this.SaveUserFile(); } /// <summary> /// Clears the user list of words /// </summary> /// <remarks> /// This method is only affects the user word list /// </remarks> public void Clear() { _userWords.Clear(); this.SaveUserFile(); } /// <summary> /// Searches all contained word lists for word /// </summary> /// <param name="word" type="string"> /// <para> /// The word to search for /// </para> /// </param> /// <returns> /// Returns true if word is found /// </returns> public bool Contains(string word) { // clean up possible base word list _possibleBaseWords.Clear(); // Step 1 Search UserWords if (_userWords.Contains(word)) { TraceWriter.TraceVerbose("Word Found in User Dictionary: {0}", word); return true; // word found } // Step 2 Search BaseWords if (_baseWords.Contains(word)) { TraceWriter.TraceVerbose("Word Found in Base Words: {0}", word); return true; // word found } // Step 3 Remove suffix, Search BaseWords // save suffixed words for use when removing prefix ArrayList suffixWords = new ArrayList(); // Add word to suffix word list suffixWords.Add(word); foreach(AffixRule rule in SuffixRules.Values) { foreach(AffixEntry entry in rule.AffixEntries) { string tempWord = AffixUtility.RemoveSuffix(word, entry); if(tempWord != word) { if (_baseWords.Contains(tempWord)) { if(this.VerifyAffixKey(tempWord, rule.Name[0])) { TraceWriter.TraceVerbose("Word Found With Base Words: {0}; Suffix Key: {1}", tempWord, rule.Name[0]); return true; // word found } } if(rule.AllowCombine) { // saving word to check if it is a word after prefix is removed suffixWords.Add(tempWord); } else { // saving possible base words for use in generating suggestions _possibleBaseWords.Add(tempWord); } } } } // saving possible base words for use in generating suggestions _possibleBaseWords.AddRange(suffixWords); // Step 4 Remove Prefix, Search BaseWords foreach(AffixRule rule in PrefixRules.Values) { foreach(AffixEntry entry in rule.AffixEntries) { foreach(string suffixWord in suffixWords) { string tempWord = AffixUtility.RemovePrefix(suffixWord, entry); if (tempWord != suffixWord) { if (_baseWords.Contains(tempWord)) { if(this.VerifyAffixKey(tempWord, rule.Name[0])) { TraceWriter.TraceVerbose("Word Found With Base Words: {0}; Prefix Key: {1}", tempWord, rule.Name[0]); return true; // word found } } // saving possible base words for use in generating suggestions _possibleBaseWords.Add(tempWord); } } // suffix word } // prefix rule entry } // prefix rule // word not found TraceWriter.TraceVerbose("Possible Base Words: {0}", _possibleBaseWords.Count); return false; } /// <summary> /// Expands an affix compressed base word /// </summary> /// <param name="word" type="NetSpell.SpellChecker.Dictionary.Word"> /// <para> /// The word to expand /// </para> /// </param> /// <returns> /// A System.Collections.ArrayList of words expanded from base word /// </returns> public ArrayList ExpandWord(Word word) { ArrayList suffixWords = new ArrayList(); ArrayList words = new ArrayList(); suffixWords.Add(word.Text); string prefixKeys = ""; // check suffix keys first foreach(char key in word.AffixKeys) { if (_suffixRules.ContainsKey(key.ToString(CultureInfo.CurrentUICulture))) { AffixRule rule = _suffixRules[key.ToString(CultureInfo.CurrentUICulture)]; string tempWord = AffixUtility.AddSuffix(word.Text, rule); if (tempWord != word.Text) { if (rule.AllowCombine) { suffixWords.Add(tempWord); } else { words.Add(tempWord); } } } else if (_prefixRules.ContainsKey(key.ToString(CultureInfo.CurrentUICulture))) { prefixKeys += key.ToString(CultureInfo.CurrentUICulture); } } // apply prefixes foreach(char key in prefixKeys) { AffixRule rule = _prefixRules[key.ToString(CultureInfo.CurrentUICulture)]; // apply prefix to all suffix words foreach (string suffixWord in suffixWords) { string tempWord = AffixUtility.AddPrefix(suffixWord, rule); if (tempWord != suffixWord) { words.Add(tempWord); } } } words.AddRange(suffixWords); TraceWriter.TraceVerbose("Word Expanded: {0}; Child Words: {1}", word.Text, words.Count); return words; } /// <summary> /// Initializes the dictionary by loading and parsing the /// dictionary file and the user file. /// </summary> public void Initialize() { // clean up data first _baseWords.Clear(); _replaceCharacters.Clear(); _prefixRules.Clear(); _suffixRules.Clear(); _phoneticRules.Clear(); _tryCharacters = ""; // the following is used to split a line by white space Regex _spaceRegx = new Regex(@"[^\s]+", RegexOptions.Compiled); MatchCollection partMatches; string currentSection = ""; AffixRule currentRule = null; string dictionaryPath = Path.Combine(_dictionaryFolder, _dictionaryFile); TraceWriter.TraceInfo("Loading Dictionary:{0}", dictionaryPath); // open dictionary file FileStream fs = new FileStream(dictionaryPath, FileMode.Open, FileAccess.Read, FileShare.Read); StreamReader sr = new StreamReader(fs, Encoding.UTF8); // read line by line while (sr.Peek() >= 0) { string tempLine = sr.ReadLine().Trim(); if (tempLine.Length > 0) { // check for section flag switch (tempLine) { case "[Copyright]" : case "[Try]" : case "[Replace]" : case "[Prefix]" : case "[Suffix]" : case "[Phonetic]" : case "[Words]" : // set current section that is being parsed currentSection = tempLine; break; default : // parse line and place in correct object switch (currentSection) { case "[Copyright]" : this.Copyright += tempLine + "\r\n"; break; case "[Try]" : // ISpell try chars this.TryCharacters += tempLine; break; case "[Replace]" : // ISpell replace chars this.ReplaceCharacters.Add(tempLine); break; case "[Prefix]" : // MySpell prefix rules case "[Suffix]" : // MySpell suffix rules // split line by white space partMatches = _spaceRegx.Matches(tempLine); // if 3 parts, then new rule if (partMatches.Count == 3) { currentRule = new AffixRule(); // part 1 = affix key currentRule.Name = partMatches[0].Value; // part 2 = combine flag if (partMatches[1].Value == "Y") currentRule.AllowCombine = true; // part 3 = entry count, not used if (currentSection == "[Prefix]") { // add to prefix collection this.PrefixRules.Add(currentRule.Name, currentRule); } else { // add to suffix collection this.SuffixRules.Add(currentRule.Name, currentRule); } } //if 4 parts, then entry for current rule else if (partMatches.Count == 4) { // part 1 = affix key if (currentRule.Name == partMatches[0].Value) { AffixEntry entry = new AffixEntry(); // part 2 = strip char if (partMatches[1].Value != "0") entry.StripCharacters = partMatches[1].Value; // part 3 = add chars entry.AddCharacters = partMatches[2].Value; // part 4 = conditions AffixUtility.EncodeConditions(partMatches[3].Value, entry); currentRule.AffixEntries.Add(entry); } } break; case "[Phonetic]" : // ASpell phonetic rules // split line by white space partMatches = _spaceRegx.Matches(tempLine); if (partMatches.Count >= 2) { PhoneticRule rule = new PhoneticRule(); PhoneticUtility.EncodeRule(partMatches[0].Value, ref rule); rule.ReplaceString = partMatches[1].Value; _phoneticRules.Add(rule); } break; case "[Words]" : // dictionary word list // splits word into its parts string[] parts = tempLine.Split('/'); Word tempWord = new Word(); // part 1 = base word tempWord.Text = parts[0]; // part 2 = affix keys if (parts.Length >= 2) tempWord.AffixKeys = parts[1]; // part 3 = phonetic code if (parts.Length >= 3) tempWord.PhoneticCode = parts[2]; this.BaseWords.Add(tempWord.Text, tempWord); break; } // currentSection swith break; } //tempLine switch } // if templine } // read line // close files sr.Close(); fs.Close(); TraceWriter.TraceInfo("Dictionary Loaded BaseWords:{0}; PrefixRules:{1}; SuffixRules:{2}; PhoneticRules:{3}", this.BaseWords.Count, this.PrefixRules.Count, this.SuffixRules.Count, this.PhoneticRules.Count); this.LoadUserFile(); _initialized = true; } /// <summary> /// Generates a phonetic code of how the word sounds /// </summary> /// <param name="word" type="string"> /// <para> /// The word to generated the sound code from /// </para> /// </param> /// <returns> /// A code of how the word sounds /// </returns> public string PhoneticCode(string word) { string tempWord = word.ToUpper(); string prevWord = ""; StringBuilder code = new StringBuilder(); while (tempWord.Length > 0) { // save previous word prevWord = tempWord; foreach (PhoneticRule rule in _phoneticRules) { bool begining = tempWord.Length == word.Length ? true : false; bool ending = rule.ConditionCount == tempWord.Length ? true : false; if ((rule.BeginningOnly == begining || !rule.BeginningOnly) && (rule.EndOnly == ending || !rule.EndOnly) && rule.ConditionCount <= tempWord.Length) { int passCount = 0; // loop through conditions for (int i = 0; i < rule.ConditionCount; i++) { int charCode = (int)tempWord[i]; if ((rule.Condition[charCode] & (1 << i)) == (1 << i)) { passCount++; // condition passed } else { break; // rule fails if one condition fails } } // if all condtions passed if (passCount == rule.ConditionCount) { if (rule.ReplaceMode) { tempWord = rule.ReplaceString + tempWord.Substring(rule.ConditionCount - rule.ConsumeCount); } else { if (rule.ReplaceString != "_") { code.Append(rule.ReplaceString); } tempWord = tempWord.Substring(rule.ConditionCount - rule.ConsumeCount); } break; } } } // for each // if no match consume one char if (prevWord.Length == tempWord.Length) { tempWord = tempWord.Substring(1); } }// while return code.ToString(); } /// <summary> /// Removes a word from the user list /// </summary> /// <param name="word" type="string"> /// <para> /// The word to remove /// </para> /// </param> /// <remarks> /// This method is only affects the user word list /// </remarks> public void Remove(string word) { _userWords.Remove(word); this.SaveUserFile(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } /// <summary> /// The collection of base words for the dictionary /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Hashtable BaseWords { get {return _baseWords;} } /// <summary> /// Copyright text for the dictionary /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string Copyright { get {return _copyright;} set {_copyright = value;} } /// <summary> /// The file name for the main dictionary /// </summary> [DefaultValue("en-US.dic")] [CategoryAttribute("Dictionary")] [Description("The file name for the main dictionary")] [NotifyParentProperty(true)] public string DictionaryFile { get {return _dictionaryFile;} set { _dictionaryFile = value; if (_dictionaryFile.Length == 0) { _dictionaryFile = Thread.CurrentThread.CurrentCulture.Name + ".dic"; } } } /// <summary> /// Folder containing the dictionaries /// </summary> [DefaultValue("")] [CategoryAttribute("Dictionary")] [Description("The folder containing dictionaries")] [Editor(typeof(FolderNameEditor), typeof(UITypeEditor))] [NotifyParentProperty(true)] public string DictionaryFolder { get {return _dictionaryFolder;} set {_dictionaryFolder = value;} } /// <summary> /// Set this to true to automaticly create a user dictionary when /// a word is added. /// </summary> /// <remarks> /// This should be set to false in a web environment /// </remarks> [DefaultValue(true)] [CategoryAttribute("Options")] [Description("Set this to true to automaticly create a user dictionary")] [NotifyParentProperty(true)] public bool EnableUserFile { get {return _enableUserFile;} set {_enableUserFile = value;} } /// <summary> /// True if the dictionary has been initialized /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool Initialized { get {return _initialized;} } /// <summary> /// Collection of phonetic rules for this dictionary /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public PhoneticRuleCollection PhoneticRules { get {return _phoneticRules;} } /// <summary> /// Collection of affix prefixes for the base words in this dictionary /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public AffixRuleCollection PrefixRules { get {return _prefixRules;} } /// <summary> /// List of characters to use when generating suggestions using the near miss stratigy /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public ArrayList ReplaceCharacters { get {return _replaceCharacters;} } /// <summary> /// Collection of affix suffixes for the base words in this dictionary /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public AffixRuleCollection SuffixRules { get {return _suffixRules;} } /// <summary> /// List of characters to try when generating suggestions using the near miss stratigy /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string TryCharacters { get {return _tryCharacters;} set {_tryCharacters = value;} } /// <summary> /// The file name for the user word list for this dictionary /// </summary> [DefaultValue("user.dic")] [CategoryAttribute("Dictionary")] [Description("The file name for the user word list for this dictionary")] [NotifyParentProperty(true)] public string UserFile { get {return _userFile;} set {_userFile = value;} } /// <summary> /// List of user entered words in this dictionary /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Hashtable UserWords { get {return _userWords;} } /// <summary> /// List of text saved from when 'Contains' is called. /// This list is used to generate suggestions from if Contains /// doesn't find a word. /// </summary> /// <remarks> /// These are not actual words. /// </remarks> internal ArrayList PossibleBaseWords { get {return _possibleBaseWords;} } #region Component 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() { components = new System.ComponentModel.Container(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace Orleans.Runtime.Scheduler { internal class WorkerPool : IDisposable { private Semaphore threadLimitingSemaphore; private readonly HashSet<WorkerPoolThread> pool; private readonly WorkerPoolThread systemThread; private readonly OrleansTaskScheduler scheduler; private readonly object lockable; private bool running; private int runningThreadCount; private int createThreadCount; private SafeTimer longTurnTimer; internal readonly int MaxActiveThreads; internal readonly TimeSpan MaxWorkQueueWait; internal readonly bool EnableWorkerThreadInjection; private readonly ICorePerformanceMetrics performanceMetrics; internal bool ShouldInjectWorkerThread { get { return EnableWorkerThreadInjection && runningThreadCount < WorkerPoolThread.MAX_THREAD_COUNT_TO_REPLACE; } } internal WorkerPool(OrleansTaskScheduler sched, ICorePerformanceMetrics performanceMetrics, int maxActiveThreads, bool enableWorkerThreadInjection) { scheduler = sched; MaxActiveThreads = maxActiveThreads; EnableWorkerThreadInjection = enableWorkerThreadInjection; MaxWorkQueueWait = TimeSpan.FromMilliseconds(50); this.performanceMetrics = performanceMetrics; if (EnableWorkerThreadInjection) { threadLimitingSemaphore = new Semaphore(maxActiveThreads, maxActiveThreads); } pool = new HashSet<WorkerPoolThread>(); createThreadCount = 0; lockable = new object(); for (createThreadCount = 0; createThreadCount < MaxActiveThreads; createThreadCount++) { var t = new WorkerPoolThread(this, scheduler, performanceMetrics, createThreadCount); pool.Add(t); } createThreadCount++; systemThread = new WorkerPoolThread(this, scheduler, performanceMetrics, createThreadCount, true); running = false; runningThreadCount = 0; longTurnTimer = null; } internal void Start() { running = true; systemThread.Start(); foreach (WorkerPoolThread t in pool) t.Start(); if (EnableWorkerThreadInjection) longTurnTimer = new SafeTimer(obj => CheckForLongTurns(), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1)); } internal void Stop() { running = false; if (longTurnTimer != null) { longTurnTimer.Dispose(); longTurnTimer = null; } WorkerPoolThread[] threads; lock (lockable) { threads = pool.ToArray<WorkerPoolThread>(); } foreach (WorkerPoolThread thread in threads) thread.Stop(); systemThread.Stop(); } internal void TakeCpu() { // maintain the threadLimitingSemaphore ONLY if thread injection is enabled. if (EnableWorkerThreadInjection) threadLimitingSemaphore.WaitOne(); } internal void PutCpu() { if (EnableWorkerThreadInjection) threadLimitingSemaphore.Release(); } internal void RecordRunningThread() { // maintain the runningThreadCount ONLY if thread injection is enabled. if (EnableWorkerThreadInjection) Interlocked.Increment(ref runningThreadCount); } internal void RecordIdlingThread() { if (EnableWorkerThreadInjection) Interlocked.Decrement(ref runningThreadCount); } internal bool CanExit() { lock (lockable) { if (running && (pool.Count <= MaxActiveThreads + 2)) return false; } return true; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "tnew continues to execute after this method call returned")] internal void RecordLeavingThread(WorkerPoolThread t) { bool restart = false; lock (lockable) { pool.Remove(t); if (running && (pool.Count < MaxActiveThreads + 2)) restart = true; if (!restart) return; createThreadCount++; var tnew = new WorkerPoolThread(this, scheduler, this.performanceMetrics, createThreadCount); tnew.Start(); } } internal void CreateNewThread() { lock (lockable) { createThreadCount++; var t = new WorkerPoolThread(this, scheduler, this.performanceMetrics, createThreadCount); pool.Add(t); t.Start(); } } public void Dispose() { if (threadLimitingSemaphore != null) { threadLimitingSemaphore.Dispose(); threadLimitingSemaphore = null; } GC.SuppressFinalize(this); } private void CheckForLongTurns() { List<WorkerPoolThread> currentPool; lock (lockable) { currentPool = pool.ToList(); } foreach (var thread in currentPool) thread.CheckForLongTurns(); } internal bool DoHealthCheck() { bool ok = true; // Note that we want to make sure we run DoHealthCheck on each thread even if one of them fails, so we can't just use &&= because of short-circuiting lock (lockable) { foreach (WorkerPoolThread thread in pool) if (!thread.DoHealthCheck()) ok = false; } if (!systemThread.DoHealthCheck()) ok = false; return ok; } public void DumpStatus(StringBuilder sb) { List<WorkerPoolThread> threads; lock (lockable) { sb.AppendFormat("WorkerPool MaxActiveThreads={0} MaxWorkQueueWait={1} {2}", MaxActiveThreads, MaxWorkQueueWait, running ? "" : "STOPPED").AppendLine(); sb.AppendFormat(" PoolSize={0} ActiveThreads={1}", pool.Count + 1, runningThreadCount).AppendLine(); threads = pool.ToList(); } sb.AppendLine("System Thread:"); systemThread.DumpStatus(sb); sb.AppendLine("Worker Threads:"); foreach (var workerThread in threads) workerThread.DumpStatus(sb); } } }
//////////////////////////////////////////////////////////////// // // // Neoforce Controls // // // //////////////////////////////////////////////////////////////// // // // File: Panel.cs // // // // Version: 0.7 // // // // Date: 11/09/2010 // // // // Author: Tom Shane // // // //////////////////////////////////////////////////////////////// // // // Copyright (c) by Tom Shane // // // //////////////////////////////////////////////////////////////// #region //// Using ///////////// //////////////////////////////////////////////////////////////////////////// using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; //////////////////////////////////////////////////////////////////////////// #endregion namespace TomShane.Neoforce.Controls { public class Panel: Container { #region //// Fields //////////// //////////////////////////////////////////////////////////////////////////// private Bevel bevel = null; private BevelStyle bevelStyle = BevelStyle.None; private BevelBorder bevelBorder = BevelBorder.None; private int bevelMargin = 0; private Color bevelColor = Color.Transparent; //////////////////////////////////////////////////////////////////////////// #endregion #region //// Properties //////// //////////////////////////////////////////////////////////////////////////// public BevelStyle BevelStyle { get { return bevelStyle; } set { if (bevelStyle != value) { bevelStyle = bevel.Style = value; AdjustMargins(); if (!Suspended) OnBevelStyleChanged(new EventArgs()); } } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public BevelBorder BevelBorder { get { return bevelBorder; } set { if (bevelBorder != value) { bevelBorder = bevel.Border = value; bevel.Visible = bevelBorder != BevelBorder.None; AdjustMargins(); if (!Suspended) OnBevelBorderChanged(new EventArgs()); } } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public int BevelMargin { get { return bevelMargin; } set { if (bevelMargin != value) { bevelMargin = value; AdjustMargins(); if (!Suspended) OnBevelMarginChanged(new EventArgs()); } } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual Color BevelColor { get { return bevelColor; } set { bevel.Color = bevelColor = value; } } //////////////////////////////////////////////////////////////////////////// #endregion #region //// Events //////////// //////////////////////////////////////////////////////////////////////////// public event EventHandler BevelBorderChanged; public event EventHandler BevelStyleChanged; public event EventHandler BevelMarginChanged; //////////////////////////////////////////////////////////////////////////// #endregion #region //// Construstors ////// //////////////////////////////////////////////////////////////////////////// public Panel(Manager manager): base(manager) { Passive = false; CanFocus = false; Width = 64; Height = 64; bevel = new Bevel(Manager); } //////////////////////////////////////////////////////////////////////////// #endregion #region //// Methods /////////// //////////////////////////////////////////////////////////////////////////// public override void Init() { base.Init(); bevel.Init(); bevel.Style = bevelStyle; bevel.Border = bevelBorder; bevel.Left = 0; bevel.Top = 0; bevel.Width = Width; bevel.Height = Height; bevel.Color = bevelColor; bevel.Visible = (bevelBorder != BevelBorder.None); bevel.Anchor = Anchors.Left | Anchors.Top | Anchors.Right | Anchors.Bottom; Add(bevel, false); AdjustMargins(); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected internal override void InitSkin() { base.InitSkin(); Skin = new SkinControl(Manager.Skin.Controls["Panel"]); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected override void AdjustMargins() { int l = 0; int t = 0; int r = 0; int b = 0; int s = bevelMargin; if (bevelBorder != BevelBorder.None) { if (bevelStyle != BevelStyle.Flat) { s += 2; } else { s += 1; } if (bevelBorder == BevelBorder.Left || bevelBorder == BevelBorder.All) { l = s; } if (bevelBorder == BevelBorder.Top || bevelBorder == BevelBorder.All) { t = s; } if (bevelBorder == BevelBorder.Right || bevelBorder == BevelBorder.All) { r = s; } if (bevelBorder == BevelBorder.Bottom || bevelBorder == BevelBorder.All) { b = s; } } ClientMargins = new Margins(Skin.ClientMargins.Left + l, Skin.ClientMargins.Top + t, Skin.ClientMargins.Right + r, Skin.ClientMargins.Bottom + b); base.AdjustMargins(); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected override void DrawControl(Renderer renderer, Rectangle rect, GameTime gameTime) { int x = rect.Left; int y = rect.Top; int w = rect.Width; int h = rect.Height; int s = bevelMargin; if (bevelBorder != BevelBorder.None) { if (bevelStyle != BevelStyle.Flat) { s += 2; } else { s += 1; } if (bevelBorder == BevelBorder.Left || bevelBorder == BevelBorder.All) { x += s; w -= s; } if (bevelBorder == BevelBorder.Top || bevelBorder == BevelBorder.All) { y += s; h -= s; } if (bevelBorder == BevelBorder.Right || bevelBorder == BevelBorder.All) { w -= s; } if (bevelBorder == BevelBorder.Bottom || bevelBorder == BevelBorder.All) { h -= s; } } base.DrawControl(renderer, new Rectangle(x, y, w, h), gameTime); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected virtual void OnBevelBorderChanged(EventArgs e) { if (BevelBorderChanged != null) BevelBorderChanged.Invoke(this, e); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected virtual void OnBevelStyleChanged(EventArgs e) { if (BevelStyleChanged != null) BevelStyleChanged.Invoke(this, e); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected virtual void OnBevelMarginChanged(EventArgs e) { if (BevelMarginChanged != null) BevelMarginChanged.Invoke(this, e); } //////////////////////////////////////////////////////////////////////////// #endregion } }
using UnityEngine; using System.Collections; [AddComponentMenu("2D Toolkit/Camera/tk2dCameraAnchor")] [ExecuteInEditMode] /// <summary> /// Anchors children to anchor position, offset by number of pixels /// </summary> public class tk2dCameraAnchor : MonoBehaviour { // Legacy anchor // Order: Upper [Left, Center, Right], Middle, Lower [SerializeField] int anchor = -1; // Backing variable for AnchorPoint accessor [SerializeField] tk2dBaseSprite.Anchor _anchorPoint = tk2dBaseSprite.Anchor.UpperLeft; [SerializeField] bool anchorToNativeBounds = false; /// <summary> /// Anchor point location /// </summary> public tk2dBaseSprite.Anchor AnchorPoint { get { if (anchor != -1) { if (anchor >= 0 && anchor <= 2) _anchorPoint = (tk2dBaseSprite.Anchor)( anchor + 6 ); else if (anchor >= 6 && anchor <= 8) _anchorPoint = (tk2dBaseSprite.Anchor)( anchor - 6 ); else _anchorPoint = (tk2dBaseSprite.Anchor)( anchor ); anchor = -1; #if UNITY_EDITOR UnityEditor.EditorUtility.SetDirty(this); #endif } return _anchorPoint; } set { _anchorPoint = value; } } [SerializeField] Vector2 offset = Vector2.zero; /// <summary> /// Offset in pixels from the anchor. /// This is consistently in screen space, i.e. +y = top of screen, +x = right of screen /// Eg. If you need to inset 10 pixels from from top right anchor, you'd use (-10, -10) /// </summary> public Vector2 AnchorOffsetPixels { get { return offset; } set { offset = value; } } /// <summary> /// Anchor this to the tk2dCamera native bounds, instead of the screen bounds. /// </summary> public bool AnchorToNativeBounds { get { return anchorToNativeBounds; } set { anchorToNativeBounds = value; } } // Another backwards compatiblity only thing here [SerializeField] tk2dCamera tk2dCamera = null; // New field [SerializeField] Camera _anchorCamera = null; // Used to decide when to try to find the tk2dCamera component again Camera _anchorCameraCached = null; tk2dCamera _anchorTk2dCamera = null; /// <summary> /// Offset in pixels from the anchor. /// This is consistently in screen space, i.e. +y = top of screen, +x = right of screen /// Eg. If you need to inset 10 pixels from from top right anchor, you'd use (-10, -10) /// </summary> public Camera AnchorCamera { get { if (tk2dCamera != null) { _anchorCamera = tk2dCamera.GetComponent<Camera>(); tk2dCamera = null; #if UNITY_EDITOR UnityEditor.EditorUtility.SetDirty(this); #endif } return _anchorCamera; } set { _anchorCamera = value; _anchorCameraCached = null; } } tk2dCamera AnchorTk2dCamera { get { if (_anchorCameraCached != _anchorCamera) { _anchorTk2dCamera = _anchorCamera.GetComponent<tk2dCamera>(); _anchorCameraCached = _anchorCamera; } return _anchorTk2dCamera; } } // cache transform locally Transform _myTransform; Transform myTransform { get { if (_myTransform == null) _myTransform = transform; return _myTransform; } } void Start() { UpdateTransform(); } void UpdateTransform() { // Break out if anchor camera is not bound if (AnchorCamera == null) { return; } float pixelScale = 1; // size of one pixel Vector3 position = myTransform.localPosition; // we're ignoring perspective tk2dCameras for now tk2dCamera currentCamera = (AnchorTk2dCamera != null && AnchorTk2dCamera.CameraSettings.projection != tk2dCameraSettings.ProjectionType.Perspective) ? AnchorTk2dCamera : null; Rect rect = new Rect(); if (currentCamera != null) { rect = anchorToNativeBounds ? currentCamera.NativeScreenExtents : currentCamera.ScreenExtents; pixelScale = currentCamera.GetSizeAtDistance( 1 ); } else { rect.Set(0, 0, AnchorCamera.pixelWidth, AnchorCamera.pixelHeight); } float y_bot = rect.yMin; float y_top = rect.yMax; float y_ctr = (y_bot + y_top) * 0.5f; float x_lhs = rect.xMin; float x_rhs = rect.xMax; float x_ctr = (x_lhs + x_rhs) * 0.5f; Vector3 anchoredPosition = Vector3.zero; switch (AnchorPoint) { case tk2dBaseSprite.Anchor.UpperLeft: anchoredPosition = new Vector3(x_lhs, y_top, position.z); break; case tk2dBaseSprite.Anchor.UpperCenter: anchoredPosition = new Vector3(x_ctr, y_top, position.z); break; case tk2dBaseSprite.Anchor.UpperRight: anchoredPosition = new Vector3(x_rhs, y_top, position.z); break; case tk2dBaseSprite.Anchor.MiddleLeft: anchoredPosition = new Vector3(x_lhs, y_ctr, position.z); break; case tk2dBaseSprite.Anchor.MiddleCenter: anchoredPosition = new Vector3(x_ctr, y_ctr, position.z); break; case tk2dBaseSprite.Anchor.MiddleRight: anchoredPosition = new Vector3(x_rhs, y_ctr, position.z); break; case tk2dBaseSprite.Anchor.LowerLeft: anchoredPosition = new Vector3(x_lhs, y_bot, position.z); break; case tk2dBaseSprite.Anchor.LowerCenter: anchoredPosition = new Vector3(x_ctr, y_bot, position.z); break; case tk2dBaseSprite.Anchor.LowerRight: anchoredPosition = new Vector3(x_rhs, y_bot, position.z); break; } Vector3 screenAnchoredPosition = anchoredPosition + new Vector3(pixelScale * offset.x, pixelScale * offset.y, 0); if (currentCamera == null) { // not a tk2dCamera, we need to transform Vector3 worldAnchoredPosition = AnchorCamera.ScreenToWorldPoint( screenAnchoredPosition ); if (myTransform.position != worldAnchoredPosition) { myTransform.position = worldAnchoredPosition; } } else { Vector3 oldPosition = myTransform.localPosition; if (oldPosition != screenAnchoredPosition) { myTransform.localPosition = screenAnchoredPosition; } } } public void ForceUpdateTransform() { UpdateTransform(); } // Update is called once per frame void LateUpdate () { UpdateTransform(); } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcsv = Google.Cloud.SecurityCenter.V1; using sys = System; namespace Google.Cloud.SecurityCenter.V1 { /// <summary>Resource name for the <c>Source</c> resource.</summary> public sealed partial class SourceName : gax::IResourceName, sys::IEquatable<SourceName> { /// <summary>The possible contents of <see cref="SourceName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>organizations/{organization}/sources/{source}</c>.</summary> OrganizationSource = 1, /// <summary>A resource name with pattern <c>folders/{folder}/sources/{source}</c>.</summary> FolderSource = 2, /// <summary>A resource name with pattern <c>projects/{project}/sources/{source}</c>.</summary> ProjectSource = 3, } private static gax::PathTemplate s_organizationSource = new gax::PathTemplate("organizations/{organization}/sources/{source}"); private static gax::PathTemplate s_folderSource = new gax::PathTemplate("folders/{folder}/sources/{source}"); private static gax::PathTemplate s_projectSource = new gax::PathTemplate("projects/{project}/sources/{source}"); /// <summary>Creates a <see cref="SourceName"/> 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="SourceName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static SourceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new SourceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="SourceName"/> with the pattern <c>organizations/{organization}/sources/{source}</c>. /// </summary> /// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="SourceName"/> constructed from the provided ids.</returns> public static SourceName FromOrganizationSource(string organizationId, string sourceId) => new SourceName(ResourceNameType.OrganizationSource, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), sourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId))); /// <summary> /// Creates a <see cref="SourceName"/> with the pattern <c>folders/{folder}/sources/{source}</c>. /// </summary> /// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="SourceName"/> constructed from the provided ids.</returns> public static SourceName FromFolderSource(string folderId, string sourceId) => new SourceName(ResourceNameType.FolderSource, folderId: gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), sourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId))); /// <summary> /// Creates a <see cref="SourceName"/> with the pattern <c>projects/{project}/sources/{source}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="SourceName"/> constructed from the provided ids.</returns> public static SourceName FromProjectSource(string projectId, string sourceId) => new SourceName(ResourceNameType.ProjectSource, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), sourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="SourceName"/> with pattern /// <c>organizations/{organization}/sources/{source}</c>. /// </summary> /// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SourceName"/> with pattern /// <c>organizations/{organization}/sources/{source}</c>. /// </returns> public static string Format(string organizationId, string sourceId) => FormatOrganizationSource(organizationId, sourceId); /// <summary> /// Formats the IDs into the string representation of this <see cref="SourceName"/> with pattern /// <c>organizations/{organization}/sources/{source}</c>. /// </summary> /// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SourceName"/> with pattern /// <c>organizations/{organization}/sources/{source}</c>. /// </returns> public static string FormatOrganizationSource(string organizationId, string sourceId) => s_organizationSource.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="SourceName"/> with pattern /// <c>folders/{folder}/sources/{source}</c>. /// </summary> /// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SourceName"/> with pattern <c>folders/{folder}/sources/{source}</c> /// . /// </returns> public static string FormatFolderSource(string folderId, string sourceId) => s_folderSource.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="SourceName"/> with pattern /// <c>projects/{project}/sources/{source}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SourceName"/> with pattern /// <c>projects/{project}/sources/{source}</c>. /// </returns> public static string FormatProjectSource(string projectId, string sourceId) => s_projectSource.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId))); /// <summary>Parses the given resource name string into a new <see cref="SourceName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>organizations/{organization}/sources/{source}</c></description></item> /// <item><description><c>folders/{folder}/sources/{source}</c></description></item> /// <item><description><c>projects/{project}/sources/{source}</c></description></item> /// </list> /// </remarks> /// <param name="sourceName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="SourceName"/> if successful.</returns> public static SourceName Parse(string sourceName) => Parse(sourceName, false); /// <summary> /// Parses the given resource name string into a new <see cref="SourceName"/> 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>organizations/{organization}/sources/{source}</c></description></item> /// <item><description><c>folders/{folder}/sources/{source}</c></description></item> /// <item><description><c>projects/{project}/sources/{source}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="sourceName">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="SourceName"/> if successful.</returns> public static SourceName Parse(string sourceName, bool allowUnparsed) => TryParse(sourceName, allowUnparsed, out SourceName 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="SourceName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>organizations/{organization}/sources/{source}</c></description></item> /// <item><description><c>folders/{folder}/sources/{source}</c></description></item> /// <item><description><c>projects/{project}/sources/{source}</c></description></item> /// </list> /// </remarks> /// <param name="sourceName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="SourceName"/>, 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 sourceName, out SourceName result) => TryParse(sourceName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="SourceName"/> 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>organizations/{organization}/sources/{source}</c></description></item> /// <item><description><c>folders/{folder}/sources/{source}</c></description></item> /// <item><description><c>projects/{project}/sources/{source}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="sourceName">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="SourceName"/>, 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 sourceName, bool allowUnparsed, out SourceName result) { gax::GaxPreconditions.CheckNotNull(sourceName, nameof(sourceName)); gax::TemplatedResourceName resourceName; if (s_organizationSource.TryParseName(sourceName, out resourceName)) { result = FromOrganizationSource(resourceName[0], resourceName[1]); return true; } if (s_folderSource.TryParseName(sourceName, out resourceName)) { result = FromFolderSource(resourceName[0], resourceName[1]); return true; } if (s_projectSource.TryParseName(sourceName, out resourceName)) { result = FromProjectSource(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(sourceName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private SourceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string folderId = null, string organizationId = null, string projectId = null, string sourceId = null) { Type = type; UnparsedResource = unparsedResourceName; FolderId = folderId; OrganizationId = organizationId; ProjectId = projectId; SourceId = sourceId; } /// <summary> /// Constructs a new instance of a <see cref="SourceName"/> class from the component parts of pattern /// <c>organizations/{organization}/sources/{source}</c> /// </summary> /// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param> public SourceName(string organizationId, string sourceId) : this(ResourceNameType.OrganizationSource, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), sourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId))) { } /// <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>Folder</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string FolderId { get; } /// <summary> /// The <c>Organization</c> ID. May be <c>null</c>, depending on which resource name is contained by this /// instance. /// </summary> public string OrganizationId { get; } /// <summary> /// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Source</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string SourceId { 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.OrganizationSource: return s_organizationSource.Expand(OrganizationId, SourceId); case ResourceNameType.FolderSource: return s_folderSource.Expand(FolderId, SourceId); case ResourceNameType.ProjectSource: return s_projectSource.Expand(ProjectId, SourceId); 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 SourceName); /// <inheritdoc/> public bool Equals(SourceName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(SourceName a, SourceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(SourceName a, SourceName b) => !(a == b); } public partial class Source { /// <summary> /// <see cref="gcsv::SourceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcsv::SourceName SourceName { get => string.IsNullOrEmpty(Name) ? null : gcsv::SourceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
//------------------------------------------------------------------------------ // <copyright file="PooledStream.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Net { using System; using System.Net.Sockets; using System.IO; using System.Diagnostics; using System.Security.Permissions; using System.Threading; using System.Threading.Tasks; internal class PooledStream : Stream { // managed pooling lifetime controls private bool m_CheckLifetime; // true when the connection is only to live for a specific timespan private TimeSpan m_Lifetime; // the timespan the connection is to live for private DateTime m_CreateTime; // when the connection was created. private bool m_ConnectionIsDoomed;// true when the connection should no longer be used. // managed pooling private ConnectionPool m_ConnectionPool; // the pooler that the connection came from private WeakReference m_Owner; // the owning object, when not in the pool. private int m_PooledCount; // the number of times this object has been pushed into the pool less the number of times it's been popped (0 == inPool) // connection info private bool m_Initalizing; // true while we're creating the stream private IPAddress m_ServerAddress; // IP address of server we're connected to private NetworkStream m_NetworkStream; // internal stream for socket private Socket m_AbortSocket; // in abort scenarios, used to abort connect private Socket m_AbortSocket6; // in abort scenarios, used to abort connect private bool m_JustConnected; internal PooledStream(object owner) : base() { // non-pooled constructor m_Owner = new WeakReference(owner); m_PooledCount = -1; m_Initalizing = true; m_NetworkStream = new NetworkStream(); m_CreateTime = DateTime.UtcNow; } internal PooledStream(ConnectionPool connectionPool, TimeSpan lifetime, bool checkLifetime) : base () { // pooled constructor m_ConnectionPool = connectionPool; m_Lifetime = lifetime; m_CheckLifetime = checkLifetime; m_Initalizing = true; m_NetworkStream = new NetworkStream(); m_CreateTime = DateTime.UtcNow; } internal bool JustConnected { get{ if (m_JustConnected) { m_JustConnected = false; return true; } return false; } } internal IPAddress ServerAddress { get { return m_ServerAddress; } } internal bool IsInitalizing { get { return m_Initalizing; } } internal bool CanBePooled { get { if (m_Initalizing) { GlobalLog.Print("PooledStream#" + ValidationHelper.HashString(this) + "::CanBePooled " + "init: true"); return true; } if (!m_NetworkStream.Connected) { GlobalLog.Print("PooledStream#" + ValidationHelper.HashString(this) + "::CanBePooled " + "not-connected: false"); return false; } WeakReference weakref = m_Owner; bool flag = (!m_ConnectionIsDoomed && ((null == weakref) || !weakref.IsAlive)); GlobalLog.Print("PooledStream#" + ValidationHelper.HashString(this) + "::CanBePooled " + "flag: " + flag.ToString()); return (flag); } set { m_ConnectionIsDoomed |= !value; } } internal bool IsEmancipated { get { WeakReference owner = m_Owner; bool value = (0 >= m_PooledCount) && (null == owner || !owner.IsAlive); return value; } } internal object Owner { // We use a weak reference to the owning object so we can identify when // it has been garbage collected without thowing exceptions. get { WeakReference weakref = m_Owner; if ((null != weakref) && weakref.IsAlive) { return weakref.Target; } return null; } set{ lock(this){ if(null != m_Owner){ m_Owner.Target = value; } } } } internal ConnectionPool Pool { get { return m_ConnectionPool; } } internal virtual ServicePoint ServicePoint { get { return Pool.ServicePoint; } } private GeneralAsyncDelegate m_AsyncCallback; internal bool Activate(object owningObject, GeneralAsyncDelegate asyncCallback) { return Activate(owningObject, asyncCallback != null, asyncCallback); } protected bool Activate(object owningObject, bool async, GeneralAsyncDelegate asyncCallback) { GlobalLog.Assert(owningObject == Owner || Owner == null, "PooledStream::Activate|Owner is not the same as expected."); try { if (m_Initalizing) { IPAddress address = null; m_AsyncCallback = asyncCallback; Socket socket = ServicePoint.GetConnection(this, owningObject, async, out address, ref m_AbortSocket, ref m_AbortSocket6); if (socket != null) { if (Logging.On) { Logging.PrintInfo(Logging.Web, this, SR.GetString(SR.net_log_socket_connected, socket.LocalEndPoint, socket.RemoteEndPoint)); } m_NetworkStream.InitNetworkStream(socket, FileAccess.ReadWrite); m_ServerAddress = address; m_Initalizing = false; m_JustConnected = true; m_AbortSocket = null; m_AbortSocket6 = null; return true; } return false; } else if (async && asyncCallback != null) { asyncCallback(owningObject, this); } return true; } catch { m_Initalizing = false; throw; } } internal void Deactivate() { // Called when the connection is about to be placed back into the pool; this m_AsyncCallback = null; if (!m_ConnectionIsDoomed && m_CheckLifetime) { // check lifetime here - as a side effect it will doom connection if // it's lifetime has elapsed CheckLifetime(); } } internal virtual void ConnectionCallback(object owningObject, Exception e, Socket socket, IPAddress address) { GlobalLog.Assert(owningObject == Owner || Owner == null, "PooledStream::ConnectionCallback|Owner is not the same as expected."); object result = null; if (e != null) { m_Initalizing = false; result = e; } else { try { if (Logging.On) { Logging.PrintInfo(Logging.Web, this, SR.GetString(SR.net_log_socket_connected, socket.LocalEndPoint, socket.RemoteEndPoint)); } m_NetworkStream.InitNetworkStream(socket, FileAccess.ReadWrite); result = this; } catch (Exception ex) { if (NclUtilities.IsFatal(ex)) throw; result = ex; } m_ServerAddress = address; m_Initalizing = false; m_JustConnected = true; } if (m_AsyncCallback != null) { m_AsyncCallback(owningObject, result); } m_AbortSocket = null; m_AbortSocket6 = null; } protected void CheckLifetime() { bool okay = !m_ConnectionIsDoomed; if (okay) { // Returns whether or not this object's lifetime has had expired. // True means the object is still good, false if it has timed out. // obtain current time DateTime utcNow = DateTime.UtcNow; // obtain timespan TimeSpan timeSpan = utcNow.Subtract(m_CreateTime); // compare timeSpan with lifetime, if equal or less, // designate this object to be killed m_ConnectionIsDoomed = (0 < TimeSpan.Compare(m_Lifetime, timeSpan)); } } /// <devdoc> /// <para>Updates the lifetime of the time for this stream to live</para> /// </devdoc> internal void UpdateLifetime() { int timeout = ServicePoint.ConnectionLeaseTimeout; TimeSpan connectionLifetime; if (timeout == System.Threading.Timeout.Infinite) { connectionLifetime = TimeSpan.MaxValue; m_CheckLifetime = false; } else { connectionLifetime = new TimeSpan(0, 0, 0, 0, timeout); m_CheckLifetime = true; } if (connectionLifetime != m_Lifetime) { m_Lifetime = connectionLifetime; } } internal void PrePush(object expectedOwner) { lock (this) { //3 // The following tests are retail assertions of things we can't allow to happen. if (null == expectedOwner) { if (null != m_Owner && null != m_Owner.Target) throw new InternalException(); // new unpooled object has an owner } else { if (null == m_Owner || m_Owner.Target != expectedOwner) throw new InternalException(); // unpooled object has incorrect owner } m_PooledCount++; if (1 != m_PooledCount) throw new InternalException(); // pushing object onto stack a second time if (null != m_Owner) m_Owner.Target = null; } } internal void PostPop (object newOwner) { GlobalLog.Assert(!IsEmancipated, "Pooled object not in pool."); GlobalLog.Assert(CanBePooled, "Pooled object is not poolable."); lock (this) { if (null == m_Owner) m_Owner = new WeakReference(newOwner); else { if (null != m_Owner.Target) throw new InternalException(); // pooled connection already has an owner! m_Owner.Target = newOwner; } m_PooledCount--; if (null != Pool) { if (0 != m_PooledCount) throw new InternalException(); // popping object off stack with multiple pooledCount } else { if (-1 != m_PooledCount) throw new InternalException(); // popping object off stack with multiple pooledCount } } } /// <devdoc> /// <para>True if we're using a TlsStream</para> /// </devdoc> protected bool UsingSecureStream { get { #if !FEATURE_PAL return (m_NetworkStream is TlsStream); #else return false; #endif // !FEATURE_PAL } } /// <devdoc> /// <para>Allows inherited objects to modify NetworkStream</para> /// </devdoc> internal NetworkStream NetworkStream { get { return m_NetworkStream; } set { m_Initalizing = false; m_NetworkStream = value; } } /// <devdoc> /// <para>Gives the socket for internal use.</para> /// </devdoc> protected Socket Socket { get { return m_NetworkStream.InternalSocket; } } /// <devdoc> /// <para>Indicates that data can be read from the stream. /// </devdoc> public override bool CanRead { get { return m_NetworkStream.CanRead; } } /// <devdoc> /// <para>Indicates that the stream is seekable</para> /// </devdoc> public override bool CanSeek { get { return m_NetworkStream.CanSeek; } } /// <devdoc> /// <para>Indicates that the stream is writeable</para> /// </devdoc> public override bool CanWrite { get { return m_NetworkStream.CanWrite; } } /// <devdoc> /// <para>Indicates whether we can timeout</para> /// </devdoc> public override bool CanTimeout { get { return m_NetworkStream.CanTimeout; } } /// <devdoc> /// <para>Set/Get ReadTimeout</para> /// </devdoc> public override int ReadTimeout { get { return m_NetworkStream.ReadTimeout; } set { m_NetworkStream.ReadTimeout = value; } } /// <devdoc> /// <para>Set/Get WriteTimeout</para> /// </devdoc> public override int WriteTimeout { get { return m_NetworkStream.WriteTimeout; } set { m_NetworkStream.WriteTimeout = value; } } /// <devdoc> /// <para>Indicates that the stream is writeable</para> /// </devdoc> public override long Length { get { return m_NetworkStream.Length; } } /// <devdoc> /// <para>Gets or sets the position in the stream. Always throws <see cref='NotSupportedException'/>.</para> /// </devdoc> public override long Position { get { return m_NetworkStream.Position; } set { m_NetworkStream.Position = value; } } /* // Consider removing. /// <devdoc> /// <para>Indicates the avail bytes</para> /// </devdoc> public bool DataAvailable { get { return m_NetworkStream.DataAvailable; } } */ /// <devdoc> /// <para>Seeks a specific position in the stream.</para> /// </devdoc> public override long Seek(long offset, SeekOrigin origin) { return m_NetworkStream.Seek(offset, origin); } /// <devdoc> /// <para> Reads data from the stream. </para> /// </devdoc> public override int Read(byte[] buffer, int offset, int size) { int result = m_NetworkStream.Read(buffer, offset, size); GlobalLog.Dump(buffer, offset, result); return result; } /// <devdoc> /// <para>Writes data to the stream.</para> /// </devdoc> public override void Write(byte[] buffer, int offset, int size) { GlobalLog.Dump(buffer, offset, size); m_NetworkStream.Write(buffer, offset, size); } /// <devdoc> /// <para>Writes multiple buffers at once</para> /// </devdoc> internal void MultipleWrite(BufferOffsetSize[] buffers) { #if TRAVE for (int i = 0; i < buffers.Length; ++i) { GlobalLog.Dump(buffers[i].Buffer, buffers[i].Offset, buffers[i].Size); } #endif m_NetworkStream.MultipleWrite(buffers); } /// <devdoc> /// <para> /// Closes the stream, and then closes the underlying socket. /// </para> /// </devdoc> protected override void Dispose(bool disposing) { try { if (disposing) { m_Owner = null; m_ConnectionIsDoomed = true; // no timeout so that socket will close gracefully CloseSocket(); } } finally { base.Dispose(disposing); } } internal void CloseSocket() { Socket socket = m_AbortSocket; Socket socket6 = m_AbortSocket6; m_NetworkStream.Close(); if (socket != null) { socket.Close(); } if (socket6 != null) { socket6.Close(); } } public void Close(int timeout) { Socket socket = m_AbortSocket; Socket socket6 = m_AbortSocket6; m_NetworkStream.Close(timeout); if (socket != null) { socket.Close(timeout); } if (socket6 != null) { socket6.Close(timeout); } } /// <devdoc> /// <para> /// Begins an asychronous read from a stream. /// </para> /// </devdoc> [HostProtection(ExternalThreading=true)] public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) { return m_NetworkStream.BeginRead(buffer, offset, size, callback, state); } internal virtual IAsyncResult UnsafeBeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) { return m_NetworkStream.UnsafeBeginRead(buffer, offset, size, callback, state); } /// <devdoc> /// <para> /// Handle the end of an asynchronous read. /// </para> /// </devdoc> public override int EndRead(IAsyncResult asyncResult) { // only caller can recover the debug dump for the read result return m_NetworkStream.EndRead(asyncResult); } /// <devdoc> /// <para> /// Begins an asynchronous write to a stream. /// </para> /// </devdoc> [HostProtection(ExternalThreading=true)] public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) { GlobalLog.Dump(buffer, offset, size); return m_NetworkStream.BeginWrite(buffer, offset, size, callback, state); } internal virtual IAsyncResult UnsafeBeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) { GlobalLog.Dump(buffer, offset, size); return m_NetworkStream.UnsafeBeginWrite(buffer, offset, size, callback, state); } /// <devdoc> /// <para> /// Handle the end of an asynchronous write. /// </para> /// </devdoc> public override void EndWrite(IAsyncResult asyncResult) { m_NetworkStream.EndWrite(asyncResult); } /// <devdoc> /// <para> /// Begins an asynchronous write to a stream. /// </para> /// </devdoc> [HostProtection(ExternalThreading=true)] internal IAsyncResult BeginMultipleWrite(BufferOffsetSize[] buffers, AsyncCallback callback, object state) { #if TRAVE for (int i = 0; i < buffers.Length; ++i) { GlobalLog.Dump(buffers[i].Buffer, buffers[i].Offset, buffers[i].Size); } #endif return m_NetworkStream.BeginMultipleWrite(buffers, callback, state); } /* // Consider removing. internal IAsyncResult UnsafeBeginMultipleWrite(BufferOffsetSize[] buffers, AsyncCallback callback, object state) { #if TRAVE for (int i = 0; i < buffers.Length; ++i) { GlobalLog.Dump(buffers[i].Buffer, buffers[i].Offset, buffers[i].Size); } #endif return m_NetworkStream.UnsafeBeginMultipleWrite(buffers, callback, state); } */ /// <devdoc> /// <para> /// Handle the end of an asynchronous write. /// </para> /// </devdoc> internal void EndMultipleWrite(IAsyncResult asyncResult) { m_NetworkStream.EndMultipleWrite(asyncResult); } /// <devdoc> /// <para> /// Flushes data from the stream. /// </para> /// </devdoc> public override void Flush() { m_NetworkStream.Flush(); } public override Task FlushAsync(CancellationToken cancellationToken) { return m_NetworkStream.FlushAsync(cancellationToken); } /// <devdoc> /// <para>Sets the length of the stream.</para> /// </devdoc> public override void SetLength(long value) { m_NetworkStream.SetLength(value); } internal void SetSocketTimeoutOption(SocketShutdown mode, int timeout, bool silent) { m_NetworkStream.SetSocketTimeoutOption(mode, timeout, silent); } internal bool Poll(int microSeconds, SelectMode mode) { return m_NetworkStream.Poll(microSeconds, mode); } internal bool PollRead() { return m_NetworkStream.PollRead(); } } } // System.Net
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Xml; using System.Xml.XPath; using System.Xml.Schema; using System.Diagnostics; using System.Collections; using System.ComponentModel; namespace System.Xml.Xsl.Runtime { /// <summary> /// Iterate over all child content nodes (this is different from the QIL Content operator, which iterates over content + attributes). /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public struct ContentIterator { private XPathNavigator _navCurrent; private bool _needFirst; /// <summary> /// Initialize the ContentIterator. /// </summary> public void Create(XPathNavigator context) { _navCurrent = XmlQueryRuntime.SyncToNavigator(_navCurrent, context); _needFirst = true; } /// <summary> /// Position the iterator on the next child content node. Return true if such a child exists and /// set Current property. Otherwise, return false (Current property is undefined). /// </summary> public bool MoveNext() { if (_needFirst) { _needFirst = !_navCurrent.MoveToFirstChild(); return !_needFirst; } return _navCurrent.MoveToNext(); } /// <summary> /// Return the current result navigator. This is only defined after MoveNext() has returned true. /// </summary> public XPathNavigator Current { get { return _navCurrent; } } } /// <summary> /// Iterate over all child elements with a matching name. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public struct ElementContentIterator { private string _localName, _ns; private XPathNavigator _navCurrent; private bool _needFirst; /// <summary> /// Initialize the ElementContentIterator. /// </summary> public void Create(XPathNavigator context, string localName, string ns) { _navCurrent = XmlQueryRuntime.SyncToNavigator(_navCurrent, context); _localName = localName; _ns = ns; _needFirst = true; } /// <summary> /// Position the iterator on the next child element with a matching name. Return true if such a child exists and /// set Current property. Otherwise, return false (Current property is undefined). /// </summary> public bool MoveNext() { if (_needFirst) { _needFirst = !_navCurrent.MoveToChild(_localName, _ns); return !_needFirst; } return _navCurrent.MoveToNext(_localName, _ns); } /// <summary> /// Return the current result navigator. This is only defined after MoveNext() has returned true. /// </summary> public XPathNavigator Current { get { return _navCurrent; } } } /// <summary> /// Iterate over all child content nodes with a matching node kind. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public struct NodeKindContentIterator { private XPathNodeType _nodeType; private XPathNavigator _navCurrent; private bool _needFirst; /// <summary> /// Initialize the NodeKindContentIterator. /// </summary> public void Create(XPathNavigator context, XPathNodeType nodeType) { Debug.Assert(nodeType != XPathNodeType.Attribute && nodeType != XPathNodeType.Namespace); _navCurrent = XmlQueryRuntime.SyncToNavigator(_navCurrent, context); _nodeType = nodeType; _needFirst = true; } /// <summary> /// Position the iterator on the next child content node with a matching node kind. Return true if such a child /// exists and set Current property. Otherwise, return false (Current property is undefined). /// </summary> public bool MoveNext() { if (_needFirst) { _needFirst = !_navCurrent.MoveToChild(_nodeType); return !_needFirst; } return _navCurrent.MoveToNext(_nodeType); } /// <summary> /// Return the current result navigator. This is only defined after MoveNext() has returned true. /// </summary> public XPathNavigator Current { get { return _navCurrent; } } } /// <summary> /// Iterate over all attributes. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public struct AttributeIterator { private XPathNavigator _navCurrent; private bool _needFirst; /// <summary> /// Initialize the AttributeIterator. /// </summary> public void Create(XPathNavigator context) { _navCurrent = XmlQueryRuntime.SyncToNavigator(_navCurrent, context); _needFirst = true; } /// <summary> /// Position the iterator on the attribute. Return true if such a child exists and set Current /// property. Otherwise, return false (Current property is undefined). /// </summary> public bool MoveNext() { if (_needFirst) { _needFirst = !_navCurrent.MoveToFirstAttribute(); return !_needFirst; } return _navCurrent.MoveToNextAttribute(); } /// <summary> /// Return the current result navigator. This is only defined after MoveNext() has returned true. /// </summary> public XPathNavigator Current { get { return _navCurrent; } } } /// <summary> /// Iterate over all namespace nodes. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public struct NamespaceIterator { private XPathNavigator _navCurrent; private XmlNavigatorStack _navStack; /// <summary> /// Initialize the NamespaceIterator. /// </summary> public void Create(XPathNavigator context) { // Push all of context's in-scope namespaces onto a stack in order to return them in document order // (MoveToXXXNamespace methods return namespaces in reverse document order) _navStack.Reset(); if (context.MoveToFirstNamespace(XPathNamespaceScope.All)) { do { // Don't return the default namespace undeclaration if (context.LocalName.Length != 0 || context.Value.Length != 0) _navStack.Push(context.Clone()); } while (context.MoveToNextNamespace(XPathNamespaceScope.All)); context.MoveToParent(); } } /// <summary> /// Pop the top namespace from the stack and save it as navCurrent. If there are no more namespaces, return false. /// </summary> public bool MoveNext() { if (_navStack.IsEmpty) return false; _navCurrent = _navStack.Pop(); return true; } /// <summary> /// Return the current result navigator. This is only defined after MoveNext() has returned true. /// </summary> public XPathNavigator Current { get { return _navCurrent; } } } /// <summary> /// Iterate over all attribute and child content nodes. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public struct AttributeContentIterator { private XPathNavigator _navCurrent; private bool _needFirst; /// <summary> /// Initialize the AttributeContentIterator. /// </summary> public void Create(XPathNavigator context) { _navCurrent = XmlQueryRuntime.SyncToNavigator(_navCurrent, context); _needFirst = true; } /// <summary> /// Position the iterator on the next child content node with a matching node kind. Return true if such a child /// exists and set Current property. Otherwise, return false (Current property is undefined). /// </summary> public bool MoveNext() { if (_needFirst) { _needFirst = !XmlNavNeverFilter.MoveToFirstAttributeContent(_navCurrent); return !_needFirst; } return XmlNavNeverFilter.MoveToNextAttributeContent(_navCurrent); } /// <summary> /// Return the current result navigator. This is only defined after MoveNext() has returned true. /// </summary> public XPathNavigator Current { get { return _navCurrent; } } } /// <summary> /// Iterate over child content nodes or following-sibling nodes. Maintain document order by using a stack. Input /// nodes are assumed to be in document order, but can contain one another (ContentIterator doesn't allow this). /// </summary> /// <remarks> /// 1. Assume that the list I of input nodes is in document order, with no duplicates. There are N nodes in list I. /// 2. For each node in list I, derive a list of nodes consisting of matching children or following-sibling nodes. /// Call these lists S(1)...S(N). /// 3. Let F be the first node in any list S(X), where X &gt;= 1 and X &lt; N /// 4. There exists exactly one contiguous sequence of lists S(Y)...S(Z), where Y &gt; X and Z &lt;= N, such that the lists /// S(X+1)...S(N) can be partitioned into these three groups: /// a. 1st group (S(X+1)...S(Y-1)) -- All nodes in these lists precede F in document order /// b. 2nd group (S(Y)...S(Z)) -- All nodes in these lists are duplicates of nodes in list S(X) /// c. 3rd group (&gt; S(Z)) -- All nodes in these lists succeed F in document order /// 5. Given #4, node F can be returned once all nodes in the 1st group have been returned. Lists S(Y)...S(Z) can be /// discarded. And only a single node in the 3rd group need be generated in order to guarantee that all nodes in /// the 1st and 2nd groups have already been generated. /// </remarks> [EditorBrowsable(EditorBrowsableState.Never)] public struct ContentMergeIterator { private XmlNavigatorFilter _filter; private XPathNavigator _navCurrent, _navNext; private XmlNavigatorStack _navStack; private IteratorState _state; private enum IteratorState { NeedCurrent = 0, HaveCurrentNeedNext, HaveCurrentNoNext, HaveCurrentHaveNext, }; /// <summary> /// Initialize the ContentMergeIterator (merge multiple sets of content nodes in document order and remove duplicates). /// </summary> public void Create(XmlNavigatorFilter filter) { _filter = filter; _navStack.Reset(); _state = IteratorState.NeedCurrent; } /// <summary> /// Position this iterator to the next content or sibling node. Return IteratorResult.NoMoreNodes if there are /// no more content or sibling nodes. Return IteratorResult.NeedInputNode if the next input node needs to be /// fetched first. Return IteratorResult.HaveCurrent if the Current property is set to the next node in the /// iteration. /// </summary> public IteratorResult MoveNext(XPathNavigator input) { return MoveNext(input, true); } /// <summary> /// Position this iterator to the next content or sibling node. Return IteratorResult.NoMoreNodes if there are /// no more content or sibling nodes. Return IteratorResult.NeedInputNode if the next input node needs to be /// fetched first. Return IteratorResult.HaveCurrent if the Current property is set to the next node in the /// iteration. /// </summary> internal IteratorResult MoveNext(XPathNavigator input, bool isContent) { switch (_state) { case IteratorState.NeedCurrent: // If there are no more input nodes, then iteration is complete if (input == null) return IteratorResult.NoMoreNodes; // Save the input node as the current node _navCurrent = XmlQueryRuntime.SyncToNavigator(_navCurrent, input); // If matching child or sibling is found, then we have a current node if (isContent ? _filter.MoveToContent(_navCurrent) : _filter.MoveToFollowingSibling(_navCurrent)) _state = IteratorState.HaveCurrentNeedNext; return IteratorResult.NeedInputNode; case IteratorState.HaveCurrentNeedNext: if (input == null) { // There are no more input nodes, so enter HaveCurrentNoNext state and return Current _state = IteratorState.HaveCurrentNoNext; return IteratorResult.HaveCurrentNode; } // Save the input node as the next node _navNext = XmlQueryRuntime.SyncToNavigator(_navNext, input); // If matching child or sibling is found, if (isContent ? _filter.MoveToContent(_navNext) : _filter.MoveToFollowingSibling(_navNext)) { // Then compare position of current and next nodes _state = IteratorState.HaveCurrentHaveNext; return DocOrderMerge(); } // Input node does not result in matching child or sibling, so get next input node return IteratorResult.NeedInputNode; case IteratorState.HaveCurrentNoNext: case IteratorState.HaveCurrentHaveNext: // If the current node has no more matching siblings, if (isContent ? !_filter.MoveToNextContent(_navCurrent) : !_filter.MoveToFollowingSibling(_navCurrent)) { if (_navStack.IsEmpty) { if (_state == IteratorState.HaveCurrentNoNext) { // No more input nodes, so iteration is complete return IteratorResult.NoMoreNodes; } // Make navNext the new current node and fetch a new navNext _navCurrent = XmlQueryRuntime.SyncToNavigator(_navCurrent, _navNext); _state = IteratorState.HaveCurrentNeedNext; return IteratorResult.NeedInputNode; } // Pop new current node from the stack _navCurrent = _navStack.Pop(); } // If there is no next node, then no need to call DocOrderMerge; just return the current node if (_state == IteratorState.HaveCurrentNoNext) return IteratorResult.HaveCurrentNode; // Compare positions of current and next nodes return DocOrderMerge(); } Debug.Fail($"Invalid IteratorState {_state}"); return IteratorResult.NoMoreNodes; } /// <summary> /// Return the current result navigator. This is only defined after MoveNext() has returned IteratorResult.HaveCurrentNode. /// </summary> public XPathNavigator Current { get { return _navCurrent; } } /// <summary> /// If the context node-set returns a node that is contained in the subtree of the previous node, /// then returning children of each node in "natural" order may not correspond to document order. /// Therefore, in order to guarantee document order, keep a stack in order to push the sibling of /// ancestor nodes. These siblings will not be returned until all of the descendants' children are /// returned first. /// </summary> private IteratorResult DocOrderMerge() { XmlNodeOrder cmp; Debug.Assert(_state == IteratorState.HaveCurrentHaveNext); // Compare location of navCurrent with navNext cmp = _navCurrent.ComparePosition(_navNext); // If navCurrent is before navNext in document order, // If cmp = XmlNodeOrder.Unknown, then navCurrent is before navNext (since input is is doc order) if (cmp == XmlNodeOrder.Before || cmp == XmlNodeOrder.Unknown) { // Then navCurrent can be returned (it is guaranteed to be first in document order) return IteratorResult.HaveCurrentNode; } // If navCurrent is after navNext in document order, then delay returning navCurrent // Otherwise, discard navNext since it is positioned to the same node as navCurrent if (cmp == XmlNodeOrder.After) { _navStack.Push(_navCurrent); _navCurrent = _navNext; _navNext = null; } // Need next input node _state = IteratorState.HaveCurrentNeedNext; return IteratorResult.NeedInputNode; } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using ASC.HealthCheck.Classes; using ASC.HealthCheck.Models; using ASC.HealthCheck.Resources; using log4net; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Net.Sockets; using System.Threading.Tasks; using System.Web.Http; namespace ASC.HealthCheck.Controllers { public class PortsCheckApiController : ApiController { private static readonly object syncRoot = new object(); private static string host; private readonly ILog log = LogManager.GetLogger(typeof(PortsCheckApiController)); private const int PortsCount = 9; private readonly Port[] ports = { new Port { Name = "HTTP", Number = 80, AllowClosedForIncomingRequests = false, Description = HealthCheckResource.HttpDescription }, new Port { Name = "HTTPS", Number = 443, AllowClosedForIncomingRequests = false, Description = HealthCheckResource.HttpsDescription }, new Port { Name = "SMTP", Number = 25, Description = HealthCheckResource.SmtpDescription }, new Port { Name = "SMTPS", Number = 465, Description = HealthCheckResource.SmtpsDescription }, new Port { Name = "IMAP", Number = 143, Description = HealthCheckResource.ImapDescription }, new Port { Name = "IMAPS", Number = 993, Description = HealthCheckResource.ImapsDescription }, new Port { Name = "POP3", Number = 110, Description = HealthCheckResource.Pop3Description }, new Port { Name = "POP3S", Number = 995, Description = HealthCheckResource.Pop3sDescription }, new Port { Name = "XMPP", Number = 5222, AllowClosedForIncomingRequests = false, Description = HealthCheckResource.XmppDescription } }; private readonly Task[] tasks = new Task[PortsCount]; static PortsCheckApiController() { try { host = new ShellExe().ExecuteCommand("dig", "+short myip.opendns.com @resolver1.opendns.com"). Replace(Environment.NewLine, string.Empty); } catch { host = string.Empty; } } [HttpGet] public IList<Port> GetPortList() { try { log.DebugFormat("GetPortList host = {0}", host); lock (syncRoot) { return ports; } } catch (Exception ex) { log.ErrorFormat("Unexpected error on GetPortList: {0} {1}", ex.ToString(), ex.InnerException != null ? ex.InnerException.Message : string.Empty); return null; } } [HttpGet] public IList<JObject> GetPortStatus() { try { log.Debug("GetPortStatus"); lock (syncRoot) { for (int i = 0; i < ports.Length; i++) { int j = i; tasks[i] = Task.Run(() => { CheckPortStatus(j); }); } Task.WaitAll(tasks); var portStatuses = new List<JObject>(); foreach (var port in ports) { dynamic jsonObject = new JObject(); jsonObject.Number = port.Number; jsonObject.PortStatus = port.PortStatus; jsonObject.Status = port.Status; jsonObject.StatusDescription = port.StatusDescription; portStatuses.Add(jsonObject); } return portStatuses; } } catch (Exception ex) { log.ErrorFormat("Unexpected error on GetPortStatus: {0} {1}", ex.ToString(), ex.InnerException != null ? ex.InnerException.Message : string.Empty); return null; } } private void CheckPortStatus(int j) { var tuple = GetPortStatus(ports[j]); ports[j].PortStatus = tuple.Item1; ports[j].StatusDescription = tuple.Item2; ports[j].Status = ports[j].PortStatus == PortStatus.Open ? HealthCheckResource.PortStatusOpen : HealthCheckResource.PortStatusClose; } private Tuple<PortStatus, string> GetPortStatus(Port port) { PortStatus portStatus = PortStatus.Open; string statusDescription = HealthCheckResource.PortStatusOpen; if (!port.AllowClosedForOutgoingRequests && IsClosedForOutgoingRequests(port.Number)) { portStatus = PortStatus.Closed; statusDescription = HealthCheckResource.PortStatusClosedForOutgoingRequests; } if (!port.AllowClosedForIncomingRequests && IsClosedForIncomingRequests(port.Number)) { portStatus = PortStatus.Closed; statusDescription = HealthCheckResource.PortStatusClosedForIncomingRequests; } return Tuple.Create(portStatus, statusDescription); } private bool IsClosedForOutgoingRequests(int portNumber) { return !TryConnect("portquiz.net", portNumber); } private bool IsClosedForIncomingRequests(int portNumber) { return !TryConnect(host, portNumber); } private bool TryConnect(string host, int port) { var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { IAsyncResult result = socket.BeginConnect(host, port, null, null); bool success = result.AsyncWaitHandle.WaitOne(7000, true); if (success) { socket.EndConnect(result); return true; } else { throw new SocketException((int)SocketError.TimedOut); // Connection timed out. } } catch (SocketException ex) { var socketErrorCode = (SocketError)ex.ErrorCode; if (socketErrorCode == SocketError.AccessDenied || socketErrorCode == SocketError.Fault || socketErrorCode == SocketError.HostNotFound || socketErrorCode == SocketError.NetworkUnreachable || socketErrorCode == SocketError.NotConnected || socketErrorCode == SocketError.TimedOut || socketErrorCode == SocketError.AddressNotAvailable) { log.DebugFormat("Can't connect to host: {0}, port:{1}. {2}, socketErrorCode = {3}", host, port, ex.ToString(), socketErrorCode); return false; } log.DebugFormat("Can't connect to host: {0}, port:{1}. {2}, socketErrorCode = {3}, not problem", host, port, ex.ToString(), socketErrorCode); return true; } catch (Exception ex) { log.ErrorFormat("Unexpected Error: {0}", ex.ToString()); return false; } finally { socket.Close(); } } } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Data; using System.Xml.Serialization; using CALI.Database.Contracts; using CALI.Database.Contracts.Auth; ////////////////////////////////////////////////////////////// //Do not modify this file. Use a partial class to extend. // //Override methods in the logic front class. // ////////////////////////////////////////////////////////////// namespace CALI.Database.Logic.Auth { [Serializable] public abstract partial class UserLogicBase : LogicBase<UserLogicBase> { //Put your code in a separate file. This is auto generated. [XmlArray] public List<UserContract> Results; public UserLogicBase() { Results = new List<UserContract>(); } /// <summary> /// Run User_Insert. /// </summary> /// <param name="fldUserName">Value for UserName</param> /// <param name="fldPassword">Value for Password</param> /// <param name="fldDisplayName">Value for DisplayName</param> /// <param name="fldEmail">Value for Email</param> /// <param name="fldAuthToken">Value for AuthToken</param> /// <param name="fldUserToken">Value for UserToken</param> /// <param name="fldFailedLogins">Value for FailedLogins</param> /// <param name="fldIsActive">Value for IsActive</param> /// <param name="fldWINSID">Value for WINSID</param> /// <returns>The new ID</returns> public virtual int? Insert(string fldUserName , byte[] fldPassword , string fldDisplayName , string fldEmail , Guid fldAuthToken , Guid fldUserToken , int fldFailedLogins , bool fldIsActive , string fldWINSID ) { int? result = null; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_Insert]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserName", fldUserName) , new SqlParameter("@Password", fldPassword) , new SqlParameter("@DisplayName", fldDisplayName) , new SqlParameter("@Email", fldEmail) , new SqlParameter("@AuthToken", fldAuthToken) , new SqlParameter("@UserToken", fldUserToken) , new SqlParameter("@FailedLogins", fldFailedLogins) , new SqlParameter("@IsActive", fldIsActive) , new SqlParameter("@WINSID", fldWINSID) }); result = (int?)cmd.ExecuteScalar(); } }); return result; } /// <summary> /// Run User_Insert. /// </summary> /// <param name="fldUserName">Value for UserName</param> /// <param name="fldPassword">Value for Password</param> /// <param name="fldDisplayName">Value for DisplayName</param> /// <param name="fldEmail">Value for Email</param> /// <param name="fldAuthToken">Value for AuthToken</param> /// <param name="fldUserToken">Value for UserToken</param> /// <param name="fldFailedLogins">Value for FailedLogins</param> /// <param name="fldIsActive">Value for IsActive</param> /// <param name="fldWINSID">Value for WINSID</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The new ID</returns> public virtual int? Insert(string fldUserName , byte[] fldPassword , string fldDisplayName , string fldEmail , Guid fldAuthToken , Guid fldUserToken , int fldFailedLogins , bool fldIsActive , string fldWINSID , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Auth].[User_Insert]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserName", fldUserName) , new SqlParameter("@Password", fldPassword) , new SqlParameter("@DisplayName", fldDisplayName) , new SqlParameter("@Email", fldEmail) , new SqlParameter("@AuthToken", fldAuthToken) , new SqlParameter("@UserToken", fldUserToken) , new SqlParameter("@FailedLogins", fldFailedLogins) , new SqlParameter("@IsActive", fldIsActive) , new SqlParameter("@WINSID", fldWINSID) }); return (int?)cmd.ExecuteScalar(); } } /// <summary> /// Insert by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>1, if insert was successful</returns> public int Insert(UserContract row) { int? result = null; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_Insert]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserName", row.UserName) , new SqlParameter("@Password", row.Password) , new SqlParameter("@DisplayName", row.DisplayName) , new SqlParameter("@Email", row.Email) , new SqlParameter("@AuthToken", row.AuthToken) , new SqlParameter("@UserToken", row.UserToken) , new SqlParameter("@FailedLogins", row.FailedLogins) , new SqlParameter("@IsActive", row.IsActive) , new SqlParameter("@WINSID", row.WINSID) }); result = (int?)cmd.ExecuteScalar(); row.UserId = result; } }); return result != null ? 1 : 0; } /// <summary> /// Insert by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>1, if insert was successful</returns> public int Insert(UserContract row, SqlConnection connection, SqlTransaction transaction) { int? result = null; using ( var cmd = new SqlCommand("[Auth].[User_Insert]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserName", row.UserName) , new SqlParameter("@Password", row.Password) , new SqlParameter("@DisplayName", row.DisplayName) , new SqlParameter("@Email", row.Email) , new SqlParameter("@AuthToken", row.AuthToken) , new SqlParameter("@UserToken", row.UserToken) , new SqlParameter("@FailedLogins", row.FailedLogins) , new SqlParameter("@IsActive", row.IsActive) , new SqlParameter("@WINSID", row.WINSID) }); result = (int?)cmd.ExecuteScalar(); row.UserId = result; } return result != null ? 1 : 0; } /// <summary> /// Insert the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Insert</param> /// <returns>The number of rows affected.</returns> public virtual int InsertAll(List<UserContract> rows) { var rowCount = 0; CALIDb.ConnectThen(x => { rowCount = InsertAll(rows, x, null); }); return rowCount; } /// <summary> /// Insert the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Insert</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int InsertAll(List<UserContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Insert(row, connection, transaction); return rowCount; } /// <summary> /// Run User_Update. /// </summary> /// <returns>The number of rows affected.</returns> /// <param name="fldUserId">Value for UserId</param> /// <param name="fldUserName">Value for UserName</param> /// <param name="fldPassword">Value for Password</param> /// <param name="fldDisplayName">Value for DisplayName</param> /// <param name="fldEmail">Value for Email</param> /// <param name="fldAuthToken">Value for AuthToken</param> /// <param name="fldUserToken">Value for UserToken</param> /// <param name="fldFailedLogins">Value for FailedLogins</param> /// <param name="fldIsActive">Value for IsActive</param> /// <param name="fldWINSID">Value for WINSID</param> public virtual int Update(int fldUserId , string fldUserName , byte[] fldPassword , string fldDisplayName , string fldEmail , Guid fldAuthToken , Guid fldUserToken , int fldFailedLogins , bool fldIsActive , string fldWINSID ) { var rowCount = 0; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_Update]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", fldUserId) , new SqlParameter("@UserName", fldUserName) , new SqlParameter("@Password", fldPassword) , new SqlParameter("@DisplayName", fldDisplayName) , new SqlParameter("@Email", fldEmail) , new SqlParameter("@AuthToken", fldAuthToken) , new SqlParameter("@UserToken", fldUserToken) , new SqlParameter("@FailedLogins", fldFailedLogins) , new SqlParameter("@IsActive", fldIsActive) , new SqlParameter("@WINSID", fldWINSID) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Run User_Update. /// </summary> /// <param name="fldUserId">Value for UserId</param> /// <param name="fldUserName">Value for UserName</param> /// <param name="fldPassword">Value for Password</param> /// <param name="fldDisplayName">Value for DisplayName</param> /// <param name="fldEmail">Value for Email</param> /// <param name="fldAuthToken">Value for AuthToken</param> /// <param name="fldUserToken">Value for UserToken</param> /// <param name="fldFailedLogins">Value for FailedLogins</param> /// <param name="fldIsActive">Value for IsActive</param> /// <param name="fldWINSID">Value for WINSID</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Update(int fldUserId , string fldUserName , byte[] fldPassword , string fldDisplayName , string fldEmail , Guid fldAuthToken , Guid fldUserToken , int fldFailedLogins , bool fldIsActive , string fldWINSID , SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Auth].[User_Update]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", fldUserId) , new SqlParameter("@UserName", fldUserName) , new SqlParameter("@Password", fldPassword) , new SqlParameter("@DisplayName", fldDisplayName) , new SqlParameter("@Email", fldEmail) , new SqlParameter("@AuthToken", fldAuthToken) , new SqlParameter("@UserToken", fldUserToken) , new SqlParameter("@FailedLogins", fldFailedLogins) , new SqlParameter("@IsActive", fldIsActive) , new SqlParameter("@WINSID", fldWINSID) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Update by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public virtual int Update(UserContract row) { var rowCount = 0; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_Update]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", row.UserId) , new SqlParameter("@UserName", row.UserName) , new SqlParameter("@Password", row.Password) , new SqlParameter("@DisplayName", row.DisplayName) , new SqlParameter("@Email", row.Email) , new SqlParameter("@AuthToken", row.AuthToken) , new SqlParameter("@UserToken", row.UserToken) , new SqlParameter("@FailedLogins", row.FailedLogins) , new SqlParameter("@IsActive", row.IsActive) , new SqlParameter("@WINSID", row.WINSID) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Update by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Update(UserContract row, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Auth].[User_Update]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", row.UserId) , new SqlParameter("@UserName", row.UserName) , new SqlParameter("@Password", row.Password) , new SqlParameter("@DisplayName", row.DisplayName) , new SqlParameter("@Email", row.Email) , new SqlParameter("@AuthToken", row.AuthToken) , new SqlParameter("@UserToken", row.UserToken) , new SqlParameter("@FailedLogins", row.FailedLogins) , new SqlParameter("@IsActive", row.IsActive) , new SqlParameter("@WINSID", row.WINSID) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Update the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Update</param> /// <returns>The number of rows affected.</returns> public virtual int UpdateAll(List<UserContract> rows) { var rowCount = 0; CALIDb.ConnectThen(x => { rowCount = UpdateAll(rows, x, null); }); return rowCount; } /// <summary> /// Update the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Update</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int UpdateAll(List<UserContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Update(row, connection, transaction); return rowCount; } /// <summary> /// Run User_Delete. /// </summary> /// <returns>The number of rows affected.</returns> /// <param name="fldUserId">Value for UserId</param> public virtual int Delete(int fldUserId ) { var rowCount = 0; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_Delete]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", fldUserId) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Run User_Delete. /// </summary> /// <param name="fldUserId">Value for UserId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Delete(int fldUserId , SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Auth].[User_Delete]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", fldUserId) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Delete by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public virtual int Delete(UserContract row) { var rowCount = 0; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_Delete]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", row.UserId) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Delete by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Delete(UserContract row, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Auth].[User_Delete]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", row.UserId) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Delete the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Delete</param> /// <returns>The number of rows affected.</returns> public virtual int DeleteAll(List<UserContract> rows) { var rowCount = 0; CALIDb.ConnectThen(x => { rowCount = DeleteAll(rows, x, null); }); return rowCount; } /// <summary> /// Delete the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Delete</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int DeleteAll(List<UserContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Delete(row, connection, transaction); return rowCount; } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldUserId">Value for UserId</param> /// <returns>True, if the values exist, or false.</returns> public virtual bool Exists(int fldUserId ) { bool result = false; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_Exists]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", fldUserId) }); result = (bool)cmd.ExecuteScalar(); } }); return result; } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldUserId">Value for UserId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>True, if the values exist, or false.</returns> public virtual bool Exists(int fldUserId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Auth].[User_Exists]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", fldUserId) }); return (bool)cmd.ExecuteScalar(); } } /// <summary> /// Run User_Search, and return results as a list of UserRow. /// </summary> /// <param name="fldUserName">Value for UserName</param> /// <param name="fldDisplayName">Value for DisplayName</param> /// <param name="fldEmail">Value for Email</param> /// <param name="fldWINSID">Value for WINSID</param> /// <returns>A collection of UserRow.</returns> public virtual bool Search(string fldUserName , string fldDisplayName , string fldEmail , string fldWINSID ) { var result = false; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_Search]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserName", fldUserName) , new SqlParameter("@DisplayName", fldDisplayName) , new SqlParameter("@Email", fldEmail) , new SqlParameter("@WINSID", fldWINSID) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run User_Search, and return results as a list of UserRow. /// </summary> /// <param name="fldUserName">Value for UserName</param> /// <param name="fldDisplayName">Value for DisplayName</param> /// <param name="fldEmail">Value for Email</param> /// <param name="fldWINSID">Value for WINSID</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of UserRow.</returns> public virtual bool Search(string fldUserName , string fldDisplayName , string fldEmail , string fldWINSID , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Auth].[User_Search]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserName", fldUserName) , new SqlParameter("@DisplayName", fldDisplayName) , new SqlParameter("@Email", fldEmail) , new SqlParameter("@WINSID", fldWINSID) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run User_SelectAll, and return results as a list of UserRow. /// </summary> /// <returns>A collection of UserRow.</returns> public virtual bool SelectAll() { var result = false; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_SelectAll]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run User_SelectAll, and return results as a list of UserRow. /// </summary> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of UserRow.</returns> public virtual bool SelectAll(SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Auth].[User_SelectAll]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run User_List, and return results as a list. /// </summary> /// <param name="fldUserName">Value for UserName</param> /// <returns>A collection of __ListItemRow.</returns> public virtual List<ListItemContract> List(string fldUserName ) { List<ListItemContract> result = null; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_List]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserName", fldUserName) }); using(var r = cmd.ExecuteReader()) result = ListItemLogic.ReadAllNow(r); } }); return result; } /// <summary> /// Run User_List, and return results as a list. /// </summary> /// <param name="fldUserName">Value for UserName</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of __ListItemRow.</returns> public virtual List<ListItemContract> List(string fldUserName , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Auth].[User_List]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserName", fldUserName) }); using(var r = cmd.ExecuteReader()) return ListItemLogic.ReadAllNow(r); } } /// <summary> /// Run User_SelectBy_UserId, and return results as a list of UserRow. /// </summary> /// <param name="fldUserId">Value for UserId</param> /// <returns>A collection of UserRow.</returns> public virtual bool SelectBy_UserId(int fldUserId ) { var result = false; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_SelectBy_UserId]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", fldUserId) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run User_SelectBy_UserId, and return results as a list of UserRow. /// </summary> /// <param name="fldUserId">Value for UserId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of UserRow.</returns> public virtual bool SelectBy_UserId(int fldUserId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Auth].[User_SelectBy_UserId]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", fldUserId) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run User_SelectBy_UserName, and return results as a list of UserRow. /// </summary> /// <param name="fldUserName">Value for UserName</param> /// <returns>A collection of UserRow.</returns> public virtual bool SelectBy_UserName(string fldUserName ) { var result = false; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_SelectBy_UserName]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserName", fldUserName) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run User_SelectBy_UserName, and return results as a list of UserRow. /// </summary> /// <param name="fldUserName">Value for UserName</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of UserRow.</returns> public virtual bool SelectBy_UserName(string fldUserName , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Auth].[User_SelectBy_UserName]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserName", fldUserName) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run User_SelectBy_Email, and return results as a list of UserRow. /// </summary> /// <param name="fldEmail">Value for Email</param> /// <returns>A collection of UserRow.</returns> public virtual bool SelectBy_Email(string fldEmail ) { var result = false; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_SelectBy_Email]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@Email", fldEmail) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run User_SelectBy_Email, and return results as a list of UserRow. /// </summary> /// <param name="fldEmail">Value for Email</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of UserRow.</returns> public virtual bool SelectBy_Email(string fldEmail , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Auth].[User_SelectBy_Email]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@Email", fldEmail) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run User_SelectBy_UserToken, and return results as a list of UserRow. /// </summary> /// <param name="fldUserToken">Value for UserToken</param> /// <returns>A collection of UserRow.</returns> public virtual bool SelectBy_UserToken(Guid fldUserToken ) { var result = false; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_SelectBy_UserToken]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserToken", fldUserToken) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run User_SelectBy_UserToken, and return results as a list of UserRow. /// </summary> /// <param name="fldUserToken">Value for UserToken</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of UserRow.</returns> public virtual bool SelectBy_UserToken(Guid fldUserToken , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Auth].[User_SelectBy_UserToken]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserToken", fldUserToken) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run User_SelectBy_WINSID, and return results as a list of UserRow. /// </summary> /// <param name="fldWINSID">Value for WINSID</param> /// <returns>A collection of UserRow.</returns> public virtual bool SelectBy_WINSID(string fldWINSID ) { var result = false; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_SelectBy_WINSID]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@WINSID", fldWINSID) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run User_SelectBy_WINSID, and return results as a list of UserRow. /// </summary> /// <param name="fldWINSID">Value for WINSID</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of UserRow.</returns> public virtual bool SelectBy_WINSID(string fldWINSID , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Auth].[User_SelectBy_WINSID]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@WINSID", fldWINSID) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Read all items into this collection /// </summary> /// <param name="reader">The result of running a sql command.</param> public virtual bool ReadAll(SqlDataReader reader) { var canRead = ReadOne(reader); var result = canRead; while (canRead) canRead = ReadOne(reader); return result; } /// <summary> /// Read one item into Results /// </summary> /// <param name="reader">The result of running a sql command.</param> public virtual bool ReadOne(SqlDataReader reader) { if (reader.Read()) { Results.Add( new UserContract { UserId = reader.GetInt32(0), UserName = reader.GetString(1), Password = (byte[])reader.GetValue(2), DisplayName = reader.GetString(3), Email = reader.GetString(4), AuthToken = reader.GetGuid(5), UserToken = reader.GetGuid(6), FailedLogins = reader.GetInt32(7), IsActive = reader.GetBoolean(8), WINSID = reader.IsDBNull(9) ? null : reader.GetString(9), }); return true; } return false; } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <returns>The number of rows affected.</returns> public virtual int Save(UserContract row) { if(row == null) return 0; if(row.UserId != null) return Update(row); return Insert(row); } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Save(UserContract row, SqlConnection connection, SqlTransaction transaction) { if(row == null) return 0; if(row.UserId != null) return Update(row, connection, transaction); return Insert(row, connection, transaction); } /// <summary> /// Save the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Save</param> /// <returns>The number of rows affected.</returns> public virtual int SaveAll(List<UserContract> rows) { var rowCount = 0; CALIDb.ConnectThen(x => { foreach(var row in rows) rowCount += Save(row, x, null); }); return rowCount; } /// <summary> /// Save the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int SaveAll(List<UserContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Save(row, connection, transaction); return rowCount; } } }
using System; using System.Collections.Generic; using System.Reflection; using System.Xml; using VersionOne.SDK.APIClient; using VersionOne.ServiceHost.Eventing; using VersionOne.Profile; using VersionOne.ServiceHost.Core.Configuration; using VersionOne.ServiceHost.Core.Logging; namespace VersionOne.ServiceHost.Core.Services { public abstract class V1WriterServiceBase : IHostedService { private IServices services; protected XmlElement Config; protected IEventManager EventManager; protected ILogger Logger; private const string MemberType = "Member"; private const string DefaultRoleNameProperty = "DefaultRole.Name"; protected virtual IServices Services { get { if (services == null) { try { var settings = VersionOneSettings.FromXmlElement(Config["Settings"]); var connector = V1Connector .WithInstanceUrl(settings.Url) .WithUserAgentHeader("VersionOne.Integration.JIRASync", Assembly.GetEntryAssembly().GetName().Version.ToString()); ICanSetProxyOrEndpointOrGetConnector connectorWithAuth; switch (settings.AuthenticationType) { case AuthenticationTypes.AccessToken: connectorWithAuth = connector.WithAccessToken(settings.AccessToken); break; case AuthenticationTypes.Basic: connectorWithAuth = connector.WithUsernameAndPassword(settings.Username, settings.Password); break; case AuthenticationTypes.Integrated: connectorWithAuth = connector.WithWindowsIntegrated(); break; case AuthenticationTypes.IntegratedWithCredentials: connectorWithAuth = connector.WithWindowsIntegrated(settings.Username, settings.Password); break; default: throw new Exception("Invalid authentication type"); } if (settings.ProxySettings.Enabled) connectorWithAuth.WithProxy( new ProxyProvider( new Uri(settings.ProxySettings.Url), settings.ProxySettings.Username, settings.ProxySettings.Password, settings.ProxySettings.Domain)); services = new SDK.APIClient.Services(connectorWithAuth.Build()); if (!services.LoggedIn.IsNull) LogVersionOneConnectionInformation(); } catch (Exception ex) { Logger.Log("Failed to connect to VersionOne server", ex); throw; } } return services; } } private void LogVersionOneConnectionInformation() { try { var metaVersion = ((MetaModel)Services.Meta).Version.ToString(); var memberOid = Services.LoggedIn.Momentless.ToString(); var defaultRole = GetLoggedInMemberRole(); Logger.LogVersionOneConnectionInformation(LogMessage.SeverityType.Info, metaVersion, memberOid, defaultRole); } catch (Exception ex) { Logger.Log(LogMessage.SeverityType.Warning, "Failed to log VersionOne connection information.", ex); } } private string GetLoggedInMemberRole() { var defaultRoleAttribute = Services.Meta.GetAssetType(MemberType).GetAttributeDefinition(DefaultRoleNameProperty); return Services.Localization(defaultRoleAttribute); } public virtual void Initialize(XmlElement config, IEventManager eventManager, IProfile profile) { Config = config; EventManager = eventManager; Logger = new Logger(eventManager); Logger.LogVersionOneConfiguration(LogMessage.SeverityType.Info, Config["Settings"]); } public void Start() { // TODO move subscriptions to timer events, etc. here } protected abstract IEnumerable<NeededAssetType> NeededAssetTypes { get; } protected void VerifyMeta() { try { VerifyNeededMeta(NeededAssetTypes); VerifyRuntimeMeta(); } catch (MetaException ex) { throw new ApplicationException("Necessary meta is not present in this VersionOne system", ex); } } protected virtual void VerifyRuntimeMeta() { } protected struct NeededAssetType { public readonly string Name; public readonly string[] AttributeDefinitionNames; public NeededAssetType(string name, string[] attributedefinitionnames) { Name = name; AttributeDefinitionNames = attributedefinitionnames; } } protected void VerifyNeededMeta(IEnumerable<NeededAssetType> neededassettypes) { foreach (var neededAssetType in neededassettypes) { var assettype = Services.Meta.GetAssetType(neededAssetType.Name); foreach (var attributeDefinitionName in neededAssetType.AttributeDefinitionNames) { var attribdef = assettype.GetAttributeDefinition(attributeDefinitionName); } } } #region Meta wrappers protected IAssetType RequestType { get { return Services.Meta.GetAssetType("Request"); } } protected IAssetType DefectType { get { return Services.Meta.GetAssetType("Defect"); } } protected IAssetType StoryType { get { return Services.Meta.GetAssetType("Story"); } } protected IAssetType ReleaseVersionType { get { return Services.Meta.GetAssetType("StoryCategory"); } } protected IAssetType LinkType { get { return Services.Meta.GetAssetType("Link"); } } protected IAssetType NoteType { get { return Services.Meta.GetAssetType("Note"); } } protected IAttributeDefinition DefectName { get { return DefectType.GetAttributeDefinition("Name"); } } protected IAttributeDefinition DefectDescription { get { return DefectType.GetAttributeDefinition("Description"); } } protected IAttributeDefinition DefectOwners { get { return DefectType.GetAttributeDefinition("Owners"); } } protected IAttributeDefinition DefectScope { get { return DefectType.GetAttributeDefinition("Scope"); } } protected IAttributeDefinition DefectAssetState { get { return RequestType.GetAttributeDefinition("AssetState"); } } protected IAttributeDefinition RequestCompanyName { get { return RequestType.GetAttributeDefinition("Name"); } } protected IAttributeDefinition RequestNumber { get { return RequestType.GetAttributeDefinition("Number"); } } protected IAttributeDefinition RequestSuggestedInstance { get { return RequestType.GetAttributeDefinition("Reference"); } } protected IAttributeDefinition RequestMethodology { get { return RequestType.GetAttributeDefinition("Source"); } } protected IAttributeDefinition RequestMethodologyName { get { return RequestType.GetAttributeDefinition("Source.Name"); } } protected IAttributeDefinition RequestCommunityEdition { get { return RequestType.GetAttributeDefinition("Custom_CommunityEdition"); } } protected IAttributeDefinition RequestAssetState { get { return RequestType.GetAttributeDefinition("AssetState"); } } protected IAttributeDefinition RequestCreateDate { get { return RequestType.GetAttributeDefinition("CreateDate"); } } protected IAttributeDefinition RequestCreatedBy { get { return RequestType.GetAttributeDefinition("CreatedBy"); } } protected IOperation RequestInactivate { get { return Services.Meta.GetOperation("Request.Inactivate"); } } protected IAttributeDefinition StoryName { get { return StoryType.GetAttributeDefinition("Name"); } } protected IAttributeDefinition StoryActualInstance { get { return StoryType.GetAttributeDefinition("Reference"); } } protected IAttributeDefinition StoryRequests { get { return StoryType.GetAttributeDefinition("Requests"); } } protected IAttributeDefinition StoryReleaseVersion { get { return StoryType.GetAttributeDefinition("Category"); } } protected IAttributeDefinition StoryMethodology { get { return StoryType.GetAttributeDefinition("Source"); } } protected IAttributeDefinition StoryCommunitySite { get { return StoryType.GetAttributeDefinition("Custom_CommunitySite"); } } protected IAttributeDefinition StoryScope { get { return StoryType.GetAttributeDefinition("Scope"); } } protected IAttributeDefinition StoryOwners { get { return StoryType.GetAttributeDefinition("Owners"); } } protected IAttributeDefinition ReleaseVersionName { get { return ReleaseVersionType.GetAttributeDefinition("Name"); } } protected IAttributeDefinition LinkAsset { get { return LinkType.GetAttributeDefinition("Asset"); } } protected IAttributeDefinition LinkOnMenu { get { return LinkType.GetAttributeDefinition("OnMenu"); } } protected IAttributeDefinition LinkUrl { get { return LinkType.GetAttributeDefinition("URL"); } } protected IAttributeDefinition LinkName { get { return LinkType.GetAttributeDefinition("Name"); } } protected IAttributeDefinition NoteName { get { return NoteType.GetAttributeDefinition("Name"); } } protected IAttributeDefinition NoteAsset { get { return NoteType.GetAttributeDefinition("Asset"); } } protected IAttributeDefinition NotePersonal { get { return NoteType.GetAttributeDefinition("Personal"); } } protected IAttributeDefinition NoteContent { get { return NoteType.GetAttributeDefinition("Content"); } } #endregion } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace Core.Throttling { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
#if DNX451 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using OmniSharp.Api.V2; using OmniSharp.Models.V2; using OmniSharp.Services; using Xunit; namespace OmniSharp.Tests { public class CodingActionsV2Facts { private OmnisharpWorkspace _workspace; private string bufferPath = $"{Path.DirectorySeparatorChar}somepath{Path.DirectorySeparatorChar}buffer.cs"; [Fact] public async Task Can_get_code_actions_from_nrefactory() { var source = @"public class Class1 { public void Whatever() { int$ i = 1; } }"; var refactorings = await FindRefactoringNamesAsync(source); Assert.Contains("Use 'var' keyword", refactorings); } [Fact] public async Task Can_get_code_actions_from_roslyn() { var source = @"public class Class1 { public void Whatever() { Conso$le.Write(""should be using System;""); } }"; var refactorings = await FindRefactoringNamesAsync(source); Assert.Contains("using System;", refactorings); } [Fact] public async Task Can_sort_usings() { var source = @"using MyNamespace3; using MyNamespace4; using MyNamespace2; using System; u$sing MyNamespace1;"; var expected = @"using System; using MyNamespace1; using MyNamespace2; using MyNamespace3; using MyNamespace4;"; var response = await RunRefactoring(source, "Sort usings"); Assert.Equal(expected, response.Changes.First().Buffer); } [Fact] public async Task Can_remove_unnecessary_usings() { var source = @"using MyNamespace3; using MyNamespace4; using MyNamespace2; using System; u$sing MyNamespace1; public class c {public c() {Console.Write(1);}}"; var expected = @"using System; public class c {public c() {Console.Write(1);}}"; var response = await RunRefactoring(source, "Remove Unnecessary Usings"); AssertIgnoringIndent(expected, response.Changes.First().Buffer); } [Fact] public async Task Can_get_ranged_code_action() { var source = @"public class Class1 { public void Whatever() { $Console.Write(""should be using System;"");$ } }"; var refactorings = await FindRefactoringNamesAsync(source); Assert.Contains("Extract Method", refactorings); } [Fact] public async Task Can_extract_method() { var source = @"public class Class1 { public void Whatever() { $Console.Write(""should be using System;"");$ } }"; var expected = @"public class Class1 { public void Whatever() { NewMethod(); } private static void NewMethod() { Console.Write(""should be using System;""); } }"; var response = await RunRefactoring(source, "Extract Method"); AssertIgnoringIndent(expected, response.Changes.First().Buffer); } [Fact] public async Task Can_create_a_class_with_a_new_method_in_adjacent_file() { var source = @"namespace MyNamespace public class Class1 { public void Whatever() { MyNew$Class.DoSomething(); } }"; var response = await RunRefactoring(source, "Generate class for 'MyNewClass' in 'MyNamespace' (in new file)", true); var change = response.Changes.First(); Assert.Equal($"{Path.DirectorySeparatorChar}somepath{Path.DirectorySeparatorChar}MyNewClass.cs", change.FileName); var expected = @"namespace MyNamespace { internal class MyNewClass { } }"; AssertIgnoringIndent(expected, change.Changes.First().NewText); source = @"namespace MyNamespace public class Class1 { public void Whatever() { MyNewClass.DoS$omething(); } }"; response = await RunRefactoring(source, "Generate method 'MyNewClass.DoSomething'", true); expected = @"internal static void DoSomething() { throw new NotImplementedException(); } "; change = response.Changes.First(); AssertIgnoringIndent(expected, change.Changes.First().NewText); } private void AssertIgnoringIndent(string expected, string actual) { Assert.Equal(TrimLines(expected), TrimLines(actual), false, true, true); } private string TrimLines(string source) { return string.Join("\n", source.Split('\n').Select(s => s.Trim())); } private async Task<RunCodeActionResponse> RunRefactoring(string source, string refactoringName, bool wantsChanges = false) { var refactorings = await FindRefactoringsAsync(source); Assert.Contains(refactoringName, refactorings.Select(a => a.Name)); var identifier = refactorings.First(action => action.Name.Equals(refactoringName)).Identifier; return await RunRefactoringsAsync(source, identifier, wantsChanges); } private async Task<IEnumerable<string>> FindRefactoringNamesAsync(string source) { var codeActions = await FindRefactoringsAsync(source); return codeActions.Select(a => a.Name); } private async Task<IEnumerable<OmniSharpCodeAction>> FindRefactoringsAsync(string source) { var request = CreateGetCodeActionsRequest(source); _workspace = _workspace ?? TestHelpers.CreateSimpleWorkspace(request.Buffer, bufferPath); var controller = new Api.V2.CodeActionController(_workspace, new ICodeActionProvider[] { new RoslynCodeActionProvider(), new NRefactoryCodeActionProvider() }, new FakeLoggerFactory()); var response = await controller.GetCodeActions(request); return response.CodeActions; } private async Task<RunCodeActionResponse> RunRefactoringsAsync(string source, string identifier, bool wantsChanges = false) { var request = CreateRunCodeActionRequest(source, identifier, wantsChanges); _workspace = _workspace ?? TestHelpers.CreateSimpleWorkspace(request.Buffer, bufferPath); var controller = new Api.V2.CodeActionController(_workspace, new ICodeActionProvider[] { new RoslynCodeActionProvider(), new NRefactoryCodeActionProvider() }, new FakeLoggerFactory()); var response = await controller.RunCodeAction(request); return response; } private GetCodeActionsRequest CreateGetCodeActionsRequest(string source) { var range = TestHelpers.GetRangeFromDollars(source); Range selection = GetSelection(range); return new GetCodeActionsRequest { Line = range.Start.Line, Column = range.Start.Column, FileName = bufferPath, Buffer = source.Replace("$", ""), Selection = selection }; } private RunCodeActionRequest CreateRunCodeActionRequest(string source, string identifier, bool wantChanges) { var range = TestHelpers.GetRangeFromDollars(source); var selection = GetSelection(range); return new RunCodeActionRequest { Line = range.Start.Line, Column = range.Start.Column, Selection = selection, FileName = bufferPath, Buffer = source.Replace("$", ""), Identifier = identifier, WantsTextChanges = wantChanges }; } private static Range GetSelection(TestHelpers.Range range) { Range selection = null; if (!range.IsEmpty) { var start = new Point { Line = range.Start.Line, Column = range.Start.Column }; var end = new Point { Line = range.End.Line, Column = range.End.Column }; selection = new Range { Start = start, End = end }; } return selection; } } } #endif
using Signum.Engine.Basics; using Signum.Engine.Dynamic; using Signum.Engine.DynamicQuery; using Signum.Engine.Maps; using Signum.Entities; using Signum.React.Facades; using Signum.Utilities; using Signum.Utilities.ExpressionTrees; using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc; using Signum.React.Filters; using System.ComponentModel.DataAnnotations; using System.Runtime.CompilerServices; using System.Reflection; using Signum.Utilities.Reflection; namespace Signum.React.TypeHelp { [ValidateModelFilter] public class TypeHelpController : ControllerBase { [HttpPost("api/typeHelp/autocompleteEntityCleanType")] public List<string> AutocompleteEntityCleanType([Required, FromBody]AutocompleteEntityCleanTypeRequest request) { Schema s = Schema.Current; var types = TypeLogic.NameToType .Where(kvp => s.IsAllowed(kvp.Value, true) == null) .Select(kvp => kvp.Key).ToList(); var result = Filter(types, request.query, request.limit); return result; } public class AutocompleteEntityCleanTypeRequest { public string query; public int limit; } [HttpPost("api/typeHelp/autocompleteType")] public List<string> AutocompleteType([Required, FromBody]AutocompleteTypeRequest request) //Not comprehensive, just useful { var types = GetTypes(request); return Filter(types, request.query, request.limit); } private List<string> Filter(List<string> types, string query, int limit) { var result = types .Where(a => a.StartsWith(query, StringComparison.InvariantCultureIgnoreCase)) .OrderBy(a => a.Length) .ThenBy(a => a) .Take(limit).ToList(); if (result.Count < limit) result.AddRange(types.Where(a => a.Contains(query, StringComparison.InvariantCultureIgnoreCase)) .OrderBy(a => a.Length) .ThenBy(a => a) .Take(result.Count - limit).ToList()); return result; } public class AutocompleteTypeRequest { public string query; public int limit; public bool includeBasicTypes; public bool includeEntities; public bool includeModelEntities; public bool includeEmbeddedEntities; public bool includeMList; public bool includeQueriable; } public static List<string> AditionalTypes = new List<string> { "Date", "DateTime", "TimeSpan", "Guid", }; List<string> GetTypes(AutocompleteTypeRequest request) { List<string> result = new List<string>(); if (request.includeBasicTypes) { result.AddRange(CSharpRenderer.BasicTypeNames.Values); result.AddRange(AditionalTypes); } if (request.includeEntities) { result.AddRange(TypeLogic.TypeToEntity.Keys.Select(a => a.Name)); } if (request.includeModelEntities) { result.AddRange(DynamicTypeLogic.AvailableModelEntities.Value.Select(a => a.Name)); } if (request.includeEmbeddedEntities) { result.AddRange(DynamicTypeLogic.AvailableEmbeddedEntities.Value.Select(a => a.Name)); } if (request.includeMList) return Fix(result, "MList", request.query); if (request.includeQueriable) return Fix(result, "IQueryable", request.query); return result; } List<string> Fix(List<string> result, string token, string query) { if (query.StartsWith(token)) return result.Select(a => token + "<" + a + ">").ToList(); else { result.Add(token + "<"); return result; } } [HttpGet("api/typeHelp/{typeName}/{mode}")] public TypeHelpTS? GetTypeHelp(string typeName, TypeHelpMode mode) { Type? type = TypeLogic.TryGetType(typeName); if (type == null) return null; var isEnum = EnumEntity.IsEnumEntity(type); var members = new List<TypeMemberHelpTS>(); if (isEnum) { var enumType = EnumEntity.Extract(type)!; var values = EnumEntity.GetValues(enumType).ToList(); members.AddRange(values.Select(ev => new TypeMemberHelpTS(ev))); } else { var routes = PropertyRoute.GenerateRoutes(type); var root = TreeHelper.ToTreeC(routes, a => a.Parent).SingleEx(); members = root.Children .Where(a => mode == TypeHelpMode.CSharp || ReflectionServer.InTypeScript(a.Value)) .Select(pr => new TypeMemberHelpTS(pr, mode)).ToList(); if (mode == TypeHelpMode.CSharp) { var expressions = QueryLogic.Expressions.RegisteredExtensions.GetValue(type); members.AddRange(expressions.Values.Select(ex => new TypeMemberHelpTS(ex))); } } return new TypeHelpTS { type = (isEnum ? EnumEntity.Extract(type)!.Name : type.Name), cleanTypeName = typeName, isEnum = isEnum, members = members }; } } public enum TypeHelpMode { CSharp, Typescript } public class TypeHelpTS { public string type; public string cleanTypeName; public bool isEnum; public List<TypeMemberHelpTS> members; } public class TypeMemberHelpTS { public string? propertyString; public string? name; public string type; public string? cleanTypeName; public bool isExpression; public bool isEnum; public List<TypeMemberHelpTS> subMembers; public TypeMemberHelpTS(Node<PropertyRoute> node, TypeHelpMode mode) { var pr = node.Value; this.propertyString = pr.PropertyString(); this.name = mode == TypeHelpMode.Typescript ? pr.PropertyInfo?.Name.FirstLower() : pr.PropertyInfo?.Name; this.type = mode == TypeHelpMode.Typescript && ReflectionServer.IsId(pr) ? PrimaryKey.Type(pr.RootType).Nullify().TypeName() : pr.Let(propertyRoute => { var typeName = propertyRoute.Type.TypeName(); var nullable = propertyRoute.PropertyInfo?.IsNullable(); return typeName + (nullable == true ? "?" : ""); }); this.isExpression = false; this.isEnum = pr.Type.UnNullify().IsEnum; this.cleanTypeName = GetCleanTypeName(pr.Type.UnNullify().IsEnum ? EnumEntity.Generate(pr.Type.UnNullify()) : pr.Type); this.subMembers = node.Children.Select(a => new TypeMemberHelpTS(a, mode)).ToList(); } public TypeMemberHelpTS(ExtensionInfo ex) { this.name = ex.Key; this.type = ex.Type.TypeName(); this.isExpression = true; this.isEnum = false; this.cleanTypeName = GetCleanTypeName(ex.Type); this.subMembers = new List<TypeMemberHelpTS>(); } public TypeMemberHelpTS(Enum ev) { this.name = ev.ToString(); this.type = ev.GetType().TypeName(); this.isExpression = false; this.isEnum = true; this.cleanTypeName = null; this.subMembers = new List<TypeMemberHelpTS>(); } string? GetCleanTypeName(Type type) { type = type.ElementType() ?? type; return TypeLogic.TryGetCleanName(type.CleanType()); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Buffers; using System.IO.Pipelines; using System.Numerics; using System.Runtime.CompilerServices; using System.Text.Http.Parser.Internal; namespace System.Text.Http.Parser { public class HttpParser : IHttpParser { // TODO: commented out; //public ILogger Log { get; set; } // byte types don't have a data type annotation so we pre-cast them; to avoid in-place casts private const byte ByteCR = (byte)'\r'; private const byte ByteLF = (byte)'\n'; private const byte ByteColon = (byte)':'; private const byte ByteSpace = (byte)' '; private const byte ByteTab = (byte)'\t'; private const byte ByteQuestionMark = (byte)'?'; private const byte BytePercentage = (byte)'%'; public unsafe bool ParseRequestLine<T>(T handler, ReadableBuffer buffer, out ReadCursor consumed, out ReadCursor examined) where T : IHttpRequestLineHandler { consumed = buffer.Start; examined = buffer.End; // Prepare the first span var span = buffer.First.Span; var lineIndex = span.IndexOf(ByteLF); if (lineIndex >= 0) { consumed = buffer.Move(consumed, lineIndex + 1); span = span.Slice(0, lineIndex + 1); } else if (buffer.IsSingleSpan) { return false; } else { span = TryGetNewLineSpan(ref buffer, out consumed); if (span.Length == 0) { // No request line end return false; } } // Fix and parse the span fixed (byte* data = &span.DangerousGetPinnableReference()) { ParseRequestLine(handler, data, span.Length); } examined = consumed; return true; } static readonly byte[] s_Eol = Encoding.UTF8.GetBytes("\r\n"); public unsafe bool ParseRequestLine<T>(ref T handler, ReadOnlyBytes buffer, out int consumed) where T : IHttpRequestLineHandler { // Prepare the first span var span = buffer.First.Span; var lineIndex = span.IndexOf(ByteLF); if (lineIndex >= 0) { consumed = lineIndex + 1; span = span.Slice(0, lineIndex + 1); } else { var eol = buffer.IndexOf(s_Eol); if (eol == -1) { consumed = 0; return false; } span = buffer.Slice(0, eol + s_Eol.Length).ToSpan(); } // Fix and parse the span fixed (byte* data = &span.DangerousGetPinnableReference()) { ParseRequestLine(handler, data, span.Length); } consumed = span.Length; return true; } private unsafe void ParseRequestLine<T>(T handler, byte* data, int length) where T : IHttpRequestLineHandler { int offset; ReadOnlySpan<byte> customMethod; // Get Method and set the offset var method = HttpUtilities.GetKnownMethod(data, length, out offset); if (method == Http.Method.Custom) { customMethod = GetUnknownMethod(data, length, out offset); } // Skip space offset++; byte ch = 0; // Target = Path and Query var pathEncoded = false; var pathStart = -1; for (; offset < length; offset++) { ch = data[offset]; if (ch == ByteSpace) { if (pathStart == -1) { // Empty path is illegal RejectRequestLine(data, length); } break; } else if (ch == ByteQuestionMark) { if (pathStart == -1) { // Empty path is illegal RejectRequestLine(data, length); } break; } else if (ch == BytePercentage) { if (pathStart == -1) { // Path starting with % is illegal RejectRequestLine(data, length); } pathEncoded = true; } else if (pathStart == -1) { pathStart = offset; } } if (pathStart == -1) { // Start of path not found RejectRequestLine(data, length); } var pathBuffer = new ReadOnlySpan<byte>(data + pathStart, offset - pathStart); // Query string var queryStart = offset; if (ch == ByteQuestionMark) { // We have a query string for (; offset < length; offset++) { ch = data[offset]; if (ch == ByteSpace) { break; } } } // End of query string not found if (offset == length) { RejectRequestLine(data, length); } var targetBuffer = new ReadOnlySpan<byte>(data + pathStart, offset - pathStart); var query = new ReadOnlySpan<byte>(data + queryStart, offset - queryStart); // Consume space offset++; // Version var httpVersion = HttpUtilities.GetKnownVersion(data + offset, length - offset); if (httpVersion == Http.Version.Unknown) { if (data[offset] == ByteCR || data[length - 2] != ByteCR) { // If missing delimiter or CR before LF, reject and log entire line RejectRequestLine(data, length); } else { // else inform HTTP version is unsupported. RejectUnknownVersion(data + offset, length - offset - 2); } } // After version's 8 bytes and CR, expect LF if (data[offset + 8 + 1] != ByteLF) { RejectRequestLine(data, length); } var line = new ReadOnlySpan<byte>(data, length); handler.OnStartLine(method, httpVersion, targetBuffer, pathBuffer, query, customMethod, pathEncoded); } public unsafe bool ParseHeaders<T>(T handler, ReadableBuffer buffer, out ReadCursor consumed, out ReadCursor examined, out int consumedBytes) where T : IHttpHeadersHandler { consumed = buffer.Start; examined = buffer.End; consumedBytes = 0; var bufferEnd = buffer.End; var reader = new ReadableBufferReader(buffer); var start = default(ReadableBufferReader); var done = false; try { while (!reader.End) { var span = reader.Span; var remaining = span.Length - reader.Index; fixed (byte* pBuffer = &span.DangerousGetPinnableReference()) { while (remaining > 0) { var index = reader.Index; int ch1; int ch2; // Fast path, we're still looking at the same span if (remaining >= 2) { ch1 = pBuffer[index]; ch2 = pBuffer[index + 1]; } else { // Store the reader before we look ahead 2 bytes (probably straddling // spans) start = reader; // Possibly split across spans ch1 = reader.Take(); ch2 = reader.Take(); } if (ch1 == ByteCR) { // Check for final CRLF. if (ch2 == -1) { // Reset the reader so we don't consume anything reader = start; return false; } else if (ch2 == ByteLF) { // If we got 2 bytes from the span directly so skip ahead 2 so that // the reader's state matches what we expect if (index == reader.Index) { reader.Skip(2); } done = true; return true; } // Headers don't end in CRLF line. RejectRequest(RequestRejectionReason.InvalidRequestHeadersNoCRLF); } // We moved the reader so look ahead 2 bytes so reset both the reader // and the index if (index != reader.Index) { reader = start; index = reader.Index; } var endIndex = new ReadOnlySpan<byte>(pBuffer + index, remaining).IndexOf(ByteLF); var length = 0; if (endIndex != -1) { length = endIndex + 1; var pHeader = pBuffer + index; TakeSingleHeader(pHeader, length, handler); } else { var current = reader.Cursor; // Split buffers if (ReadCursorOperations.Seek(current, bufferEnd, out var lineEnd, ByteLF) == -1) { // Not there return false; } // Make sure LF is included in lineEnd lineEnd = buffer.Move(lineEnd, 1); var headerSpan = buffer.Slice(current, lineEnd).ToSpan(); length = headerSpan.Length; fixed (byte* pHeader = &headerSpan.DangerousGetPinnableReference()) { TakeSingleHeader(pHeader, length, handler); } // We're going to the next span after this since we know we crossed spans here // so mark the remaining as equal to the headerSpan so that we end up at 0 // on the next iteration remaining = length; } // Skip the reader forward past the header line reader.Skip(length); remaining -= length; } } } return false; } finally { consumed = reader.Cursor; consumedBytes = reader.ConsumedBytes; if (done) { examined = consumed; } } } public unsafe bool ParseHeaders<T>(T handler, ReadOnlyBytes buffer, out int consumedBytes) where T : class, IHttpHeadersHandler { return ParseHeaders(ref handler, buffer, out consumedBytes); } public unsafe bool ParseHeaders<T>(ref T handler, ReadOnlyBytes buffer, out int consumedBytes) where T : IHttpHeadersHandler { var index = 0; var rest = buffer.Rest; var span = buffer.First.Span; var remaining = span.Length; consumedBytes = 0; while (true) { fixed (byte* pBuffer = &span.DangerousGetPinnableReference()) { while (remaining > 0) { int ch1; int ch2; // Fast path, we're still looking at the same span if (remaining >= 2) { ch1 = pBuffer[index]; ch2 = pBuffer[index + 1]; } // Slow Path else { ReadNextTwoChars(pBuffer, remaining, index, out ch1, out ch2, rest); } if (ch1 == ByteCR) { if (ch2 == ByteLF) { consumedBytes += 2; return true; } if (ch2 == -1) { consumedBytes = 0; return false; } // Headers don't end in CRLF line. RejectRequest(RequestRejectionReason.InvalidRequestHeadersNoCRLF); } var endIndex = new ReadOnlySpan<byte>(pBuffer + index, remaining).IndexOf(ByteLF); var length = 0; if (endIndex != -1) { length = endIndex + 1; var pHeader = pBuffer + index; TakeSingleHeader(pHeader, length, handler); } else { // Split buffers var end = buffer.Slice(index).IndexOf(ByteLF); if (end == -1) { // Not there consumedBytes = 0; return false; } var headerSpan = buffer.Slice(index, end - index + 1).ToSpan(); length = headerSpan.Length; fixed (byte* pHeader = &headerSpan.DangerousGetPinnableReference()) { TakeSingleHeader(pHeader, length, handler); } } // Skip the reader forward past the header line index += length; consumedBytes += length; remaining -= length; } } if (rest != null) { span = rest.First.Span; rest = rest.Rest; remaining = span.Length + remaining; index = span.Length - remaining; } else { consumedBytes = 0; return false; } } } private static unsafe void ReadNextTwoChars(byte* pBuffer, int remaining, int index, out int ch1, out int ch2, IReadOnlyBufferList<byte> rest) { if (remaining == 1) { ch1 = pBuffer[index]; if (rest == null) { ch2 = -1; } else { ch2 = rest.First.Span[0]; } } else { ch1 = -1; ch2 = -1; if (rest != null) { var nextSpan = rest.First.Span; if (nextSpan.Length > 0) { ch1 = nextSpan[0]; if (nextSpan.Length > 1) { ch2 = nextSpan[1]; } else { ch2 = -1; } } else { ch2 = -1; } } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe int FindEndOfName(byte* headerLine, int length) { var index = 0; var sawWhitespace = false; for (; index < length; index++) { var ch = headerLine[index]; if (ch == ByteColon) { break; } if (ch == ByteTab || ch == ByteSpace || ch == ByteCR) { sawWhitespace = true; } } if (index == length || sawWhitespace) { RejectRequestHeader(headerLine, length); } return index; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe void TakeSingleHeader<T>(byte* headerLine, int length, T handler) where T : IHttpHeadersHandler { // Skip CR, LF from end position var valueEnd = length - 3; var nameEnd = FindEndOfName(headerLine, length); if (headerLine[valueEnd + 2] != ByteLF) { RejectRequestHeader(headerLine, length); } if (headerLine[valueEnd + 1] != ByteCR) { RejectRequestHeader(headerLine, length); } // Skip colon from value start var valueStart = nameEnd + 1; // Ignore start whitespace for (; valueStart < valueEnd; valueStart++) { var ch = headerLine[valueStart]; if (ch != ByteTab && ch != ByteSpace && ch != ByteCR) { break; } else if (ch == ByteCR) { RejectRequestHeader(headerLine, length); } } // Check for CR in value var i = valueStart + 1; if (Contains(headerLine + i, valueEnd - i, ByteCR)) { RejectRequestHeader(headerLine, length); } // Ignore end whitespace for (; valueEnd >= valueStart; valueEnd--) { var ch = headerLine[valueEnd]; if (ch != ByteTab && ch != ByteSpace) { break; } } var nameBuffer = new ReadOnlySpan<byte>(headerLine, nameEnd); var valueBuffer = new ReadOnlySpan<byte>(headerLine + valueStart, valueEnd - valueStart + 1); handler.OnHeader(nameBuffer, valueBuffer); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static unsafe bool Contains(byte* searchSpace, int length, byte value) { var i = 0; if (Vector.IsHardwareAccelerated) { // Check Vector lengths if (length - Vector<byte>.Count >= i) { var vValue = GetVector(value); do { if (!Vector<byte>.Zero.Equals(Vector.Equals(vValue, Unsafe.Read<Vector<byte>>(searchSpace + i)))) { goto found; } i += Vector<byte>.Count; } while (length - Vector<byte>.Count >= i); } } // Check remaining for CR for (; i <= length; i++) { var ch = searchSpace[i]; if (ch == value) { goto found; } } return false; found: return true; } [MethodImpl(MethodImplOptions.NoInlining)] private static Span<byte> TryGetNewLineSpan(ref ReadableBuffer buffer, out ReadCursor end) { var start = buffer.Start; if (ReadCursorOperations.Seek(start, buffer.End, out end, ByteLF) != -1) { // Move 1 byte past the \n end = buffer.Move(end, 1); return buffer.Slice(start, end).ToSpan(); } return default(Span<byte>); } [MethodImpl(MethodImplOptions.NoInlining)] private unsafe ReadOnlySpan<byte> GetUnknownMethod(byte* data, int length, out int methodLength) { methodLength = 0; for (var i = 0; i < length; i++) { var ch = data[i]; if (ch == ByteSpace) { if (i == 0) { RejectRequestLine(data, length); } methodLength = i; break; } else if (!IsValidTokenChar((char)ch)) { RejectRequestLine(data, length); } } return new ReadOnlySpan<byte>(data, methodLength); } // TODO: this could be optimized by using a table private static bool IsValidTokenChar(char c) { // Determines if a character is valid as a 'token' as defined in the // HTTP spec: https://tools.ietf.org/html/rfc7230#section-3.2.6 return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '!' || c == '#' || c == '$' || c == '%' || c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' || c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~'; } private void RejectRequest(RequestRejectionReason reason) => throw BadHttpRequestException.GetException(reason); private unsafe void RejectRequestLine(byte* requestLine, int length) => throw GetInvalidRequestException(RequestRejectionReason.InvalidRequestLine, requestLine, length); private unsafe void RejectRequestHeader(byte* headerLine, int length) => throw GetInvalidRequestException(RequestRejectionReason.InvalidRequestHeader, headerLine, length); private unsafe void RejectUnknownVersion(byte* version, int length) => throw GetInvalidRequestException(RequestRejectionReason.UnrecognizedHTTPVersion, version, length); private unsafe BadHttpRequestException GetInvalidRequestException(RequestRejectionReason reason, byte* detail, int length) { return BadHttpRequestException.GetException(reason, ""); } public void Reset() { } [MethodImpl(MethodImplOptions.AggressiveInlining)] static Vector<byte> GetVector(byte vectorByte) { // Vector<byte> .ctor doesn't become an intrinsic due to detection issue // However this does cause it to become an intrinsic (with additional multiply and reg->reg copy) // https://github.com/dotnet/coreclr/issues/7459#issuecomment-253965670 return Vector.AsVectorByte(new Vector<uint>(vectorByte * 0x01010101u)); } enum State : byte { ParsingName, BeforValue, ParsingValue, ArferCR, } } }
// 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; /// <summary> /// MakeByRefType() /// </summary> public class TypeMakeByRefType { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Call MakeByRefType for reference type"); try { Type type = typeof(String); Type refType = type.MakeByRefType(); if (!refType.IsByRef) { TestLibrary.TestFramework.LogError("001", "Call MakeByRefType for reference type does not make a byref type"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Call MakeByRefType for value type"); try { Type type = typeof(int); Type refType = type.MakeByRefType(); if (!refType.IsByRef) { TestLibrary.TestFramework.LogError("003", "Call MakeByRefType for value type does not make a byref type"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Call MakeByRefType for value array type"); try { Type type = typeof(int[]); Type refType = type.MakeByRefType(); if (!refType.IsByRef) { TestLibrary.TestFramework.LogError("005", "Call MakeByRefType for value array type does not make a byref type"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Call MakeByRefType for reference array type"); try { Type type = typeof(String[]); Type refType = type.MakeByRefType(); if (!refType.IsByRef) { TestLibrary.TestFramework.LogError("007", "Call MakeByRefType for reference array type does not make a byref type"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Call MakeByRefType for pointer type"); try { Type type = typeof(char *); Type refType = type.MakeByRefType(); if (!refType.IsByRef) { TestLibrary.TestFramework.LogError("009", "Call MakeByRefType for pointer type does not make a byref type"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: TypeLoadException will be thrown when calling MakeByRefType for ByRef type"); try { Type type = typeof(Object); type = type.MakeByRefType(); Type refType = type.MakeByRefType(); TestLibrary.TestFramework.LogError("101", "TypeLoadException is not thrown when calling MakeByRefType for ByRef type"); retVal = false; } catch (TypeLoadException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { TypeMakeByRefType test = new TypeMakeByRefType(); TestLibrary.TestFramework.BeginTestCase("TypeMakeByRefType"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } }
using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Diagnostics; namespace GuruComponents.Netrix.UserInterface.FontPicker { /// <summary> /// Enhances the font listbox to show currently selected fonts. /// </summary> /// <remarks> /// This class provides the elementary list which is able to shows the fontnames /// in there appropriate font. /// </remarks> [ToolboxItem(false)] public class FontListBox : System.Windows.Forms.ListBox { /// <summary> /// Used as left space between border and the beginning of font. In pixel. /// </summary> private const int imageWidth = 16; /// <summary> /// Current font. /// </summary> private Font nfont; /// <summary> /// Type of listbox. /// </summary> private ListBoxType _listtype = ListBoxType.FontNameAndSample; /// <summary> /// Max width, unlimited in 0. /// </summary> private int maxwid = 0; /// <summary> /// Sample string to display fonts. /// </summary> private string samplestr = " - NET.RIX"; /// <summary> /// Default font list shown. /// </summary> private FontFamilyType type = FontFamilyType.System; /// <summary> /// Array of user fonts. /// </summary> private string[] _userfonts = null; /// <summary> /// The contructor is used to instantiate the control. /// </summary> /// <remarks> /// Some base values are set: /// <list type="bullet"> /// <item><term>IntegralHeight</term><description>false</description></item> /// <item><term>Sorted</term><description>false</description></item> /// <item><term>DrawMode</term><description>DrawMode.OwnerDrawVariable</description></item> /// <item><term>FamilyType</term><description>FontFamilyType.Web</description></item> /// </list> /// The list of selected fonts is always clear. /// </remarks> public FontListBox() : base() { IntegralHeight = false; Sorted = false; DrawMode = DrawMode.OwnerDrawVariable; this.SelectionMode = SelectionMode.MultiExtended; this.FamilyType = FontFamilyType.Web; this.Items.Clear(); } /// <summary> /// Select a specific entry. /// </summary> /// <param name="index"></param> private void Select (int index) { this.SelectedIndex = index; // string s = this.Items[index].ToString(); // Rectangle rect = GetItemRectangle(index); } /// <summary> /// Set the highlighter ones down in the list. /// </summary> /// <remarks> /// This method can be used if the list is used as separate control to /// set the highlighted entry depending on an external event. /// </remarks> public void HighlightNext() { this.SelectedIndex++; } /// <summary> /// Set the highlighter ones up in the list. /// </summary> /// <remarks> /// This method can be used if the list is used as separate control to /// set the highlighted entry depending on an external event. /// </remarks> public void HighlightPrevious() { this.SelectedIndex--; } /// <summary> /// Number of elements in the listbox. /// </summary> /// <remarks> /// This returns simply the <c>Count</c> property of the base list. /// </remarks> public int Count { get { return Items.Count; } } /// <summary> /// Recognizes the F2 (select), Insert (select and take), Del (remove), Enter (select), /// KeyDown/KeyUp (moves current font). /// </summary> /// <param name="e"></param> protected override void OnKeyDown(KeyEventArgs e) { if( e.KeyData == Keys.F2 ) { int index = SelectedIndex; if( index == ListBox.NoMatches || index == 65535 ) { if( Items.Count > 0 ) { index = 0; } } if (index != ListBox.NoMatches && index != 65535) { this.Select(index); } } else if (e.KeyData == Keys.Insert) { if (this.Items.Count > 0) this.SelectedIndex = 0; } else if (e.KeyData == Keys.Delete) { this.RemoveSelected(); } else if (e.KeyData == Keys.Enter) { if (this.Items.Count > 0) this.SelectedIndex = 0; } else if( ( e.KeyCode == Keys.Down ) && e.Control ) { this.MoveSelectedDown(); if( this.SelectedIndex > 0 ) { this.SelectedIndex--; } } else if( ( e.KeyCode == Keys.Up ) && e.Control ) { this.MoveSelectedUp(); if( this.SelectedIndex < ( this.Items.Count - 1 ) ) { this.SelectedIndex++; } } base.OnKeyDown( e ); } /// <summary> /// Called if a new item is inserted. /// </summary> /// <remarks> /// If called from outside the control the item will be added to the list and /// control will refresh. If it has no focus the focus is moved there. /// The method checks for the given font name and will not insert the font more /// than once. The font is compared using the name, not the real font file. /// The method does nothing if the font already exists in the list. /// </remarks> /// <param name="FontName"></param> public void NewItem(string FontName) { if (!this.Items.Contains(FontName)) { base.Items.Add(FontName); this.Select(base.Items.Count - 1); this.Focus(); } } /// <summary> /// Called if the current font should removed. /// </summary> /// <remarks> /// If one or more lines highlighted within the list this method removes these /// fonts from the list. /// </remarks> public void RemoveSelected() { if( this.Items.Count > 0 ) { this.BeginUpdate(); int newItems = this.Items.Count - this.SelectedIndices.Count; object[] temp = new object[newItems]; for (int i = 0, j = 0; i < this.Items.Count; i++) { if (!this.SelectedIndices.Contains(i)) { temp[j++] = this.Items[i]; } } this.Items.Clear(); this.Items.AddRange(temp); if (this.Items.Count > 0) { this.Select(0); } this.EndUpdate(); this.Focus(); } } /// <summary> /// Move one up. /// </summary> /// <remarks> /// The currently selected font will be moved upwards in the list. /// This method expects that exactly one (1) font is selected. If no font or /// more than one is selected the method ignores the call and does nothing. /// </remarks> public void MoveSelectedUp() { object tmp; int index; if(this.SelectedIndices.Count == 1 && this.SelectedIndex > 0) { tmp = this.SelectedItem; index = this.SelectedIndex; this.Items.RemoveAt( index ); this.Items.Insert( index - 1, tmp ); this.Select(index - 1); this.Focus(); this.SelectedIndex = index - 1; } } /// <summary> /// Move one down. /// </summary> /// <remarks> /// The currently selected font will be moved downwards in the list. /// This method expects that exactly one (1) font is selected. If no font or /// more than one is selected the method ignores the call and does nothing. /// </remarks> public void MoveSelectedDown() { int index = this.SelectedIndex; if (this.SelectedIndices.Count == 1 && (index + 1) < this.Items.Count) { object tmp = this.SelectedItem; this.Items.RemoveAt(index); this.Items.Insert(index + 1, tmp); this.Select(index + 1); this.Focus(); this.SelectedIndex = index + 1; } } # region Base /// <summary> /// Used to override the sample string. /// </summary> /// <remarks> /// Gets or sets the sample string. /// </remarks> public string SampleString { set { samplestr = value; } get { return samplestr; } } /// <summary> /// Used to set or get the font family type. /// </summary> /// <remarks> /// If the list is prefilled with fonts (which is an option) this property /// determines the type of font list. If the list is used for the final font selection the /// user mades the type <see cref="FontFamilyType.User"/> is used. /// </remarks> public FontFamilyType FamilyType { set { type = value; } get { return type; } } /// <summary> /// Used to get or set the user fonts. /// </summary> /// <remarks> /// If the list type is user and the prefilled user list is used this property allows to /// set the list of fonts as an string array. /// </remarks> public string[] UserFonts { set { _userfonts = value; } get { return _userfonts; } } /// <summary> /// Used to set or get the listbox type. /// </summary> /// <remarks> /// Related to the base list the control derived from. /// </remarks> public ListBoxType ListType { set { _listtype = value; } get { return _listtype; } } /// <summary> /// Used to fill the listbox with a predefined font list. /// </summary> /// <remarks> /// After the various property are set this method will fill the list with the /// selected fonts. After setting the font the selected index is set to 0. /// </remarks> public void Populate() { switch (type) { case FontFamilyType.Generic: Items.Clear(); Items.AddRange(new string[] {"Sans-Serif", "Monospace", "Serif"}); break; case FontFamilyType.System: FontFamilyTypeSystem: Items.Clear(); foreach (FontFamily ff in FontFamily.Families) { if(ff.IsStyleAvailable(FontStyle.Regular)) Items.Add(ff.Name); } break; case FontFamilyType.Web: Items.Clear(); Items.AddRange(new string[] {"Verdana", "Tahoma", "Courier New", "Times"}); break; case FontFamilyType.User: Items.Clear(); if (UserFonts != null) { Items.AddRange(UserFonts); } break; default: goto FontFamilyTypeSystem; } if(Items.Count > 0) SelectedIndex=0; } /// <summary> /// Measures one entry in the owner drawn listbox. /// </summary> /// <param name="e"></param> protected override void OnMeasureItem(System.Windows.Forms.MeasureItemEventArgs e) { if(e.Index > -1 && Items.Count > 0) { int w = 0; string fontstring = Items[e.Index].ToString(); Graphics g = CreateGraphics(); e.ItemHeight = (int)g.MeasureString(fontstring, new Font(fontstring,10)).Height; w = (int)g.MeasureString(fontstring, new Font(fontstring,10)).Width; if(ListType == ListBoxType.FontNameAndSample) { int h1 = (int)g.MeasureString(samplestr, new Font(fontstring,10)).Height; int h2 = (int)g.MeasureString(Items[e.Index].ToString(), new Font("Arial",10)).Height; int w1 = (int)g.MeasureString(samplestr, new Font(fontstring,10)).Width; int w2 = (int)g.MeasureString(Items[e.Index].ToString(), new Font("Arial",10)).Width; if(h1 > h2 ) h2 = h1; e.ItemHeight = h2; w = w1 + w2; } w += imageWidth * 2; if(w > maxwid) maxwid=w; if(e.ItemHeight > 20) e.ItemHeight = 20; } base.OnMeasureItem(e); } /// <summary> /// Creates on entry in the owner drawn listbox. /// </summary> /// <param name="e"></param> protected override void OnDrawItem(System.Windows.Forms.DrawItemEventArgs e) { if(e.Index > -1 && Items.Count > 0) { string fontstring = Items[e.Index].ToString(); switch (type) { case FontFamilyType.Generic: switch (fontstring) { case "Sans-Serif": nfont = new Font("Arial",10); break; case "Serif": nfont = new Font("Times New Roman",10); break; case "Monospace": nfont = new Font("Courier New",10); break; } break; case FontFamilyType.System: nfont = new Font(fontstring, 10); break; case FontFamilyType.Web: nfont = new Font(fontstring, 10); break; case FontFamilyType.User: nfont = new Font(fontstring, 10); break; } Font afont = new Font("Arial",10); if (nfont == null) return; switch (ListType) { case ListBoxType.FontNameAndSample: Graphics g = CreateGraphics(); int w = (int)g.MeasureString(fontstring, afont).Width; if((e.State & DrawItemState.Selected)==0) { e.Graphics.FillRectangle(new SolidBrush(SystemColors.Window), e.Bounds.X + imageWidth,e.Bounds.Y,e.Bounds.Width,e.Bounds.Height); e.Graphics.DrawString(fontstring,afont,new SolidBrush(SystemColors.WindowText), e.Bounds.X + imageWidth,e.Bounds.Y); e.Graphics.DrawString(samplestr,nfont,new SolidBrush(SystemColors.WindowText), e.Bounds.X+w + imageWidth,e.Bounds.Y); } else { e.Graphics.FillRectangle(new SolidBrush(SystemColors.Highlight), e.Bounds.X + imageWidth,e.Bounds.Y,e.Bounds.Width,e.Bounds.Height); e.Graphics.DrawString(fontstring,afont,new SolidBrush(SystemColors.HighlightText), e.Bounds.X + imageWidth,e.Bounds.Y); e.Graphics.DrawString(samplestr,nfont,new SolidBrush(SystemColors.HighlightText), e.Bounds.X+w + imageWidth,e.Bounds.Y); } break; case ListBoxType.FontSample: if((e.State & DrawItemState.Selected)==0) { e.Graphics.FillRectangle(new SolidBrush(SystemColors.Window), e.Bounds.X + imageWidth,e.Bounds.Y,e.Bounds.Width,e.Bounds.Height); e.Graphics.DrawString(fontstring,nfont,new SolidBrush(SystemColors.WindowText), e.Bounds.X + imageWidth,e.Bounds.Y); } else { e.Graphics.FillRectangle(new SolidBrush(SystemColors.Highlight), e.Bounds.X + imageWidth,e.Bounds.Y,e.Bounds.Width,e.Bounds.Height); e.Graphics.DrawString(fontstring,nfont,new SolidBrush(SystemColors.HighlightText), e.Bounds.X + imageWidth,e.Bounds.Y); } break; } //e.Graphics.DrawImage(image, new Point(e.Bounds.X, e.Bounds.Y)); } base.OnDrawItem(e); } # endregion } }
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> /// A company or business entity. /// </summary> public class CompanyModel { /// <summary> /// The unique ID number of this company. /// </summary> public Int32 id { get; set; } /// <summary> /// The unique ID number of the account this company belongs to. /// </summary> public Int32 accountId { get; set; } /// <summary> /// If this company is fully owned by another company, this is the unique identity of the parent company. /// </summary> public Int32? parentCompanyId { get; set; } /// <summary> /// If this company files Streamlined Sales Tax, this is the PID of this company as defined by the Streamlined Sales Tax governing board. /// </summary> public String sstPid { get; set; } /// <summary> /// A unique code that references this company within your account. /// </summary> public String companyCode { get; set; } /// <summary> /// The name of this company, as shown to customers. /// </summary> public String name { get; set; } /// <summary> /// This flag is true if this company is the default company for this account. Only one company may be set as the default. /// </summary> public Boolean? isDefault { get; set; } /// <summary> /// If set, this is the unique ID number of the default location for this company. /// </summary> public Int32? defaultLocationId { get; set; } /// <summary> /// This flag indicates whether tax activity can occur for this company. Set this flag to true to permit the company to process transactions. /// </summary> public Boolean? isActive { get; set; } /// <summary> /// For United States companies, this field contains your Taxpayer Identification Number. /// This is a nine digit number that is usually called an EIN for an Employer Identification Number if this company is a corporation, /// or SSN for a Social Security Number if this company is a person. /// This value is required if the address provided is inside the US and if you subscribed to the Avalara Managed Returns or SST Certified Service Provider service. Otherwise it is optional. /// </summary> public String taxpayerIdNumber { get; set; } /// <summary> /// Set this field to true if the taxPayerIdNumber is a FEIN. /// </summary> public Boolean? isFein { get; set; } /// <summary> /// Set this flag to true to give this company its own unique tax profile. /// If this flag is true, this company will have its own Nexus, TaxRule, TaxCode, and Item definitions. /// If this flag is false, this company will inherit all profile values from its parent. /// </summary> public Boolean? hasProfile { get; set; } /// <summary> /// Set this flag to true if this company must file its own tax returns. /// For users who have Returns enabled, this flag turns on monthly Worksheet generation for the company. /// </summary> public Boolean? isReportingEntity { get; set; } /// <summary> /// If this company participates in Streamlined Sales Tax, this is the date when the company joined the SST program. /// </summary> public DateTime? sstEffectiveDate { get; set; } /// <summary> /// The two character ISO-3166 country code of the default country for this company. /// </summary> public String defaultCountry { get; set; } /// <summary> /// This is the three character ISO-4217 currency code of the default currency used by this company. /// </summary> public String baseCurrencyCode { get; set; } /// <summary> /// Indicates whether this company prefers to round amounts at the document level or line level. /// </summary> public RoundingLevelId? roundingLevelId { get; set; } /// <summary> /// Set this value to true to receive warnings in API calls via SOAP. /// </summary> public Boolean? warningsEnabled { get; set; } /// <summary> /// Set this flag to true to indicate that this company is a test company. /// If you have Returns enabled, Test companies will not file tax returns and can be used for validation purposes. /// </summary> public Boolean? isTest { get; set; } /// <summary> /// Used to apply tax detail dependency at a jurisdiction level. /// </summary> public TaxDependencyLevelId? taxDependencyLevelId { get; set; } /// <summary> /// Set this value to true to indicate that you are still working to finish configuring this company. /// While this value is true, no tax reporting will occur and the company will not be usable for transactions. /// </summary> public Boolean? inProgress { get; set; } /// <summary> /// Business Identification No /// </summary> public String businessIdentificationNo { 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> /// Optional: A list of contacts defined for this company. To fetch this list, add the query string `?$include=Contacts` to your URL. /// /// When calling `CreateCompany`, you may provide a list of objects in this element and they will be created alongside the company. /// The `UpdateCompany` API does not permit updating nested objects. /// </summary> public List<ContactModel> contacts { get; set; } /// <summary> /// Optional: A list of items defined for this company. To fetch this list, add the query string `?$include=Items` to your URL. /// /// When calling `CreateCompany`, you may provide a list of objects in this element and they will be created alongside the company. /// The `UpdateCompany` API does not permit updating nested objects. /// </summary> public List<ItemModel> items { get; set; } /// <summary> /// Optional: A list of locations defined for this company. To fetch this list, add the query string `?$include=Locations` to your URL. /// /// When calling `CreateCompany`, you may provide a list of objects in this element and they will be created alongside the company. /// The `UpdateCompany` API does not permit updating nested objects. /// </summary> public List<LocationModel> locations { get; set; } /// <summary> /// Optional: A list of nexus defined for this company. To fetch this list, add the query string `?$include=Nexus` to your URL. /// /// When calling `CreateCompany`, you may provide a list of objects in this element and they will be created alongside the company. /// The `UpdateCompany` API does not permit updating nested objects. /// </summary> public List<NexusModel> nexus { get; set; } /// <summary> /// Optional: A list of settings defined for this company. To fetch this list, add the query string `?$include=Settings` to your URL. /// /// When calling `CreateCompany`, you may provide a list of objects in this element and they will be created alongside the company. /// The `UpdateCompany` API does not permit updating nested objects. /// </summary> public List<SettingModel> settings { get; set; } /// <summary> /// Optional: A list of tax codes defined for this company. To fetch this list, add the query string `?$include=TaxCodes` to your URL. /// /// When calling `CreateCompany`, you may provide a list of objects in this element and they will be created alongside the company. /// The `UpdateCompany` API does not permit updating nested objects. /// </summary> public List<TaxCodeModel> taxCodes { get; set; } /// <summary> /// Optional: A list of tax rules defined for this company. To fetch this list, add the query string `?$include=TaxRules` to your URL. /// /// When calling `CreateCompany`, you may provide a list of objects in this element and they will be created alongside the company. /// The `UpdateCompany` API does not permit updating nested objects. /// </summary> public List<TaxRuleModel> taxRules { get; set; } /// <summary> /// Optional: A list of UPCs defined for this company. To fetch this list, add the query string `?$include=UPCs` to your URL. /// /// When calling `CreateCompany`, you may provide a list of objects in this element and they will be created alongside the company. /// The `UpdateCompany` API does not permit updating nested objects. /// </summary> public List<UPCModel> upcs { get; set; } /// <summary> /// Optional: A list of non reporting child companies associated with this company. To fetch this list, add the query string `?$include=NonReportingChildren` to your URL. /// </summary> public List<CompanyModel> nonReportingChildCompanies { get; set; } /// <summary> /// DEPRECATED - Date: 9/15/2017, Version: 17.10, Message: Please use the `ListCertificates` API. /// </summary> public List<EcmsModel> exemptCerts { get; set; } /// <summary> /// The unique identifier of the mini-one-stop-shop used for Value Added Tax (VAT) processing. /// </summary> public String mossId { get; set; } /// <summary> /// The country code of the mini-one-stop-shop used for Value Added Tax (VAT) processing. /// </summary> public String mossCountry { get; set; } /// <summary> /// The parameters of a company /// </summary> public List<CompanyParameterDetailModel> parameters { get; set; } /// <summary> /// The customers and suppliers of a company /// </summary> public List<CustomerSupplierModel> supplierandcustomers { 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 }); } } }
/* Licensed under the MIT/X11 license. * Copyright (c) 2011 Xamarin Inc. * Copyright 2013 Xamarin Inc * This notice may not be removed from any source distribution. * See license.txt for licensing detailed licensing details. */ using System; using System.ComponentModel; using System.Drawing; using System.Runtime.InteropServices; using System.Security; using System.Timers; using System.Threading; using System.Threading.Tasks; using OpenTK; using OpenTK.Graphics; using OpenTK.Platform; using OpenTK.Platform.Android; using Android.Content; using Android.Util; using Android.Views; using Android.Runtime; using Android.Graphics; using OpenTK.Platform.Egl; using SurfaceType = Android.Views.SurfaceType; namespace OpenTK.Platform.Android { [Register ("opentk_1_1/platform/android/AndroidGameView")] public partial class AndroidGameView : GameViewBase, ISurfaceHolderCallback { private bool disposed; private System.Timers.Timer timer; private Java.Util.Timer j_timer; private ISurfaceHolder mHolder; private GLCalls gl; private AndroidWindow windowInfo; private Object ticking = new Object (); private bool stopped = true; private bool renderOn = false; private bool sizeChanged = false; private bool requestRender = false; private bool autoSetContextOnRenderFrame = true; private bool renderOnUIThread = true; private bool callMakeCurrent = false; private CancellationTokenSource source; private Task renderTask; private Thread renderingThread; private ManualResetEvent pauseSignal; private global::Android.Graphics.Rect surfaceRect; private Size size; private System.Diagnostics.Stopwatch stopWatch; private double tick = 0; [Register (".ctor", "(Landroid/content/Context;)V", "")] public AndroidGameView (Context context) : base (context) { Init (); } [Register (".ctor", "(Landroid/content/Context;Landroid/util/AttributeSet;)V", "")] public AndroidGameView (Context context, IAttributeSet attrs) : base (context, attrs) { Init (); } public AndroidGameView (IntPtr handle, global::Android.Runtime.JniHandleOwnership transfer) : base (handle, transfer) { Init (); } private void Init () { // default ContextRenderingApi = GLVersion.ES1; mHolder = Holder; RenderThreadRestartRetries = 3; // Add callback to get the SurfaceCreated etc events mHolder.AddCallback (this); // Force the SurfaceType to be Gpu to API_11 and earlier // it is ignored in later API's mHolder.SetType (SurfaceType.Gpu); windowInfo = new AndroidWindow (mHolder); pauseSignal = new ManualResetEvent (true); } public void SurfaceCreated (ISurfaceHolder holder) { log ("SurfaceCreated"); callMakeCurrent = true; CreateSurface (); // Surface size or format has changed surfaceRect = holder.SurfaceFrame; size = new Size (surfaceRect.Right - surfaceRect.Left, surfaceRect.Bottom - surfaceRect.Top); LoadInternal (EventArgs.Empty); } public void SurfaceDestroyed (ISurfaceHolder holder) { log ("SurfaceDestroyed"); // TODO: Somehow DestroySurface is being called twice (once by SurfaceDestroyed and once by UnloadInternal->DestroyFrameBuffer) DestroySurface(); UnloadInternal (EventArgs.Empty); } public void SurfaceChanged (ISurfaceHolder holder, Format format, int w, int h) { log ("SurfaceChanged"); callMakeCurrent = true; Width = w; Height = h; // Surface size or format has changed surfaceRect = holder.SurfaceFrame; size = new Size (surfaceRect.Right - surfaceRect.Left, surfaceRect.Bottom - surfaceRect.Top); if (OpenTK.Graphics.GraphicsContext.CurrentContextHandle.Handle != IntPtr.Zero && RenderOnUIThread) { GLCalls.Viewport (0, 0, size.Width, size.Height); GLCalls.Scissor (0, 0, size.Width, size.Height); } OnResize (EventArgs.Empty); } public override void Close () { EnsureUndisposed (); Stop (); base.Close (); DestroyContext (); windowInfo.TerminateDisplay (); } protected override void Dispose (bool disposing) { if (disposed) return; // Stop the timer before anything else StopThread (); if (disposing) OnDisposed (EventArgs.Empty); disposed = true; base.Dispose (disposing); } protected virtual void DestroyFrameBuffer () { // TODO: Somehow DestroySurface is being called twice (once by SurfaceDestroyed and once by UnloadInternal->DestroyFrameBuffer) DestroySurface(); } public override void MakeCurrent () { EnsureUndisposed (); AssertContext (); try { GraphicsContext.MakeCurrent (WindowInfo); } catch (EglException e) { if (e.ErrorCode == ErrorCode.BAD_ALLOC || e.ErrorCode == ErrorCode.CONTEXT_LOST) { log(string.Format("Egl error: {0}", e.ErrorCode)); OnContextLost(null); } } } protected override void OnContextLost (EventArgs e) { base.OnContextLost (e); CreateContext (); GraphicsContext.MakeCurrent (WindowInfo); } public override void SwapBuffers () { EnsureUndisposed (); AssertContext (); if (Context != null) { Context.SwapBuffers(); } else GraphicsContext.SwapBuffers (); } private double updates; public override void Run () { EnsureUndisposed (); updates = 0; #if TIMING targetFps = currentFps = 0; avgFps = 1; #endif restartCounter = 0; StartThread (); } public override void Run (double updatesPerSecond) { EnsureUndisposed (); #if TIMING avgFps = targetFps = currentFps = updatesPerSecond; #endif updates = 1000 / updatesPerSecond; restartCounter = 0; StartThread (); } public void Stop () { EnsureUndisposed (); StopThread (); UnloadInternal (EventArgs.Empty); } public virtual void Pause () { log ("Pause"); EnsureUndisposed (); PauseThread (); } public virtual void Resume () { log ("Resume"); EnsureUndisposed (); ResumeThread (); } private void LoadInternal (EventArgs e) { OnLoad (e); } private void UnloadInternal (EventArgs e) { OnUnload (e); DestroyFrameBuffer (); } private void RenderFrameInternal (FrameEventArgs e) { #if TIMING Mark (); #endif if (!ReadyToRender) return; if (autoSetContextOnRenderFrame) MakeCurrent (); OnRenderFrame (e); } #if TIMING int frames = 0; double prev = 0; double avgFps = 0; double currentFps = 0; double targetFps = 0; void Mark () { double cur = stopWatch.Elapsed.TotalMilliseconds; if (cur < 2000) { return; } frames ++; if (cur - prev >= 995) { avgFps = 0.8 * avgFps + 0.2 * frames; Log.Verbose ("AndroidGameView", "frames {0} elapsed {1}ms {2:F2} fps", frames, cur - prev, avgFps); frames = 0; prev = cur; } } #endif private void UpdateFrameInternal (FrameEventArgs e) { if (!ReadyToRender) return; OnUpdateFrame (e); } private void EnsureUndisposed () { if (disposed) throw new ObjectDisposedException (""); } private void AssertContext () { if (GraphicsContext == null) throw new InvalidOperationException ("Operation requires a GraphicsContext, which hasn't been created yet."); } private void CreateSurface() { if (GraphicsContext == null) { // First time: create context (which will create config & surface) CreateFrameBuffer(); CreateContext(); } else { // Context already created, so only recreate the surface windowInfo.CreateSurface(GraphicsContext.GraphicsMode.Index.Value); } MakeCurrent(); } private void DestroySurface() { log("DestroySurface"); windowInfo.DestroySurface(); } private void CreateContext () { log ("CreateContext"); // Setup GraphicsMode to default if not set if (GraphicsMode == null) GraphicsMode = GraphicsMode.Default; GraphicsContext = new GraphicsContext(GraphicsMode, WindowInfo, (int)ContextRenderingApi, 0, GraphicsContextFlags.Embedded); } private void DestroyContext () { if (GraphicsContext != null) { GraphicsContext.Dispose (); GraphicsContext = null; } } private int restartCounter = 0; public int RenderThreadRestartRetries { get; set; } public Exception RenderThreadException; private void StartThread () { log ("StartThread"); renderOn = true; stopped = false; callMakeCurrent = true; if (source != null) return; source = new CancellationTokenSource (); RenderThreadException = null; renderTask = Task.Factory.StartNew ((k) => { try { stopWatch = System.Diagnostics.Stopwatch.StartNew (); tick = 0; renderingThread = Thread.CurrentThread; var token = (CancellationToken)k; while (true) { if (token.IsCancellationRequested) return; tick = stopWatch.Elapsed.TotalMilliseconds; pauseSignal.WaitOne (); if (!RenderOnUIThread && callMakeCurrent) { MakeCurrent (); callMakeCurrent = false; } if (RenderOnUIThread) global::Android.App.Application.SynchronizationContext.Send (_ => { RunIteration (token); }, null); else RunIteration (token); if (updates > 0) { var t = updates - (stopWatch.Elapsed.TotalMilliseconds - tick); if (t > 0) { #if TIMING //Log.Verbose ("AndroidGameView", "took {0:F2}ms, should take {1:F2}ms, sleeping for {2:F2}", stopWatch.Elapsed.TotalMilliseconds - tick, updates, t); #endif if (token.IsCancellationRequested) return; pauseSignal.Reset (); pauseSignal.WaitOne ((int)t); if (renderOn) pauseSignal.Set (); } } } } catch (Exception e) { RenderThreadException = e; } }, source.Token).ContinueWith ((t) => { if (!source.IsCancellationRequested) { restartCounter++; source = null; if (restartCounter >= RenderThreadRestartRetries) OnRenderThreadExited (null); else { callMakeCurrent = true; StartThread (); } } else { restartCounter = 0; source = null; } }); } private void StopThread () { log ("StopThread"); restartCounter = 0; if (source == null) return; stopped = true; renderOn = false; source.Cancel (); // if the render thread is paused, let it run so it exits pauseSignal.Set (); if (stopWatch != null) stopWatch.Stop (); } private void PauseThread () { log ("PauseThread"); restartCounter = 0; if (source == null) return; pauseSignal.Reset (); renderOn = false; } private void ResumeThread () { log ("ResumeThread"); restartCounter = 0; if (source == null) return; if (!renderOn) { tick = 0; renderOn = true; pauseSignal.Set (); } } private bool ReadyToRender { get { return windowInfo.HasSurface && renderOn && !stopped; } } private DateTime prevUpdateTime; private DateTime prevRenderTime; private DateTime curUpdateTime; private DateTime curRenderTime; private FrameEventArgs updateEventArgs = new FrameEventArgs(); private FrameEventArgs renderEventArgs = new FrameEventArgs(); // this method is called on the main thread if RenderOnUIThread is true private void RunIteration (CancellationToken token) { if (token.IsCancellationRequested) return; if (!ReadyToRender) return; curUpdateTime = DateTime.Now; if (prevUpdateTime.Ticks != 0) { var t = (curUpdateTime - prevUpdateTime).TotalSeconds; updateEventArgs.Time = t; } UpdateFrameInternal (updateEventArgs); prevUpdateTime = curUpdateTime; curRenderTime = DateTime.Now; if (prevRenderTime.Ticks == 0) { var t = (curRenderTime - prevRenderTime).TotalSeconds; renderEventArgs.Time = t; } RenderFrameInternal (renderEventArgs); prevRenderTime = curRenderTime; } partial void log (string msg); #if LOGGING partial void log (string msg) { global::Android.Util.Log.Debug ("AndroidGameView", String.Format("====== " + msg + " =======")); global::Android.Util.Log.Debug ("AndroidGameView", String.Format("tid {0}", Java.Lang.Thread.CurrentThread().Id)); global::Android.Util.Log.Debug ("AndroidGameView", String.Format("stopped {0}", stopped)); global::Android.Util.Log.Debug ("AndroidGameView", String.Format("hasSurface {0}", hasSurface)); global::Android.Util.Log.Debug ("AndroidGameView", String.Format("renderOn {0}", renderOn)); global::Android.Util.Log.Debug ("AndroidGameView", String.Format("GraphicsContext? {0}", GraphicsContext != null)); if (source != null) global::Android.Util.Log.Debug ("AndroidGameView", String.Format("IsCancellationRequested {0}", source.IsCancellationRequested)); global::Android.Util.Log.Debug ("AndroidGameView", String.Format("width:{0} height:{1} size:{2} surfaceRect:{3}", Width, Height, size, surfaceRect)); } #endif public bool AutoSetContextOnRenderFrame { get { return autoSetContextOnRenderFrame; } set { autoSetContextOnRenderFrame = value; } } public bool RenderOnUIThread { get { return renderOnUIThread; } set { renderOnUIThread = value; } } private GLCalls GLCalls { get { if (gl == null || gl.Version != ContextRenderingApi) gl = GLCalls.GetGLCalls (ContextRenderingApi); return gl; } } private IGraphicsContext Context { get { return GraphicsContext; } } public GraphicsMode GraphicsMode { get; set; } private Format surfaceFormat = Format.Rgb565; public Format SurfaceFormat { get { return surfaceFormat; } set { if (windowInfo.HasSurface) { throw new InvalidOperationException("The Surface has already been created"); } surfaceFormat = value; mHolder.SetFormat(SurfaceFormat); } } private GLVersion api; public GLVersion ContextRenderingApi { get { EnsureUndisposed (); return api; } set { EnsureUndisposed (); if (GraphicsContext != null) throw new NotSupportedException ("Can't change RenderingApi after GraphicsContext is constructed."); this.api = value; } } /// <summary>The visibility of the window. Always returns true.</summary> /// <value></value> /// <exception cref="T:System.ObjectDisposed">The instance has been disposed</exception> public new virtual bool Visible { get { EnsureUndisposed (); return true; } set { EnsureUndisposed (); } } /// <summary>Gets information about the containing window.</summary> /// <value>By default, returns an instance of <see cref="F:OpenTK.Platform.Android.AndroidWindow" /></value> /// <exception cref="T:System.ObjectDisposed">The instance has been disposed</exception> public override IWindowInfo WindowInfo { get { EnsureUndisposed (); return windowInfo; } } /// <summary>Always returns <see cref="F:OpenTK.WindowState.Normal" />.</summary> /// <value></value> /// <exception cref="T:System.ObjectDisposed">The instance has been disposed</exception> public override WindowState WindowState { get { EnsureUndisposed (); return WindowState.Normal; } set {} } /// <summary>Always returns <see cref="F:OpenTK.WindowBorder.Hidden" />.</summary> /// <value></value> /// <exception cref="T:System.ObjectDisposed">The instance has been disposed</exception> public override WindowBorder WindowBorder { get { EnsureUndisposed (); return WindowBorder.Hidden; } set {} } /// <summary>The size of the current view.</summary> /// <value>A <see cref="T:System.Drawing.Size" /> which is the size of the current view.</value> /// <exception cref="T:System.ObjectDisposed">The instance has been disposed</exception> public override Size Size { get { EnsureUndisposed (); return size; } set { EnsureUndisposed (); if (size != value) { size = value; OnResize (EventArgs.Empty); } } } } }
using System.Collections.Generic; using System.Linq; using System.Text; using KSP.Localization; namespace KERBALISM.Planner { ///<summary> Contains all the data for a single resource within the planners vessel simulator </summary> public sealed class SimulatedResource { public SimulatedResource(string name) { ResetSimulatorDisplayValues(); _storage = new Dictionary<Resource_location, double>(); _capacity = new Dictionary<Resource_location, double>(); _amount = new Dictionary<Resource_location, double>(); vessel_wide_location = new Resource_location(); InitDicts(vessel_wide_location); _vessel_wide_view = new Simulated_resource_view_impl(null, resource_name, this); resource_name = name; } /// <summary>reset the values that are displayed to the user in the planner UI</summary> /// <remarks> /// use this after several simulator steps to do the final calculations under steady state /// where resources that are initially empty at vessel start have been created, otherwise /// user sees data only relevant for first simulation step (typically 1/50 seconds) /// </remarks> public void ResetSimulatorDisplayValues() { consumers = new Dictionary<string, Wrapper>(); producers = new Dictionary<string, Wrapper>(); harvests = new List<string>(); consumed = 0.0; produced = 0.0; } /// <summary> /// Identifier to identify the part or vessel where resources are stored /// </summary> /// <remarks> /// KSP 1.3 does not support the necessary persistent identifier for per part resources /// KSP 1.3 always defaults to vessel wide /// design is shared with Resource_location in Resource.cs module /// </remarks> private class Resource_location { public Resource_location(Part p) { vessel_wide = false; persistent_identifier = p.persistentId; } public Resource_location() { } /// <summary>Equals method in order to ensure object behaves like a value object</summary> public override bool Equals(object obj) { if (obj == null || obj.GetType() != GetType()) { return false; } return (((Resource_location)obj).persistent_identifier == persistent_identifier) && (((Resource_location)obj).vessel_wide == vessel_wide); } /// <summary>GetHashCode method in order to ensure object behaves like a value object</summary> public override int GetHashCode() { return (int)persistent_identifier; } public bool IsVesselWide() { return vessel_wide; } public uint GetPersistentPartId() { return persistent_identifier; } private bool vessel_wide = true; private uint persistent_identifier = 0; } /// <summary>implementation of Simulated_resource_view</summary> /// <remarks>only constructed by Simulated_resource class to hide the dependencies between the two</remarks> private class Simulated_resource_view_impl: SimulatedResourceView { public Simulated_resource_view_impl(Part p, string resource_name, SimulatedResource i) { info = i; location = info.vessel_wide_location; } public override void AddPartResources(Part p) { info.AddPartResources(location, p); } public override void Produce(double quantity, string name) { info.Produce(location, quantity, name); } public override void Consume(double quantity, string name) { info.Consume(location, quantity, name); } public override void Clamp() { info.Clamp(location); } public override double amount { get => info._amount[location]; } public override double capacity { get => info._capacity[location]; } public override double storage { get => info._storage[location]; } private SimulatedResource info; private Resource_location location; } /// <summary>initialize resource amounts for new resource location</summary> /// <remarks>typically for a part that has not yet used this resource</remarks> private void InitDicts(Resource_location location) { _storage[location] = 0.0; _amount[location] = 0.0; _capacity[location] = 0.0; } /// <summary>obtain a view on this resource for a given loaded part</summary> /// <remarks>passing a null part forces it vessel wide view</remarks> public SimulatedResourceView GetSimulatedResourceView(Part p) { return _vessel_wide_view; } /// <summary>add resource information contained within part to vessel wide simulator</summary> public void AddPartResources(Part p) { AddPartResources(vessel_wide_location, p); } /// <summary>add resource information within part to per-part simulator</summary> private void AddPartResources(Resource_location location, Part p) { _storage[location] += Lib.Amount(p, resource_name); _amount[location] += Lib.Amount(p, resource_name); _capacity[location] += Lib.Capacity(p, resource_name); } /// <summary>consume resource from the vessel wide bookkeeping</summary> public void Consume(double quantity, string name) { Consume(vessel_wide_location, quantity, name); } /// <summary>consume resource from the per-part bookkeeping</summary> /// <remarks>also works for vessel wide location</remarks> private void Consume(Resource_location location, double quantity, string name) { if (quantity >= double.Epsilon) { _amount[location] -= quantity; consumed += quantity; if (!consumers.ContainsKey(name)) consumers.Add(name, new Wrapper()); consumers[name].value += quantity; } } /// <summary>produce resource for the vessel wide bookkeeping</summary> public void Produce(double quantity, string name) { Produce(vessel_wide_location, quantity, name); } /// <summary>produce resource for the per-part bookkeeping</summary> /// <remarks>also works for vessel wide location</remarks> private void Produce(Resource_location location, double quantity, string name) { if (quantity >= double.Epsilon) { _amount[location] += quantity; produced += quantity; if (!producers.ContainsKey(name)) producers.Add(name, new Wrapper()); producers[name].value += quantity; } } /// <summary>clamp resource amount to capacity for the vessel wide bookkeeping</summary> public void Clamp() { Clamp(vessel_wide_location); } /// <summary>clamp resource amount to capacity for the per-part bookkeeping</summary> private void Clamp(Resource_location location) { _amount[location] = Lib.Clamp(_amount[location], 0.0, _capacity[location]); } /// <summary>determine how long a resource will last at simulated consumption/production levels</summary> public double Lifetime() { double rate = produced - consumed; return amount <= double.Epsilon ? 0.0 : rate > -1e-10 ? double.NaN : amount / -rate; } /// <summary>generate resource tooltip multi-line string</summary> public string Tooltip(bool invert = false) { IDictionary<string, Wrapper> green = !invert ? producers : consumers; IDictionary<string, Wrapper> red = !invert ? consumers : producers; StringBuilder sb = new StringBuilder(); foreach (KeyValuePair<string, Wrapper> pair in green) { if (sb.Length > 0) sb.Append("\n"); sb.Append(Lib.Color(Lib.HumanReadableRate(pair.Value.value), Lib.Kolor.PosRate, true)); sb.Append("\t"); sb.Append(pair.Key); } foreach (KeyValuePair<string, Wrapper> pair in red) { if (sb.Length > 0) sb.Append("\n"); sb.Append(Lib.Color(Lib.HumanReadableRate(pair.Value.value), Lib.Kolor.NegRate, true)); sb.Append("\t"); sb.Append(pair.Key); } if (harvests.Count > 0) { sb.Append("\n\n<b>"); sb.Append(Local.Harvests);//Harvests sb.Append("</b>"); foreach (string s in harvests) { sb.Append("\n"); sb.Append(s); } } return Lib.BuildString("<align=left />", sb.ToString()); } // Enforce that modification happens through official accessor functions // Many external classes need to read these values, and they want convenient access // However direct modification of these members from outside would make the coupling far too high public string resource_name { get { return _resource_name; } private set { _resource_name = value; } } public List<string> harvests { get { return _harvests; } private set { _harvests = value; } } public double consumed { get { return _consumed; } private set { _consumed = value; } } public double produced { get { return _produced; } private set { _produced = value; } } // only getters, use official interface for setting that support resource location public double storage { get { return _storage.Values.Sum(); } } public double capacity { get { return _capacity.Values.Sum(); } } public double amount { get { return _amount.Values.Sum(); } } private string _resource_name; // associated resource name private List<string> _harvests; // some extra data about harvests private double _consumed; // total consumption rate private double _produced; // total production rate private IDictionary<Resource_location, double> _storage; // amount stored (at the start of simulation) private IDictionary<Resource_location, double> _capacity; // storage capacity private IDictionary<Resource_location, double> _amount; // amount stored (during simulation) private class Wrapper { public double value; } private IDictionary<string, Wrapper> consumers; // consumers metadata private IDictionary<string, Wrapper> producers; // producers metadata private Resource_location vessel_wide_location; private SimulatedResourceView _vessel_wide_view; } } // KERBALISM
// // SalesOrdersController.cs // // Author: // Eddy Zavaleta <[email protected]> // // Copyright (C) 2013-2020 Eddy Zavaleta, Mictlanix, and contributors. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Linq; using System.Web.Mvc; using Castle.ActiveRecord; using Mictlanix.BE.Model; using Mictlanix.BE.Web.Models; using Mictlanix.BE.Web.Mvc; using Mictlanix.BE.Web.Helpers; namespace Mictlanix.BE.Web.Controllers.Mvc { [Authorize] public class SalesOrdersController : CustomController { public ViewResult Index () { if (WebConfig.Store == null) { return View ("InvalidStore"); } if (WebConfig.PointOfSale == null) { return View ("InvalidPointOfSale"); } if (!CashHelpers.ValidateExchangeRate ()) { return View ("InvalidExchangeRate"); } var search = SearchSalesOrders (new Search<SalesOrder> { Limit = WebConfig.PageSize }); return View (search); } [HttpPost] public ActionResult Index (Search<SalesOrder> search) { if (ModelState.IsValid) { search = SearchSalesOrders (search); } if (Request.IsAjaxRequest ()) { return PartialView ("_Index", search); } return View (search); } Search<SalesOrder> SearchSalesOrders (Search<SalesOrder> search) { var item = WebConfig.Store; var pattern = (search.Pattern ?? string.Empty).Trim (); IQueryable<SalesOrder> query = from x in SalesOrder.Queryable select x; if (!WebConfig.ShowSalesOrdersFromAllStores) { query = query.Where (x => x.Store.Id == item.Id); } if (int.TryParse (pattern, out int id) && id > 0) { query = query.Where (x => x.Id == id || x.Serial == id); } else if (string.IsNullOrEmpty (pattern)) { query = from x in query orderby (x.IsCompleted || x.IsCancelled ? 1 : 0), x.Date descending select x; } else { query = from x in query where x.Customer.Name.Contains (pattern) || x.SalesPerson.Nickname.Contains (pattern) || (x.SalesPerson.FirstName + " " + x.SalesPerson.LastName).Contains (pattern) orderby (x.IsCompleted || x.IsCancelled ? 1 : 0), x.Date descending select x; } search.Total = query.Count (); search.Results = query.Skip (search.Offset).Take (search.Limit).ToList (); return search; } public ViewResult View (int id) { var item = SalesOrder.Find (id); return View (item); } public ViewResult Print (int id) { var model = SalesOrder.Find (id); return View (model); } public virtual ActionResult Pdf (int id) { var model = SalesOrder.Find (id); return PdfView ("Print", model); } [HttpPost] public ActionResult New () { var dt = DateTime.Now; var item = new SalesOrder (); item.PointOfSale = WebConfig.PointOfSale; if (item.PointOfSale == null) { return View ("InvalidPointOfSale"); } if (!CashHelpers.ValidateExchangeRate ()) { return View ("InvalidExchangeRate"); } // Store and Serial item.Store = item.PointOfSale.Store; try { item.Serial = (from x in SalesOrder.Queryable where x.Store.Id == item.Store.Id select x.Serial).Max () + 1; } catch { item.Serial = 1; } item.Customer = Customer.TryFind (WebConfig.DefaultCustomer); item.SalesPerson = CurrentUser.Employee; item.Date = dt; item.PromiseDate = dt; item.DueDate = dt; item.Currency = WebConfig.DefaultCurrency; item.ExchangeRate = CashHelpers.GetTodayDefaultExchangeRate (); item.Terms = item.Customer.HasCredit ? PaymentTerms.NetD : PaymentTerms.Immediate; item.Creator = CurrentUser.Employee; item.CreationTime = dt; item.Updater = item.Creator; item.ModificationTime = dt; using (var scope = new TransactionScope ()) { item.CreateAndFlush (); } return RedirectToAction ("Edit", new { id = item.Id }); } [HttpPost] public ActionResult CreateFromSalesQuote (int id) { var dt = DateTime.Now; var item = new SalesOrder (); var salesquote = SalesQuote.Find (id); item.PointOfSale = WebConfig.PointOfSale; if (item.PointOfSale == null) { return View ("InvalidPointOfSale"); } if (!CashHelpers.ValidateExchangeRate ()) { return View ("InvalidExchangeRate"); } if (salesquote.IsCancelled || !salesquote.IsCompleted) { return RedirectToAction ("Index", "Quotations"); } // Store and Serial item.Store = item.PointOfSale.Store; try { item.Serial = (from x in SalesOrder.Queryable where x.Store.Id == item.Store.Id select x.Serial).Max () + 1; } catch { item.Serial = 1; } item.Customer = salesquote.Customer; item.SalesPerson = salesquote.SalesPerson; item.Date = dt; item.PromiseDate = dt; item.Terms = salesquote.Terms; item.DueDate = dt.AddDays (item.Customer.CreditDays); item.Currency = salesquote.Currency; item.ExchangeRate = salesquote.ExchangeRate; item.Contact = salesquote.Contact; item.Comment = salesquote.Comment; item.ShipTo = salesquote.ShipTo; item.CustomerShipTo = salesquote.ShipTo == null ? "" : salesquote.ShipTo.ToString (); item.Creator = CurrentUser.Employee; item.CreationTime = dt; item.Updater = item.Creator; item.ModificationTime = dt; var details = salesquote.Details.Select (x => new SalesOrderDetail { Currency = x.Currency, ExchangeRate = x.ExchangeRate, IsTaxIncluded = x.IsTaxIncluded, Price = x.Price, Product = x.Product, ProductCode = x.ProductCode, ProductName = x.ProductName, Quantity = x.Quantity, SalesOrder = item, TaxRate = x.TaxRate, Warehouse = item.PointOfSale.Warehouse, Comment = x.Comment, DiscountRate = x.DiscountRate }).ToList (); using (var scope = new TransactionScope ()) { item.CreateAndFlush (); details.ForEach (x => x.CreateAndFlush ()); } return RedirectToAction ("Edit", new { id = item.Id }); } public ActionResult Edit (int id) { var item = SalesOrder.Find (id); if (item.IsCompleted || item.IsCancelled) { return RedirectToAction ("View", new { id = item.Id }); } if (!CashHelpers.ValidateExchangeRate ()) { return View ("InvalidExchangeRate"); } return View (item); } public JsonResult Contacts (int id) { var item = SalesOrder.TryFind (id); var query = from x in item.Customer.Contacts select new { value = x.Id, text = x.ToString () }; return Json (query.ToList (), JsonRequestBehavior.AllowGet); } public JsonResult Recipients (int id) { var item = SalesOrder.TryFind (id); var query = from x in item.Customer.Taxpayers select new { value = x.Id, text = x.ToString () }; return Json (query.ToList (), JsonRequestBehavior.AllowGet); } public JsonResult Addresses (int id) { var item = SalesOrder.TryFind (id); var query = from x in item.Customer.Addresses select new { value = x.Id, text = x.ToString () }; return Json (query.ToList (), JsonRequestBehavior.AllowGet); } public JsonResult Terms () { var query = from x in Enum.GetValues (typeof (PaymentTerms)).Cast<PaymentTerms> () select new { value = (int) x, text = x.GetDisplayName () }; return Json (query.ToList (), JsonRequestBehavior.AllowGet); } [HttpPost] public ActionResult SetCustomer (int id, int value) { var entity = SalesOrder.Find (id); var item = Customer.TryFind (value); if (entity.IsCompleted || entity.IsCancelled) { Response.StatusCode = 400; return Content (Resources.ItemAlreadyCompletedOrCancelled); } if (item != null) { entity.Customer = item; entity.Contact = null; entity.ShipTo = null; entity.CustomerShipTo = null; entity.CustomerName = null; if (item.SalesPerson == null) { entity.SalesPerson = CurrentUser.Employee; } else { entity.SalesPerson = item.SalesPerson; } if (entity.Terms == PaymentTerms.NetD && !entity.Customer.HasCredit) { entity.Terms = PaymentTerms.Immediate; } switch (entity.Terms) { case PaymentTerms.Immediate: entity.DueDate = entity.Date; break; case PaymentTerms.NetD: entity.DueDate = entity.Date.AddDays (entity.Customer.CreditDays); break; } entity.Updater = CurrentUser.Employee; entity.ModificationTime = DateTime.Now; entity.Recipient = string.Empty; entity.RecipientName = string.Empty; entity.RecipientAddress = null; using (var scope = new TransactionScope ()) { entity.UpdateAndFlush (); } } return Json (new { id = id, value = entity.FormattedValueFor (x => x.Customer), terms = entity.Terms, termsText = entity.Terms.GetDisplayName (), dueDate = entity.FormattedValueFor (x => x.DueDate), salesPerson = entity.SalesPerson.Id, salesPersonName = entity.SalesPerson.Name }); } [HttpPost] public ActionResult SetCustomerName (int id, string value) { var entity = SalesOrder.Find (id); string val = (value ?? string.Empty).Trim (); if (entity.IsCompleted || entity.IsCancelled) { Response.StatusCode = 400; return Content (Resources.ItemAlreadyCompletedOrCancelled); } entity.CustomerName = (value.Length == 0) ? null : val; entity.Updater = CurrentUser.Employee; entity.ModificationTime = DateTime.Now; using (var scope = new TransactionScope ()) { entity.UpdateAndFlush (); } return Json (new { id = id, value = value }); } public ActionResult GetCustomerName (int id) { return PartialView ("_CustomerName", SalesOrder.Find (id)); } [HttpPost] public ActionResult SetSalesPerson (int id, int value) { var entity = SalesOrder.Find (id); var item = Employee.TryFind (value); if (entity.IsCompleted || entity.IsCancelled) { Response.StatusCode = 400; return Content (Resources.ItemAlreadyCompletedOrCancelled); } if (item != null) { entity.SalesPerson = item; entity.Updater = CurrentUser.Employee; entity.ModificationTime = DateTime.Now; using (var scope = new TransactionScope ()) { entity.UpdateAndFlush (); } } return Json (new { id = id, value = entity.SalesPerson.ToString () }); } [HttpPost] public ActionResult SetContact (int id, int value) { var entity = SalesOrder.Find (id); var item = Contact.TryFind (value); if (entity.IsCompleted || entity.IsCancelled) { Response.StatusCode = 400; return Content (Resources.ItemAlreadyCompletedOrCancelled); } if (item != null) { entity.Contact = item; entity.Updater = CurrentUser.Employee; entity.ModificationTime = DateTime.Now; using (var scope = new TransactionScope ()) { entity.UpdateAndFlush (); } } return Json (new { id = id, value = entity.Contact.ToString () }); } [HttpPost] public ActionResult SetShipTo (int id, int value) { var entity = SalesOrder.Find (id); var item = Address.TryFind (value); if (entity.IsCompleted || entity.IsCancelled) { Response.StatusCode = 400; return Content (Resources.ItemAlreadyCompletedOrCancelled); } if (item != null) { entity.ShipTo = item; entity.CustomerShipTo = item.ToString (); entity.Updater = CurrentUser.Employee; entity.ModificationTime = DateTime.Now; using (var scope = new TransactionScope ()) { entity.UpdateAndFlush (); } } return Json (new { id = id, value = entity.ShipTo.ToString () }); } [HttpPost] public ActionResult SetComment (int id, string value) { var entity = SalesOrder.Find (id); string val = (value ?? string.Empty).Trim (); if (entity.IsCompleted || entity.IsCancelled) { Response.StatusCode = 400; return Content (Resources.ItemAlreadyCompletedOrCancelled); } entity.Comment = (value.Length == 0) ? null : val; entity.Updater = CurrentUser.Employee; entity.ModificationTime = DateTime.Now; using (var scope = new TransactionScope ()) { entity.UpdateAndFlush (); } return Json (new { id = id, value = entity.Comment }); } [HttpPost] public ActionResult SetRecipient (int id, string value) { var entity = SalesOrder.Find (id); string val = (value ?? string.Empty).Trim (); if (entity.IsCompleted || entity.IsCancelled) { Response.StatusCode = 400; return Content (Resources.ItemAlreadyCompletedOrCancelled); } var item = entity.Customer.Taxpayers.Single (x => x.Id == val); entity.Recipient = item.Id; entity.RecipientName = item.Name; using (var scope = new TransactionScope ()) { entity.UpdateAndFlush (); } return Json (new { id = id, value = item.Name }); } [HttpPost] public ActionResult SetPromiseDate (int id, DateTime? value) { var entity = SalesOrder.Find (id); if (entity.IsCompleted || entity.IsCancelled) { Response.StatusCode = 400; return Content (Resources.ItemAlreadyCompletedOrCancelled); } if (value != null) { entity.PromiseDate = value.Value; entity.Updater = CurrentUser.Employee; entity.ModificationTime = DateTime.Now; using (var scope = new TransactionScope ()) { entity.UpdateAndFlush (); } } return Json (new { id = id, value = entity.FormattedValueFor (x => x.PromiseDate) }); } [HttpPost] public ActionResult SetCurrency (int id, string value) { var entity = SalesOrder.Find (id); CurrencyCode val; bool success; if (entity.IsCompleted || entity.IsCancelled) { Response.StatusCode = 400; return Content (Resources.ItemAlreadyCompletedOrCancelled); } success = Enum.TryParse<CurrencyCode> (value.Trim (), out val); if (success) { decimal rate = CashHelpers.GetTodayExchangeRate (val); if (rate == 0m) { Response.StatusCode = 400; return Content (Resources.Message_InvalidExchangeRate); } entity.Currency = val; entity.ExchangeRate = rate; entity.Updater = CurrentUser.Employee; entity.ModificationTime = DateTime.Now; using (var scope = new TransactionScope ()) { foreach (var item in entity.Details) { item.Currency = val; item.ExchangeRate = rate; item.Update (); } entity.UpdateAndFlush (); } } return Json (new { id = entity.Id, value = entity.FormattedValueFor (x => x.Currency), rate = entity.FormattedValueFor (x => x.ExchangeRate), itemsChanged = success }); } [HttpPost] public ActionResult SetExchangeRate (int id, string value) { var entity = SalesOrder.Find (id); bool success; decimal val; if (entity.IsCompleted || entity.IsCancelled) { Response.StatusCode = 400; return Content (Resources.ItemAlreadyCompletedOrCancelled); } success = decimal.TryParse (value.Trim (), out val); if (success) { if (entity.Currency == WebConfig.BaseCurrency) { Response.StatusCode = 400; return Content (Resources.Message_InvalidBaseExchangeRate); } if (val <= 0m) { Response.StatusCode = 400; return Content (Resources.Message_InvalidExchangeRate); } entity.ExchangeRate = val; entity.Updater = CurrentUser.Employee; entity.ModificationTime = DateTime.Now; using (var scope = new TransactionScope ()) { foreach (var item in entity.Details) { item.ExchangeRate = val; item.Update (); } entity.UpdateAndFlush (); } } return Json (new { id = entity.Id, value = entity.FormattedValueFor (x => x.ExchangeRate), itemsChanged = success }); } [HttpPost] public ActionResult SetTerms (int id, string value) { bool success; PaymentTerms val; var entity = SalesOrder.Find (id); if (entity.IsCompleted || entity.IsCancelled) { Response.StatusCode = 400; return Content (Resources.ItemAlreadyCompletedOrCancelled); } success = Enum.TryParse (value.Trim (), out val); if (success) { if (val == PaymentTerms.NetD && !entity.Customer.HasCredit) { Response.StatusCode = 400; return Content (Resources.CreditLimitIsNotSet); } entity.Terms = val; entity.Updater = CurrentUser.Employee; entity.ModificationTime = DateTime.Now; switch (entity.Terms) { case PaymentTerms.Immediate: entity.DueDate = entity.Date; break; case PaymentTerms.NetD: entity.DueDate = entity.Date.AddDays (entity.Customer.CreditDays); break; } using (var scope = new TransactionScope ()) { entity.UpdateAndFlush (); } } return Json (new { id = id, value = entity.Terms, dueDate = entity.FormattedValueFor (x => x.DueDate), totalsChanged = success }); } [HttpPost] public ActionResult AddItem (int order, int product) { var entity = SalesOrder.TryFind (order); var p = Product.TryFind (product); int pl = entity.Customer.PriceList.Id; var cost = (from x in ProductPrice.Queryable where x.Product.Id == product && x.List.Id == 0 select x).SingleOrDefault (); var price = (from x in ProductPrice.Queryable where x.Product.Id == product && x.List.Id == pl select x).SingleOrDefault (); var discount = (from x in CustomerDiscount.Queryable where x.Product.Id == product && x.Customer.Id == entity.Customer.Id select x.Discount).SingleOrDefault (); if (entity.IsCompleted || entity.IsCancelled) { Response.StatusCode = 400; return Content (Resources.ItemAlreadyCompletedOrCancelled); } if (cost == null) { cost = new ProductPrice { Value = decimal.Zero }; } if (price == null) { price = new ProductPrice { Value = decimal.MaxValue }; } var item = new SalesOrderDetail { SalesOrder = entity, Product = p, Warehouse = entity.PointOfSale.Warehouse, ProductCode = p.Code, ProductName = p.Name, TaxRate = p.TaxRate, IsTaxIncluded = p.IsTaxIncluded, Quantity = p.MinimumOrderQuantity, Cost = cost.Value, Price = price.Value, DiscountRate = discount, Currency = entity.Currency, ExchangeRate = entity.ExchangeRate, Comment = p.Comment }; if (p.Currency != entity.Currency) { item.Cost = cost.Value * CashHelpers.GetTodayExchangeRate (p.Currency, entity.Currency); item.Price = price.Value * CashHelpers.GetTodayExchangeRate (p.Currency, entity.Currency); } using (var scope = new TransactionScope ()) { item.CreateAndFlush (); } return Json (new { id = item.Id }); } [HttpPost] public ActionResult RemoveItem (int id) { var entity = SalesOrderDetail.Find (id); if (entity.SalesOrder.IsCompleted || entity.SalesOrder.IsCancelled) { Response.StatusCode = 400; return Content (Resources.ItemAlreadyCompletedOrCancelled); } using (var scope = new TransactionScope ()) { entity.DeleteAndFlush (); } return Json (new { id = id, result = true }); } public ActionResult Item (int id) { var entity = SalesOrderDetail.Find (id); return PartialView ("_ItemEditorView", entity); } public ActionResult Items (int id) { var entity = SalesOrder.Find (id); return PartialView ("_Items", entity.Details); } public ActionResult Totals (int id) { var entity = SalesOrder.Find (id); return PartialView ("_Totals", entity); } [HttpPost] public ActionResult SetItemProductName (int id, string value) { var entity = SalesOrderDetail.Find (id); string val = (value ?? string.Empty).Trim (); if (entity.SalesOrder.IsCompleted || entity.SalesOrder.IsCancelled) { Response.StatusCode = 400; return Content (Resources.ItemAlreadyCompletedOrCancelled); } if (val.Length == 0) { entity.ProductName = entity.Product.Name; } else { entity.ProductName = val; } using (var scope = new TransactionScope ()) { entity.UpdateAndFlush (); } return Json (new { id = entity.Id, value = entity.ProductName }); } [HttpPost] public ActionResult SetItemComment (int id, string value) { var entity = SalesOrderDetail.Find (id); if (entity.SalesOrder.IsCompleted || entity.SalesOrder.IsCancelled) { Response.StatusCode = 400; return Content (Resources.ItemAlreadyCompletedOrCancelled); } entity.Comment = string.IsNullOrWhiteSpace (value) ? null : value.Trim (); using (var scope = new TransactionScope ()) { entity.UpdateAndFlush (); } return Json (new { id = id, value = entity.Comment }); } [HttpPost] public ActionResult SetItemQuantity (int id, decimal value) { var entity = SalesOrderDetail.Find (id); if (entity.SalesOrder.IsCompleted || entity.SalesOrder.IsCancelled) { Response.StatusCode = 400; return Content (Resources.ItemAlreadyCompletedOrCancelled); } if (value < entity.Product.MinimumOrderQuantity) { Response.StatusCode = 400; return Content (string.Format (Resources.MinimumQuantityRequired, entity.Product.MinimumOrderQuantity)); } entity.Quantity = value; using (var scope = new TransactionScope ()) { entity.UpdateAndFlush (); } return Json (new { id = entity.Id, value = entity.FormattedValueFor (x => x.Quantity), total = entity.FormattedValueFor (x => x.Total), total2 = entity.FormattedValueFor (x => x.TotalEx) }); } [HttpPost] public ActionResult SetItemPrice (int id, string value) { var entity = SalesOrderDetail.Find (id); bool success; decimal val; if (entity.SalesOrder.IsCompleted || entity.SalesOrder.IsCancelled) { Response.StatusCode = 400; return Content (Resources.ItemAlreadyCompletedOrCancelled); } success = decimal.TryParse (value.Trim (), System.Globalization.NumberStyles.Currency, null, out val); if (success && entity.Price >= 0) { var price_in_list = ProductPrice.Queryable.Where (x => x.List == entity.SalesOrder.Customer.PriceList && x.Product == entity.Product).SingleOrDefault (); if (price_in_list != null) { var current_price = price_in_list.Value; if (price_in_list.Product.Currency != entity.Currency) { current_price = current_price * CashHelpers.GetTodayExchangeRate (price_in_list.Product.Currency, entity.Currency); } if (current_price > val) { Response.StatusCode = 400; return Content (Resources.Validation_WrongDiscount); } } entity.Price = val; using (var scope = new TransactionScope ()) { entity.UpdateAndFlush (); } } return Json (new { id = entity.Id, discount_percentage = entity.FormattedValueFor (x => x.DiscountRate), discount_price = string.Format ("{0:C}", entity.Price * entity.DiscountRate), value = entity.FormattedValueFor (x => x.Price), total = entity.FormattedValueFor (x => x.Total), total2 = entity.FormattedValueFor (x => x.TotalEx) }); } [HttpPost] public ActionResult SetItemDiscountPercentage (int id, string value) { var entity = SalesOrderDetail.Find (id); bool success; decimal val; if (entity.SalesOrder.IsCompleted || entity.SalesOrder.IsCancelled) { Response.StatusCode = 400; return Content (Resources.ItemAlreadyCompletedOrCancelled); } success = decimal.TryParse (value.TrimEnd (new char [] { ' ', '%' }), out val); val /= 100m; if (success && val <= 1.0m && val >= 0.0m) { entity.DiscountRate = val; using (var scope = new TransactionScope ()) { entity.UpdateAndFlush (); } } return Json (new { id = entity.Id, value = entity.FormattedValueFor (x => x.DiscountRate), discountPrice = string.Format ("{0:C}", entity.Price * entity.DiscountRate), total = entity.FormattedValueFor (x => x.Total), total2 = entity.FormattedValueFor (x => x.TotalEx) }); } [HttpPost] public ActionResult SetItemDiscountPrice (int id, string value) { var entity = SalesOrderDetail.Find (id); bool success; decimal val; if (entity.SalesOrder.IsCompleted || entity.SalesOrder.IsCancelled) { Response.StatusCode = 400; return Content (Resources.ItemAlreadyCompletedOrCancelled); } success = decimal.TryParse (value.TrimEnd (new char [] { ' ', '%' }), out val); if (success && val <= entity.Price && val >= 0 && entity.Price > 0) { entity.DiscountRate = val / entity.Price; using (var scope = new TransactionScope ()) { entity.UpdateAndFlush (); } } return Json (new { id = entity.Id, discountRate = entity.FormattedValueFor (x => x.DiscountRate), value = string.Format ("{0:C}", entity.Price * entity.DiscountRate), total = entity.FormattedValueFor (x => x.Total), total2 = entity.FormattedValueFor (x => x.TotalEx) }); } [HttpPost] public ActionResult SetItemTaxRate (int id, string value) { var entity = SalesOrderDetail.Find (id); bool success; decimal val; if (entity.SalesOrder.IsCompleted || entity.SalesOrder.IsCancelled) { Response.StatusCode = 400; return Content (Resources.ItemAlreadyCompletedOrCancelled); } success = decimal.TryParse (value.TrimEnd (new char [] { ' ', '%' }), out val); // TODO: VAT value range validation if (success) { entity.TaxRate = val; using (var scope = new TransactionScope ()) { entity.Update (); } } return Json (new { id = entity.Id, value = entity.FormattedValueFor (x => x.TaxRate), total = entity.FormattedValueFor (x => x.Total), total2 = entity.FormattedValueFor (x => x.TotalEx) }); } [HttpPost] public virtual ActionResult Confirm (int id) { var entity = SalesOrder.TryFind (id); if (entity == null || entity.IsCompleted || entity.IsCancelled) { return RedirectToAction ("Index"); } entity.Updater = CurrentUser.Employee; entity.ModificationTime = DateTime.Now; entity.IsDelivered = false; entity.IsCompleted = true; foreach (var detail in entity.Details) { if (detail.Price == decimal.Zero) { return View ("ZeroPriceError", entity); } } if (entity.ShipTo == null) { //entity.IsDelivered = true; using (var scope = new TransactionScope ()) { var warehouse = entity.PointOfSale.Warehouse; var dt = DateTime.Now; foreach (var x in entity.Details) { x.Warehouse = warehouse; x.Update (); InventoryHelpers.ChangeNotification (TransactionType.SalesOrder, entity.Id, dt, warehouse, null, x.Product, -x.Quantity); } entity.UpdateAndFlush (); } } else { DeliveryOrder deliver = new DeliveryOrder (); deliver.Date = DateTime.Now; deliver.CreationTime = DateTime.Now; deliver.Creator = CurrentUser.Employee; deliver.Updater = entity.Creator; deliver.Customer = entity.Customer; deliver.ShipTo = entity.ShipTo; deliver.Store = entity.Store; using (var scope = new TransactionScope ()) { deliver.CreateAndFlush (); } foreach (var detail in entity.Details) { var detaild = (new DeliveryOrderDetail { DeliveryOrder = deliver, OrderDetail = detail, Quantity = detail.Quantity, ProductName = detail.ProductName, Product = detail.Product, ProductCode = detail.ProductCode }); using (var scope = new TransactionScope ()) { detaild.CreateAndFlush (); } } } return RedirectToAction ("Index"); } [HttpPost] public ActionResult Cancel (int id) { var entity = SalesOrder.Find (id); if (entity.IsCancelled || entity.IsPaid) { return RedirectToAction ("Index"); } entity.Updater = CurrentUser.Employee; entity.ModificationTime = DateTime.Now; entity.IsCancelled = true; using (var scope = new TransactionScope ()) { entity.UpdateAndFlush (); } return RedirectToAction ("Index"); } // TODO: Rename param: order -> id public JsonResult GetSuggestions (int order, string pattern) { int pl = SalesOrder.Queryable.Where (x => x.Id == order) .Select (x => x.Customer.PriceList.Id).Single (); var query = from x in ProductPrice.Queryable where x.List.Id == pl && ( x.Product.Name.Contains (pattern) || x.Product.Code.Contains (pattern) || x.Product.Model.Contains (pattern) || x.Product.SKU.Contains (pattern) || x.Product.Brand.Contains (pattern)) orderby x.Product.Name select new { x.Product.Id, x.Product.Name, x.Product.Code, x.Product.Model, x.Product.SKU, x.Product.Photo, Price = x.Value }; var items = from x in query.Take (15).ToList () select new { id = x.Id, name = x.Name, code = x.Code, model = x.Model ?? Resources.None, sku = x.SKU ?? Resources.None, url = Url.Content (x.Photo), price = x.Price, quantity = LotSerialTracking.Queryable.Where (y => y.Product.Code == x.Code && y.Warehouse == WebConfig.PointOfSale.Warehouse) .Sum (y => (decimal?) y.Quantity) ?? 0 }; return Json (items.ToList (), JsonRequestBehavior.AllowGet); } } }
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT // 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.Collections.Immutable; using Microsoft.Extensions.Logging; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using NakedFramework.Architecture.Adapter; using NakedFramework.Architecture.Component; using NakedFramework.Architecture.Facet; using NakedFramework.Architecture.Framework; using NakedFramework.Architecture.Reflect; using NakedFramework.Architecture.SpecImmutable; using NakedFramework.Core.Adapter; using NakedFramework.Metamodel.Facet; using NakedObjects.Reflector.Facet; using NakedObjects.Reflector.FacetFactory; // ReSharper disable UnusedMember.Global // ReSharper disable UnusedMember.Local // ReSharper disable ParameterOnlyUsedForPreconditionCheck.Local namespace NakedObjects.Reflector.Test.FacetFactory; [TestClass] public class CallbackMethodsFacetFactoryTest : AbstractFacetFactoryTest { private CallbackMethodsFacetFactory facetFactory; protected override Type[] SupportedTypes => new[] { typeof(ICreatedCallbackFacet), typeof(IPersistingCallbackFacet), typeof(IPersistedCallbackFacet), typeof(IUpdatingCallbackFacet), typeof(IUpdatedCallbackFacet), typeof(ILoadingCallbackFacet), typeof(ILoadedCallbackFacet), typeof(IDeletingCallbackFacet), typeof(IDeletedCallbackFacet) }; protected override IFacetFactory FacetFactory => facetFactory; private INakedObjectAdapter AdapterFor(object obj) { var session = new Mock<ISession>().Object; var lifecycleManager = new Mock<ILifecycleManager>().Object; var persistor = new Mock<IObjectPersistor>().Object; var manager = new Mock<INakedObjectManager>().Object; var loggerFactory = new Mock<ILoggerFactory>().Object; var logger = new Mock<ILogger<NakedObjectAdapter>>().Object; var framework = new Mock<INakedFramework>().Object; return new NakedObjectAdapter(obj, null, framework, loggerFactory, logger); } [TestMethod] public void TestCreatedLifecycleMethodPickedUpOn() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var method = FindMethod(typeof(Customer), "Created"); metamodel = facetFactory.Process(Reflector, typeof(Customer), MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(ICreatedCallbackFacet)); Assert.IsNotNull(facet); Assert.IsTrue(facet is CreatedCallbackFacetViaMethod); var createdCallbackFacetViaMethod = (CreatedCallbackFacetViaMethod)facet; Assert.AreEqual(method, createdCallbackFacetViaMethod.GetMethod()); AssertMethodsRemoved(new[] { method }); Assert.IsNotNull(metamodel); } [TestMethod] public void TestDeletedLifecycleMethodPickedUpOn() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var method = FindMethod(typeof(Customer8), "Deleted"); metamodel = facetFactory.Process(Reflector, typeof(Customer8), MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(IDeletedCallbackFacet)); Assert.IsNotNull(facet); Assert.IsTrue(facet is DeletedCallbackFacetViaMethod); var deletedCallbackFacetViaMethod = (DeletedCallbackFacetViaMethod)facet; Assert.AreEqual(method, deletedCallbackFacetViaMethod.GetMethod()); AssertMethodsRemoved(new[] { method }); Assert.IsNotNull(metamodel); } [TestMethod] public void TestDeletingLifecycleMethodPickedUpOn() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var method = FindMethod(typeof(Customer7), "Deleting"); metamodel = facetFactory.Process(Reflector, typeof(Customer7), MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(IDeletingCallbackFacet)); Assert.IsNotNull(facet); Assert.IsTrue(facet is DeletingCallbackFacetViaMethod); var deletingCallbackFacetViaMethod = (DeletingCallbackFacetViaMethod)facet; Assert.AreEqual(method, deletingCallbackFacetViaMethod.GetMethod()); AssertMethodsRemoved(new[] { method }); Assert.IsNotNull(metamodel); } [TestMethod] public override void TestFeatureTypes() { var featureTypes = facetFactory.FeatureTypes; Assert.IsTrue(featureTypes.HasFlag(FeatureType.Objects)); Assert.IsFalse(featureTypes.HasFlag(FeatureType.Properties)); Assert.IsFalse(featureTypes.HasFlag(FeatureType.Collections)); Assert.IsFalse(featureTypes.HasFlag(FeatureType.Actions)); Assert.IsFalse(featureTypes.HasFlag(FeatureType.ActionParameters)); } [TestMethod] public void TestLoadedLifecycleMethodPickedUpOn() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var method = FindMethod(typeof(Customer6), "Loaded"); metamodel = facetFactory.Process(Reflector, typeof(Customer6), MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(ILoadedCallbackFacet)); Assert.IsNotNull(facet); Assert.IsTrue(facet is LoadedCallbackFacetViaMethod); var loadedCallbackFacetViaMethod = (LoadedCallbackFacetViaMethod)facet; Assert.AreEqual(method, loadedCallbackFacetViaMethod.GetMethod()); AssertMethodsRemoved(new[] { method }); Assert.IsNotNull(metamodel); } [TestMethod] public void TestLoadingLifecycleMethodPickedUpOn() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var method = FindMethod(typeof(Customer5), "Loading"); metamodel = facetFactory.Process(Reflector, typeof(Customer5), MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(ILoadingCallbackFacet)); Assert.IsNotNull(facet); Assert.IsTrue(facet is LoadingCallbackFacetViaMethod); var loadingCallbackFacetViaMethod = (LoadingCallbackFacetViaMethod)facet; Assert.AreEqual(method, loadingCallbackFacetViaMethod.GetMethod()); AssertMethodsRemoved(new[] { method }); Assert.IsNotNull(metamodel); } [TestMethod] public void TestOnPersistingErrorLifecycleMethodNullFacet() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var method = FindMethod(typeof(Customer10), "OnPersistingError", new[] { typeof(Exception) }); Assert.IsNull(method); metamodel = facetFactory.Process(Reflector, typeof(Customer10), MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(IOnPersistingErrorCallbackFacet)); Assert.IsNotNull(facet); Assert.IsTrue(facet is OnPersistingErrorCallbackFacetNull); Assert.IsNotNull(metamodel); } [TestMethod] public void TestOnPersistingErrorLifecycleMethodPickedUpOn() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var method1 = FindMethod(typeof(Customer11), "OnUpdatingError", new[] { typeof(Exception) }); var method2 = FindMethod(typeof(Customer11), "OnPersistingError", new[] { typeof(Exception) }); metamodel = facetFactory.Process(Reflector, typeof(Customer11), MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(IOnPersistingErrorCallbackFacet)); Assert.IsNotNull(facet); Assert.IsTrue(facet is OnPersistingErrorCallbackFacetViaMethod); var onPersistingErrorCallbackFacetViaMethod = (OnPersistingErrorCallbackFacetViaMethod)facet; Assert.AreEqual(method2, onPersistingErrorCallbackFacetViaMethod.GetMethod()); AssertMethodsRemoved(new[] { method1, method2 }); // and test exception is passed through (assert in Customer11) var adapter = AdapterFor(new Customer11()); onPersistingErrorCallbackFacetViaMethod.Invoke(adapter, new Exception()); Assert.IsNotNull(metamodel); } [TestMethod] public void TestOnUpdatingErrorLifecycleMethodPickedUpOn() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var method1 = FindMethod(typeof(Customer11), "OnUpdatingError", new[] { typeof(Exception) }); var method2 = FindMethod(typeof(Customer11), "OnPersistingError", new[] { typeof(Exception) }); metamodel = facetFactory.Process(Reflector, typeof(Customer11), MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(IOnUpdatingErrorCallbackFacet)); Assert.IsNotNull(facet); Assert.IsTrue(facet is OnUpdatingErrorCallbackFacetViaMethod); var onUpdatingErrorCallbackFacetViaMethod = (OnUpdatingErrorCallbackFacetViaMethod)facet; Assert.AreEqual(method1, onUpdatingErrorCallbackFacetViaMethod.GetMethod()); AssertMethodsRemoved(new[] { method1, method2 }); // and test exception is passed through (assert in Customer11) var adapter = AdapterFor(new Customer11()); onUpdatingErrorCallbackFacetViaMethod.Invoke(adapter, new Exception()); Assert.IsNotNull(metamodel); } [TestMethod] public void TestOnUpdatingErrorLifecycleNullFacet() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var method = FindMethod(typeof(Customer10), "OnUpdatingError", new[] { typeof(Exception) }); Assert.IsNull(method); metamodel = facetFactory.Process(Reflector, typeof(Customer10), MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(IOnUpdatingErrorCallbackFacet)); Assert.IsNotNull(facet); Assert.IsTrue(facet is OnUpdatingErrorCallbackFacetNull); Assert.IsNotNull(metamodel); } [TestMethod] public void TestPersistedLifecycleMethodPickedUpOn() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var method = FindMethod(typeof(Customer2), "Persisted"); metamodel = facetFactory.Process(Reflector, typeof(Customer2), MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(IPersistedCallbackFacet)); Assert.IsNotNull(facet); Assert.IsTrue(facet is PersistedCallbackFacetViaMethod); var persistedCallbackFacetViaMethod = (PersistedCallbackFacetViaMethod)facet; Assert.AreEqual(method, persistedCallbackFacetViaMethod.GetMethod()); AssertMethodsRemoved(new[] { method }); Assert.IsNotNull(metamodel); } [TestMethod] public void TestPersistingLifecycleMethodPickedUpOn() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var method = FindMethod(typeof(Customer1), "Persisting"); metamodel = facetFactory.Process(Reflector, typeof(Customer1), MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(IPersistingCallbackFacet)); Assert.IsNotNull(facet); Assert.IsTrue(facet is PersistingCallbackFacetViaMethod); var persistingCallbackFacetViaMethod = (PersistingCallbackFacetViaMethod)facet; Assert.AreEqual(method, persistingCallbackFacetViaMethod.GetMethod()); AssertMethodsRemoved(new[] { method }); Assert.IsNotNull(metamodel); } [TestMethod] public void TestSavedLifecycleMethodNotPickedUpOn() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); metamodel = facetFactory.Process(Reflector, typeof(Customer10), MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(IPersistedCallbackFacet)); Assert.IsNotNull(facet); Assert.IsTrue(facet is PersistedCallbackFacetNull); Assert.IsNotNull(metamodel); } [TestMethod] public void TestSavingLifecycleMethodNotPickedUpOn() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); metamodel = facetFactory.Process(Reflector, typeof(Customer9), MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(IPersistingCallbackFacet)); Assert.IsNotNull(facet); Assert.IsTrue(facet is PersistingCallbackFacetNull); Assert.IsNotNull(metamodel); } [TestMethod] public void TestUpdatedLifecycleMethodPickedUpOn() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var method = FindMethod(typeof(Customer4), "Updated"); metamodel = facetFactory.Process(Reflector, typeof(Customer4), MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(IUpdatedCallbackFacet)); Assert.IsNotNull(facet); Assert.IsTrue(facet is UpdatedCallbackFacetViaMethod); var updatedCallbackFacetViaMethod = (UpdatedCallbackFacetViaMethod)facet; Assert.AreEqual(method, updatedCallbackFacetViaMethod.GetMethod()); AssertMethodsRemoved(new[] { method }); Assert.IsNotNull(metamodel); } [TestMethod] public void TestUpdatingLifecycleMethodPickedUpOn() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var method = FindMethod(typeof(Customer3), "Updating"); metamodel = facetFactory.Process(Reflector, typeof(Customer3), MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(IUpdatingCallbackFacet)); Assert.IsNotNull(facet); Assert.IsTrue(facet is UpdatingCallbackFacetViaMethod); var updatingCallbackFacetViaMethod = (UpdatingCallbackFacetViaMethod)facet; Assert.AreEqual(method, updatingCallbackFacetViaMethod.GetMethod()); AssertMethodsRemoved(new[] { method }); Assert.IsNotNull(metamodel); } #region Setup/Teardown [TestInitialize] public override void SetUp() { base.SetUp(); facetFactory = new CallbackMethodsFacetFactory(GetOrder<CallbackMethodsFacetFactory>(), LoggerFactory); } [TestCleanup] public override void TearDown() { facetFactory = null; base.TearDown(); } #endregion private class Customer { public void Created() { } } private class Customer1 { public void Persisting() { } } private class Customer2 { public void Persisted() { } } private class Customer3 { public void Updating() { } } private class Customer4 { public void Updated() { } } private class Customer5 { public void Loading() { } } private class Customer6 { public void Loaded() { } } private class Customer7 { public void Deleting() { } } private class Customer8 { public void Deleted() { } } private class Customer9 { public void Saving() { } } private class Customer10 { public void Saved() { } } // ReSharper disable UnusedParameter.Local private class Customer11 { public string OnPersistingError(Exception e) { Assert.IsNotNull(e); return string.Empty; } public string OnUpdatingError(Exception e) { Assert.IsNotNull(e); return string.Empty; } } // ReSharper restore UnusedParameter.Local // ReSharper restore UnusedMember.Local } // Copyright (c) Naked Objects Group Ltd.
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Screens; using osu.Framework.Testing; using osu.Game.Graphics.Containers; using osu.Game.Graphics.Cursor; using osu.Game.Rulesets; using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.Scoring; using osu.Game.Screens.Play; using osuTK; using osuTK.Input; namespace osu.Game.Tests.Visual.Gameplay { public class TestScenePause : PlayerTestScene { protected new PausePlayer Player => (PausePlayer)base.Player; private readonly Container content; protected override Container<Drawable> Content => content; public TestScenePause() : base(new OsuRuleset()) { base.Content.Add(content = new MenuCursorContainer { RelativeSizeAxes = Axes.Both }); } [SetUpSteps] public override void SetUpSteps() { base.SetUpSteps(); AddStep("resume player", () => Player.GameplayClockContainer.Start()); confirmClockRunning(true); } [Test] public void TestPauseResume() { AddStep("move cursor outside", () => InputManager.MoveMouseTo(Player.ScreenSpaceDrawQuad.TopLeft - new Vector2(10))); pauseAndConfirm(); resumeAndConfirm(); } [Test] public void TestResumeWithResumeOverlay() { AddStep("move cursor to center", () => InputManager.MoveMouseTo(Player.ScreenSpaceDrawQuad.Centre)); AddUntilStep("wait for hitobjects", () => Player.ScoreProcessor.Health.Value < 1); pauseAndConfirm(); resume(); confirmClockRunning(false); confirmPauseOverlayShown(false); AddStep("click to resume", () => { InputManager.PressButton(MouseButton.Left); InputManager.ReleaseButton(MouseButton.Left); }); confirmClockRunning(true); } [Test] public void TestResumeWithResumeOverlaySkipped() { AddStep("move cursor to button", () => InputManager.MoveMouseTo(Player.HUDOverlay.HoldToQuit.Children.OfType<HoldToConfirmContainer>().First().ScreenSpaceDrawQuad.Centre)); AddUntilStep("wait for hitobjects", () => Player.ScoreProcessor.Health.Value < 1); pauseAndConfirm(); resumeAndConfirm(); } [Test] public void TestPauseTooSoon() { AddStep("move cursor outside", () => InputManager.MoveMouseTo(Player.ScreenSpaceDrawQuad.TopLeft - new Vector2(10))); pauseAndConfirm(); resume(); pause(); confirmClockRunning(true); confirmPauseOverlayShown(false); } [Test] public void TestExitTooSoon() { pauseAndConfirm(); resume(); AddStep("exit too soon", () => Player.Exit()); confirmClockRunning(true); confirmPauseOverlayShown(false); AddAssert("not exited", () => Player.IsCurrentScreen()); } [Test] public void TestPauseAfterFail() { AddUntilStep("wait for fail", () => Player.HasFailed); AddUntilStep("fail overlay shown", () => Player.FailOverlayVisible); confirmClockRunning(false); pause(); confirmClockRunning(false); confirmPauseOverlayShown(false); AddAssert("fail overlay still shown", () => Player.FailOverlayVisible); exitAndConfirm(); } [Test] public void TestExitFromFailedGameplay() { AddUntilStep("wait for fail", () => Player.HasFailed); AddStep("exit", () => Player.Exit()); confirmExited(); } [Test] public void TestQuickRetryFromFailedGameplay() { AddUntilStep("wait for fail", () => Player.HasFailed); AddStep("quick retry", () => Player.GameplayClockContainer.OfType<HotkeyRetryOverlay>().First().Action?.Invoke()); confirmExited(); } [Test] public void TestQuickExitFromFailedGameplay() { AddUntilStep("wait for fail", () => Player.HasFailed); AddStep("quick exit", () => Player.GameplayClockContainer.OfType<HotkeyExitOverlay>().First().Action?.Invoke()); confirmExited(); } [Test] public void TestExitFromGameplay() { AddStep("exit", () => Player.Exit()); confirmExited(); } [Test] public void TestQuickExitFromGameplay() { AddStep("quick exit", () => Player.GameplayClockContainer.OfType<HotkeyExitOverlay>().First().Action?.Invoke()); confirmExited(); } [Test] public void TestExitViaHoldToExit() { AddStep("exit", () => { InputManager.MoveMouseTo(Player.HUDOverlay.HoldToQuit.First(c => c is HoldToConfirmContainer)); InputManager.PressButton(MouseButton.Left); }); confirmPaused(); AddStep("release", () => InputManager.ReleaseButton(MouseButton.Left)); exitAndConfirm(); } [Test] public void TestExitFromPause() { pauseAndConfirm(); exitAndConfirm(); } [Test] public void TestRestartAfterResume() { pauseAndConfirm(); resumeAndConfirm(); restart(); confirmExited(); } private void pauseAndConfirm() { pause(); confirmPaused(); } private void resumeAndConfirm() { resume(); confirmResumed(); } private void exitAndConfirm() { AddUntilStep("player not exited", () => Player.IsCurrentScreen()); AddStep("exit", () => Player.Exit()); confirmExited(); } private void confirmPaused() { confirmClockRunning(false); AddAssert("player not exited", () => Player.IsCurrentScreen()); AddAssert("player not failed", () => !Player.HasFailed); AddAssert("pause overlay shown", () => Player.PauseOverlayVisible); } private void confirmResumed() { confirmClockRunning(true); confirmPauseOverlayShown(false); } private void confirmExited() { AddUntilStep("player exited", () => !Player.IsCurrentScreen()); } private void restart() => AddStep("restart", () => Player.Restart()); private void pause() => AddStep("pause", () => Player.Pause()); private void resume() => AddStep("resume", () => Player.Resume()); private void confirmPauseOverlayShown(bool isShown) => AddAssert("pause overlay " + (isShown ? "shown" : "hidden"), () => Player.PauseOverlayVisible == isShown); private void confirmClockRunning(bool isRunning) => AddUntilStep("clock " + (isRunning ? "running" : "stopped"), () => Player.GameplayClockContainer.GameplayClock.IsRunning == isRunning); protected override bool AllowFail => true; protected override Player CreatePlayer(Ruleset ruleset) => new PausePlayer(); protected class PausePlayer : TestPlayer { public new GameplayClockContainer GameplayClockContainer => base.GameplayClockContainer; public new ScoreProcessor ScoreProcessor => base.ScoreProcessor; public new HUDOverlay HUDOverlay => base.HUDOverlay; public bool FailOverlayVisible => FailOverlay.State.Value == Visibility.Visible; public bool PauseOverlayVisible => PauseOverlay.State.Value == Visibility.Visible; public override void OnEntering(IScreen last) { base.OnEntering(last); GameplayClockContainer.Stop(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /** This testcase attempts to delete some directories in a mounted volume - Different drive is mounted on the current drive - Current drive is mounted on a different drive - Current drive is mounted on current directory - refer to the directory in a recursive manner in addition to the normal one **/ using System; using System.IO; using System.Text; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Xunit; public class Directory_Delete_MountVolume { private delegate void ExceptionCode(); private static bool s_pass = true; [Fact] [ActiveIssue(1221)] [PlatformSpecific(PlatformID.Windows)] // testing volumes / mounts / drive letters public static void RunTest() { try { const String MountPrefixName = "LaksMount"; String mountedDirName; String dirName; String dirNameWithoutRoot; String dirNameReferedFromMountedDrive; //Adding debug info since this test hangs sometime in RTS runs String debugFileName = "Co7604Delete_MountVolume_Debug.txt"; DeleteFile(debugFileName); String scenarioDescription; scenarioDescription = "Scenario 1: Vanilla - Different drive is mounted on the current drive"; try { File.AppendAllText(debugFileName, String.Format("{0}{1}", scenarioDescription, Environment.NewLine)); string otherDriveInMachine = IOServices.GetNtfsDriveOtherThanCurrent(); //out labs use UIP tools in one drive and don't expect this drive to be used by others. We avoid this problem by not testing if the other drive is not NTFS if (FileSystemDebugInfo.IsCurrentDriveNTFS() && otherDriveInMachine != null) { Console.WriteLine(scenarioDescription); mountedDirName = Path.GetFullPath(ManageFileSystem.GetNonExistingDir(Path.DirectorySeparatorChar.ToString(), MountPrefixName)); try { Directory.CreateDirectory(mountedDirName); File.AppendAllText(debugFileName, String.Format("Mounting on {0}{1}{2}", otherDriveInMachine.Substring(0, 2), mountedDirName, Environment.NewLine)); MountHelper.Mount(otherDriveInMachine.Substring(0, 2), mountedDirName); dirName = ManageFileSystem.GetNonExistingDir(otherDriveInMachine, ManageFileSystem.DirPrefixName); File.AppendAllText(debugFileName, String.Format("Creating a sub tree at: {0}{1}", dirName, Environment.NewLine)); using (ManageFileSystem fileManager = new ManageFileSystem(dirName, 3, 100)) { Eval(Directory.Exists(dirName), "Err_3974g! Directory {0} doesn't exist: {1}", dirName, Directory.Exists(dirName)); //Lets refer to these via mounted drive and check dirNameWithoutRoot = dirName.Substring(3); dirNameReferedFromMountedDrive = Path.Combine(mountedDirName, dirNameWithoutRoot); Directory.Delete(dirNameReferedFromMountedDrive, true); Task.Delay(300).Wait(); Eval(!Directory.Exists(dirName), "Err_20387g! Directory {0} still exist: {1}", dirName, Directory.Exists(dirName)); } } finally { MountHelper.Unmount(mountedDirName); DeleteDir(mountedDirName, true); } File.AppendAllText(debugFileName, String.Format("Completed scenario {0}", Environment.NewLine)); } else File.AppendAllText(debugFileName, String.Format("Scenario 1 - Vanilla - NOT RUN: Different drive is mounted on the current drive {0}", Environment.NewLine)); } catch (Exception ex) { s_pass = false; Console.WriteLine("Err_768lme! Exception caught in scenario: {0}", ex); } scenarioDescription = "Scenario 2: Current drive is mounted on a different drive"; Console.WriteLine(scenarioDescription); File.AppendAllText(debugFileName, String.Format("{0}{1}", scenarioDescription, Environment.NewLine)); try { string otherDriveInMachine = IOServices.GetNtfsDriveOtherThanCurrent(); if (otherDriveInMachine != null) { mountedDirName = Path.GetFullPath(ManageFileSystem.GetNonExistingDir(otherDriveInMachine.Substring(0, 3), MountPrefixName)); try { Directory.CreateDirectory(mountedDirName); File.AppendAllText(debugFileName, String.Format("Mounting on {0}{1}{2}", Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName, Environment.NewLine)); MountHelper.Mount(Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName); dirName = ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), ManageFileSystem.DirPrefixName); File.AppendAllText(debugFileName, String.Format("Creating a sub tree at: {0}{1}", dirName, Environment.NewLine)); using (ManageFileSystem fileManager = new ManageFileSystem(dirName, 3, 100)) { Eval(Directory.Exists(dirName), "Err_239ufz! Directory {0} doesn't exist: {1}", dirName, Directory.Exists(dirName)); //Lets refer to these via mounted drive and check dirNameWithoutRoot = dirName.Substring(3); dirNameReferedFromMountedDrive = Path.Combine(mountedDirName, dirNameWithoutRoot); Directory.Delete(dirNameReferedFromMountedDrive, true); Task.Delay(300).Wait(); Eval(!Directory.Exists(dirName), "Err_794aiu! Directory {0} still exist: {1}", dirName, Directory.Exists(dirName)); } } finally { MountHelper.Unmount(mountedDirName); DeleteDir(mountedDirName, true); } File.AppendAllText(debugFileName, String.Format("Completed scenario {0}", Environment.NewLine)); } } catch (Exception ex) { s_pass = false; Console.WriteLine("Err_231vwf! Exception caught in scenario: {0}", ex); } //scenario 3.1: Current drive is mounted on current drive scenarioDescription = "Scenario 3.1 - Current drive is mounted on current drive"; try { if (FileSystemDebugInfo.IsCurrentDriveNTFS()) { File.AppendAllText(debugFileName, String.Format("{0}{1}", scenarioDescription, Environment.NewLine)); mountedDirName = Path.GetFullPath(ManageFileSystem.GetNonExistingDir(Path.DirectorySeparatorChar.ToString(), MountPrefixName)); try { Directory.CreateDirectory(mountedDirName); File.AppendAllText(debugFileName, String.Format("Mounting on {0}{1}{2}", Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName, Environment.NewLine)); MountHelper.Mount(Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName); dirName = ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), ManageFileSystem.DirPrefixName); File.AppendAllText(debugFileName, String.Format("Creating a sub tree at: {0}{1}", dirName, Environment.NewLine)); using (ManageFileSystem fileManager = new ManageFileSystem(dirName, 3, 100)) { Eval(Directory.Exists(dirName), "Err_324eez! Directory {0} doesn't exist: {1}", dirName, Directory.Exists(dirName)); //Lets refer to these via mounted drive and check dirNameWithoutRoot = dirName.Substring(3); dirNameReferedFromMountedDrive = Path.Combine(mountedDirName, dirNameWithoutRoot); Directory.Delete(dirNameReferedFromMountedDrive, true); Task.Delay(300).Wait(); Eval(!Directory.Exists(dirName), "Err_195whv! Directory {0} still exist: {1}", dirName, Directory.Exists(dirName)); } } finally { MountHelper.Unmount(mountedDirName); DeleteDir(mountedDirName, true); } File.AppendAllText(debugFileName, String.Format("Completed scenario {0}", Environment.NewLine)); } } catch (Exception ex) { s_pass = false; Console.WriteLine("Err_493ojg! Exception caught in scenario: {0}", ex); } //scenario 3.2: Current drive is mounted on current directory scenarioDescription = "Scenario 3.2 - Current drive is mounted on current directory"; try { if (FileSystemDebugInfo.IsCurrentDriveNTFS()) { File.AppendAllText(debugFileName, String.Format("{0}{1}", scenarioDescription, Environment.NewLine)); mountedDirName = Path.GetFullPath(ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), MountPrefixName)); try { Directory.CreateDirectory(mountedDirName); File.AppendAllText(debugFileName, String.Format("Mounting on {0}{1}{2}", Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName, Environment.NewLine)); MountHelper.Mount(Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName); dirName = ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), ManageFileSystem.DirPrefixName); File.AppendAllText(debugFileName, String.Format("Creating a sub tree at: {0}{1}", dirName, Environment.NewLine)); using (ManageFileSystem fileManager = new ManageFileSystem(dirName, 3, 100)) { Eval(Directory.Exists(dirName), "Err_951ipb! Directory {0} doesn't exist: {1}", dirName, Directory.Exists(dirName)); //Lets refer to these via mounted drive and check dirNameWithoutRoot = dirName.Substring(3); dirNameReferedFromMountedDrive = Path.Combine(mountedDirName, dirNameWithoutRoot); Directory.Delete(dirNameReferedFromMountedDrive, true); Task.Delay(300).Wait(); Eval(!Directory.Exists(dirName), "Err_493yin! Directory {0} still exist: {1}", dirName, Directory.Exists(dirName)); } } finally { MountHelper.Unmount(mountedDirName); DeleteDir(mountedDirName, true); } File.AppendAllText(debugFileName, String.Format("Completed scenario {0}", Environment.NewLine)); } } catch (Exception ex) { s_pass = false; Console.WriteLine("Err_432qcp! Exception caught in scenario: {0}", ex); } //@WATCH - potentially dangerous code - can delete the whole drive!! //scenario 3.3: we call delete on the mounted volume - this should only delete the mounted drive? //Current drive is mounted on current directory scenarioDescription = "Scenario 3.3 - we call delete on the mounted volume"; try { if (FileSystemDebugInfo.IsCurrentDriveNTFS()) { File.AppendAllText(debugFileName, String.Format("{0}{1}", scenarioDescription, Environment.NewLine)); mountedDirName = Path.GetFullPath(ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), MountPrefixName)); try { Directory.CreateDirectory(mountedDirName); File.AppendAllText(debugFileName, String.Format("Mounting on {0}{1}{2}", Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName, Environment.NewLine)); MountHelper.Mount(Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName); Directory.Delete(mountedDirName, true); Task.Delay(300).Wait(); } finally { if (!Eval(!Directory.Exists(mountedDirName), "Err_001yph! Directory {0} still exist: {1}", mountedDirName, Directory.Exists(mountedDirName))) { MountHelper.Unmount(mountedDirName); DeleteDir(mountedDirName, true); } } File.AppendAllText(debugFileName, String.Format("Completed scenario {0}", Environment.NewLine)); } } catch (Exception ex) { s_pass = false; Console.WriteLine("Err_386rpj! Exception caught in scenario: {0}", ex); } //@WATCH - potentially dangerous code - can delete the whole drive!! //scenario 3.4: we call delete on parent directory of the mounted volume, the parent directory will have some other directories and files //Current drive is mounted on current directory scenarioDescription = "Scenario 3.4 - we call delete on parent directory of the mounted volume, the parent directory will have some other directories and files"; try { if (FileSystemDebugInfo.IsCurrentDriveNTFS()) { File.AppendAllText(debugFileName, String.Format("{0}{1}", scenarioDescription, Environment.NewLine)); mountedDirName = null; try { dirName = ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), ManageFileSystem.DirPrefixName); File.AppendAllText(debugFileName, String.Format("Creating a sub tree at: {0}{1}", dirName, Environment.NewLine)); using (ManageFileSystem fileManager = new ManageFileSystem(dirName, 2, 20)) { Eval(Directory.Exists(dirName), "Err_469yvh! Directory {0} doesn't exist: {1}", dirName, Directory.Exists(dirName)); String[] dirs = fileManager.GetDirectories(1); mountedDirName = Path.GetFullPath(dirs[0]); if (Eval(Directory.GetDirectories(mountedDirName).Length == 0, "Err_974tsg! the sub directory has directories: {0}", mountedDirName)) { foreach (String file in Directory.GetFiles(mountedDirName)) File.Delete(file); if (Eval(Directory.GetFiles(mountedDirName).Length == 0, "Err_13ref! the mounted directory has files: {0}", mountedDirName)) { File.AppendAllText(debugFileName, String.Format("Mounting on {0}{1}{2}", Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName, Environment.NewLine)); MountHelper.Mount(Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName); //now lets call delete on the parent directory Directory.Delete(dirName, true); Task.Delay(300).Wait(); Eval(!Directory.Exists(dirName), "Err_006jsf! Directory {0} still exist: {1}", dirName, Directory.Exists(dirName)); Console.WriteLine("Completed Scenario 3.4"); } } } } finally { if (!Eval(!Directory.Exists(mountedDirName), "Err_625ckx! Directory {0} still exist: {1}", mountedDirName, Directory.Exists(mountedDirName))) { MountHelper.Unmount(mountedDirName); DeleteDir(mountedDirName, true); } } File.AppendAllText(debugFileName, String.Format("Completed scenario {0}", Environment.NewLine)); } } catch (Exception ex) { s_pass = false; Console.WriteLine("Err_578tni! Exception caught in scenario: {0}", ex); } //@WATCH - potentially dangerous code - can delete the whole drive!! //scenario 3.5: we call delete on parent directory of the mounted volume, the parent directory will have some other directories and files //we call a different directory than the first //Current drive is mounted on current directory scenarioDescription = "Scenario 3.5 - we call delete on parent directory of the mounted volume, the parent directory will have some other directories and files"; try { if (FileSystemDebugInfo.IsCurrentDriveNTFS()) { File.AppendAllText(debugFileName, String.Format("{0}{1}", scenarioDescription, Environment.NewLine)); mountedDirName = null; try { dirName = ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), ManageFileSystem.DirPrefixName); File.AppendAllText(debugFileName, String.Format("Creating a sub tree at: {0}{1}", dirName, Environment.NewLine)); using (ManageFileSystem fileManager = new ManageFileSystem(dirName, 2, 30)) { Eval(Directory.Exists(dirName), "Err_715tdq! Directory {0} doesn't exist: {1}", dirName, Directory.Exists(dirName)); String[] dirs = fileManager.GetDirectories(1); mountedDirName = Path.GetFullPath(dirs[0]); if (dirs.Length > 1) mountedDirName = Path.GetFullPath(dirs[1]); if (Eval(Directory.GetDirectories(mountedDirName).Length == 0, "Err_492qwl! the sub directory has directories: {0}", mountedDirName)) { foreach (String file in Directory.GetFiles(mountedDirName)) File.Delete(file); if (Eval(Directory.GetFiles(mountedDirName).Length == 0, "Err_904kij! the mounted directory has files: {0}", mountedDirName)) { File.AppendAllText(debugFileName, String.Format("Mounting on {0}{1}{2}", Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName, Environment.NewLine)); MountHelper.Mount(Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName); //now lets call delete on the parent directory Directory.Delete(dirName, true); Task.Delay(300).Wait(); Eval(!Directory.Exists(dirName), "Err_900edl! Directory {0} still exist: {1}", dirName, Directory.Exists(dirName)); Console.WriteLine("Completed Scenario 3.5: {0}", mountedDirName); } } } } finally { if (!Eval(!Directory.Exists(mountedDirName), "Err_462xtc! Directory {0} still exist: {1}", mountedDirName, Directory.Exists(mountedDirName))) { MountHelper.Unmount(mountedDirName); DeleteDir(mountedDirName, true); } } File.AppendAllText(debugFileName, String.Format("Completed scenario {0}", Environment.NewLine)); } } catch (Exception ex) { s_pass = false; Console.WriteLine("Err_471jli! Exception caught in scenario: {0}", ex); } } catch (Exception ex) { s_pass = false; Console.WriteLine("Err_234rsgf! Uncaught exception in RunTest: {0}", ex); } finally { Assert.True(s_pass); } } private static void DeleteFile(String debugFileName) { if (File.Exists(debugFileName)) File.Delete(debugFileName); } private static void DeleteDir(String debugFileName, bool sub) { bool deleted = false; int maxAttempts = 5; while (!deleted && maxAttempts > 0) { if (Directory.Exists(debugFileName)) { try { Directory.Delete(debugFileName, sub); deleted = true; } catch (Exception) { if (--maxAttempts == 0) throw; else Task.Delay(300).Wait(); } } } } //Checks for error private static bool Eval(bool expression, String msg, params Object[] values) { return Eval(expression, String.Format(msg, values)); } private static bool Eval<T>(T actual, T expected, String errorMsg) { bool retValue = expected == null ? actual == null : expected.Equals(actual); if (!retValue) Eval(retValue, errorMsg + " Expected:" + (null == expected ? "<null>" : expected.ToString()) + " Actual:" + (null == actual ? "<null>" : actual.ToString())); return retValue; } private static bool Eval(bool expression, String msg) { if (!expression) { s_pass = false; Console.WriteLine(msg); } return expression; } //Checks for a particular type of exception private static void CheckException<E>(ExceptionCode test, string error) { CheckException<E>(test, error, null); } //Checks for a particular type of exception and an Exception msg in the English locale private static void CheckException<E>(ExceptionCode test, string error, String msgExpected) { bool exception = false; try { test(); error = String.Format("{0} Exception NOT thrown ", error); } catch (Exception e) { if (e.GetType() == typeof(E)) { exception = true; if (System.Globalization.CultureInfo.CurrentUICulture.Name == "en-US" && msgExpected != null && e.Message != msgExpected) { exception = false; error = String.Format("{0} Message Different: <{1}>", error, e.Message); } } else error = String.Format("{0} Exception type: {1}", error, e.GetType().Name); } Eval(exception, error); } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace sep10v2.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ActionDescriptor.ReturnType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.NotificationHubs { using Microsoft.Rest.Azure; using Models; /// <summary> /// NotificationHubsOperations operations. /// </summary> public partial interface INotificationHubsOperations { /// <summary> /// Checks the availability of the given notificationHub in a /// namespace. /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj870968.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='parameters'> /// The notificationHub name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<CheckAvailabilityResult>> CheckAvailabilityWithHttpMessagesAsync(string resourceGroupName, string namespaceName, CheckAvailabilityParameters parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Creates/Update a NotificationHub in a namespace. /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/update a NotificationHub /// Resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<NotificationHubResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, NotificationHubCreateOrUpdateParameters parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Deletes a notification hub associated with a namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Lists the notification hubs associated with a namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<NotificationHubResource>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Creates/Updates an authorization rule for a NotificationHub /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='authorizationRuleName'> /// Authorization Rule Name. /// </param> /// <param name='parameters'> /// The shared access authorization rule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<SharedAccessAuthorizationRuleResource>> CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Deletes a notificationHub authorization rule /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='authorizationRuleName'> /// Authorization Rule Name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Gets an authorization rule for a NotificationHub by name. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='authorizationRuleName'> /// authorization rule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<SharedAccessAuthorizationRuleResource>> GetAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Lists the notification hubs associated with a namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NotificationHubResource>>> ListWithHttpMessagesAsync(string resourceGroupName, string namespaceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Gets the authorization rules for a NotificationHub. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<SharedAccessAuthorizationRuleResource>>> ListAuthorizationRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Gets the Primary and Secondary ConnectionStrings to the /// NotificationHub /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='authorizationRuleName'> /// The connection string of the NotificationHub for the specified /// authorizationRule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<ResourceListKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Regenerates the Primary/Secondary Keys to the NotificationHub /// Authorization Rule /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='authorizationRuleName'> /// The connection string of the NotificationHub for the specified /// authorizationRule. /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate the NotificationHub /// Authorization Rule Key. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<ResourceListKeys>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName, PolicykeyResource parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Lists the PNS Credentials associated with a notification hub . /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<PnsCredentialsResource>> GetPnsCredentialsWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Lists the notification hubs associated with a namespace. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NotificationHubResource>>> ListNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Gets the authorization rules for a NotificationHub. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<SharedAccessAuthorizationRuleResource>>> ListAuthorizationRulesNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } }
#region usings using System; using System.Net; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using System.Linq; using System.Text.RegularExpressions; using VVVV.PluginInterfaces.V1; using VVVV.PluginInterfaces.V2; using VVVV.Utils.VColor; using VVVV.Utils.VMath; using VVVV.Core.Logging; using YoutubeExtractor; #endregion usings namespace mp.essentials.Nodes.Network { public enum YoutubeVideoQuality { p140 = 140, p240 = 240, p360 = 360, p480 = 480, p720 = 720, p1080 = 1080, p1440 = 1440, p2160 = 2160 } public enum YoutubeVideoType { Mp4 = VideoType.Mp4, WebM = VideoType.WebM } public class YoutubeDownloadSlot { public string URL; public string Destination; public IEnumerable<VideoInfo> AllVideoInfo; public VideoInfo CurrentVideoInfo; public double Progress = 0; public bool Ready = false; public bool Success = false; public bool Error = false; public string Message = ""; public VideoDownloader VideoClient; public AudioDownloader AudioClient; public Task DownloadTask; public YoutubeDownloadSlot(string src, string dst, bool audio, int resolution, YoutubeVideoType type) { URL = src; try { AllVideoInfo = DownloadUrlResolver.GetDownloadUrls(src); if (AllVideoInfo == null) throw new Exception("Problem with VideoInfo list."); if (audio) { try { CurrentVideoInfo = AllVideoInfo .Where(vi => vi.CanExtractAudio) .OrderByDescending(va => va.AudioBitrate) .First(); if (CurrentVideoInfo.RequiresDecryption) DownloadUrlResolver.DecryptDownloadUrl(CurrentVideoInfo); var filename = string.IsNullOrEmpty(CurrentVideoInfo.Title) ? src : CurrentVideoInfo.Title; filename = Regex.Replace(filename, @"[^a-zA-Z0-9-\.]", ""); Destination = Path.Combine(dst, filename + CurrentVideoInfo.AudioExtension); AudioClient = new AudioDownloader(CurrentVideoInfo, Destination); AudioClient.DownloadProgressChanged += (sender, args) => Progress = args.ProgressPercentage / 100; AudioClient.AudioExtractionProgressChanged += (sender, args) => Progress = args.ProgressPercentage / 100 + 1; AudioClient.DownloadFinished += (sender, args) => { Ready = true; Success = true; }; } catch { Message = "Audio only is not available. Falling back to video"; audio = false; } } if (!audio) { var filteredinfo = AllVideoInfo .Where(vi => vi.VideoType == (VideoType)type && vi.AudioType != AudioType.Unknown); CurrentVideoInfo = filteredinfo.First(vi => { if (filteredinfo.Any(vii => vii.Resolution == resolution)) return vi.Resolution == resolution; else return vi.Resolution == filteredinfo.Max(vii => vii.Resolution); }); if (CurrentVideoInfo.RequiresDecryption) DownloadUrlResolver.DecryptDownloadUrl(CurrentVideoInfo); var filename = string.IsNullOrEmpty(CurrentVideoInfo.Title) ? src : CurrentVideoInfo.Title; filename = Regex.Replace(filename, @"[^a-zA-Z0-9-\.]", ""); Destination = Path.Combine(dst, filename + CurrentVideoInfo.VideoExtension); VideoClient = new VideoDownloader(CurrentVideoInfo, Destination); VideoClient.DownloadProgressChanged += (sender, args) => Progress = args.ProgressPercentage / 100; VideoClient.DownloadFinished += (sender, args) => { Ready = true; Success = true; }; } } catch (Exception e) { Ready = true; Error = true; Message = e.Message; } } public void Start() { if (VideoClient == null) { DownloadTask = Task.Factory.StartNew(() => { try { AudioClient.Execute(); } catch (Exception e) { Ready = true; Error = true; Message = e.Message; } }); } if (AudioClient == null) { DownloadTask = Task.Factory.StartNew(() => { try { VideoClient.Execute(); } catch (Exception e) { Ready = true; Error = true; Message = e.Message; } }); } } } [PluginInfo( Name = "YoutubeDownloader", Category = "File", Author = "microdee" )] public class YoutubeDownloaderNode : IPluginEvaluate { #region fields & pins [Input("Youtube Link", StringType = StringType.URL)] public ISpread<string> FURL; [Input("Destination Folder", StringType = StringType.Directory, DefaultString = "")] public ISpread<string> FDSTDir; [Input("Resolution", DefaultEnumEntry = "p1080")] public ISpread<YoutubeVideoQuality> FResolution; [Input("Type", DefaultEnumEntry = "Mp4")] public ISpread<YoutubeVideoType> FYTType; [Input("Try Audio Only")] public ISpread<bool> FAudioOnly; [Input("Start", IsBang = true)] public ISpread<bool> FStart; [Output("Youtube Link Out", StringType = StringType.URL)] public ISpread<string> FDURL; [Output("Video Info", StringType = StringType.URL)] public ISpread<VideoInfo> FVideoInfo; [Output("Destination", StringType = StringType.Filename)] public ISpread<string> FDDST; [Output("Progress")] public ISpread<double> FProg; [Output("Ready", IsBang = true)] public ISpread<bool> FReady; [Output("Error", IsBang = true)] public ISpread<bool> FError; [Output("Error Message")] public ISpread<string> FMessage; protected Dictionary<string, YoutubeDownloadSlot> slots = new Dictionary<string, YoutubeDownloadSlot>(); protected List<string> removeslot = new List<string>(); [Import()] public ILogger FLogger; #endregion fields & pins //called when data for any output pin is requested public void Evaluate(int SpreadMax) { removeslot.Clear(); for (int i = 0; i < FReady.SliceCount; i++) { if(FReady[i]) { FReady[i] = false; removeslot.Add(FDURL[i]); } } foreach (var k in removeslot) { slots.Remove(k); } for (int i = 0; i < SpreadMax; i++) { if(slots.ContainsKey(FURL[i])) continue; if(FURL[i] == "") continue; if (FStart[i]) { var slot = new YoutubeDownloadSlot(FURL[i], FDSTDir[i], FAudioOnly[i], (int)FResolution[i], FYTType[i]); slots.Add(FURL[i], slot); slot.Start(); } } FDURL.SliceCount = slots.Count; FVideoInfo.SliceCount = slots.Count; FDDST.SliceCount = slots.Count; FProg.SliceCount = slots.Count; FReady.SliceCount = slots.Count; FError.SliceCount = slots.Count; FMessage.SliceCount = slots.Count; int ii = 0; foreach (var s in slots.Values) { FDURL[ii] = s.URL; FVideoInfo[ii] = s.CurrentVideoInfo; FDDST[ii] = s.Destination; FProg[ii] = s.Progress; FReady[ii] = s.Ready; FError[ii] = s.Error; FMessage[ii] = s.Message; ii++; } //FLogger.Log(LogType.Debug, "Logging to Renderer (TTY)"); } } }
using System; using System.Reflection; namespace Python.Runtime { /// <summary> /// Implements a Python type that wraps a CLR ctor call. Constructor objects /// support a .Overloads[] syntax to allow explicit ctor overload selection. /// </summary> /// <remarks> /// ClassManager stores a ConstructorBinding instance in the class's __dict__['Overloads'] /// SomeType.Overloads[Type, ...] works like this: /// 1) Python retrieves the Overloads attribute from this ClassObject's dictionary normally /// and finds a non-null tp_descr_get slot which is called by the interpreter /// and returns an IncRef()ed pyHandle to itself. /// 2) The ConstructorBinding object handles the [] syntax in its mp_subscript by matching /// the Type object parameters to a constructor overload using Type.GetConstructor() /// [NOTE: I don't know why method overloads are not searched the same way.] /// and creating the BoundContructor object which contains ContructorInfo object. /// 3) In tp_call, if ctorInfo is not null, ctorBinder.InvokeRaw() is called. /// </remarks> [Serializable] internal class ConstructorBinding : ExtensionType { private MaybeType type; // The managed Type being wrapped in a ClassObject private IntPtr pyTypeHndl; // The python type tells GetInstHandle which Type to create. private ConstructorBinder ctorBinder; [NonSerialized] private IntPtr repr; public ConstructorBinding(Type type, IntPtr pyTypeHndl, ConstructorBinder ctorBinder) { this.type = type; this.pyTypeHndl = pyTypeHndl; // steal a type reference this.ctorBinder = ctorBinder; repr = IntPtr.Zero; } /// <summary> /// Descriptor __get__ implementation. /// Implements a Python type that wraps a CLR ctor call that requires the use /// of a .Overloads[pyTypeOrType...] syntax to allow explicit ctor overload /// selection. /// </summary> /// <param name="op"> PyObject* to a Constructors wrapper </param> /// <param name="instance"> /// the instance that the attribute was accessed through, /// or None when the attribute is accessed through the owner /// </param> /// <param name="owner"> always the owner class </param> /// <returns> /// a CtorMapper (that borrows a reference to this python type and the /// ClassObject's ConstructorBinder) wrapper. /// </returns> /// <remarks> /// Python 2.6.5 docs: /// object.__get__(self, instance, owner) /// Called to get the attribute of the owner class (class attribute access) /// or of an instance of that class (instance attribute access). /// owner is always the owner class, while instance is the instance that /// the attribute was accessed through, or None when the attribute is accessed through the owner. /// This method should return the (computed) attribute value or raise an AttributeError exception. /// </remarks> public static IntPtr tp_descr_get(IntPtr op, IntPtr instance, IntPtr owner) { var self = (ConstructorBinding)GetManagedObject(op); if (self == null) { return IntPtr.Zero; } // It doesn't seem to matter if it's accessed through an instance (rather than via the type). /*if (instance != IntPtr.Zero) { // This is ugly! PyObject_IsInstance() returns 1 for true, 0 for false, -1 for error... if (Runtime.PyObject_IsInstance(instance, owner) < 1) { return Exceptions.RaiseTypeError("How in the world could that happen!"); } }*/ Runtime.XIncref(self.pyHandle); return self.pyHandle; } /// <summary> /// Implement explicit overload selection using subscript syntax ([]). /// </summary> /// <remarks> /// ConstructorBinding.GetItem(PyObject *o, PyObject *key) /// Return element of o corresponding to the object key or NULL on failure. /// This is the equivalent of the Python expression o[key]. /// </remarks> public static IntPtr mp_subscript(IntPtr op, IntPtr key) { var self = (ConstructorBinding)GetManagedObject(op); if (!self.type.Valid) { return Exceptions.RaiseTypeError(self.type.DeletedMessage); } Type tp = self.type.Value; Type[] types = Runtime.PythonArgsToTypeArray(key); if (types == null) { return Exceptions.RaiseTypeError("type(s) expected"); } //MethodBase[] methBaseArray = self.ctorBinder.GetMethods(); //MethodBase ci = MatchSignature(methBaseArray, types); ConstructorInfo ci = tp.GetConstructor(types); if (ci == null) { return Exceptions.RaiseTypeError("No match found for constructor signature"); } var boundCtor = new BoundContructor(tp, self.pyTypeHndl, self.ctorBinder, ci); return boundCtor.pyHandle; } /// <summary> /// ConstructorBinding __repr__ implementation [borrowed from MethodObject]. /// </summary> public static IntPtr tp_repr(IntPtr ob) { var self = (ConstructorBinding)GetManagedObject(ob); if (self.repr != IntPtr.Zero) { Runtime.XIncref(self.repr); return self.repr; } var methods = self.ctorBinder.GetMethods(); if (!self.type.Valid) { return Exceptions.RaiseTypeError(self.type.DeletedMessage); } string name = self.type.Value.FullName; var doc = ""; foreach (var methodInformation in methods) { var t = methodInformation.MethodBase; if (doc.Length > 0) { doc += "\n"; } string str = t.ToString(); int idx = str.IndexOf("("); doc += string.Format("{0}{1}", name, str.Substring(idx)); } self.repr = Runtime.PyString_FromString(doc); Runtime.XIncref(self.repr); return self.repr; } /// <summary> /// ConstructorBinding dealloc implementation. /// </summary> public new static void tp_dealloc(IntPtr ob) { var self = (ConstructorBinding)GetManagedObject(ob); Runtime.XDecref(self.repr); self.Dealloc(); } public static int tp_clear(IntPtr ob) { var self = (ConstructorBinding)GetManagedObject(ob); Runtime.Py_CLEAR(ref self.repr); return 0; } public static int tp_traverse(IntPtr ob, IntPtr visit, IntPtr arg) { var self = (ConstructorBinding)GetManagedObject(ob); int res = PyVisit(self.pyTypeHndl, visit, arg); if (res != 0) return res; res = PyVisit(self.repr, visit, arg); if (res != 0) return res; return 0; } } /// <summary> /// Implements a Python type that constructs the given Type given a particular ContructorInfo. /// </summary> /// <remarks> /// Here mostly because I wanted a new __repr__ function for the selected constructor. /// An earlier implementation hung the __call__ on the ContructorBinding class and /// returned an Incref()ed self.pyHandle from the __get__ function. /// </remarks> [Serializable] internal class BoundContructor : ExtensionType { private Type type; // The managed Type being wrapped in a ClassObject private IntPtr pyTypeHndl; // The python type tells GetInstHandle which Type to create. private ConstructorBinder ctorBinder; private ConstructorInfo ctorInfo; private IntPtr repr; public BoundContructor(Type type, IntPtr pyTypeHndl, ConstructorBinder ctorBinder, ConstructorInfo ci) { this.type = type; this.pyTypeHndl = pyTypeHndl; // steal a type reference this.ctorBinder = ctorBinder; ctorInfo = ci; repr = IntPtr.Zero; } /// <summary> /// BoundContructor.__call__(PyObject *callable_object, PyObject *args, PyObject *kw) /// </summary> /// <param name="op"> PyObject *callable_object </param> /// <param name="args"> PyObject *args </param> /// <param name="kw"> PyObject *kw </param> /// <returns> A reference to a new instance of the class by invoking the selected ctor(). </returns> public static IntPtr tp_call(IntPtr op, IntPtr args, IntPtr kw) { var self = (BoundContructor)GetManagedObject(op); // Even though a call with null ctorInfo just produces the old behavior /*if (self.ctorInfo == null) { string msg = "Usage: Class.Overloads[CLR_or_python_Type, ...]"; return Exceptions.RaiseTypeError(msg); }*/ // Bind using ConstructorBinder.Bind and invoke the ctor providing a null instancePtr // which will fire self.ctorInfo using ConstructorInfo.Invoke(). object obj = self.ctorBinder.InvokeRaw(IntPtr.Zero, args, kw, self.ctorInfo); if (obj == null) { // XXX set an error return IntPtr.Zero; } // Instantiate the python object that wraps the result of the method call // and return the PyObject* to it. return CLRObject.GetInstHandle(obj, self.pyTypeHndl); } /// <summary> /// BoundContructor __repr__ implementation [borrowed from MethodObject]. /// </summary> public static IntPtr tp_repr(IntPtr ob) { var self = (BoundContructor)GetManagedObject(ob); if (self.repr != IntPtr.Zero) { Runtime.XIncref(self.repr); return self.repr; } string name = self.type.FullName; string str = self.ctorInfo.ToString(); int idx = str.IndexOf("("); str = string.Format("returns a new {0}{1}", name, str.Substring(idx)); self.repr = Runtime.PyString_FromString(str); Runtime.XIncref(self.repr); return self.repr; } /// <summary> /// ConstructorBinding dealloc implementation. /// </summary> public new static void tp_dealloc(IntPtr ob) { var self = (BoundContructor)GetManagedObject(ob); Runtime.XDecref(self.repr); self.Dealloc(); } public static int tp_clear(IntPtr ob) { var self = (BoundContructor)GetManagedObject(ob); Runtime.Py_CLEAR(ref self.repr); return 0; } public static int tp_traverse(IntPtr ob, IntPtr visit, IntPtr arg) { var self = (BoundContructor)GetManagedObject(ob); int res = PyVisit(self.pyTypeHndl, visit, arg); if (res != 0) return res; res = PyVisit(self.repr, visit, arg); if (res != 0) return res; return 0; } } }
// 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.Reflection; using System.Collections; using System.Globalization; using System.Diagnostics.Contracts; namespace System.Reflection.Emit { internal sealed class TypeBuilderInstantiation : TypeInfo { public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo) { if (typeInfo == null) return false; return IsAssignableFrom(typeInfo.AsType()); } #region Static Members internal static Type MakeGenericType(Type type, Type[] typeArguments) { Contract.Requires(type != null, "this is only called from RuntimeType.MakeGenericType and TypeBuilder.MakeGenericType so 'type' cannot be null"); if (!type.IsGenericTypeDefinition) throw new InvalidOperationException(); if (typeArguments == null) throw new ArgumentNullException(nameof(typeArguments)); Contract.EndContractBlock(); foreach (Type t in typeArguments) { if (t == null) throw new ArgumentNullException(nameof(typeArguments)); } return new TypeBuilderInstantiation(type, typeArguments); } #endregion #region Private Data Members private Type m_type; private Type[] m_inst; private string m_strFullQualName; internal Hashtable m_hashtable = new Hashtable(); #endregion #region Constructor private TypeBuilderInstantiation(Type type, Type[] inst) { m_type = type; m_inst = inst; m_hashtable = new Hashtable(); } #endregion #region Object Overrides public override String ToString() { return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString); } #endregion #region MemberInfo Overrides public override Type DeclaringType { get { return m_type.DeclaringType; } } public override Type ReflectedType { get { return m_type.ReflectedType; } } public override String Name { get { return m_type.Name; } } public override Module Module { get { return m_type.Module; } } #endregion #region Type Overrides public override Type MakePointerType() { return SymbolType.FormCompoundType("*", this, 0); } public override Type MakeByRefType() { return SymbolType.FormCompoundType("&", this, 0); } public override Type MakeArrayType() { return SymbolType.FormCompoundType("[]", this, 0); } public override Type MakeArrayType(int rank) { if (rank <= 0) throw new IndexOutOfRangeException(); Contract.EndContractBlock(); string comma = ""; for (int i = 1; i < rank; i++) comma += ","; string s = String.Format(CultureInfo.InvariantCulture, "[{0}]", comma); return SymbolType.FormCompoundType(s, this, 0); } public override Guid GUID { get { throw new NotSupportedException(); } } public override Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters) { throw new NotSupportedException(); } public override Assembly Assembly { get { return m_type.Assembly; } } public override RuntimeTypeHandle TypeHandle { get { throw new NotSupportedException(); } } public override String FullName { get { if (m_strFullQualName == null) m_strFullQualName = TypeNameBuilder.ToString(this, TypeNameBuilder.Format.FullName); return m_strFullQualName; } } public override String Namespace { get { return m_type.Namespace; } } public override String AssemblyQualifiedName { get { return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.AssemblyQualifiedName); } } private Type Substitute(Type[] substitutes) { Type[] inst = GetGenericArguments(); Type[] instSubstituted = new Type[inst.Length]; for (int i = 0; i < instSubstituted.Length; i++) { Type t = inst[i]; if (t is TypeBuilderInstantiation) { instSubstituted[i] = (t as TypeBuilderInstantiation).Substitute(substitutes); } else if (t is GenericTypeParameterBuilder) { // Substitute instSubstituted[i] = substitutes[t.GenericParameterPosition]; } else { instSubstituted[i] = t; } } return GetGenericTypeDefinition().MakeGenericType(instSubstituted); } public override Type BaseType { // B<A,B,C> // D<T,S> : B<S,List<T>,char> // D<string,int> : B<int,List<string>,char> // D<S,T> : B<T,List<S>,char> // D<S,string> : B<string,List<S>,char> get { Type typeBldrBase = m_type.BaseType; if (typeBldrBase == null) return null; TypeBuilderInstantiation typeBldrBaseAs = typeBldrBase as TypeBuilderInstantiation; if (typeBldrBaseAs == null) return typeBldrBase; return typeBldrBaseAs.Substitute(GetGenericArguments()); } } protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); } public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { throw new NotSupportedException(); } protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); } public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { throw new NotSupportedException(); } public override FieldInfo GetField(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); } public override FieldInfo[] GetFields(BindingFlags bindingAttr) { throw new NotSupportedException(); } public override Type GetInterface(String name, bool ignoreCase) { throw new NotSupportedException(); } public override Type[] GetInterfaces() { throw new NotSupportedException(); } public override EventInfo GetEvent(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); } public override EventInfo[] GetEvents() { throw new NotSupportedException(); } protected override PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); } public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { throw new NotSupportedException(); } public override Type[] GetNestedTypes(BindingFlags bindingAttr) { throw new NotSupportedException(); } public override Type GetNestedType(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); } public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr) { throw new NotSupportedException(); } public override InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new NotSupportedException(); } public override EventInfo[] GetEvents(BindingFlags bindingAttr) { throw new NotSupportedException(); } public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { throw new NotSupportedException(); } protected override TypeAttributes GetAttributeFlagsImpl() { return m_type.Attributes; } public override bool IsTypeDefinition => false; public override bool IsSZArray => false; protected override bool IsArrayImpl() { return false; } protected override bool IsByRefImpl() { return false; } protected override bool IsPointerImpl() { return false; } protected override bool IsPrimitiveImpl() { return false; } protected override bool IsCOMObjectImpl() { return false; } public override Type GetElementType() { throw new NotSupportedException(); } protected override bool HasElementTypeImpl() { return false; } public override Type UnderlyingSystemType { get { return this; } } public override Type[] GetGenericArguments() { return m_inst; } public override bool IsGenericTypeDefinition { get { return false; } } public override bool IsGenericType { get { return true; } } public override bool IsConstructedGenericType { get { return true; } } public override bool IsGenericParameter { get { return false; } } public override int GenericParameterPosition { get { throw new InvalidOperationException(); } } protected override bool IsValueTypeImpl() { return m_type.IsValueType; } public override bool ContainsGenericParameters { get { for (int i = 0; i < m_inst.Length; i++) { if (m_inst[i].ContainsGenericParameters) return true; } return false; } } public override MethodBase DeclaringMethod { get { return null; } } public override Type GetGenericTypeDefinition() { return m_type; } public override Type MakeGenericType(params Type[] inst) { throw new InvalidOperationException(SR.Arg_NotGenericTypeDefinition); } public override bool IsAssignableFrom(Type c) { throw new NotSupportedException(); } [Pure] public override bool IsSubclassOf(Type c) { throw new NotSupportedException(); } #endregion #region ICustomAttributeProvider Implementation public override Object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotSupportedException(); } #endregion } }
using System; using System.Collections.Generic; using System.Text; using FlatRedBall; using FlatRedBall.Input; using FlatRedBall.Instructions; using FlatRedBall.AI.Pathfinding; using FlatRedBall.Graphics.Animation; using FlatRedBall.Graphics.Particle; using FlatRedBall.Math.Geometry; using FlatRedBall.Glue.StateInterpolation; using Microsoft.Xna.Framework; using StateInterpolationPlugin; using FishKing.Extensions; namespace FishKing.Entities { public partial class Fish { private Random random = new Random(); private float xAcceleration; private double outOfWaterTime; private Direction directionFrom; private float originalTextureScale; SpriteList waterDropParticles = new SpriteList(); float minWaterDropHitY; float maxWaterDropHitY; Tweener distanceTweener; Tweener verticalTweener; private bool hasLanded = false; private double timeToLive { get { return 0.5f * (1-(originalTextureScale/ SpriteInstanceTextureScale)); } } public Vector3 MouthPosition { get { SpriteInstance.UpdateDependencies(FlatRedBall.TimeManager.CurrentTime); return SpriteInstance.GetKeyPixelPosition(FishType.Name); } } /// <summary> /// Initialization logic which is execute only one time for this Entity (unless the Entity is pooled). /// This method is called when the Entity is added to managers. Entities which are instantiated but not /// added to managers will not have this method called. /// </summary> private void CustomInitialize() { ShadowInstance.Visible = false; ShadowInstance.SpriteInstanceAlpha = 0.5f; ShadowInstance.RelativeZ = -0.5f; WaterDropEmitter.RelativeZ = -0.5f; } private void CustomActivity() { if (Visible) { if (Visible && ShadowInstance.Visible) { if (hasLanded) { ShadowInstance.Detach(); } else { if (directionFrom == Direction.Left || directionFrom == Direction.Right) { ShadowInstance.RelativeY = -8 + -RelativeY; ShadowInstance.SpriteInstanceWidth = this.SpriteInstance.Width * (1 - (RelativeY + 8) / 64); ShadowInstance.SpriteInstanceAlpha = 0.5f * (1 - (RelativeY + 8) / 50); } else { ShadowInstance.RelativeY = (-20 * (1 - (originalTextureScale / SpriteInstanceTextureScale))); ShadowInstance.SpriteInstanceWidth = this.SpriteInstance.Width * (originalTextureScale / SpriteInstanceTextureScale); ShadowInstance.SpriteInstanceAlpha = 0.5f * (originalTextureScale / SpriteInstanceTextureScale); } } } this.WaterDropEmitter.TimedEmit(waterDropParticles); } if (waterDropParticles.Count > 0) { UpdateWaterParticles(); } } private void UpdateWaterParticles() { if (distanceTweener != null && distanceTweener.Running) { WaterDropEmitter.XAcceleration = xAcceleration; } else { WaterDropEmitter.XAcceleration = 0; } var timeOutOfWater = FlatRedBall.TimeManager.CurrentTime - outOfWaterTime; WaterDropEmitter.SecondFrequency = (float)(2 * Math.Min(1,(timeOutOfWater / 20))); WaterDropEmitter.NumberPerEmission = Math.Max(0, 6 - (int)timeOutOfWater); Sprite sprite; if (hasLanded || directionFrom == Direction.Left || directionFrom == Direction.Right) { for (int i = waterDropParticles.Count - 1; i > -1; i--) { sprite = waterDropParticles[i]; if (sprite.Alpha == 1) { sprite.Alpha = 1 - sprite.TextureScale; } if (sprite.Y <= minWaterDropHitY && sprite.YVelocity < 0 && sprite.Y > maxWaterDropHitY) { if (random.NextDouble() > 0.9) { sprite.YVelocity = 0; sprite.CurrentChainName = "Splash"; sprite.Alpha = 0.3f; } } else if (sprite.Y <= maxWaterDropHitY) { sprite.YVelocity = 0; sprite.CurrentChainName = "Splash"; sprite.Alpha = 0.3f; } if (sprite.CurrentChainName == "Splash" && sprite.JustCycled) { SpriteManager.RemoveSprite(sprite); } } } else { var currentTime = FlatRedBall.TimeManager.CurrentTime; double timeAlive; double maxTimeToLive = 1; for (int i = waterDropParticles.Count - 1; i > -1; i--) { sprite = waterDropParticles[i]; timeAlive = currentTime - sprite.TimeCreated; if (sprite.Alpha == 1) { sprite.Alpha = 1 - sprite.TextureScale; } if (timeAlive >= timeToLive && sprite.YVelocity < 0 && timeAlive < maxTimeToLive) { if (random.NextDouble() > 0.9) { sprite.YVelocity = 0; sprite.CurrentChainName = "Splash"; sprite.Alpha = 0.3f; } } else if (timeAlive > maxTimeToLive) { sprite.YVelocity = 0; sprite.CurrentChainName = "Splash"; sprite.Alpha = 0.3f; } if (sprite.CurrentChainName == "Splash" && sprite.JustCycled) { SpriteManager.RemoveSprite(sprite); } } } } private void CustomDestroy() { for (int i = waterDropParticles.Count - 1; i > -1; i--) { SpriteManager.RemoveSprite(waterDropParticles[i]); } } private static void CustomLoadStaticContent(string contentManagerName) { } public void PullInAndLand(Vector3 targetPosition, Direction direction, Action afterAction) { outOfWaterTime = FlatRedBall.TimeManager.CurrentTime; directionFrom = direction; Visible = true; ShadowInstance.Visible = true; this.Position = targetPosition; SetRelativeFromAbsolute(); if (direction == Direction.Up) { this.Z += -1.5f; } else { this.Z += -0.5f; } GlobalContent.SplashOut.Play(); WaterSplashInstance.Play(); double tweenDuration = 0; originalTextureScale = SpriteInstanceTextureScale; var wasCastHorizontally = direction == Direction.Left || direction == Direction.Right; if (wasCastHorizontally) { var destY = -8; SpriteInstanceFlipHorizontal = (direction == Direction.Left); tweenDuration = Math.Abs(RelativeX / 96); distanceTweener = this.Tween("RelativeX").To(0).During(tweenDuration).Using(InterpolationType.Sinusoidal, Easing.Out); verticalTweener = this.Tween("RelativeY").To(20).During(tweenDuration / 2).Using(InterpolationType.Quadratic, Easing.Out); verticalTweener.Ended += () => { var lastUpdate = RelativeY; var updateBeforeLast = lastUpdate; var downTween = this.Tween("RelativeY").To(destY).During(tweenDuration / 2).Using(InterpolationType.Bounce, Easing.Out); downTween.PositionChanged += (a) => { if (a > lastUpdate && updateBeforeLast > lastUpdate) { GlobalContent.FishSplat.Play(); } updateBeforeLast = lastUpdate; lastUpdate = a; }; downTween.Start(); }; } else { Position.X += SpriteInstance.Width / 2; SetRelativeFromAbsolute(); tweenDuration = Math.Abs(RelativeY / 96); distanceTweener = this.Tween("RelativeY").To(-8).During(tweenDuration).Using(InterpolationType.Sinusoidal, Easing.Out); this.Tween("RelativeX").To(0).During(tweenDuration).Using(InterpolationType.Linear, Easing.InOut).Start(); var newScale = originalTextureScale * 2f; verticalTweener = this.Tween("SpriteInstanceTextureScale").To(newScale).During(tweenDuration / 2).Using(InterpolationType.Quadratic, Easing.Out); verticalTweener.Ended += () => { var lastUpdate = SpriteInstanceTextureScale; var updateBeforeLast = lastUpdate; var downTween = this.Tween("SpriteInstanceTextureScale").To(originalTextureScale).During(tweenDuration / 2).Using(InterpolationType.Bounce, Easing.Out); downTween.PositionChanged += (a) => { if (a > lastUpdate && updateBeforeLast > lastUpdate) { GlobalContent.FishSplat.Play(); } updateBeforeLast = lastUpdate; lastUpdate = a; }; downTween.Start(); }; } distanceTweener.Ended += () => { hasLanded = true; SetGroundLocation(); }; distanceTweener.Ended += afterAction; distanceTweener.Start(); verticalTweener.Start(); //Set waterdrop variables SetGroundLocation(); xAcceleration = -this.RelativeX / (float)tweenDuration; } private void SetGroundLocation() { minWaterDropHitY = this.Y; maxWaterDropHitY = minWaterDropHitY - SpriteInstance.Height / 2; } } }