context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using UnityEngine; using System.Collections.Generic; using Pathfinding.Serialization; #if UNITY_5_5_OR_NEWER using UnityEngine.Profiling; #endif namespace Pathfinding { public interface INavmesh { void GetNodes (GraphNodeDelegateCancelable del); } /** Generates graphs based on navmeshes. * \ingroup graphs * Navmeshes are meshes where each polygon define a walkable area. * These are great because the AI can get so much more information on how it can walk. * Polygons instead of points mean that the funnel smoother can produce really nice looking paths and the graphs are also really fast to search * and have a low memory footprint because of their smaller size to describe the same area (compared to grid graphs). * \see Pathfinding.RecastGraph * * \shadowimage{navmeshgraph_graph.png} * \shadowimage{navmeshgraph_inspector.png} * */ [JsonOptIn] public class NavMeshGraph : NavGraph, INavmesh, IUpdatableGraph, INavmeshHolder { /** Mesh to construct navmesh from */ [JsonMember] public Mesh sourceMesh; /** Offset in world space */ [JsonMember] public Vector3 offset; /** Rotation in degrees */ [JsonMember] public Vector3 rotation; /** Scale of the graph */ [JsonMember] public float scale = 1; /** More accurate nearest node queries. * When on, looks for the closest point on every triangle instead of if point is inside the node triangle in XZ space. * This is slower, but a lot better if your mesh contains overlaps (e.g bridges over other areas of the mesh). * Note that for maximum effect the Full Get Nearest Node Search setting should be toggled in A* Inspector Settings. */ [JsonMember] public bool accurateNearestNode = true; public TriangleMeshNode[] nodes; public TriangleMeshNode[] TriNodes { get { return nodes; } } public override void GetNodes (GraphNodeDelegateCancelable del) { if (nodes == null) return; for (int i = 0; i < nodes.Length && del(nodes[i]); i++) {} } public override void OnDestroy () { base.OnDestroy(); // Cleanup TriangleMeshNode.SetNavmeshHolder(active.astarData.GetGraphIndex(this), null); } public Int3 GetVertex (int index) { return vertices[index]; } public int GetVertexArrayIndex (int index) { return index; } public void GetTileCoordinates (int tileIndex, out int x, out int z) { //Tiles not supported x = z = 0; } /** Bounding Box Tree. Enables really fast lookups of nodes. \astarpro */ BBTree _bbTree; public BBTree bbTree { get { return _bbTree; } set { _bbTree = value; } } [System.NonSerialized] Int3[] _vertices; public Int3[] vertices { get { return _vertices; } set { _vertices = value; } } [System.NonSerialized] Vector3[] originalVertices; [System.NonSerialized] public int[] triangles; public void GenerateMatrix () { SetMatrix(Matrix4x4.TRS(offset, Quaternion.Euler(rotation), new Vector3(scale, scale, scale))); } /** Transforms the nodes using newMatrix from their initial positions. * The "oldMatrix" variable can be left out in this function call (only for this graph generator) * since the information can be taken from other saved data, which gives better precision. */ public override void RelocateNodes (Matrix4x4 oldMatrix, Matrix4x4 newMatrix) { if (vertices == null || vertices.Length == 0 || originalVertices == null || originalVertices.Length != vertices.Length) { return; } for (int i = 0; i < _vertices.Length; i++) { _vertices[i] = (Int3)newMatrix.MultiplyPoint3x4(originalVertices[i]); } for (int i = 0; i < nodes.Length; i++) { var node = nodes[i]; node.UpdatePositionFromVertices(); if (node.connections != null) { for (int q = 0; q < node.connections.Length; q++) { node.connectionCosts[q] = (uint)(node.position-node.connections[q].position).costMagnitude; } } } SetMatrix(newMatrix); RebuildBBTree(this); } public static NNInfo GetNearest (NavMeshGraph graph, GraphNode[] nodes, Vector3 position, NNConstraint constraint, bool accurateNearestNode) { if (nodes == null || nodes.Length == 0) { Debug.LogError("NavGraph hasn't been generated yet or does not contain any nodes"); return new NNInfo(); } if (constraint == null) constraint = NNConstraint.None; return GetNearestForceBoth(graph, graph, position, NNConstraint.None, accurateNearestNode); } public override NNInfo GetNearest (Vector3 position, NNConstraint constraint, GraphNode hint) { return GetNearest(this, nodes, position, constraint, accurateNearestNode); } /** This performs a linear search through all polygons returning the closest one. * This is usually only called in the Free version of the A* Pathfinding Project since the Pro one supports BBTrees and will do another query */ public override NNInfo GetNearestForce (Vector3 position, NNConstraint constraint) { return GetNearestForce(this, this, position, constraint, accurateNearestNode); //Debug.LogWarning ("This function shouldn't be called since constrained nodes are sent back in the GetNearest call"); //return new NNInfo (); } /** This performs a linear search through all polygons returning the closest one */ public static NNInfo GetNearestForce (NavGraph graph, INavmeshHolder navmesh, Vector3 position, NNConstraint constraint, bool accurateNearestNode) { NNInfo nn = GetNearestForceBoth(graph, navmesh, position, constraint, accurateNearestNode); nn.node = nn.constrainedNode; nn.clampedPosition = nn.constClampedPosition; return nn; } /** This performs a linear search through all polygons returning the closest one. * This will fill the NNInfo with .node for the closest node not necessarily complying with the NNConstraint, and .constrainedNode with the closest node * complying with the NNConstraint. * \see GetNearestForce(Node[],Int3[],Vector3,NNConstraint,bool) */ public static NNInfo GetNearestForceBoth (NavGraph graph, INavmeshHolder navmesh, Vector3 position, NNConstraint constraint, bool accurateNearestNode) { var pos = (Int3)position; float minDist = -1; GraphNode minNode = null; float minConstDist = -1; GraphNode minConstNode = null; float maxDistSqr = constraint.constrainDistance ? AstarPath.active.maxNearestNodeDistanceSqr : float.PositiveInfinity; GraphNodeDelegateCancelable del = delegate(GraphNode _node) { var node = _node as TriangleMeshNode; if (accurateNearestNode) { Vector3 closest = node.ClosestPointOnNode(position); float dist = ((Vector3)pos-closest).sqrMagnitude; if (minNode == null || dist < minDist) { minDist = dist; minNode = node; } if (dist < maxDistSqr && constraint.Suitable(node)) { if (minConstNode == null || dist < minConstDist) { minConstDist = dist; minConstNode = node; } } } else { if (!node.ContainsPoint((Int3)position)) { float dist = (node.position-pos).sqrMagnitude; if (minNode == null || dist < minDist) { minDist = dist; minNode = node; } if (dist < maxDistSqr && constraint.Suitable(node)) { if (minConstNode == null || dist < minConstDist) { minConstDist = dist; minConstNode = node; } } } else { int dist = System.Math.Abs(node.position.y-pos.y); if (minNode == null || dist < minDist) { minDist = dist; minNode = node; } if (dist < maxDistSqr && constraint.Suitable(node)) { if (minConstNode == null || dist < minConstDist) { minConstDist = dist; minConstNode = node; } } } } return true; }; graph.GetNodes(del); var nninfo = new NNInfo(minNode); //Find the point closest to the nearest triangle if (nninfo.node != null) { var node = nninfo.node as TriangleMeshNode;//minNode2 as MeshNode; Vector3 clP = node.ClosestPointOnNode(position); nninfo.clampedPosition = clP; } nninfo.constrainedNode = minConstNode; if (nninfo.constrainedNode != null) { var node = nninfo.constrainedNode as TriangleMeshNode;//minNode2 as MeshNode; Vector3 clP = node.ClosestPointOnNode(position); nninfo.constClampedPosition = clP; } return nninfo; } public GraphUpdateThreading CanUpdateAsync (GraphUpdateObject o) { return GraphUpdateThreading.UnityThread; } public void UpdateAreaInit (GraphUpdateObject o) {} public void UpdateArea (GraphUpdateObject o) { UpdateArea(o, this); } public static void UpdateArea (GraphUpdateObject o, INavmesh graph) { Bounds bounds = o.bounds; // Bounding rectangle with floating point coordinates Rect r = Rect.MinMaxRect(bounds.min.x, bounds.min.z, bounds.max.x, bounds.max.z); // Bounding rectangle with int coordinates var r2 = new IntRect( Mathf.FloorToInt(bounds.min.x*Int3.Precision), Mathf.FloorToInt(bounds.min.z*Int3.Precision), Mathf.FloorToInt(bounds.max.x*Int3.Precision), Mathf.FloorToInt(bounds.max.z*Int3.Precision) ); // Corners of the bounding rectangle var a = new Int3(r2.xmin, 0, r2.ymin); var b = new Int3(r2.xmin, 0, r2.ymax); var c = new Int3(r2.xmax, 0, r2.ymin); var d = new Int3(r2.xmax, 0, r2.ymax); var ymin = ((Int3)bounds.min).y; var ymax = ((Int3)bounds.max).y; // Loop through all nodes graph.GetNodes(_node => { var node = _node as TriangleMeshNode; bool inside = false; int allLeft = 0; int allRight = 0; int allTop = 0; int allBottom = 0; // Check bounding box rect in XZ plane for (int v = 0; v < 3; v++) { Int3 p = node.GetVertex(v); var vert = (Vector3)p; if (r2.Contains(p.x, p.z)) { inside = true; break; } if (vert.x < r.xMin) allLeft++; if (vert.x > r.xMax) allRight++; if (vert.z < r.yMin) allTop++; if (vert.z > r.yMax) allBottom++; } if (!inside) { if (allLeft == 3 || allRight == 3 || allTop == 3 || allBottom == 3) { return true; } } // Check if the polygon edges intersect the bounding rect for (int v = 0; v < 3; v++) { int v2 = v > 1 ? 0 : v+1; Int3 vert1 = node.GetVertex(v); Int3 vert2 = node.GetVertex(v2); if (VectorMath.SegmentsIntersectXZ(a, b, vert1, vert2)) { inside = true; break; } if (VectorMath.SegmentsIntersectXZ(a, c, vert1, vert2)) { inside = true; break; } if (VectorMath.SegmentsIntersectXZ(c, d, vert1, vert2)) { inside = true; break; } if (VectorMath.SegmentsIntersectXZ(d, b, vert1, vert2)) { inside = true; break; } } // Check if the node contains any corner of the bounding rect if (inside || node.ContainsPoint(a) || node.ContainsPoint(b) || node.ContainsPoint(c) || node.ContainsPoint(d)) { inside = true; } if (!inside) { return true; } int allAbove = 0; int allBelow = 0; // Check y coordinate for (int v = 0; v < 3; v++) { Int3 p = node.GetVertex(v); if (p.y < ymin) allBelow++; if (p.y > ymax) allAbove++; } // Polygon is either completely above the bounding box or completely below it if (allBelow == 3 || allAbove == 3) return true; // Triangle is inside the bounding box! // Update it! o.WillUpdateNode(node); o.Apply(node); return true; }); } /** Returns the closest point of the node. * The only reason this is here is because it is slightly faster compared to TriangleMeshNode.ClosestPointOnNode * since it doesn't involve so many indirections. * * Use TriangleMeshNode.ClosestPointOnNode in most other cases. */ static Vector3 ClosestPointOnNode (TriangleMeshNode node, Int3[] vertices, Vector3 pos) { return Polygon.ClosestPointOnTriangle((Vector3)vertices[node.v0], (Vector3)vertices[node.v1], (Vector3)vertices[node.v2], pos); } /** Returns if the point is inside the node in XZ space */ [System.Obsolete("Use TriangleMeshNode.ContainsPoint instead")] public bool ContainsPoint (TriangleMeshNode node, Vector3 pos) { if (VectorMath.IsClockwiseXZ((Vector3)vertices[node.v0], (Vector3)vertices[node.v1], pos) && VectorMath.IsClockwiseXZ((Vector3)vertices[node.v1], (Vector3)vertices[node.v2], pos) && VectorMath.IsClockwiseXZ((Vector3)vertices[node.v2], (Vector3)vertices[node.v0], pos)) { return true; } return false; } /** Returns if the point is inside the node in XZ space */ [System.Obsolete("Use TriangleMeshNode.ContainsPoint instead")] public static bool ContainsPoint (TriangleMeshNode node, Vector3 pos, Int3[] vertices) { if (!VectorMath.IsClockwiseMarginXZ((Vector3)vertices[node.v0], (Vector3)vertices[node.v1], (Vector3)vertices[node.v2])) { Debug.LogError("Noes!"); } if (VectorMath.IsClockwiseMarginXZ((Vector3)vertices[node.v0], (Vector3)vertices[node.v1], pos) && VectorMath.IsClockwiseMarginXZ((Vector3)vertices[node.v1], (Vector3)vertices[node.v2], pos) && VectorMath.IsClockwiseMarginXZ((Vector3)vertices[node.v2], (Vector3)vertices[node.v0], pos)) { return true; } return false; } /** Scans the graph using the path to an .obj mesh */ public void ScanInternal (string objMeshPath) { Mesh mesh = ObjImporter.ImportFile(objMeshPath); if (mesh == null) { Debug.LogError("Couldn't read .obj file at '"+objMeshPath+"'"); return; } sourceMesh = mesh; ScanInternal(); } public override void ScanInternal (OnScanStatus statusCallback) { if (sourceMesh == null) { return; } GenerateMatrix(); Vector3[] vectorVertices = sourceMesh.vertices; triangles = sourceMesh.triangles; TriangleMeshNode.SetNavmeshHolder(active.astarData.GetGraphIndex(this), this); GenerateNodes(vectorVertices, triangles, out originalVertices, out _vertices); } /** Generates a navmesh. Based on the supplied vertices and triangles */ void GenerateNodes (Vector3[] vectorVertices, int[] triangles, out Vector3[] originalVertices, out Int3[] vertices) { Profiler.BeginSample("Init"); if (vectorVertices.Length == 0 || triangles.Length == 0) { originalVertices = vectorVertices; vertices = new Int3[0]; nodes = new TriangleMeshNode[0]; return; } vertices = new Int3[vectorVertices.Length]; int c = 0; for (int i = 0; i < vertices.Length; i++) { vertices[i] = (Int3)matrix.MultiplyPoint3x4(vectorVertices[i]); } var hashedVerts = new Dictionary<Int3, int>(); var newVertices = new int[vertices.Length]; Profiler.EndSample(); Profiler.BeginSample("Hashing"); for (int i = 0; i < vertices.Length; i++) { if (!hashedVerts.ContainsKey(vertices[i])) { newVertices[c] = i; hashedVerts.Add(vertices[i], c); c++; } } for (int x = 0; x < triangles.Length; x++) { Int3 vertex = vertices[triangles[x]]; triangles[x] = hashedVerts[vertex]; } Int3[] totalIntVertices = vertices; vertices = new Int3[c]; originalVertices = new Vector3[c]; for (int i = 0; i < c; i++) { vertices[i] = totalIntVertices[newVertices[i]]; originalVertices[i] = vectorVertices[newVertices[i]]; } Profiler.EndSample(); Profiler.BeginSample("Constructing Nodes"); nodes = new TriangleMeshNode[triangles.Length/3]; int graphIndex = active.astarData.GetGraphIndex(this); // Does not have to set this, it is set in ScanInternal //TriangleMeshNode.SetNavmeshHolder ((int)graphIndex,this); for (int i = 0; i < nodes.Length; i++) { nodes[i] = new TriangleMeshNode(active); TriangleMeshNode node = nodes[i];//new MeshNode (); node.GraphIndex = (uint)graphIndex; node.Penalty = initialPenalty; node.Walkable = true; node.v0 = triangles[i*3]; node.v1 = triangles[i*3+1]; node.v2 = triangles[i*3+2]; if (!VectorMath.IsClockwiseXZ(vertices[node.v0], vertices[node.v1], vertices[node.v2])) { //Debug.DrawLine (vertices[node.v0],vertices[node.v1],Color.red); //Debug.DrawLine (vertices[node.v1],vertices[node.v2],Color.red); //Debug.DrawLine (vertices[node.v2],vertices[node.v0],Color.red); int tmp = node.v0; node.v0 = node.v2; node.v2 = tmp; } if (VectorMath.IsColinearXZ(vertices[node.v0], vertices[node.v1], vertices[node.v2])) { Debug.DrawLine((Vector3)vertices[node.v0], (Vector3)vertices[node.v1], Color.red); Debug.DrawLine((Vector3)vertices[node.v1], (Vector3)vertices[node.v2], Color.red); Debug.DrawLine((Vector3)vertices[node.v2], (Vector3)vertices[node.v0], Color.red); } // Make sure position is correctly set node.UpdatePositionFromVertices(); } Profiler.EndSample(); var sides = new Dictionary<Int2, TriangleMeshNode>(); for (int i = 0, j = 0; i < triangles.Length; j += 1, i += 3) { sides[new Int2(triangles[i+0], triangles[i+1])] = nodes[j]; sides[new Int2(triangles[i+1], triangles[i+2])] = nodes[j]; sides[new Int2(triangles[i+2], triangles[i+0])] = nodes[j]; } Profiler.BeginSample("Connecting Nodes"); var connections = new List<MeshNode>(); var connectionCosts = new List<uint>(); for (int i = 0, j = 0; i < triangles.Length; j += 1, i += 3) { connections.Clear(); connectionCosts.Clear(); TriangleMeshNode node = nodes[j]; for (int q = 0; q < 3; q++) { TriangleMeshNode other; if (sides.TryGetValue(new Int2(triangles[i+((q+1)%3)], triangles[i+q]), out other)) { connections.Add(other); connectionCosts.Add((uint)(node.position-other.position).costMagnitude); } } node.connections = connections.ToArray(); node.connectionCosts = connectionCosts.ToArray(); } Profiler.EndSample(); Profiler.BeginSample("Rebuilding BBTree"); RebuildBBTree(this); Profiler.EndSample(); } /** Rebuilds the BBTree on a NavGraph. * \astarpro * \see NavMeshGraph.bbTree */ public static void RebuildBBTree (NavMeshGraph graph) { // BBTree is an A* Pathfinding Project Pro only feature - The Pro version can be bought in the Unity Asset Store or on arongranberg.com } public void PostProcess () { } public override void OnDrawGizmos (bool drawNodes) { if (!drawNodes) { return; } Matrix4x4 preMatrix = matrix; GenerateMatrix(); if (nodes == null) { //Scan (); } if (nodes == null) { return; } if (preMatrix != matrix) { //Debug.Log ("Relocating Nodes"); RelocateNodes(preMatrix, matrix); } PathHandler debugData = AstarPath.active.debugPathData; for (int i = 0; i < nodes.Length; i++) { var node = nodes[i]; Gizmos.color = NodeColor(node, AstarPath.active.debugPathData); if (node.Walkable) { if (AstarPath.active.showSearchTree && debugData != null && debugData.GetPathNode(node).parent != null) { Gizmos.DrawLine((Vector3)node.position, (Vector3)debugData.GetPathNode(node).parent.node.position); } else { for (int q = 0; q < node.connections.Length; q++) { Gizmos.DrawLine((Vector3)node.position, Vector3.Lerp((Vector3)node.position, (Vector3)node.connections[q].position, 0.45f)); } } Gizmos.color = AstarColor.MeshEdgeColor; } else { Gizmos.color = AstarColor.UnwalkableNode; } Gizmos.DrawLine((Vector3)vertices[node.v0], (Vector3)vertices[node.v1]); Gizmos.DrawLine((Vector3)vertices[node.v1], (Vector3)vertices[node.v2]); Gizmos.DrawLine((Vector3)vertices[node.v2], (Vector3)vertices[node.v0]); } } public override void DeserializeExtraInfo (GraphSerializationContext ctx) { uint graphIndex = ctx.graphIndex; TriangleMeshNode.SetNavmeshHolder((int)graphIndex, this); int nodeCount = ctx.reader.ReadInt32(); int vertexCount = ctx.reader.ReadInt32(); if (nodeCount == -1) { nodes = new TriangleMeshNode[0]; _vertices = new Int3[0]; originalVertices = new Vector3[0]; return; } nodes = new TriangleMeshNode[nodeCount]; _vertices = new Int3[vertexCount]; originalVertices = new Vector3[vertexCount]; for (int i = 0; i < vertexCount; i++) { _vertices[i] = ctx.DeserializeInt3(); originalVertices[i] = ctx.DeserializeVector3(); } for (int i = 0; i < nodeCount; i++) { nodes[i] = new TriangleMeshNode(active); TriangleMeshNode node = nodes[i]; node.DeserializeNode(ctx); node.UpdatePositionFromVertices(); } } public override void SerializeExtraInfo (GraphSerializationContext ctx) { if (nodes == null || originalVertices == null || _vertices == null || originalVertices.Length != _vertices.Length) { ctx.writer.Write(-1); ctx.writer.Write(-1); return; } ctx.writer.Write(nodes.Length); ctx.writer.Write(_vertices.Length); for (int i = 0; i < _vertices.Length; i++) { ctx.SerializeInt3(_vertices[i]); ctx.SerializeVector3(originalVertices[i]); } for (int i = 0; i < nodes.Length; i++) { nodes[i].SerializeNode(ctx); } } public override void DeserializeSettingsCompatibility (GraphSerializationContext ctx) { base.DeserializeSettingsCompatibility(ctx); sourceMesh = ctx.DeserializeUnityObject() as Mesh; offset = ctx.DeserializeVector3(); rotation = ctx.DeserializeVector3(); scale = ctx.reader.ReadSingle(); accurateNearestNode = ctx.reader.ReadBoolean(); } } }
/* * 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 Apache.Ignite.Core.Tests.Cache { using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Transactions; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Transactions; using NUnit.Framework; /// <summary> /// Transactional cache tests. /// </summary> public abstract class CacheAbstractTransactionalTest : CacheAbstractTest { /// <summary> /// Simple cache lock test (while <see cref="TestLock"/> is ignored). /// </summary> [Test] public void TestLockSimple() { var cache = Cache(); const int key = 7; Action<ICacheLock> checkLock = lck => { using (lck) { Assert.Throws<InvalidOperationException>(lck.Exit); // can't exit if not entered lck.Enter(); Assert.IsTrue(cache.IsLocalLocked(key, true)); Assert.IsTrue(cache.IsLocalLocked(key, false)); lck.Exit(); Assert.IsFalse(cache.IsLocalLocked(key, true)); Assert.IsFalse(cache.IsLocalLocked(key, false)); Assert.IsTrue(lck.TryEnter()); Assert.IsTrue(cache.IsLocalLocked(key, true)); Assert.IsTrue(cache.IsLocalLocked(key, false)); lck.Exit(); } Assert.Throws<ObjectDisposedException>(lck.Enter); // Can't enter disposed lock }; checkLock(cache.Lock(key)); checkLock(cache.LockAll(new[] { key, 1, 2, 3 })); } /// <summary> /// Tests cache locks. /// </summary> [Test] [Ignore("IGNITE-835")] public void TestLock() { var cache = Cache(); const int key = 7; // Lock CheckLock(cache, key, () => cache.Lock(key)); // LockAll CheckLock(cache, key, () => cache.LockAll(new[] { key, 2, 3, 4, 5 })); } /// <summary> /// Internal lock test routine. /// </summary> /// <param name="cache">Cache.</param> /// <param name="key">Key.</param> /// <param name="getLock">Function to get the lock.</param> private static void CheckLock(ICache<int, int> cache, int key, Func<ICacheLock> getLock) { var sharedLock = getLock(); using (sharedLock) { Assert.Throws<InvalidOperationException>(() => sharedLock.Exit()); // can't exit if not entered sharedLock.Enter(); try { Assert.IsTrue(cache.IsLocalLocked(key, true)); Assert.IsTrue(cache.IsLocalLocked(key, false)); EnsureCannotLock(getLock, sharedLock); sharedLock.Enter(); try { Assert.IsTrue(cache.IsLocalLocked(key, true)); Assert.IsTrue(cache.IsLocalLocked(key, false)); EnsureCannotLock(getLock, sharedLock); } finally { sharedLock.Exit(); } Assert.IsTrue(cache.IsLocalLocked(key, true)); Assert.IsTrue(cache.IsLocalLocked(key, false)); EnsureCannotLock(getLock, sharedLock); Assert.Throws<SynchronizationLockException>(() => sharedLock.Dispose()); // can't dispose while locked } finally { sharedLock.Exit(); } Assert.IsFalse(cache.IsLocalLocked(key, true)); Assert.IsFalse(cache.IsLocalLocked(key, false)); var innerTask = new Task(() => { Assert.IsTrue(sharedLock.TryEnter()); sharedLock.Exit(); using (var otherLock = getLock()) { Assert.IsTrue(otherLock.TryEnter()); otherLock.Exit(); } }); innerTask.Start(); innerTask.Wait(); } Assert.IsFalse(cache.IsLocalLocked(key, true)); Assert.IsFalse(cache.IsLocalLocked(key, false)); var outerTask = new Task(() => { using (var otherLock = getLock()) { Assert.IsTrue(otherLock.TryEnter()); otherLock.Exit(); } }); outerTask.Start(); outerTask.Wait(); Assert.Throws<ObjectDisposedException>(() => sharedLock.Enter()); // Can't enter disposed lock } /// <summary> /// Ensure that lock cannot be obtained by other threads. /// </summary> /// <param name="getLock">Get lock function.</param> /// <param name="sharedLock">Shared lock.</param> private static void EnsureCannotLock(Func<ICacheLock> getLock, ICacheLock sharedLock) { var task = new Task(() => { Assert.IsFalse(sharedLock.TryEnter()); Assert.IsFalse(sharedLock.TryEnter(TimeSpan.FromMilliseconds(100))); using (var otherLock = getLock()) { Assert.IsFalse(otherLock.TryEnter()); Assert.IsFalse(otherLock.TryEnter(TimeSpan.FromMilliseconds(100))); } }); task.Start(); task.Wait(); } /// <summary> /// Tests that commit applies cache changes. /// </summary> [Test] public void TestTxCommit([Values(true, false)] bool async) { var cache = Cache(); Assert.IsNull(Transactions.Tx); using (var tx = Transactions.TxStart()) { cache.Put(1, 1); cache.Put(2, 2); if (async) { var task = tx.CommitAsync(); task.Wait(); Assert.IsTrue(task.IsCompleted); } else tx.Commit(); } Assert.AreEqual(1, cache.Get(1)); Assert.AreEqual(2, cache.Get(2)); Assert.IsNull(Transactions.Tx); } /// <summary> /// Tests that rollback reverts cache changes. /// </summary> [Test] public void TestTxRollback() { var cache = Cache(); cache.Put(1, 1); cache.Put(2, 2); Assert.IsNull(Transactions.Tx); using (var tx = Transactions.TxStart()) { cache.Put(1, 10); cache.Put(2, 20); tx.Rollback(); } Assert.AreEqual(1, cache.Get(1)); Assert.AreEqual(2, cache.Get(2)); Assert.IsNull(Transactions.Tx); } /// <summary> /// Tests that Dispose without Commit reverts changes. /// </summary> [Test] public void TestTxClose() { var cache = Cache(); cache.Put(1, 1); cache.Put(2, 2); Assert.IsNull(Transactions.Tx); using (Transactions.TxStart()) { cache.Put(1, 10); cache.Put(2, 20); } Assert.AreEqual(1, cache.Get(1)); Assert.AreEqual(2, cache.Get(2)); Assert.IsNull(Transactions.Tx); } /// <summary> /// Tests all concurrency and isolation modes with and without timeout. /// </summary> [Test] public void TestTxAllModes([Values(true, false)] bool withTimeout) { var cache = Cache(); int cntr = 0; foreach (TransactionConcurrency concurrency in Enum.GetValues(typeof(TransactionConcurrency))) { foreach (TransactionIsolation isolation in Enum.GetValues(typeof(TransactionIsolation))) { Console.WriteLine("Test tx [concurrency=" + concurrency + ", isolation=" + isolation + "]"); Assert.IsNull(Transactions.Tx); using (var tx = withTimeout ? Transactions.TxStart(concurrency, isolation, TimeSpan.FromMilliseconds(1100), 10) : Transactions.TxStart(concurrency, isolation)) { Assert.AreEqual(concurrency, tx.Concurrency); Assert.AreEqual(isolation, tx.Isolation); if (withTimeout) Assert.AreEqual(1100, tx.Timeout.TotalMilliseconds); cache.Put(1, cntr); tx.Commit(); } Assert.IsNull(Transactions.Tx); Assert.AreEqual(cntr, cache.Get(1)); cntr++; } } } /// <summary> /// Tests that transaction properties are applied and propagated properly. /// </summary> [Test] public void TestTxAttributes() { ITransaction tx = Transactions.TxStart(TransactionConcurrency.Optimistic, TransactionIsolation.RepeatableRead, TimeSpan.FromMilliseconds(2500), 100); Assert.IsFalse(tx.IsRollbackOnly); Assert.AreEqual(TransactionConcurrency.Optimistic, tx.Concurrency); Assert.AreEqual(TransactionIsolation.RepeatableRead, tx.Isolation); Assert.AreEqual(2500, tx.Timeout.TotalMilliseconds); Assert.AreEqual(TransactionState.Active, tx.State); Assert.IsTrue(tx.StartTime.Ticks > 0); Assert.AreEqual(tx.NodeId, GetIgnite(0).GetCluster().GetLocalNode().Id); DateTime startTime1 = tx.StartTime; tx.Commit(); Assert.IsFalse(tx.IsRollbackOnly); Assert.AreEqual(TransactionState.Committed, tx.State); Assert.AreEqual(TransactionConcurrency.Optimistic, tx.Concurrency); Assert.AreEqual(TransactionIsolation.RepeatableRead, tx.Isolation); Assert.AreEqual(2500, tx.Timeout.TotalMilliseconds); Assert.AreEqual(startTime1, tx.StartTime); Thread.Sleep(100); tx = Transactions.TxStart(TransactionConcurrency.Pessimistic, TransactionIsolation.ReadCommitted, TimeSpan.FromMilliseconds(3500), 200); Assert.IsFalse(tx.IsRollbackOnly); Assert.AreEqual(TransactionConcurrency.Pessimistic, tx.Concurrency); Assert.AreEqual(TransactionIsolation.ReadCommitted, tx.Isolation); Assert.AreEqual(3500, tx.Timeout.TotalMilliseconds); Assert.AreEqual(TransactionState.Active, tx.State); Assert.IsTrue(tx.StartTime.Ticks > 0); Assert.IsTrue(tx.StartTime > startTime1); DateTime startTime2 = tx.StartTime; tx.Rollback(); Assert.AreEqual(TransactionState.RolledBack, tx.State); Assert.AreEqual(TransactionConcurrency.Pessimistic, tx.Concurrency); Assert.AreEqual(TransactionIsolation.ReadCommitted, tx.Isolation); Assert.AreEqual(3500, tx.Timeout.TotalMilliseconds); Assert.AreEqual(startTime2, tx.StartTime); Thread.Sleep(100); tx = Transactions.TxStart(TransactionConcurrency.Optimistic, TransactionIsolation.RepeatableRead, TimeSpan.FromMilliseconds(2500), 100); Assert.IsFalse(tx.IsRollbackOnly); Assert.AreEqual(TransactionConcurrency.Optimistic, tx.Concurrency); Assert.AreEqual(TransactionIsolation.RepeatableRead, tx.Isolation); Assert.AreEqual(2500, tx.Timeout.TotalMilliseconds); Assert.AreEqual(TransactionState.Active, tx.State); Assert.IsTrue(tx.StartTime > startTime2); DateTime startTime3 = tx.StartTime; tx.Commit(); Assert.IsFalse(tx.IsRollbackOnly); Assert.AreEqual(TransactionState.Committed, tx.State); Assert.AreEqual(TransactionConcurrency.Optimistic, tx.Concurrency); Assert.AreEqual(TransactionIsolation.RepeatableRead, tx.Isolation); Assert.AreEqual(2500, tx.Timeout.TotalMilliseconds); Assert.AreEqual(startTime3, tx.StartTime); // Check defaults. tx = Transactions.TxStart(); Assert.AreEqual(Transactions.DefaultTransactionConcurrency, tx.Concurrency); Assert.AreEqual(Transactions.DefaultTransactionIsolation, tx.Isolation); Assert.AreEqual(Transactions.DefaultTimeout, tx.Timeout); tx.Commit(); } /// <summary> /// Tests <see cref="ITransaction.IsRollbackOnly"/> flag. /// </summary> [Test] public void TestTxRollbackOnly() { var cache = Cache(); cache.Put(1, 1); cache.Put(2, 2); var tx = Transactions.TxStart(); cache.Put(1, 10); cache.Put(2, 20); Assert.IsFalse(tx.IsRollbackOnly); tx.SetRollbackonly(); Assert.IsTrue(tx.IsRollbackOnly); Assert.AreEqual(TransactionState.MarkedRollback, tx.State); var ex = Assert.Throws<TransactionRollbackException>(() => tx.Commit()); Assert.IsTrue(ex.Message.StartsWith("Invalid transaction state for prepare [state=MARKED_ROLLBACK")); tx.Dispose(); Assert.AreEqual(TransactionState.RolledBack, tx.State); Assert.IsTrue(tx.IsRollbackOnly); Assert.AreEqual(1, cache.Get(1)); Assert.AreEqual(2, cache.Get(2)); Assert.IsNull(Transactions.Tx); } /// <summary> /// Tests transaction metrics. /// </summary> [Test] public void TestTxMetrics() { var cache = Cache(); var startTime = DateTime.UtcNow.AddSeconds(-1); Transactions.ResetMetrics(); var metrics = Transactions.GetMetrics(); Assert.AreEqual(0, metrics.TxCommits); Assert.AreEqual(0, metrics.TxRollbacks); using (Transactions.TxStart()) { cache.Put(1, 1); } using (var tx = Transactions.TxStart()) { cache.Put(1, 1); tx.Commit(); } metrics = Transactions.GetMetrics(); Assert.AreEqual(1, metrics.TxCommits); Assert.AreEqual(1, metrics.TxRollbacks); Assert.LessOrEqual(startTime, metrics.CommitTime); Assert.LessOrEqual(startTime, metrics.RollbackTime); Assert.GreaterOrEqual(DateTime.UtcNow, metrics.CommitTime); Assert.GreaterOrEqual(DateTime.UtcNow, metrics.RollbackTime); } /// <summary> /// Tests transaction state transitions. /// </summary> [Test] public void TestTxStateAndExceptions() { var tx = Transactions.TxStart(); Assert.AreEqual(TransactionState.Active, tx.State); Assert.AreEqual(Thread.CurrentThread.ManagedThreadId, tx.ThreadId); tx.AddMeta("myMeta", 42); Assert.AreEqual(42, tx.Meta<int>("myMeta")); Assert.AreEqual(42, tx.RemoveMeta<int>("myMeta")); tx.RollbackAsync().Wait(); Assert.AreEqual(TransactionState.RolledBack, tx.State); Assert.Throws<InvalidOperationException>(() => tx.Commit()); tx = Transactions.TxStart(); Assert.AreEqual(TransactionState.Active, tx.State); tx.CommitAsync().Wait(); Assert.AreEqual(TransactionState.Committed, tx.State); var task = tx.RollbackAsync(); // Illegal, but should not fail here; will fail in task Assert.Throws<AggregateException>(() => task.Wait()); } /// <summary> /// Tests the transaction deadlock detection. /// </summary> [Test] public void TestTxDeadlockDetection() { var cache = Cache(); var keys0 = Enumerable.Range(1, 100).ToArray(); cache.PutAll(keys0.ToDictionary(x => x, x => x)); var barrier = new Barrier(2); Action<int[]> increment = keys => { using (var tx = Transactions.TxStart(TransactionConcurrency.Pessimistic, TransactionIsolation.RepeatableRead, TimeSpan.FromSeconds(0.5), 0)) { foreach (var key in keys) cache[key]++; barrier.SignalAndWait(500); tx.Commit(); } }; // Increment keys within tx in different order to cause a deadlock. var aex = Assert.Throws<AggregateException>(() => Task.WaitAll(Task.Factory.StartNew(() => increment(keys0)), Task.Factory.StartNew(() => increment(keys0.Reverse().ToArray())))); Assert.AreEqual(2, aex.InnerExceptions.Count); var deadlockEx = aex.InnerExceptions.OfType<TransactionDeadlockException>().First(); Assert.IsTrue(deadlockEx.Message.Trim().StartsWith("Deadlock detected:"), deadlockEx.Message); } /// <summary> /// Test Ignite transaction enlistment in ambient <see cref="TransactionScope"/>. /// </summary> [Test] [Ignore("IGNITE-3430")] public void TestTransactionScopeSingleCache() { var cache = Cache(); cache[1] = 1; cache[2] = 2; // Commit. using (var ts = new TransactionScope()) { cache[1] = 10; cache[2] = 20; Assert.IsNotNull(cache.Ignite.GetTransactions().Tx); ts.Complete(); } Assert.AreEqual(10, cache[1]); Assert.AreEqual(20, cache[2]); // Rollback. using (new TransactionScope()) { cache[1] = 100; cache[2] = 200; } Assert.AreEqual(10, cache[1]); Assert.AreEqual(20, cache[2]); } /// <summary> /// Test Ignite transaction enlistment in ambient <see cref="TransactionScope"/> /// with multiple participating caches. /// </summary> [Test] [Ignore("IGNITE-3430")] public void TestTransactionScopeMultiCache() { var cache1 = Cache(); var cache2 = GetIgnite(0).GetOrCreateCache<int, int>(new CacheConfiguration(cache1.Name + "_") { AtomicityMode = CacheAtomicityMode.Transactional }); cache1[1] = 1; cache2[1] = 2; // Commit. using (var ts = new TransactionScope()) { cache1[1] = 10; cache2[1] = 20; ts.Complete(); } Assert.AreEqual(10, cache1[1]); Assert.AreEqual(20, cache2[1]); // Rollback. using (new TransactionScope()) { cache1[1] = 100; cache2[1] = 200; } Assert.AreEqual(10, cache1[1]); Assert.AreEqual(20, cache2[1]); } /// <summary> /// Test Ignite transaction enlistment in ambient <see cref="TransactionScope"/> /// when Ignite tx is started manually. /// </summary> [Test] [Ignore("IGNITE-3430")] public void TestTransactionScopeWithManualIgniteTx() { var cache = Cache(); var transactions = cache.Ignite.GetTransactions(); cache[1] = 1; // When Ignite tx is started manually, it won't be enlisted in TransactionScope. using (var tx = transactions.TxStart()) { using (new TransactionScope()) { cache[1] = 2; } // Revert transaction scope. tx.Commit(); // Commit manual tx. } Assert.AreEqual(2, cache[1]); } /// <summary> /// Test Ignite transaction with <see cref="TransactionScopeOption.Suppress"/> option. /// </summary> [Test] [Ignore("IGNITE-3430")] public void TestSuppressedTransactionScope() { var cache = Cache(); cache[1] = 1; using (new TransactionScope(TransactionScopeOption.Suppress)) { cache[1] = 2; } // Even though transaction is not completed, the value is updated, because tx is suppressed. Assert.AreEqual(2, cache[1]); } /// <summary> /// Test Ignite transaction enlistment in ambient <see cref="TransactionScope"/> with nested scopes. /// </summary> [Test] [Ignore("IGNITE-3430")] public void TestNestedTransactionScope() { var cache = Cache(); cache[1] = 1; foreach (var option in new[] {TransactionScopeOption.Required, TransactionScopeOption.RequiresNew}) { // Commit. using (var ts1 = new TransactionScope()) { using (var ts2 = new TransactionScope(option)) { cache[1] = 2; ts2.Complete(); } cache[1] = 3; ts1.Complete(); } Assert.AreEqual(3, cache[1]); // Rollback. using (new TransactionScope()) { using (new TransactionScope(option)) cache[1] = 4; cache[1] = 5; } // In case with Required option there is a single tx // that gets aborted, second put executes outside the tx. Assert.AreEqual(option == TransactionScopeOption.Required ? 5 : 3, cache[1], option.ToString()); } } /// <summary> /// Test that ambient <see cref="TransactionScope"/> options propagate to Ignite transaction. /// </summary> [Test] [Ignore("IGNITE-3430")] public void TestTransactionScopeOptions() { var cache = Cache(); var transactions = cache.Ignite.GetTransactions(); var modes = new[] { Tuple.Create(IsolationLevel.Serializable, TransactionIsolation.Serializable), Tuple.Create(IsolationLevel.RepeatableRead, TransactionIsolation.RepeatableRead), Tuple.Create(IsolationLevel.ReadCommitted, TransactionIsolation.ReadCommitted), Tuple.Create(IsolationLevel.ReadUncommitted, TransactionIsolation.ReadCommitted), Tuple.Create(IsolationLevel.Snapshot, TransactionIsolation.ReadCommitted), Tuple.Create(IsolationLevel.Chaos, TransactionIsolation.ReadCommitted), }; foreach (var mode in modes) { using (new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = mode.Item1 })) { cache[1] = 1; var tx = transactions.Tx; Assert.AreEqual(mode.Item2, tx.Isolation); Assert.AreEqual(transactions.DefaultTransactionConcurrency, tx.Concurrency); } } } /// <summary> /// Tests all transactional operations with <see cref="TransactionScope"/>. /// </summary> [Test] [Ignore("IGNITE-3430")] public void TestTransactionScopeAllOperations() { for (var i = 0; i < 100; i++) { CheckTxOp((cache, key) => cache.Put(key, -5)); CheckTxOp((cache, key) => cache.PutAsync(key, -5).Wait()); CheckTxOp((cache, key) => cache.PutAll(new Dictionary<int, int> {{key, -7}})); CheckTxOp((cache, key) => cache.PutAllAsync(new Dictionary<int, int> {{key, -7}}).Wait()); CheckTxOp((cache, key) => { cache.Remove(key); cache.PutIfAbsent(key, -10); }); CheckTxOp((cache, key) => { cache.Remove(key); cache.PutIfAbsentAsync(key, -10); }); CheckTxOp((cache, key) => cache.GetAndPut(key, -9)); CheckTxOp((cache, key) => cache.GetAndPutAsync(key, -9).Wait()); CheckTxOp((cache, key) => { cache.Remove(key); cache.GetAndPutIfAbsent(key, -10); }); CheckTxOp((cache, key) => { cache.Remove(key); cache.GetAndPutIfAbsentAsync(key, -10).Wait(); }); CheckTxOp((cache, key) => cache.GetAndRemove(key)); CheckTxOp((cache, key) => cache.GetAndRemoveAsync(key)); CheckTxOp((cache, key) => cache.GetAndReplace(key, -11)); CheckTxOp((cache, key) => cache.GetAndReplaceAsync(key, -11)); CheckTxOp((cache, key) => cache.Invoke(key, new AddProcessor(), 1)); CheckTxOp((cache, key) => cache.InvokeAsync(key, new AddProcessor(), 1)); CheckTxOp((cache, key) => cache.InvokeAll(new[] {key}, new AddProcessor(), 1)); CheckTxOp((cache, key) => cache.InvokeAllAsync(new[] {key}, new AddProcessor(), 1)); CheckTxOp((cache, key) => cache.Remove(key)); CheckTxOp((cache, key) => cache.RemoveAsync(key)); CheckTxOp((cache, key) => cache.RemoveAll(new[] {key})); CheckTxOp((cache, key) => cache.RemoveAllAsync(new[] {key}).Wait()); CheckTxOp((cache, key) => cache.Replace(key, 100)); CheckTxOp((cache, key) => cache.ReplaceAsync(key, 100)); CheckTxOp((cache, key) => cache.Replace(key, cache[key], 100)); CheckTxOp((cache, key) => cache.ReplaceAsync(key, cache[key], 100)); } } /// <summary> /// Checks that cache operation behaves transactionally. /// </summary> private void CheckTxOp(Action<ICache<int, int>, int> act) { var cache = Cache(); cache[1] = 1; cache[2] = 2; // Rollback. using (new TransactionScope()) { act(cache, 1); Assert.IsNotNull(cache.Ignite.GetTransactions().Tx, "Transaction has not started."); } Assert.AreEqual(1, cache[1]); Assert.AreEqual(2, cache[2]); using (new TransactionScope()) { act(cache, 1); act(cache, 2); } Assert.AreEqual(1, cache[1]); Assert.AreEqual(2, cache[2]); // Commit. using (var ts = new TransactionScope()) { act(cache, 1); ts.Complete(); } Assert.IsTrue(!cache.ContainsKey(1) || cache[1] != 1); Assert.AreEqual(2, cache[2]); using (var ts = new TransactionScope()) { act(cache, 1); act(cache, 2); ts.Complete(); } Assert.IsTrue(!cache.ContainsKey(1) || cache[1] != 1); Assert.IsTrue(!cache.ContainsKey(2) || cache[2] != 2); } [Serializable] private class AddProcessor : ICacheEntryProcessor<int, int, int, int> { public int Process(IMutableCacheEntry<int, int> entry, int arg) { entry.Value += arg; return arg; } } } }
// 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.Collections.Generic; using System.Text; namespace WebsitePanel.Providers.HostedSolution { public class ExchangeMailbox { string displayName; string accountName; bool hideFromAddressBook; bool disabled; string firstName; string initials; string lastName; string jobTitle; string company; string department; string office; ExchangeAccount managerAccount; string businessPhone; string fax; string homePhone; string mobilePhone; string pager; string webPage; string address; string city; string state; string zip; string country; string notes; bool enableForwarding; ExchangeAccount forwardingAccount; bool doNotDeleteOnForward; ExchangeAccount[] sendOnBehalfAccounts; ExchangeAccount[] acceptAccounts; ExchangeAccount[] rejectAccounts; ExchangeAccount[] fullAccessAccounts; ExchangeAccount[] sendAsAccounts; bool requireSenderAuthentication; int maxRecipients; int maxSendMessageSizeKB; int maxReceiveMessageSizeKB; bool enablePOP; bool enableIMAP; bool enableOWA; bool enableMAPI; bool enableActiveSync; long issueWarningKB; long prohibitSendKB; long prohibitSendReceiveKB; int keepDeletedItemsDays; private string domain; int totalItems; int totalSizeMB; DateTime lastLogon; DateTime lastLogoff; bool enableLitigationHold; long recoverabelItemsSpace; long recoverabelItemsWarning; string exchangeGuid; public string DisplayName { get { return this.displayName; } set { this.displayName = value; } } public string AccountName { get { return this.accountName; } set { this.accountName = value; } } public bool HideFromAddressBook { get { return this.hideFromAddressBook; } set { this.hideFromAddressBook = value; } } public bool Disabled { get { return this.disabled; } set { this.disabled = value; } } public string FirstName { get { return this.firstName; } set { this.firstName = value; } } public string Initials { get { return this.initials; } set { this.initials = value; } } public string LastName { get { return this.lastName; } set { this.lastName = value; } } public string JobTitle { get { return this.jobTitle; } set { this.jobTitle = value; } } public string Company { get { return this.company; } set { this.company = value; } } public string Department { get { return this.department; } set { this.department = value; } } public string Office { get { return this.office; } set { this.office = value; } } public ExchangeAccount ManagerAccount { get { return this.managerAccount; } set { this.managerAccount = value; } } public string BusinessPhone { get { return this.businessPhone; } set { this.businessPhone = value; } } public string Fax { get { return this.fax; } set { this.fax = value; } } public string HomePhone { get { return this.homePhone; } set { this.homePhone = value; } } public string MobilePhone { get { return this.mobilePhone; } set { this.mobilePhone = value; } } public string Pager { get { return this.pager; } set { this.pager = value; } } public string WebPage { get { return this.webPage; } set { this.webPage = value; } } public string Address { get { return this.address; } set { this.address = value; } } public string City { get { return this.city; } set { this.city = value; } } public string State { get { return this.state; } set { this.state = value; } } public string Zip { get { return this.zip; } set { this.zip = value; } } public string Country { get { return this.country; } set { this.country = value; } } public string Notes { get { return this.notes; } set { this.notes = value; } } public bool EnableForwarding { get { return this.enableForwarding; } set { this.enableForwarding = value; } } public ExchangeAccount ForwardingAccount { get { return this.forwardingAccount; } set { this.forwardingAccount = value; } } public bool DoNotDeleteOnForward { get { return this.doNotDeleteOnForward; } set { this.doNotDeleteOnForward = value; } } public ExchangeAccount[] SendOnBehalfAccounts { get { return this.sendOnBehalfAccounts; } set { this.sendOnBehalfAccounts = value; } } public ExchangeAccount[] AcceptAccounts { get { return this.acceptAccounts; } set { this.acceptAccounts = value; } } public ExchangeAccount[] RejectAccounts { get { return this.rejectAccounts; } set { this.rejectAccounts = value; } } public int MaxRecipients { get { return this.maxRecipients; } set { this.maxRecipients = value; } } public int MaxSendMessageSizeKB { get { return this.maxSendMessageSizeKB; } set { this.maxSendMessageSizeKB = value; } } public int MaxReceiveMessageSizeKB { get { return this.maxReceiveMessageSizeKB; } set { this.maxReceiveMessageSizeKB = value; } } public bool EnablePOP { get { return this.enablePOP; } set { this.enablePOP = value; } } public bool EnableIMAP { get { return this.enableIMAP; } set { this.enableIMAP = value; } } public bool EnableOWA { get { return this.enableOWA; } set { this.enableOWA = value; } } public bool EnableMAPI { get { return this.enableMAPI; } set { this.enableMAPI = value; } } public bool EnableActiveSync { get { return this.enableActiveSync; } set { this.enableActiveSync = value; } } public long IssueWarningKB { get { return this.issueWarningKB; } set { this.issueWarningKB = value; } } public long ProhibitSendKB { get { return this.prohibitSendKB; } set { this.prohibitSendKB = value; } } public long ProhibitSendReceiveKB { get { return this.prohibitSendReceiveKB; } set { this.prohibitSendReceiveKB = value; } } public int KeepDeletedItemsDays { get { return this.keepDeletedItemsDays; } set { this.keepDeletedItemsDays = value; } } public string Domain { get { return domain; } set { domain = value; } } public int TotalItems { get { return this.totalItems; } set { this.totalItems = value; } } public int TotalSizeMB { get { return this.totalSizeMB; } set { this.totalSizeMB = value; } } public DateTime LastLogon { get { return this.lastLogon; } set { this.lastLogon = value; } } public DateTime LastLogoff { get { return this.lastLogoff; } set { this.lastLogoff = value; } } public bool RequireSenderAuthentication { get { return requireSenderAuthentication; } set { requireSenderAuthentication = value; } } public ExchangeAccount[] SendAsAccounts { get { return sendAsAccounts; } set { sendAsAccounts = value; } } public ExchangeAccount[] FullAccessAccounts { get { return fullAccessAccounts; } set { fullAccessAccounts = value; } } public ExchangeAccount[] OnBehalfOfAccounts { get; set; } public ExchangeAccount[] CalendarAccounts { get; set; } public ExchangeAccount[] ContactAccounts { get; set; } public bool EnableLitigationHold { get { return enableLitigationHold; } set { enableLitigationHold = value; } } public long RecoverabelItemsSpace { get { return this.recoverabelItemsSpace; } set { this.recoverabelItemsSpace = value; } } public long RecoverabelItemsWarning { get { return this.recoverabelItemsWarning; } set { this.recoverabelItemsWarning = value; } } public string ExchangeGuid { get { return this.exchangeGuid; } set { this.exchangeGuid = value; } } public override string ToString() { return !string.IsNullOrEmpty(accountName) ? accountName : base.ToString(); } } }
//============================================================================= // System : Sandcastle Help File Builder Components // File : CachedResolveReferenceLinksComponent.cs // Author : Eric Woodruff (Eric@EWoodruff.us) // Updated : 05/22/2010 // Compiler: Microsoft Visual C# // // This file contains a build component that is derived from // ResolveReferenceLinksComponent2. The main difference is that this one loads // cached MSDN URLs from a serialized binary file rather than letting the // base component invoke the web service to look them up. This can // significantly decrease the amount of time needed to perform a build. // // This code is published under the Microsoft Public License (Ms-PL). A copy // of the license should be distributed with the code. It can also be found // at the project website: http://SHFB.CodePlex.com. This notice, the // author's name, and all copyright notices must remain intact in all // applications, documentation, and source files. // // Version Date Who Comments // ============================================================================ // 1.6.0.3 11/11/2007 EFW Created the code // 1.8.0.3 07/04/2009 EFW Add parameter to Dispose() to match base class //============================================================================= using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Windows.Forms; using System.Xml; using System.Xml.XPath; using Microsoft.Ddue.Tools; namespace SandcastleBuilder.Components { /// <summary> /// This is a derived <b>ResolveReferenceLinksComponent2</b> class that /// loads cached MSDN URLs from a serialized binary file rather than /// letting the base component invoke the web service to look them up. /// This can significantly decrease the amount of time needed to perform /// a build. /// </summary> /// <remarks>The cache is built cumulatively over time rather than having /// all 170,000+ resolved entries loaded, most of which would never be /// used. If new URLs are added to the cache during a build, the cache is /// saved during disposal so that the new entries are used on subsequent /// builds.</remarks> /// <example> /// <code lang="xml" title="Example configuration"> /// &lt;!-- Cached MSDN URL references component. This should replace /// the standard ResolveReferenceLinksComponent2 build component. --&gt; /// &lt;component type="SandcastleBuilder.Components.CachedResolveReferenceLinksComponent" /// assembly="C:\SandcastleBuilder\SandcastleBuilder.Components.dll" /// locale="en-us" linkTarget="_blank"&gt; /// &lt;cache filename="C:\SandcastleBuilder\Cache\MsdnUrl.cache" /&gt; /// &lt;targets base="C:\Program Files\Sandcastle\Data\Reflection" /// recurse="true" files="*.xml" type="MSDN" /&gt; /// &lt;targets files="reflection.xml" type="Local" /&gt; /// &lt;/component&gt; /// </code> /// </example> public class CachedResolveReferenceLinksComponent : ResolveReferenceLinksComponent2 { #region Private data members //===================================================================== private int originalCacheCount; private string cacheFile; private Dictionary<string, string> msdnCache; #endregion #region Constructor //===================================================================== /// <summary> /// Constructor /// </summary> /// <param name="assembler">A reference to the build assembler.</param> /// <param name="configuration">The configuration information</param> /// <exception cref="ConfigurationErrorsException">This is thrown if /// an error is detected in the configuration.</exception> public CachedResolveReferenceLinksComponent(BuildAssembler assembler, XPathNavigator configuration) : base(assembler, configuration) { BinaryFormatter bf = new BinaryFormatter(); Dictionary<string, string> cachedUrls; TargetCollection targets; Target target; MsdnResolver resolver; Type type; FieldInfo field; XPathNavigator node; FileStream fs = null; string path, url; Assembly asm = Assembly.GetExecutingAssembly(); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(asm.Location); base.WriteMessage(MessageLevel.Info, String.Format( CultureInfo.InvariantCulture, "\r\n [{0}, version {1}]\r\n Cached Resolve Reference " + " Links 2 Component. {2}\r\n http://SHFB.CodePlex.com", fvi.ProductName, fvi.ProductVersion, fvi.LegalCopyright)); // If a <cache> element is not specified, this will behave just // like the base class. node = configuration.SelectSingleNode("cache"); if(node == null) { base.WriteMessage(MessageLevel.Warn, "No <cache> element was " + "specified. No MSDN URL caching will occur in this build."); return; } cacheFile = node.GetAttribute("filename", String.Empty); if(String.IsNullOrEmpty(cacheFile)) throw new ConfigurationErrorsException("You must specify " + "a filename value on the cache element."); // Create the folder if it doesn't exist cacheFile = Path.GetFullPath(Environment.ExpandEnvironmentVariables( cacheFile)); path = Path.GetDirectoryName(cacheFile); if(!Directory.Exists(path)) Directory.CreateDirectory(path); type = this.GetType().BaseType; field = type.GetField("msdn", BindingFlags.NonPublic | BindingFlags.Instance); resolver = (MsdnResolver)field.GetValue(this); // No need to load the cache if MSDN links are not used if(resolver != null) { type = resolver.GetType(); field = type.GetField("cachedMsdnUrls", BindingFlags.NonPublic | BindingFlags.Instance); msdnCache = (Dictionary<string, string>)field.GetValue(resolver); // Load the cache if it exists if(!File.Exists(cacheFile)) base.WriteMessage(MessageLevel.Info, "The MSDN URL cache '" + cacheFile + "' does not exist yet. All IDs will be " + "looked up in this build."); else try { fs = new FileStream(cacheFile, FileMode.Open); cachedUrls = (Dictionary<string, string>)bf.Deserialize(fs); // Get the target collection for marking unknown URLs // as "None" links. type = this.GetType().BaseType; field = type.GetField("targets", BindingFlags.NonPublic | BindingFlags.Instance); targets = (TargetCollection)field.GetValue(this); type = typeof(Target); field = type.GetField("type", BindingFlags.NonPublic | BindingFlags.Instance); foreach(string key in cachedUrls.Keys) { url = cachedUrls[key]; msdnCache.Add(key, url); // For IDs with a null URL, mark the target as a // "None" link so that it doesn't waste a lookup. if(url == null) { target = targets[key]; if(target != null) field.SetValue(target, LinkType2.None); } } base.WriteMessage(MessageLevel.Info, String.Format( CultureInfo.InvariantCulture, "Loaded {0} cached " + "MSDN URL entries", msdnCache.Count)); } finally { if(fs != null) fs.Close(); } originalCacheCount = msdnCache.Count; } } #endregion #region Dispose of the component //===================================================================== /// <summary> /// This is overriden to save the updated cache when disposed /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (msdnCache != null && msdnCache.Count != originalCacheCount) { base.WriteMessage(MessageLevel.Info, "MSDN URL cache " + "updated. Saving new information to " + cacheFile); using (FileStream fs = new FileStream(cacheFile, FileMode.Create)) { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(fs, msdnCache); base.WriteMessage(MessageLevel.Info, String.Format( CultureInfo.InvariantCulture, "New cache size: {0} " + "entries", msdnCache.Count)); } } } base.Dispose(disposing); } #endregion } }
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Security; using BulletSharp.Math; namespace BulletSharp { public class Hacd : IDisposable { internal IntPtr _native; [UnmanagedFunctionPointer(Native.Conv), SuppressUnmanagedCodeSecurity] delegate bool CallbackFunctionUnmanagedDelegate(IntPtr msg, double progress, double globalConcavity, IntPtr n); public delegate bool CallBackFunction(string msg, double progress, double globalConcativity, int n); CallbackFunctionUnmanagedDelegate _callbackFunctionUnmanaged; CallBackFunction _callbackFunction; public Hacd() { _native = HACD_HACD_new(); } bool CallbackFunctionUnmanaged(IntPtr msg, double progress, double globalConcavity, IntPtr n) { string msg2 = Marshal.PtrToStringAnsi(msg); return _callbackFunction(msg2, progress, globalConcavity, n.ToInt32()); } public bool Compute() { return HACD_HACD_Compute(_native); } public bool Compute(bool fullCH) { return HACD_HACD_Compute2(_native, fullCH); } public bool Compute(bool fullCH, bool exportDistPoints) { return HACD_HACD_Compute3(_native, fullCH, exportDistPoints); } public void DenormalizeData() { HACD_HACD_DenormalizeData(_native); } public bool GetCH(int numCH, double[] points, long[] triangles) { if (points.Length < GetNPointsCH(numCH)) { return false; } if (triangles.Length < GetNTrianglesCH(numCH)) { return false; } GCHandle pointsArray = GCHandle.Alloc(points, GCHandleType.Pinned); GCHandle trianglesArray = GCHandle.Alloc(triangles, GCHandleType.Pinned); bool ret = HACD_HACD_GetCH(_native, numCH, pointsArray.AddrOfPinnedObject(), trianglesArray.AddrOfPinnedObject()); pointsArray.Free(); trianglesArray.Free(); return ret; } public int GetNPointsCH(int numCH) { return HACD_HACD_GetNPointsCH(_native, numCH); } public int GetNTrianglesCH(int numCH) { return HACD_HACD_GetNTrianglesCH(_native, numCH); } public double[] GetPoints() { IntPtr pointsPtr = HACD_HACD_GetPoints(_native); int pointsLen = NPoints * 3; if (pointsLen == 0 || pointsPtr == IntPtr.Zero) { return new double[0]; } double[] pointsArray = new double[pointsLen]; Marshal.Copy(pointsPtr, pointsArray, 0, pointsLen); return pointsArray; } public long[] GetTriangles() { IntPtr trianglesPtr = HACD_HACD_GetTriangles(_native); int trianglesLen = NTriangles * 3; if (trianglesLen == 0 || trianglesPtr == IntPtr.Zero) { return new long[0]; } long[] trianglesArray = new long[trianglesLen]; Marshal.Copy(trianglesPtr, trianglesArray, 0, trianglesLen); return trianglesArray; } public void NormalizeData() { HACD_HACD_NormalizeData(_native); } public bool Save(string fileName, bool uniColor) { IntPtr filenameTemp = Marshal.StringToHGlobalAnsi(fileName); bool ret = HACD_HACD_Save(_native, filenameTemp, uniColor); Marshal.FreeHGlobal(filenameTemp); return ret; } public bool Save(string fileName, bool uniColor, long numCluster) { IntPtr filenameTemp = Marshal.StringToHGlobalAnsi(fileName); bool ret = HACD_HACD_Save2(_native, filenameTemp, uniColor, numCluster); Marshal.FreeHGlobal(filenameTemp); return ret; } public void SetPoints(ICollection<double> points) { double[] pointsArray; int arrayLen = points.Count; pointsArray = points as double[]; if (pointsArray == null) { pointsArray = new double[arrayLen]; points.CopyTo(pointsArray, 0); } IntPtr pointsPtr = HACD_HACD_GetPoints(_native); if (pointsPtr != IntPtr.Zero) { Marshal.FreeHGlobal(pointsPtr); } pointsPtr = Marshal.AllocHGlobal(sizeof(double) * arrayLen); Marshal.Copy(pointsArray, 0, pointsPtr, arrayLen); HACD_HACD_SetPoints(_native, pointsPtr); NPoints = arrayLen / 3; } public void SetPoints(ICollection<Vector3> points) { double[] pointsArray = new double[points.Count * 3]; int i = 0; foreach (Vector3 v in points) { pointsArray[i++] = v.X; pointsArray[i++] = v.Y; pointsArray[i++] = v.Z; } SetPoints(pointsArray); } public void SetTriangles(ICollection<long> triangles) { long[] trianglesLong; int arrayLen = triangles.Count; trianglesLong = triangles as long[]; if (trianglesLong == null) { trianglesLong = new long[arrayLen]; triangles.CopyTo(trianglesLong, 0); } IntPtr trianglesPtr = HACD_HACD_GetTriangles(_native); if (trianglesPtr != IntPtr.Zero) { Marshal.FreeHGlobal(trianglesPtr); } trianglesPtr = Marshal.AllocHGlobal(sizeof(long) * arrayLen); Marshal.Copy(trianglesLong, 0, trianglesPtr, arrayLen); HACD_HACD_SetTriangles(_native, trianglesPtr); NTriangles = arrayLen / 3; } public void SetTriangles(ICollection<int> triangles) { int n = triangles.Count; long[] trianglesLong = new long[n]; int i = 0; foreach (int t in triangles) { trianglesLong[i++] = t; } SetTriangles(trianglesLong); } public bool AddExtraDistPoints { get { return HACD_HACD_GetAddExtraDistPoints(_native); } set { HACD_HACD_SetAddExtraDistPoints(_native, value); } } public bool AddFacesPoints { get { return HACD_HACD_GetAddFacesPoints(_native); } set { HACD_HACD_SetAddFacesPoints(_native, value); } } public bool AddNeighboursDistPoints { get { return HACD_HACD_GetAddNeighboursDistPoints(_native); } set { HACD_HACD_SetAddNeighboursDistPoints(_native, value); } } public CallBackFunction CallBack { get { return _callbackFunction; } set { _callbackFunctionUnmanaged = CallbackFunctionUnmanaged; _callbackFunction = value; if (value != null) { HACD_HACD_SetCallBack(_native, Marshal.GetFunctionPointerForDelegate(_callbackFunctionUnmanaged)); } else { HACD_HACD_SetCallBack(_native, IntPtr.Zero); } } } public double CompacityWeight { get { return HACD_HACD_GetCompacityWeight(_native); } set { HACD_HACD_SetCompacityWeight(_native, value); } } public double Concavity { get { return HACD_HACD_GetConcavity(_native); } set { HACD_HACD_SetConcavity(_native, value); } } public double ConnectDist { get { return HACD_HACD_GetConnectDist(_native); } set { HACD_HACD_SetConnectDist(_native, value); } } public int NClusters { get { return HACD_HACD_GetNClusters(_native); } set { HACD_HACD_SetNClusters(_native, value); } } public int NPoints { get { return HACD_HACD_GetNPoints(_native); } set { HACD_HACD_SetNPoints(_native, value); } } public int NTriangles { get { return HACD_HACD_GetNTriangles(_native); } set { HACD_HACD_SetNTriangles(_native, value); } } public int NVerticesPerCH { get { return HACD_HACD_GetNVerticesPerCH(_native); } set { HACD_HACD_SetNVerticesPerCH(_native, value); } } /* public long Partition { get { return HACD_HACD_GetPartition(_native); } } */ public double ScaleFactor { get { return HACD_HACD_GetScaleFactor(_native); } set { HACD_HACD_SetScaleFactor(_native, value); } } public double VolumeWeight { get { return HACD_HACD_GetVolumeWeight(_native); } set { HACD_HACD_SetVolumeWeight(_native, value); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_native != IntPtr.Zero) { IntPtr pointsPtr = HACD_HACD_GetPoints(_native); if (pointsPtr != IntPtr.Zero) { Marshal.FreeHGlobal(pointsPtr); HACD_HACD_SetPoints(_native, IntPtr.Zero); } IntPtr trianglesPtr = HACD_HACD_GetTriangles(_native); if (trianglesPtr != IntPtr.Zero) { Marshal.FreeHGlobal(trianglesPtr); HACD_HACD_SetTriangles(_native, IntPtr.Zero); } HACD_HACD_delete(_native); _native = IntPtr.Zero; } } ~Hacd() { Dispose(false); } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr HACD_HACD_new(); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool HACD_HACD_Compute(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool HACD_HACD_Compute2(IntPtr obj, bool fullCH); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool HACD_HACD_Compute3(IntPtr obj, bool fullCH, bool exportDistPoints); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void HACD_HACD_DenormalizeData(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool HACD_HACD_GetAddExtraDistPoints(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool HACD_HACD_GetAddFacesPoints(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool HACD_HACD_GetAddNeighboursDistPoints(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr HACD_HACD_GetCallBack(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool HACD_HACD_GetCH(IntPtr obj, int numCH, IntPtr points, IntPtr triangles); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern double HACD_HACD_GetCompacityWeight(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern double HACD_HACD_GetConcavity(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern double HACD_HACD_GetConnectDist(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int HACD_HACD_GetNClusters(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int HACD_HACD_GetNPoints(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int HACD_HACD_GetNPointsCH(IntPtr obj, int numCH); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int HACD_HACD_GetNTriangles(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int HACD_HACD_GetNTrianglesCH(IntPtr obj, int numCH); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int HACD_HACD_GetNVerticesPerCH(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr HACD_HACD_GetPartition(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr HACD_HACD_GetPoints(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern double HACD_HACD_GetScaleFactor(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr HACD_HACD_GetTriangles(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern double HACD_HACD_GetVolumeWeight(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void HACD_HACD_NormalizeData(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool HACD_HACD_Save(IntPtr obj, IntPtr fileName, bool uniColor); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool HACD_HACD_Save2(IntPtr obj, IntPtr fileName, bool uniColor, long numCluster); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void HACD_HACD_SetAddExtraDistPoints(IntPtr obj, bool addExtraDistPoints); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void HACD_HACD_SetAddFacesPoints(IntPtr obj, bool addFacesPoints); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void HACD_HACD_SetAddNeighboursDistPoints(IntPtr obj, bool addNeighboursDistPoints); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void HACD_HACD_SetCallBack(IntPtr obj, IntPtr callBack); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void HACD_HACD_SetCompacityWeight(IntPtr obj, double alpha); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void HACD_HACD_SetConcavity(IntPtr obj, double concavity); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void HACD_HACD_SetConnectDist(IntPtr obj, double ccConnectDist); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void HACD_HACD_SetNClusters(IntPtr obj, int nClusters); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void HACD_HACD_SetNPoints(IntPtr obj, int nPoints); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void HACD_HACD_SetNTriangles(IntPtr obj, int nTriangles); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void HACD_HACD_SetNVerticesPerCH(IntPtr obj, int nVerticesPerCH); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void HACD_HACD_SetPoints(IntPtr obj, IntPtr points); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void HACD_HACD_SetScaleFactor(IntPtr obj, double scale); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void HACD_HACD_SetTriangles(IntPtr obj, IntPtr triangles); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void HACD_HACD_SetVolumeWeight(IntPtr obj, double beta); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void HACD_HACD_delete(IntPtr obj); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using allverse3.Models; using allverse3.Models.app; using allverse3.Models.ManageViewModels; using allverse3.Services; namespace allverse3.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); } /*[HttpGet] public JsonResult GetUser() { var user = new UserModel(); user.isAuthenticated = User.Identity.IsAuthenticated; user.ID = _userManager.GetUserId(HttpContext.User); user.Name = User.Identity.Name; return Json(user); }*/ // // POST: /Manage/RemoveLogin [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel account) { ManageMessageId? message = ManageMessageId.Error; var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.RemoveLoginAsync(user, account.LoginProvider, account.ProviderKey); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); message = ManageMessageId.RemoveLoginSuccess; } } return RedirectToAction(nameof(ManageLogins), new { Message = message }); } // // GET: /Manage/AddPhoneNumber public IActionResult AddPhoneNumber() { return View(); } // // POST: /Manage/AddPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } // Generate the token and send it var user = await GetCurrentUserAsync(); var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber); await _smsSender.SendSmsAsync(model.PhoneNumber, "Your security code is: " + code); return RedirectToAction(nameof(VerifyPhoneNumber), new { PhoneNumber = model.PhoneNumber }); } // // POST: /Manage/EnableTwoFactorAuthentication [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> EnableTwoFactorAuthentication() { var user = await GetCurrentUserAsync(); if (user != null) { await _userManager.SetTwoFactorEnabledAsync(user, true); await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(1, "User enabled two-factor authentication."); } return RedirectToAction(nameof(Index), "Manage"); } // // POST: /Manage/DisableTwoFactorAuthentication [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> DisableTwoFactorAuthentication() { var user = await GetCurrentUserAsync(); if (user != null) { await _userManager.SetTwoFactorEnabledAsync(user, false); await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(2, "User disabled two-factor authentication."); } return RedirectToAction(nameof(Index), "Manage"); } // // GET: /Manage/VerifyPhoneNumber [HttpGet] public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber) { var code = await _userManager.GenerateChangePhoneNumberTokenAsync(await GetCurrentUserAsync(), phoneNumber); // Send an SMS to verify the phone number return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber }); } // // POST: /Manage/VerifyPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.AddPhoneSuccess }); } } // If we got this far, something failed, redisplay the form ModelState.AddModelError(string.Empty, "Failed to verify phone number"); return View(model); } // // POST: /Manage/RemovePhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> RemovePhoneNumber() { var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.SetPhoneNumberAsync(user, null); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.RemovePhoneSuccess }); } } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } // // GET: /Manage/ChangePassword [HttpGet] public IActionResult ChangePassword() { return View(); } // // POST: /Manage/ChangePassword [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(3, "User changed their password successfully."); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess }); } AddErrors(result); return View(model); } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } // // GET: /Manage/SetPassword [HttpGet] public IActionResult SetPassword() { return View(); } // // POST: /Manage/SetPassword [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> SetPassword(SetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.AddPasswordAsync(user, model.NewPassword); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetPasswordSuccess }); } AddErrors(result); return View(model); } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } //GET: /Manage/ManageLogins [HttpGet] public async Task<IActionResult> ManageLogins(ManageMessageId? message = null) { ViewData["StatusMessage"] = message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed." : message == ManageMessageId.AddLoginSuccess ? "The external login was added." : message == ManageMessageId.Error ? "An error has occurred." : ""; var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var userLogins = await _userManager.GetLoginsAsync(user); //var otherLogins = _signInManager.GetExternalAuthenticationSchemes().Where(auth => userLogins.All(ul => auth.AuthenticationScheme != ul.LoginProvider)).ToList(); ViewData["ShowRemoveButton"] = user.PasswordHash != null || userLogins.Count > 1; return View(new ManageLoginsViewModel { CurrentLogins = userLogins }); } // // 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 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml { using System.Text; using System.Diagnostics; using System.Xml.Schema; internal class XmlName : IXmlSchemaInfo { private string _prefix; private string _localName; private string _ns; private string _name; private int _hashCode; internal XmlDocument ownerDoc; internal XmlName next; public static XmlName Create(string prefix, string localName, string ns, int hashCode, XmlDocument ownerDoc, XmlName next, IXmlSchemaInfo schemaInfo) { if (schemaInfo == null) { return new XmlName(prefix, localName, ns, hashCode, ownerDoc, next); } else { return new XmlNameEx(prefix, localName, ns, hashCode, ownerDoc, next, schemaInfo); } } internal XmlName(string prefix, string localName, string ns, int hashCode, XmlDocument ownerDoc, XmlName next) { _prefix = prefix; _localName = localName; _ns = ns; _name = null; _hashCode = hashCode; this.ownerDoc = ownerDoc; this.next = next; } public string LocalName { get { return _localName; } } public string NamespaceURI { get { return _ns; } } public string Prefix { get { return _prefix; } } public int HashCode { get { return _hashCode; } } public XmlDocument OwnerDocument { get { return ownerDoc; } } public string Name { get { if (_name == null) { Debug.Assert(_prefix != null); if (_prefix.Length > 0) { if (_localName.Length > 0) { string n = string.Concat(_prefix, ":", _localName); lock (ownerDoc.NameTable) { if (_name == null) { _name = ownerDoc.NameTable.Add(n); } } } else { _name = _prefix; } } else { _name = _localName; } Debug.Assert(Ref.Equal(_name, ownerDoc.NameTable.Get(_name))); } return _name; } } public virtual XmlSchemaValidity Validity { get { return XmlSchemaValidity.NotKnown; } } public virtual bool IsDefault { get { return false; } } public virtual bool IsNil { get { return false; } } public virtual XmlSchemaSimpleType MemberType { get { return null; } } public virtual XmlSchemaType SchemaType { get { return null; } } public virtual XmlSchemaElement SchemaElement { get { return null; } } public virtual XmlSchemaAttribute SchemaAttribute { get { return null; } } public virtual bool Equals(IXmlSchemaInfo schemaInfo) { return schemaInfo == null; } public static int GetHashCode(string name) { int hashCode = 0; if (name != null) { for (int i = name.Length - 1; i >= 0; i--) { char ch = name[i]; if (ch == ':') break; hashCode += (hashCode << 7) ^ ch; } hashCode -= hashCode >> 17; hashCode -= hashCode >> 11; hashCode -= hashCode >> 5; } return hashCode; } } internal sealed class XmlNameEx : XmlName { private byte _flags; private XmlSchemaSimpleType _memberType; private XmlSchemaType _schemaType; private object _decl; // flags // 0,1 : Validity // 2 : IsDefault // 3 : IsNil private const byte ValidityMask = 0x03; private const byte IsDefaultBit = 0x04; private const byte IsNilBit = 0x08; internal XmlNameEx(string prefix, string localName, string ns, int hashCode, XmlDocument ownerDoc, XmlName next, IXmlSchemaInfo schemaInfo) : base(prefix, localName, ns, hashCode, ownerDoc, next) { SetValidity(schemaInfo.Validity); SetIsDefault(schemaInfo.IsDefault); SetIsNil(schemaInfo.IsNil); _memberType = schemaInfo.MemberType; _schemaType = schemaInfo.SchemaType; _decl = schemaInfo.SchemaElement != null ? (object)schemaInfo.SchemaElement : (object)schemaInfo.SchemaAttribute; } public override XmlSchemaValidity Validity { get { return ownerDoc.CanReportValidity ? (XmlSchemaValidity)(_flags & ValidityMask) : XmlSchemaValidity.NotKnown; } } public override bool IsDefault { get { return (_flags & IsDefaultBit) != 0; } } public override bool IsNil { get { return (_flags & IsNilBit) != 0; } } public override XmlSchemaSimpleType MemberType { get { return _memberType; } } public override XmlSchemaType SchemaType { get { return _schemaType; } } public override XmlSchemaElement SchemaElement { get { return _decl as XmlSchemaElement; } } public override XmlSchemaAttribute SchemaAttribute { get { return _decl as XmlSchemaAttribute; } } public void SetValidity(XmlSchemaValidity value) { _flags = (byte)((_flags & ~ValidityMask) | (byte)(value)); } public void SetIsDefault(bool value) { if (value) _flags = (byte)(_flags | IsDefaultBit); else _flags = (byte)(_flags & ~IsDefaultBit); } public void SetIsNil(bool value) { if (value) _flags = (byte)(_flags | IsNilBit); else _flags = (byte)(_flags & ~IsNilBit); } public override bool Equals(IXmlSchemaInfo schemaInfo) { if (schemaInfo != null && schemaInfo.Validity == (XmlSchemaValidity)(_flags & ValidityMask) && schemaInfo.IsDefault == ((_flags & IsDefaultBit) != 0) && schemaInfo.IsNil == ((_flags & IsNilBit) != 0) && (object)schemaInfo.MemberType == (object)_memberType && (object)schemaInfo.SchemaType == (object)_schemaType && (object)schemaInfo.SchemaElement == (object)(_decl as XmlSchemaElement) && (object)schemaInfo.SchemaAttribute == (object)(_decl as XmlSchemaAttribute)) { return true; } return false; } } }
using static System.Math; using static System.Double; namespace MathUtils { class Polynomial { static readonly double SIN_PI_3RD = Sin(PI / 3); static readonly double COS_PI_3RD = Cos(PI / 3); static readonly double SIN_MINUS_PI_3RD = Sin(-PI / 3); static readonly double COS_MINUS_PI_3RD = Cos(-PI / 3); const double ONE_3RD = 1.0 / 3.0; const double EPSILON = 1.1E-30; /// <summary> /// Returns the cube root of a value d. /// </summary> /// <param name="d">May be negative, but not NaN.</param> /// <returns>The cube root of d.</returns> public static double Cbrt(double d) { return Sign(d) * Pow(Abs(d), ONE_3RD); } /// <summary> /// Finds the root of a first order polynomial f(x) = A*x + B. /// If A is equal to zero the root will be empty. /// </summary> /// <param name="a">The linear coefficent A.</param> /// <param name="b">The constant offset B.</param> /// <returns>An array containing the root or nothing.</returns> public static double[] LinearRootD(double a, double b) { if(a == 0) { return new double[0]; } else { return LinearRootD(b / a); } } /// <summary> /// Finds the root of a first order polynomial f(x) = A*x + B, where A must NOT be zero! /// </summary> /// <param name="a">The linear coefficent A, must not be zero.</param> /// <param name="b">The constant offset B.</param> /// <returns>An array containing the root or NaN if a equal to zero.</returns> public static double[] UnsafeLinearRootD(double a, double b) { return LinearRootD(b / a); } /// <summary> /// Finds the root of a first order polynomial f(x) = x + A. /// </summary> /// <param name="a">The constant offset A.</param> /// <returns>An array containing the root.</returns> public static double[] LinearRootD(double a) { double[] root = new double[1]; root[0] = -a; return root; } /// <summary> /// Finds the real roots of a second order polynomial f(x) = A*x^2 + B*x + C. /// </summary> /// <param name="a">The quadratic coefficent A.</param> /// <param name="b">The linear coefficent B.</param> /// <param name="c">The constant offset C.</param> /// <returns>An array containing the two to zero real roots.</returns> public static double[] QuadraticRootsD(double a, double b, double c) { if(a == 0) { return LinearRootD(b, c); } else { return QuadraticRootsD(b / a, c / a); } } /// <summary> /// Finds the real roots of a second order polynomial f(x) = A*x^2 + B*x + C, where A must NOT be zero! /// </summary> /// <param name="a">The quadratic coefficent A.</param> /// <param name="b">The linear coefficent B.</param> /// <param name="c">The constant offset C.</param> /// <returns>An array containing the two to zero real roots.</returns> public static double[] UnsafeQuadraticRootsD(double a, double b, double c) { return QuadraticRootsD(b / a, c / a); } /// <summary> /// Finds the real roots of a second order polynomial f(x) = x^2 + A*x + B. /// </summary> /// <param name="a">The linear coefficent B.</param> /// <param name="b">The constant offset C.</param> /// <returns>An array containing the two to zero real roots.</returns> public static double[] QuadraticRootsD(double a, double b) { double D = 0.25 * a * a - b; if(D < 0) { return new double[0]; } else { if(D == 0) { double[] root = new double[1]; root[0] = -0.5 * a; return root; } else { D = Sqrt(D); double[] roots = new double[2]; roots[0] = -0.5 * a - D; roots[1] = -0.5 * a + D; return roots; } } } /// <summary> /// Finds the real roots of a third order polynomial f(x) = A*x^3 + B*x^2 + C*x + D. /// </summary> /// <param name="a">The cubic coefficient A.</param> /// <param name="b">The quadratic coefficent B.</param> /// <param name="c">The linear coefficent C.</param> /// <param name="d">The constant offset D.</param> /// <returns>An array containing the three to zero real roots.</returns> public static double[] CubicRootsD(double a, double b, double c, double d) { if(a == 0) { return QuadraticRootsD(b, c, d); } else { return CubicRootsD(b / a, c / a, d / a); } } /// <summary> /// Finds the real roots of a third order polynomial f(x) = A*x^3 + B*x^2 + C*x + D, where A must NOT be zero. /// </summary> /// <param name="a">The cubic coefficient A.</param> /// <param name="b">The quadratic coefficent B.</param> /// <param name="c">The linear coefficent C.</param> /// <param name="d">The constant offset D.</param> /// <returns>An array containing the three to zero real roots.</returns> public static double[] UnsafeCubicRootsD(double a, double b, double c, double d) { return CubicRootsD(b / a, c / a, d / a); } /// <summary> /// Finds the real roots of a third order polynomial f(x) = x^3 + A*x^2 + B*x + C. /// Based on the cardanos method https://de.wikipedia.org/wiki/Cardanische_Formeln. /// </summary> /// <param name="a">The quadratic coefficent A.</param> /// <param name="b">The linear coefficent B.</param> /// <param name="c">The constant offset C.</param> /// <returns>An array containing the three to one real roots.</returns> public static double[] CubicRootsD(double a, double b, double c) { double a3rd = a / 3; double p = b - a * a3rd; double q = 2 * a3rd * a3rd * a3rd - b * a3rd + c; double Disc = (q * q) / 4 + (p * p * p) / 27; if (Disc >= EPSILON) { // One real root double sqrtDisc = Sqrt(Disc); double u = Cbrt(-q * 0.5f + sqrtDisc); double v = Cbrt(-q * 0.5f - sqrtDisc); double[] solutions = new double[1]; solutions[0] = u + v - a3rd; return solutions; } else if (Abs(Disc) < EPSILON) { if (Abs(p) < EPSILON) { // One real root with multiplicity three. double[] solution = new double[1]; solution[0] = -a3rd; return solution; } else { // Two real roots, one of them is a double root double[] solutions = new double[2]; solutions[0] = 3 * q / p - a3rd; solutions[1] = -1.5f * q / p - a3rd; return solutions; } } else { // Three real, distinct roots double f = Sqrt(-4 * p / 3); double arccos = Acos(-q / 2 * Sqrt(-27 / (p * p * p))) / 3; double cos = Cos(arccos); double sin = Sin(arccos); double[] solutions = new double[3]; solutions[0] = f * cos - a3rd; solutions[1] = -f * (cos * COS_PI_3RD - sin * SIN_PI_3RD) - a3rd; solutions[2] = -f * (cos * COS_MINUS_PI_3RD - sin * SIN_MINUS_PI_3RD) - a3rd; return solutions; } } /// <summary> /// Finds a real root of a third order polynomial f(x) = x^3 + A*x^2 + B*x + C. /// </summary> /// <param name="a">The quadratic coefficent A.</param> /// <param name="b">The linear coefficent B.</param> /// <param name="c">The constant offset C.</param> /// <returns>A real root.</returns> public static double CubicRootD(double a, double b, double c) { double a3rd = a / 3; double p = b - a * a3rd; double q = 2 * a3rd * a3rd * a3rd - b * a3rd + c; double Disc = (q * q) / 4 + (p * p * p) / 27; if (Disc >= EPSILON) { double sqrtDisc = Sqrt(Disc); double u = Cbrt(-q * 0.5f + sqrtDisc); double v = Cbrt(-q * 0.5f - sqrtDisc); return u + v - a3rd; } else if (Abs(Disc) < EPSILON) { if (Abs(p) < EPSILON) { return -a3rd; } else { return 3 * q / p - a3rd; } } else { double arccos = Acos(-q / 2 * Sqrt(-27 / (p * p * p))) / 3; return Sqrt(-4 * p / 3) * Cos(arccos) - a3rd; } } /// <summary> /// Finds the real roots of a fourth order polynomial f(x) = A*x^4 + B*x^3 + C*x^2 + D*X + E. /// </summary> /// <param name="a">The quartic coefficient A.</param> /// <param name="b">The cubic coefficient B.</param> /// <param name="c">The quadratic coefficent C.</param> /// <param name="d">The linear coefficent D.</param> /// <param name="e">The constant offset E.</param> /// <returns>An array containing the four to zero real roots.</returns> public static double[] QuarticRootsD(double a, double b, double c, double d, double e) { if(a == 0) { return CubicRootsD(b, c, d, e); } else { return QuarticRootsD(b / a, c / a, d / a, e / a); } } /// <summary> /// Finds the real roots of a fourth order polynomial f(x) = A*x^4 + B*x^3 + C*x^2 + D*X + E, where A must NOT be zero. /// </summary> /// <param name="a">The quartic coefficient A.</param> /// <param name="b">The cubic coefficient B.</param> /// <param name="c">The quadratic coefficent C.</param> /// <param name="d">The linear coefficent D.</param> /// <param name="e">The constant offset E.</param> /// <returns>An array containing the four to zero real roots.</returns> public static double[] UnsafeQuarticRootsD(double a, double b, double c, double d, double e) { return QuarticRootsD(b / a, c / a, d / a, e / a); } /// <summary> /// Finds the real roots of a fourth order polynomial f(x) = x^4 + A*x^3 + B*x^2 + C*X + D. /// Based on an algorithm from http://mathworld.wolfram.com/QuarticEquation.html. /// </summary> /// <param name="a">The cubic coefficient A.</param> /// <param name="b">The quadratic coefficent B.</param> /// <param name="c">The linear coefficent C.</param> /// <param name="d">The constant offset D.</param> /// <returns>An array containing the four to zero real roots.</returns> public static double[] QuarticRootsD(double a, double b, double c, double d) { double y1 = CubicRootD(-b, c * a - 4 * d, 4 * b * d - c * c - a * a * d); double R = Sqrt(0.25 * a * a - b + y1); double D = 0, E = 0; int numRoots = 0; double[] tempRoots = new double[4]; if (Abs(R) < EPSILON) { double sqrt = Sqrt(y1 * y1 - 4 * d); D = 0.75 * a * a - 2 * b + 2 * sqrt; E = 0.75 * a * a - 2 * b - 2 * sqrt; if(Abs(D) < EPSILON || Abs(E) < EPSILON) { tempRoots[0] = -0.25 * a; numRoots = 1; } } else { D = 0.75 * a * a - R * R - 2 * b + (a * b - 2 * c - 0.25 * a * a * a) / R; E = 0.75 * a * a - R * R - 2 * b - (a * b - 2 * c - 0.25 * a * a * a) / R; if (Abs(D) < EPSILON) { tempRoots[0] = -0.25 * a + 0.5 * R; numRoots = 1; } if (Abs(E) < EPSILON) { tempRoots[numRoots] = -0.25 * a - 0.5 * R; numRoots++; } } if(D >= EPSILON) { D = Sqrt(D); tempRoots[0] = -0.25 * a + 0.5 * R + 0.5 * D; tempRoots[1] = -0.25 * a + 0.5 * R - 0.5 * D; numRoots += 2; } if (E >= EPSILON) { E = Sqrt(E); tempRoots[numRoots] = -0.25 * a - 0.5 * R + 0.5 * E; tempRoots[numRoots + 1] = -0.25 * a - 0.5 * R - 0.5 * E; numRoots += 2; } double[] roots = new double[numRoots]; System.Array.Copy(tempRoots, roots, numRoots); return roots; } } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using Adaptive.SimpleBinaryEncoding; namespace Adaptive.SimpleBinaryEncoding.Ir.Generated { public class TokenCodec { public const ushort TemplateId = (ushort)2; public const byte TemplateVersion = (byte)0; public const ushort BlockLength = (ushort)20; public const string SematicType = ""; private readonly TokenCodec _parentMessage; private DirectBuffer _buffer; private int _offset; private int _limit; private int _actingBlockLength; private int _actingVersion; public int Offset { get { return _offset; } } public TokenCodec() { _parentMessage = this; } public void WrapForEncode(DirectBuffer buffer, int offset) { _buffer = buffer; _offset = offset; _actingBlockLength = BlockLength; _actingVersion = TemplateVersion; Limit = offset + _actingBlockLength; } public void WrapForDecode(DirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { _buffer = buffer; _offset = offset; _actingBlockLength = actingBlockLength; _actingVersion = actingVersion; Limit = offset + _actingBlockLength; } public int Size { get { return _limit - _offset; } } public int Limit { get { return _limit; } set { _buffer.CheckLimit(_limit); _limit = value; } } public const int TokenOffsetSchemaId = 11; public static string TokenOffsetMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public const int TokenOffsetNullValue = -2147483648; public const int TokenOffsetMinValue = -2147483647; public const int TokenOffsetMaxValue = 2147483647; public int TokenOffset { get { return _buffer.Int32GetLittleEndian(_offset + 0); } set { _buffer.Int32PutLittleEndian(_offset + 0, value); } } public const int TokenSizeSchemaId = 12; public static string TokenSizeMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public const int TokenSizeNullValue = -2147483648; public const int TokenSizeMinValue = -2147483647; public const int TokenSizeMaxValue = 2147483647; public int TokenSize { get { return _buffer.Int32GetLittleEndian(_offset + 4); } set { _buffer.Int32PutLittleEndian(_offset + 4, value); } } public const int SchemaIdSchemaId = 13; public static string SchemaIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public const int SchemaIdNullValue = -2147483648; public const int SchemaIdMinValue = -2147483647; public const int SchemaIdMaxValue = 2147483647; public int SchemaId { get { return _buffer.Int32GetLittleEndian(_offset + 8); } set { _buffer.Int32PutLittleEndian(_offset + 8, value); } } public const int TokenVersionSchemaId = 14; public static string TokenVersionMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public const int TokenVersionNullValue = -2147483648; public const int TokenVersionMinValue = -2147483647; public const int TokenVersionMaxValue = 2147483647; public int TokenVersion { get { return _buffer.Int32GetLittleEndian(_offset + 12); } set { _buffer.Int32PutLittleEndian(_offset + 12, value); } } public const int SignalSchemaId = 15; public static string SignalMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public SignalCodec Signal { get { return (SignalCodec)_buffer.Uint8Get(_offset + 16); } set { _buffer.Uint8Put(_offset + 16, (byte)value); } } public const int PrimitiveTypeSchemaId = 16; public static string PrimitiveTypeMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public PrimitiveTypeCodec PrimitiveType { get { return (PrimitiveTypeCodec)_buffer.Uint8Get(_offset + 17); } set { _buffer.Uint8Put(_offset + 17, (byte)value); } } public const int ByteOrderSchemaId = 17; public static string ByteOrderMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public ByteOrderCodec ByteOrder { get { return (ByteOrderCodec)_buffer.Uint8Get(_offset + 18); } set { _buffer.Uint8Put(_offset + 18, (byte)value); } } public const int PresenceSchemaId = 18; public static string PresenceMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public PresenceCodec Presence { get { return (PresenceCodec)_buffer.Uint8Get(_offset + 19); } set { _buffer.Uint8Put(_offset + 19, (byte)value); } } public const int NameSchemaId = 19; public const string NameCharacterEncoding = "UTF-8"; public static string NameMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public int GetName(byte[] dst, int dstOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; _buffer.CheckLimit(limit + sizeOfLengthField); int dataLength = _buffer.Uint8Get(limit); int bytesCopied = Math.Min(length, dataLength); Limit = limit + sizeOfLengthField + dataLength; _buffer.GetBytes(limit + sizeOfLengthField, dst, dstOffset, bytesCopied); return bytesCopied; } public int SetName(byte[] src, int srcOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; Limit = limit + sizeOfLengthField + length; _buffer.Uint8Put(limit, (byte)length); _buffer.SetBytes(limit + sizeOfLengthField, src, srcOffset, length); return length; } public const int ConstValueSchemaId = 20; public const string ConstValueCharacterEncoding = "UTF-8"; public static string ConstValueMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public int GetConstValue(byte[] dst, int dstOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; _buffer.CheckLimit(limit + sizeOfLengthField); int dataLength = _buffer.Uint8Get(limit); int bytesCopied = Math.Min(length, dataLength); Limit = limit + sizeOfLengthField + dataLength; _buffer.GetBytes(limit + sizeOfLengthField, dst, dstOffset, bytesCopied); return bytesCopied; } public int SetConstValue(byte[] src, int srcOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; Limit = limit + sizeOfLengthField + length; _buffer.Uint8Put(limit, (byte)length); _buffer.SetBytes(limit + sizeOfLengthField, src, srcOffset, length); return length; } public const int MinValueSchemaId = 21; public const string MinValueCharacterEncoding = "UTF-8"; public static string MinValueMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public int GetMinValue(byte[] dst, int dstOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; _buffer.CheckLimit(limit + sizeOfLengthField); int dataLength = _buffer.Uint8Get(limit); int bytesCopied = Math.Min(length, dataLength); Limit = limit + sizeOfLengthField + dataLength; _buffer.GetBytes(limit + sizeOfLengthField, dst, dstOffset, bytesCopied); return bytesCopied; } public int SetMinValue(byte[] src, int srcOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; Limit = limit + sizeOfLengthField + length; _buffer.Uint8Put(limit, (byte)length); _buffer.SetBytes(limit + sizeOfLengthField, src, srcOffset, length); return length; } public const int MaxValueSchemaId = 22; public const string MaxValueCharacterEncoding = "UTF-8"; public static string MaxValueMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public int GetMaxValue(byte[] dst, int dstOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; _buffer.CheckLimit(limit + sizeOfLengthField); int dataLength = _buffer.Uint8Get(limit); int bytesCopied = Math.Min(length, dataLength); Limit = limit + sizeOfLengthField + dataLength; _buffer.GetBytes(limit + sizeOfLengthField, dst, dstOffset, bytesCopied); return bytesCopied; } public int SetMaxValue(byte[] src, int srcOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; Limit = limit + sizeOfLengthField + length; _buffer.Uint8Put(limit, (byte)length); _buffer.SetBytes(limit + sizeOfLengthField, src, srcOffset, length); return length; } public const int NullValueSchemaId = 23; public const string NullValueCharacterEncoding = "UTF-8"; public static string NullValueMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public int GetNullValue(byte[] dst, int dstOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; _buffer.CheckLimit(limit + sizeOfLengthField); int dataLength = _buffer.Uint8Get(limit); int bytesCopied = Math.Min(length, dataLength); Limit = limit + sizeOfLengthField + dataLength; _buffer.GetBytes(limit + sizeOfLengthField, dst, dstOffset, bytesCopied); return bytesCopied; } public int SetNullValue(byte[] src, int srcOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; Limit = limit + sizeOfLengthField + length; _buffer.Uint8Put(limit, (byte)length); _buffer.SetBytes(limit + sizeOfLengthField, src, srcOffset, length); return length; } public const int CharacterEncodingSchemaId = 24; public const string CharacterEncodingCharacterEncoding = "UTF-8"; public static string CharacterEncodingMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public int GetCharacterEncoding(byte[] dst, int dstOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; _buffer.CheckLimit(limit + sizeOfLengthField); int dataLength = _buffer.Uint8Get(limit); int bytesCopied = Math.Min(length, dataLength); Limit = limit + sizeOfLengthField + dataLength; _buffer.GetBytes(limit + sizeOfLengthField, dst, dstOffset, bytesCopied); return bytesCopied; } public int SetCharacterEncoding(byte[] src, int srcOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; Limit = limit + sizeOfLengthField + length; _buffer.Uint8Put(limit, (byte)length); _buffer.SetBytes(limit + sizeOfLengthField, src, srcOffset, length); return length; } public const int EpochSchemaId = 25; public const string EpochCharacterEncoding = "UTF-8"; public static string EpochMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public int GetEpoch(byte[] dst, int dstOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; _buffer.CheckLimit(limit + sizeOfLengthField); int dataLength = _buffer.Uint8Get(limit); int bytesCopied = Math.Min(length, dataLength); Limit = limit + sizeOfLengthField + dataLength; _buffer.GetBytes(limit + sizeOfLengthField, dst, dstOffset, bytesCopied); return bytesCopied; } public int SetEpoch(byte[] src, int srcOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; Limit = limit + sizeOfLengthField + length; _buffer.Uint8Put(limit, (byte)length); _buffer.SetBytes(limit + sizeOfLengthField, src, srcOffset, length); return length; } public const int TimeUnitSchemaId = 26; public const string TimeUnitCharacterEncoding = "UTF-8"; public static string TimeUnitMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public int GetTimeUnit(byte[] dst, int dstOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; _buffer.CheckLimit(limit + sizeOfLengthField); int dataLength = _buffer.Uint8Get(limit); int bytesCopied = Math.Min(length, dataLength); Limit = limit + sizeOfLengthField + dataLength; _buffer.GetBytes(limit + sizeOfLengthField, dst, dstOffset, bytesCopied); return bytesCopied; } public int SetTimeUnit(byte[] src, int srcOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; Limit = limit + sizeOfLengthField + length; _buffer.Uint8Put(limit, (byte)length); _buffer.SetBytes(limit + sizeOfLengthField, src, srcOffset, length); return length; } public const int SemanticTypeSchemaId = 27; public const string SemanticTypeCharacterEncoding = "UTF-8"; public static string SemanticTypeMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public int GetSemanticType(byte[] dst, int dstOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; _buffer.CheckLimit(limit + sizeOfLengthField); int dataLength = _buffer.Uint8Get(limit); int bytesCopied = Math.Min(length, dataLength); Limit = limit + sizeOfLengthField + dataLength; _buffer.GetBytes(limit + sizeOfLengthField, dst, dstOffset, bytesCopied); return bytesCopied; } public int SetSemanticType(byte[] src, int srcOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; Limit = limit + sizeOfLengthField + length; _buffer.Uint8Put(limit, (byte)length); _buffer.SetBytes(limit + sizeOfLengthField, src, srcOffset, length); return length; } } }
using System; using NUnit.Framework; using Whois.Parsers; namespace Whois.Parsing.Whois.Nic.Re.Re { [TestFixture] public class ReParsingTests : ParsingTests { private WhoisParser parser; [SetUp] public void SetUp() { SerilogConfig.Init(); parser = new WhoisParser(); } [Test] public void Test_found() { var sample = SampleReader.Read("whois.nic.re", "re", "found.txt"); var response = parser.Parse("whois.nic.re", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("generic/tld/Found05", response.TemplateName); Assert.AreEqual("nic.re", response.DomainName.ToString()); // Registrar Details Assert.AreEqual("AFNIC registry", response.Registrar.Name); Assert.AreEqual(new DateTime(2009, 03, 12, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(1995, 01, 01, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); // Registrant Details Assert.AreEqual("A1967-FRNIC", response.Registrant.RegistryId); Assert.AreEqual("AFNIC", response.Registrant.Name); // Registrant Address Assert.AreEqual(5, response.Registrant.Address.Count); Assert.AreEqual("immeuble international", response.Registrant.Address[0]); Assert.AreEqual("2, rue Stephenson", response.Registrant.Address[1]); Assert.AreEqual("Montigny-Le-Bretonneux", response.Registrant.Address[2]); Assert.AreEqual("78181 Saint Quentin en Yvelines", response.Registrant.Address[3]); Assert.AreEqual("FR", response.Registrant.Address[4]); // AdminContact Details Assert.AreEqual("NFC1-FRNIC", response.AdminContact.RegistryId); Assert.AreEqual("NIC France Contact", response.AdminContact.Name); Assert.AreEqual("+33 1 39 30 83 00", response.AdminContact.TelephoneNumber); Assert.AreEqual("hostmaster@nic.fr", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(6, response.AdminContact.Address.Count); Assert.AreEqual("AFNIC", response.AdminContact.Address[0]); Assert.AreEqual("immeuble international", response.AdminContact.Address[1]); Assert.AreEqual("2, rue Stephenson", response.AdminContact.Address[2]); Assert.AreEqual("Montigny le Bretonneux", response.AdminContact.Address[3]); Assert.AreEqual("78181 Saint Quentin en Yvelines Cedex", response.AdminContact.Address[4]); Assert.AreEqual("FR", response.AdminContact.Address[5]); // TechnicalContact Details Assert.AreEqual("NFC1-FRNIC", response.TechnicalContact.RegistryId); Assert.AreEqual("NIC France Contact", response.TechnicalContact.Name); Assert.AreEqual("+33 1 39 30 83 00", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("hostmaster@nic.fr", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(6, response.TechnicalContact.Address.Count); Assert.AreEqual("AFNIC", response.TechnicalContact.Address[0]); Assert.AreEqual("immeuble international", response.TechnicalContact.Address[1]); Assert.AreEqual("2, rue Stephenson", response.TechnicalContact.Address[2]); Assert.AreEqual("Montigny le Bretonneux", response.TechnicalContact.Address[3]); Assert.AreEqual("78181 Saint Quentin en Yvelines Cedex", response.TechnicalContact.Address[4]); Assert.AreEqual("FR", response.TechnicalContact.Address[5]); // ZoneContact Details Assert.AreEqual("NFC1-FRNIC", response.ZoneContact.RegistryId); Assert.AreEqual("NIC France Contact", response.ZoneContact.Name); Assert.AreEqual("+33 1 39 30 83 00", response.ZoneContact.TelephoneNumber); Assert.AreEqual("hostmaster@nic.fr", response.ZoneContact.Email); // ZoneContact Address Assert.AreEqual(6, response.ZoneContact.Address.Count); Assert.AreEqual("AFNIC", response.ZoneContact.Address[0]); Assert.AreEqual("immeuble international", response.ZoneContact.Address[1]); Assert.AreEqual("2, rue Stephenson", response.ZoneContact.Address[2]); Assert.AreEqual("Montigny le Bretonneux", response.ZoneContact.Address[3]); Assert.AreEqual("78181 Saint Quentin en Yvelines Cedex", response.ZoneContact.Address[4]); Assert.AreEqual("FR", response.ZoneContact.Address[5]); // Nameservers Assert.AreEqual(3, response.NameServers.Count); Assert.AreEqual("ns1.nic.fr", response.NameServers[0]); Assert.AreEqual("ns2.nic.fr", response.NameServers[1]); Assert.AreEqual("ns3.nic.fr", response.NameServers[2]); // Domain Status Assert.AreEqual(1, response.DomainStatus.Count); Assert.AreEqual("ACTIVE", response.DomainStatus[0]); Assert.AreEqual(30, response.FieldsParsed); } [Test] public void Test_throttled() { var sample = SampleReader.Read("whois.nic.re", "re", "throttled.txt"); var response = parser.Parse("whois.nic.re", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Throttled, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("generic/tld/Throttled02", response.TemplateName); Assert.AreEqual(1, response.FieldsParsed); } [Test] public void Test_not_found() { var sample = SampleReader.Read("whois.nic.re", "re", "not_found.txt"); var response = parser.Parse("whois.nic.re", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.NotFound, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("generic/tld/NotFound06", response.TemplateName); Assert.AreEqual(1, response.FieldsParsed); } [Test] public void Test_found_status_registered() { var sample = SampleReader.Read("whois.nic.re", "re", "found_status_registered.txt"); var response = parser.Parse("whois.nic.re", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("generic/tld/Found05", response.TemplateName); Assert.AreEqual("nic.re", response.DomainName.ToString()); // Registrar Details Assert.AreEqual("AFNIC registry", response.Registrar.Name); Assert.AreEqual(new DateTime(2016, 12, 31, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(1995, 01, 01, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2017, 12, 31, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("A1967-FRNIC", response.Registrant.RegistryId); Assert.AreEqual("AFNIC", response.Registrant.Name); // Registrant Address Assert.AreEqual(5, response.Registrant.Address.Count); Assert.AreEqual("immeuble international", response.Registrant.Address[0]); Assert.AreEqual("2, rue Stephenson", response.Registrant.Address[1]); Assert.AreEqual("Montigny-Le-Bretonneux", response.Registrant.Address[2]); Assert.AreEqual("78181 Saint Quentin en Yvelines", response.Registrant.Address[3]); Assert.AreEqual("FR", response.Registrant.Address[4]); // AdminContact Details Assert.AreEqual("NFC1-FRNIC", response.AdminContact.RegistryId); Assert.AreEqual("NIC France Contact", response.AdminContact.Name); Assert.AreEqual("+33 1 39 30 83 00", response.AdminContact.TelephoneNumber); Assert.AreEqual("hostmaster@nic.fr", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(6, response.AdminContact.Address.Count); Assert.AreEqual("AFNIC", response.AdminContact.Address[0]); Assert.AreEqual("immeuble international", response.AdminContact.Address[1]); Assert.AreEqual("2, rue Stephenson", response.AdminContact.Address[2]); Assert.AreEqual("Montigny le Bretonneux", response.AdminContact.Address[3]); Assert.AreEqual("78181 Saint Quentin en Yvelines Cedex", response.AdminContact.Address[4]); Assert.AreEqual("FR", response.AdminContact.Address[5]); // TechnicalContact Details Assert.AreEqual("NFC1-FRNIC", response.TechnicalContact.RegistryId); Assert.AreEqual("NIC France Contact", response.TechnicalContact.Name); Assert.AreEqual("+33 1 39 30 83 00", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("hostmaster@nic.fr", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(6, response.TechnicalContact.Address.Count); Assert.AreEqual("AFNIC", response.TechnicalContact.Address[0]); Assert.AreEqual("immeuble international", response.TechnicalContact.Address[1]); Assert.AreEqual("2, rue Stephenson", response.TechnicalContact.Address[2]); Assert.AreEqual("Montigny le Bretonneux", response.TechnicalContact.Address[3]); Assert.AreEqual("78181 Saint Quentin en Yvelines Cedex", response.TechnicalContact.Address[4]); Assert.AreEqual("FR", response.TechnicalContact.Address[5]); // ZoneContact Details Assert.AreEqual("NFC1-FRNIC", response.ZoneContact.RegistryId); Assert.AreEqual("NIC France Contact", response.ZoneContact.Name); Assert.AreEqual("+33 1 39 30 83 00", response.ZoneContact.TelephoneNumber); Assert.AreEqual("hostmaster@nic.fr", response.ZoneContact.Email); // ZoneContact Address Assert.AreEqual(6, response.ZoneContact.Address.Count); Assert.AreEqual("AFNIC", response.ZoneContact.Address[0]); Assert.AreEqual("immeuble international", response.ZoneContact.Address[1]); Assert.AreEqual("2, rue Stephenson", response.ZoneContact.Address[2]); Assert.AreEqual("Montigny le Bretonneux", response.ZoneContact.Address[3]); Assert.AreEqual("78181 Saint Quentin en Yvelines Cedex", response.ZoneContact.Address[4]); Assert.AreEqual("FR", response.ZoneContact.Address[5]); // Nameservers Assert.AreEqual(3, response.NameServers.Count); Assert.AreEqual("ns1.nic.fr", response.NameServers[0]); Assert.AreEqual("ns2.nic.fr", response.NameServers[1]); Assert.AreEqual("ns3.nic.fr", response.NameServers[2]); // Domain Status Assert.AreEqual(1, response.DomainStatus.Count); Assert.AreEqual("ACTIVE", response.DomainStatus[0]); Assert.AreEqual(31, response.FieldsParsed); } } }
// 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 Xunit; namespace System.Linq.Expressions.Tests { // Tests for features of the Expression class, rather than any derived types, // including how it acts with custom derived types. // // Unfortunately there is slightly different internal behaviour depending on whether // a derived Expression uses the new constructor, uses the old constructor, or uses // the new constructor after at least one use of the old constructor has been made, // due to static state being affected. For this reason some tests have to be done // in a particular order, with those for the old constructor coming after most of // the tests, and those affected by this being repeated after that. [TestCaseOrderer("System.Linq.Expressions.Tests.TestOrderer", "System.Linq.Expressions.Tests")] public class ExpressionTests { private static readonly Expression MarkerExtension = Expression.Constant(0); private class IncompleteExpressionOverride : Expression { public class Visitor : ExpressionVisitor { protected override Expression VisitExtension(Expression node) => MarkerExtension; } public IncompleteExpressionOverride() : base() { } public Expression VisitChildren() => VisitChildren(new Visitor()); } private class ClaimedReducibleOverride : IncompleteExpressionOverride { public override bool CanReduce => true; } private class ReducesToSame : ClaimedReducibleOverride { public override Expression Reduce() => this; } private class ReducesToNull : ClaimedReducibleOverride { public override Expression Reduce() => null; } private class ReducesToLongTyped : ClaimedReducibleOverride { private class ReducedToLongTyped : IncompleteExpressionOverride { public override Type Type => typeof(long); } public override Type Type => typeof(int); public override Expression Reduce() => new ReducedToLongTyped(); } private class Reduces : ClaimedReducibleOverride { public override Type Type => typeof(int); public override Expression Reduce() => new Reduces(); } private class ReducesFromStrangeNodeType : Expression { public override Type Type => typeof(int); public override ExpressionType NodeType => (ExpressionType)(-1); public override bool CanReduce => true; public override Expression Reduce() => Constant(3); } private class ObsoleteIncompleteExpressionOverride : Expression { #pragma warning disable 0618 // Testing obsolete behaviour. public ObsoleteIncompleteExpressionOverride(ExpressionType nodeType, Type type) : base(nodeType, type) { } #pragma warning restore 0618 } private class IrreducibleWithTypeAndNodeType : Expression { public override Type Type => typeof(void); public override ExpressionType NodeType => ExpressionType.Extension; } private class IrreduceibleWithTypeAndStrangeNodeType : Expression { public override Type Type => typeof(void); public override ExpressionType NodeType => (ExpressionType)(-1); } private class ExtensionNoToString : Expression { public override ExpressionType NodeType => ExpressionType.Extension; public override Type Type => typeof(int); public override bool CanReduce => false; } private class ExtensionToString : Expression { public override ExpressionType NodeType => ExpressionType.Extension; public override Type Type => typeof(int); public override bool CanReduce => false; public override string ToString() => "bar"; } public static IEnumerable<object[]> AllNodeTypesPlusSomeInvalid { get { foreach (ExpressionType et in Enum.GetValues(typeof(ExpressionType))) yield return new object[] { et }; yield return new object[] { (ExpressionType)(-1) }; yield return new object[] { (ExpressionType)int.MaxValue }; yield return new object[] { (ExpressionType)int.MinValue }; } } public static IEnumerable<object[]> SomeTypes => new[] { typeof(int), typeof(void), typeof(object), typeof(DateTime), typeof(string), typeof(ExpressionTests), typeof(ExpressionType) } .Select(type => new object[] { type }); [Fact] public void NodeTypeMustBeOverridden() { var exp = new IncompleteExpressionOverride(); Assert.Throws<InvalidOperationException>(() => exp.NodeType); } [Theory, TestOrder(1), MemberData(nameof(AllNodeTypesPlusSomeInvalid))] public void NodeTypeFromConstructor(ExpressionType nodeType) { Assert.Equal(nodeType, new ObsoleteIncompleteExpressionOverride(nodeType, typeof(int)).NodeType); } [Fact, TestOrder(2)] public void NodeTypeMustBeOverriddenAfterObsoleteConstructorUsed() { var exp = new IncompleteExpressionOverride(); Assert.Throws<InvalidOperationException>(() => exp.NodeType); } [Fact] public void TypeMustBeOverridden() { var exp = new IncompleteExpressionOverride(); Assert.Throws<InvalidOperationException>(() => exp.Type); } [Theory, TestOrder(1), MemberData(nameof(SomeTypes))] public void TypeFromConstructor(Type type) { Assert.Equal(type, new ObsoleteIncompleteExpressionOverride(ExpressionType.Constant, type).Type); } [Fact, TestOrder(1)] public void TypeMayBeNonNullOnObsoleteConstructedExpression() { // This is probably undesirable, but throwing here would be a breaking change. // Impact must be considered before prohibiting this. Assert.Null(new ObsoleteIncompleteExpressionOverride(ExpressionType.Add, null).Type); } [Fact, TestOrder(2)] public void TypeMustBeOverriddenCheckCorrectAfterObsoleteConstructorUsed() { var exp = new IncompleteExpressionOverride(); Assert.Throws<InvalidOperationException>(() => exp.Type); } [Fact] public void DefaultCannotReduce() { Assert.False(new IncompleteExpressionOverride().CanReduce); } [Fact] public void DefaultReducesToSame() { var exp = new IncompleteExpressionOverride(); Assert.Same(exp, exp.Reduce()); } [Fact] public void VisitChildrenThrowsAsNotReducible() { var exp = new IncompleteExpressionOverride(); AssertExtensions.Throws<ArgumentException>(null, () => exp.VisitChildren()); } [Fact] public void CanVisitChildrenIfReallyReduces() { var exp = new Reduces(); Assert.NotSame(exp, exp.VisitChildren()); } [Fact] public void VisitingCallsVisitExtension() { Assert.Same(MarkerExtension, new IncompleteExpressionOverride.Visitor().Visit(new IncompleteExpressionOverride())); } [Fact] public void ReduceAndCheckThrowsByDefault() { var exp = new IncompleteExpressionOverride(); AssertExtensions.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public void ReduceExtensionsThrowsByDefault() { var exp = new IncompleteExpressionOverride(); AssertExtensions.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public void IfClaimCanReduceMustReduce() { var exp = new ClaimedReducibleOverride(); AssertExtensions.Throws<ArgumentException>(null, () => exp.Reduce()); } [Fact] public void ReduceAndCheckThrowOnReduceToSame() { var exp = new ReducesToSame(); AssertExtensions.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public void ReduceAndCheckThrowOnReduceToNull() { var exp = new ReducesToNull(); AssertExtensions.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public void ReduceAndCheckThrowOnReducedTypeNotAssignable() { var exp = new ReducesToLongTyped(); AssertExtensions.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } #pragma warning disable 0169, 0414 // Accessed through reflection. private static int TestField; private const int TestConstant = 0; private static readonly int TestInitOnlyField = 0; #pragma warning restore 0169, 0414 private static int Unreadable { set { } } private static int Unwritable => 0; private class UnreadableIndexableClass { public int this[int index] { set { } } } private class UnwritableIndexableClass { public int this[int index] => 0; } [Fact] public void ConfirmCanRead() { var readableExpressions = new Expression[] { Expression.Constant(0), Expression.Add(Expression.Constant(0), Expression.Constant(0)), Expression.Default(typeof(int)), Expression.Property(Expression.Constant(new List<int>()), "Count"), Expression.ArrayIndex(Expression.Constant(Array.Empty<int>()), Expression.Constant(0)), Expression.Field(null, typeof(ExpressionTests), "TestField"), Expression.Field(null, typeof(ExpressionTests), "TestConstant"), Expression.Field(null, typeof(ExpressionTests), "TestInitOnlyField") }; Expression.Block(typeof(void), readableExpressions); } public static IEnumerable<Expression> UnreadableExpressions { get { yield return Expression.Property(null, typeof(ExpressionTests), "Unreadable"); yield return Expression.Property(Expression.Constant(new UnreadableIndexableClass()), "Item", Expression.Constant(0)); } } public static IEnumerable<object[]> UnreadableExpressionData => UnreadableExpressions.Concat(new Expression[1]).Select(exp => new object[] { exp }); public static IEnumerable<Expression> WritableExpressions { get { yield return Expression.Property(null, typeof(ExpressionTests), "Unreadable"); yield return Expression.Property(Expression.Constant(new UnreadableIndexableClass()), "Item", Expression.Constant(0)); yield return Expression.Field(null, typeof(ExpressionTests), "TestField"); yield return Expression.Parameter(typeof(int)); } } public static IEnumerable<Expression> UnwritableExpressions { get { yield return Expression.Property(null, typeof(ExpressionTests), "Unwritable"); yield return Expression.Property(Expression.Constant(new UnwritableIndexableClass()), "Item", Expression.Constant(0)); yield return Expression.Field(null, typeof(ExpressionTests), "TestConstant"); yield return Expression.Field(null, typeof(ExpressionTests), "TestInitOnlyField"); yield return Expression.Call(Expression.Default(typeof(ExpressionTests)), "ConfirmCannotReadSequence", new Type[0]); yield return null; } } public static IEnumerable<object[]> UnwritableExpressionData => UnwritableExpressions.Select(exp => new object[] { exp }); public static IEnumerable<object[]> WritableExpressionData => WritableExpressions.Select(exp => new object[] { exp }); [Theory, MemberData(nameof(UnreadableExpressionData))] public void ConfirmCannotRead(Expression unreadableExpression) { if (unreadableExpression == null) AssertExtensions.Throws<ArgumentNullException>("expression", () => Expression.Increment(unreadableExpression)); else AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Increment(unreadableExpression)); } [Fact] public void ConfirmCannotReadSequence() { AssertExtensions.Throws<ArgumentException>("expressions[0]", () => Expression.Block(typeof(void), UnreadableExpressions)); } [Theory, MemberData(nameof(UnwritableExpressionData))] public void ConfirmCannotWrite(Expression unwritableExpression) { if (unwritableExpression == null) AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.Assign(unwritableExpression, Expression.Constant(0))); else AssertExtensions.Throws<ArgumentException>("left", () => Expression.Assign(unwritableExpression, Expression.Constant(0))); } [Theory, MemberData(nameof(WritableExpressionData))] public void ConfirmCanWrite(Expression writableExpression) { Expression.Assign(writableExpression, Expression.Default(writableExpression.Type)); } [Theory, ClassData(typeof(CompilationTypes))] public void CompileIrreduciebleExtension(bool useInterpreter) { Expression<Action> exp = Expression.Lambda<Action>(new IrreducibleWithTypeAndNodeType()); AssertExtensions.Throws<ArgumentException>(null, () => exp.Compile(useInterpreter)); } [Theory, ClassData(typeof(CompilationTypes))] public void CompileIrreduciebleStrangeNodeTypeExtension(bool useInterpreter) { Expression<Action> exp = Expression.Lambda<Action>(new IrreduceibleWithTypeAndStrangeNodeType()); AssertExtensions.Throws<ArgumentException>(null, () => exp.Compile(useInterpreter)); } [Theory, ClassData(typeof(CompilationTypes))] public void CompileReducibleStrangeNodeTypeExtension(bool useInterpreter) { Expression<Func<int>> exp = Expression.Lambda<Func<int>>(new ReducesFromStrangeNodeType()); Assert.Equal(3, exp.Compile(useInterpreter)()); } [Fact] public void ToStringTest() { var e1 = new ExtensionNoToString(); Assert.Equal($"[{typeof(ExtensionNoToString).FullName}]", e1.ToString()); BinaryExpression e2 = Expression.Add(Expression.Constant(1), new ExtensionToString()); Assert.Equal($"(1 + bar)", e2.ToString()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Razor.TagHelpers; using Moq; using Xunit; namespace Microsoft.AspNetCore.Mvc.TagHelpers.Test { public class EnvironmentTagHelperTest { [Theory] [InlineData("Development", "Development")] [InlineData("development", "Development")] [InlineData("DEVELOPMENT", "Development")] [InlineData(" development", "Development")] [InlineData("development ", "Development")] [InlineData(" development ", "Development")] [InlineData("Development,Production", "Development")] [InlineData("Production,Development", "Development")] [InlineData("Development , Production", "Development")] [InlineData(" Development,Production ", "Development")] [InlineData("Development , Production", "Development")] [InlineData("Development\t,Production", "Development")] [InlineData("Development,\tProduction", "Development")] [InlineData(" Development,Production ", "Development")] [InlineData("Development,Staging,Production", "Development")] [InlineData("Staging,Development,Production", "Development")] [InlineData("Staging,Production,Development", "Development")] [InlineData("Test", "Test")] [InlineData("Test,Staging", "Test")] public void ShowsContentWhenCurrentEnvironmentIsSpecified(string namesAttribute, string environmentName) { ShouldShowContent(namesAttribute, environmentName); } [Theory] [InlineData("", "Development")] [InlineData(null, "Development")] [InlineData(" ", "Development")] [InlineData(", ", "Development")] [InlineData(" , ", "Development")] [InlineData("\t,\t", "Development")] [InlineData(",", "Development")] [InlineData(",,", "Development")] [InlineData(",,,", "Development")] [InlineData(",,, ", "Development")] public void ShowsContentWhenNoEnvironmentIsSpecified(string namesAttribute, string environmentName) { ShouldShowContent(namesAttribute, environmentName); } [Theory] [InlineData("Development", null)] [InlineData("Development", "")] [InlineData("Development", " ")] [InlineData("Development", " ")] [InlineData("Development", "\t")] [InlineData("Test", null)] public void ShowsContentWhenCurrentEnvironmentIsNotSet(string namesAttribute, string environmentName) { ShouldShowContent(namesAttribute, environmentName); } [Theory] [InlineData("", "", "")] [InlineData("", null, "Test")] [InlineData("Development", "", "")] [InlineData("", "Development, Test", "")] [InlineData(null, "development, TEST", "Test")] [InlineData("Development", "", "Test")] [InlineData("Development", "Test, Development", "")] [InlineData("Test", "DEVELOPMENT", null)] [InlineData("Development", "Test", "")] [InlineData("Development", null, "Test")] [InlineData("Development", "Test", "Test")] [InlineData("Test", "Development", "Test")] public void ShouldShowContent_IncludeExcludeSpecified(string namesAttribute, string includeAttribute, string excludeAttribute) { // Arrange var content = "content"; var context = MakeTagHelperContext( attributes: new TagHelperAttributeList { { "names", namesAttribute }, { "include", includeAttribute }, { "exclude", excludeAttribute }, }); var output = MakeTagHelperOutput("environment", childContent: content); var hostingEnvironment = new Mock<IWebHostEnvironment>(); hostingEnvironment.SetupProperty(h => h.EnvironmentName, "Development"); // Act var helper = new EnvironmentTagHelper(hostingEnvironment.Object) { Names = namesAttribute, Include = includeAttribute, Exclude = excludeAttribute, }; helper.Process(context, output); // Assert Assert.Null(output.TagName); Assert.False(output.IsContentModified); } [Theory] [InlineData(null, "", "Development")] [InlineData("", "Development", "development")] [InlineData("", "Test", "Development, test")] [InlineData("Development", "", "Development")] [InlineData("Test", "", "Development")] [InlineData("Development", "Development", "DEVELOPMENT, TEST")] [InlineData("Development", "Test", "Development")] [InlineData("Test", "Development", "Development")] [InlineData("Test", "Test", "Development")] [InlineData("", "Test", "Test")] [InlineData("Test", null, "Test")] [InlineData("Test", "Test", "Test")] [InlineData("", "Test", null)] [InlineData("Test", "", "")] [InlineData("Test", "Test", null)] public void DoesNotShowContent_IncludeExcludeSpecified(string namesAttribute, string includeAttribute, string excludeAttribute) { // Arrange var content = "content"; var context = MakeTagHelperContext( attributes: new TagHelperAttributeList { { "names", namesAttribute }, { "include", includeAttribute }, { "exclude", excludeAttribute }, }); var output = MakeTagHelperOutput("environment", childContent: content); var hostingEnvironment = new Mock<IWebHostEnvironment>(); hostingEnvironment.SetupProperty(h => h.EnvironmentName, "Development"); // Act var helper = new EnvironmentTagHelper(hostingEnvironment.Object) { Names = namesAttribute, Include = includeAttribute, Exclude = excludeAttribute, }; helper.Process(context, output); // Assert Assert.Null(output.TagName); Assert.Empty(output.PreContent.GetContent()); Assert.True(output.Content.GetContent().Length == 0); Assert.Empty(output.PostContent.GetContent()); Assert.True(output.IsContentModified); } [Theory] [InlineData("NotDevelopment", "Development")] [InlineData("NOTDEVELOPMENT", "Development")] [InlineData("NotDevelopment,AlsoNotDevelopment", "Development")] [InlineData("Doesn'tMatchAtAll", "Development")] [InlineData("Development and a space", "Development")] [InlineData("Development and a space,SomethingElse", "Development")] public void DoesNotShowContentWhenCurrentEnvironmentIsNotSpecified( string namesAttribute, string environmentName) { // Arrange var content = "content"; var context = MakeTagHelperContext(attributes: new TagHelperAttributeList { { "names", namesAttribute } }); var output = MakeTagHelperOutput("environment", childContent: content); var hostingEnvironment = new Mock<IWebHostEnvironment>(); hostingEnvironment.SetupProperty(h => h.EnvironmentName, environmentName); // Act var helper = new EnvironmentTagHelper(hostingEnvironment.Object) { Names = namesAttribute }; helper.Process(context, output); // Assert Assert.Null(output.TagName); Assert.Empty(output.PreContent.GetContent()); Assert.True(output.Content.GetContent().Length == 0); Assert.Empty(output.PostContent.GetContent()); Assert.True(output.IsContentModified); } private void ShouldShowContent(string namesAttribute, string environmentName) { // Arrange var content = "content"; var context = MakeTagHelperContext( attributes: new TagHelperAttributeList { { "names", namesAttribute } }); var output = MakeTagHelperOutput("environment", childContent: content); var hostingEnvironment = new Mock<IWebHostEnvironment>(); hostingEnvironment.SetupProperty(h => h.EnvironmentName, environmentName); // Act var helper = new EnvironmentTagHelper(hostingEnvironment.Object) { Names = namesAttribute }; helper.Process(context, output); // Assert Assert.Null(output.TagName); Assert.False(output.IsContentModified); } private TagHelperContext MakeTagHelperContext(TagHelperAttributeList attributes = null) { attributes = attributes ?? new TagHelperAttributeList(); return new TagHelperContext( tagName: "env", allAttributes: attributes, items: new Dictionary<object, object>(), uniqueId: Guid.NewGuid().ToString("N")); } private TagHelperOutput MakeTagHelperOutput( string tagName, TagHelperAttributeList attributes = null, string childContent = null) { attributes = attributes ?? new TagHelperAttributeList(); return new TagHelperOutput( tagName, attributes, getChildContentAsync: (useCachedResult, encoder) => { var tagHelperContent = new DefaultTagHelperContent(); tagHelperContent.SetContent(childContent); return Task.FromResult<TagHelperContent>(tagHelperContent); }); } } }
using System.Collections.Generic; using UIKit; using CoreGraphics; using Foundation; namespace Xamarin.Utilities.DialogElements { public class Section : IEnumerable<Element> { object header, footer; private readonly List<Element> _elements = new List<Element> (); public RootElement Root { get; internal set; } // X corresponds to the alignment, Y to the height of the password public CGSize EntryAlignment; public Section() { } public Section(UIView header, UIView footer = null) { HeaderView = header; FooterView = footer; } public Section(string header, string footer = null) { Header = header; Footer = footer; } /// <summary> /// The section header, as a string /// </summary> public string Header { get { return header as string; } set { header = value; } } /// <summary> /// The section footer, as a string. /// </summary> public string Footer { get { return footer as string; } set { footer = value; } } /// <summary> /// The section's header view. /// </summary> public UIView HeaderView { get { return header as UIView; } set { header = value; } } /// <summary> /// The section's footer view. /// </summary> public UIView FooterView { get { return footer as UIView; } set { footer = value; } } /// <summary> /// Adds a new child Element to the Section /// </summary> /// <param name="element"> /// An element to add to the section. /// </param> public void Add (Element element) { if (element == null) return; _elements.Add (element); element.Section = this; if (Root != null) InsertVisual (_elements.Count-1, UITableViewRowAnimation.None, 1); } public void Add(IEnumerable<Element> elements) { AddAll(elements); } /// <summary> /// Add version that can be used with LINQ /// </summary> /// <param name="elements"> /// An enumerable list that can be produced by something like: /// from x in ... select (Element) new MyElement (...) /// </param> public int AddAll(IEnumerable<Element> elements) { int count = 0; foreach (var e in elements){ Add (e); count++; } return count; } /// <summary> /// Inserts a series of elements into the Section using the specified animation /// </summary> /// <param name="idx"> /// The index where the elements are inserted /// </param> /// <param name="anim"> /// The animation to use /// </param> /// <param name="newElements"> /// A series of elements. /// </param> public void Insert (int idx, UITableViewRowAnimation anim, params Element [] newElements) { if (newElements == null) return; int pos = idx; foreach (var e in newElements) { _elements.Insert (pos++, e); e.Section = this; } if (Root != null && Root.TableView != null) { if (anim == UITableViewRowAnimation.None) Root.TableView.ReloadData (); else InsertVisual (idx, anim, newElements.Length); } } public int Insert (int idx, UITableViewRowAnimation anim, IEnumerable<Element> newElements) { if (newElements == null) return 0; int pos = idx; int count = 0; foreach (var e in newElements) { _elements.Insert (pos++, e); e.Section = this; count++; } if (Root != null && Root.TableView != null) { if (anim == UITableViewRowAnimation.None) Root.TableView.ReloadData (); else InsertVisual (idx, anim, pos-idx); } return count; } void InsertVisual (int idx, UITableViewRowAnimation anim, int count) { if (Root == null || Root.TableView == null) return; int sidx = Root.IndexOf (this); var paths = new NSIndexPath [count]; for (int i = 0; i < count; i++) paths [i] = NSIndexPath.FromRowSection (idx+i, sidx); Root.TableView.InsertRows (paths, anim); } public void Insert (int index, params Element [] newElements) { Insert (index, UITableViewRowAnimation.None, newElements); } public void Remove (Element e, UITableViewRowAnimation animation = UITableViewRowAnimation.Fade) { if (e == null) return; for (int i = _elements.Count; i > 0;) { i--; if (_elements [i] == e) { RemoveRange (i, 1, animation); e.Section = null; return; } } } public void Remove (int idx) { RemoveRange (idx, 1); } /// <summary> /// Remove a range of elements from the section with the given animation /// </summary> /// <param name="start"> /// Starting position /// </param> /// <param name="count"> /// Number of elements to remove form the section /// </param> /// <param name="anim"> /// The animation to use while removing the elements /// </param> public void RemoveRange (int start, int count, UITableViewRowAnimation anim = UITableViewRowAnimation.Fade) { if (start < 0 || start >= _elements.Count) return; if (count == 0) return; if (start+count > _elements.Count) count = _elements.Count-start; _elements.RemoveRange (start, count); if (Root != null && Root.TableView != null) { // int sidx = Root.IndexOf(this); // var paths = new NSIndexPath [count]; // for (int i = 0; i < count; i++) // paths[i] = NSIndexPath.FromRowSection(start + i, sidx); // Root.TableView.DeleteRows(paths, anim); Root.TableView.ReloadData(); } } public int Count { get { return _elements.Count; } } public IEnumerator<Element> GetEnumerator() { return _elements.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } public Element this [int idx] { get { return _elements[idx]; } } public void Clear () { foreach (var e in _elements) e.Section = null; _elements.Clear(); if (Root != null && Root.TableView != null) Root.TableView.ReloadData (); } public void Reset(IEnumerable<Element> elements, UITableViewRowAnimation animation = UITableViewRowAnimation.Fade) { _elements.Clear(); _elements.AddRange(elements); foreach (var e in _elements) e.Section = this; if (Root != null && Root.TableView != null) Root.TableView.ReloadData(); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using JabbR.Commands; using JabbR.ContentProviders.Core; using JabbR.Infrastructure; using JabbR.Models; using JabbR.Services; using JabbR.ViewModels; using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR.Hubs; using Newtonsoft.Json; namespace JabbR { [Authorize] public class Chat : Hub, INotificationService { private static readonly TimeSpan _disconnectThreshold = TimeSpan.FromSeconds(10); private readonly IJabbrRepository _repository; private readonly IChatService _service; private readonly ICache _cache; private readonly ContentProviderProcessor _resourceProcessor; public Chat(ContentProviderProcessor resourceProcessor, IChatService service, IJabbrRepository repository, ICache cache) { _resourceProcessor = resourceProcessor; _service = service; _repository = repository; _cache = cache; } private string UserAgent { get { if (Context.Headers != null) { return Context.Headers["User-Agent"]; } return null; } } private bool OutOfSync { get { string version = Context.QueryString["version"]; if (String.IsNullOrEmpty(version)) { return true; } return new Version(version) != Constants.JabbRVersion; } } public override Task OnConnected() { CheckStatus(); return base.OnConnected(); } public void Join() { Join(reconnecting: false); } public void Join(bool reconnecting) { // Get the client state var userId = Context.User.Identity.Name; // Try to get the user from the client state ChatUser user = _repository.GetUserById(userId); if (!reconnecting) { // Update some user values _service.UpdateActivity(user, Context.ConnectionId, UserAgent); _repository.CommitChanges(); } ClientState clientState = GetClientState(); OnUserInitialize(clientState, user, reconnecting); } private void CheckStatus() { if (OutOfSync) { Clients.Caller.outOfSync(); } } private void OnUserInitialize(ClientState clientState, ChatUser user, bool reconnecting) { // Update the active room on the client (only if it's still a valid room) if (user.Rooms.Any(room => room.Name.Equals(clientState.ActiveRoom, StringComparison.OrdinalIgnoreCase))) { // Update the active room on the client (only if it's still a valid room) Clients.Caller.activeRoom = clientState.ActiveRoom; } LogOn(user, Context.ConnectionId, reconnecting); } public bool Send(string content, string roomName) { var message = new ClientMessage { Content = content, Id = Guid.NewGuid().ToString("d"), Room = roomName }; return Send(message); } public bool Send(ClientMessage message) { CheckStatus(); // See if this is a valid command (starts with /) if (TryHandleCommand(message.Content, message.Room)) { return true; } var userId = Context.User.Identity.Name; ChatUser user = _repository.VerifyUserId(userId); ChatRoom room = _repository.VerifyUserRoom(_cache, user, message.Room); // REVIEW: Is it better to use _repository.VerifyRoom(message.Room, mustBeOpen: false) // here? if (room.Closed) { throw new InvalidOperationException(String.Format("You cannot post messages to '{0}'. The room is closed.", message.Room)); } // Update activity *after* ensuring the user, this forces them to be active UpdateActivity(user, room); ChatMessage chatMessage = _service.AddMessage(user, room, message.Id, message.Content); var messageViewModel = new MessageViewModel(chatMessage); Clients.Group(room.Name).addMessage(messageViewModel, room.Name); _repository.CommitChanges(); string clientMessageId = chatMessage.Id; // Update the id on the message chatMessage.Id = Guid.NewGuid().ToString("d"); _repository.CommitChanges(); var urls = UrlExtractor.ExtractUrls(chatMessage.Content); if (urls.Count > 0) { _resourceProcessor.ProcessUrls(urls, Clients, room.Name, clientMessageId, chatMessage.Id); } return true; } public UserViewModel GetUserInfo() { var userId = Context.User.Identity.Name; ChatUser user = _repository.VerifyUserId(userId); return new UserViewModel(user); } public override Task OnReconnected() { CheckStatus(); var userId = Context.User.Identity.Name; ChatUser user = _repository.VerifyUserId(userId); // Make sure this client is being tracked _service.AddClient(user, Context.ConnectionId, UserAgent); var currentStatus = (UserStatus)user.Status; if (currentStatus == UserStatus.Offline) { // Mark the user as inactive user.Status = (int)UserStatus.Inactive; _repository.CommitChanges(); // If the user was offline that means they are not in the user list so we need to tell // everyone the user is really in the room var userViewModel = new UserViewModel(user); foreach (var room in user.Rooms) { var isOwner = user.OwnedRooms.Contains(room); // Tell the people in this room that you've joined Clients.Group(room.Name).addUser(userViewModel, room.Name, isOwner); // Add the caller to the group so they receive messages Groups.Add(Context.ConnectionId, room.Name); } } return base.OnReconnected(); } public override Task OnDisconnected() { DisconnectClient(Context.ConnectionId); return base.OnDisconnected(); } public object GetCommands() { return CommandManager.GetCommandsMetaData(); } public object GetShortcuts() { return new[] { new { Name = "Tab or Shift + Tab", Category = "shortcut", Description = "Go to the next open room tab or Go to the previous open room tab." }, new { Name = "Alt + L", Category = "shortcut", Description = "Go to the Lobby."}, new { Name = "Alt + Number", Category = "shortcut", Description = "Go to specific Tab."} }; } public IEnumerable<LobbyRoomViewModel> GetRooms() { string userId = Context.User.Identity.Name; ChatUser user = _repository.VerifyUserId(userId); var rooms = _repository.GetAllowedRooms(user).Select(r => new LobbyRoomViewModel { Name = r.Name, Count = r.Users.Count(u => u.Status != (int)UserStatus.Offline), Private = r.Private, Closed = r.Closed }).ToList(); return rooms; } public IEnumerable<MessageViewModel> GetPreviousMessages(string messageId) { var previousMessages = (from m in _repository.GetPreviousMessages(messageId) orderby m.When descending select m).Take(100); return previousMessages.AsEnumerable() .Reverse() .Select(m => new MessageViewModel(m)); } public RoomViewModel GetRoomInfo(string roomName) { if (String.IsNullOrEmpty(roomName)) { return null; } string userId = Context.User.Identity.Name; ChatUser user = _repository.VerifyUserId(userId); ChatRoom room = _repository.GetRoomByName(roomName); if (room == null || (room.Private && !user.AllowedRooms.Contains(room))) { return null; } var recentMessages = (from m in _repository.GetMessagesByRoom(room) orderby m.When descending select m).Take(30).ToList(); // Reverse them since we want to get them in chronological order recentMessages.Reverse(); // Get online users through the repository IEnumerable<ChatUser> onlineUsers = _repository.GetOnlineUsers(room).ToList(); return new RoomViewModel { Name = room.Name, Users = from u in onlineUsers select new UserViewModel(u), Owners = from u in room.Owners.Online() select u.Name, RecentMessages = recentMessages.Select(m => new MessageViewModel(m)), Topic = room.Topic ?? "", Welcome = room.Welcome ?? "", Closed = room.Closed }; } public void Typing(string roomName) { string userId = Context.User.Identity.Name; ChatUser user = _repository.GetUserById(userId); ChatRoom room = _repository.VerifyUserRoom(_cache, user, roomName); UpdateActivity(user, room); var userViewModel = new UserViewModel(user); Clients.Group(room.Name).setTyping(userViewModel, room.Name); } public void UpdateActivity() { CheckStatus(); string userId = Context.User.Identity.Name; ChatUser user = _repository.GetUserById(userId); foreach (var room in user.Rooms) { UpdateActivity(user, room); } } private void LogOn(ChatUser user, string clientId, bool reconnecting) { if (!reconnecting) { // Update the client state Clients.Caller.id = user.Id; Clients.Caller.name = user.Name; Clients.Caller.hash = user.Hash; } var rooms = new List<RoomViewModel>(); var userViewModel = new UserViewModel(user); var ownedRooms = user.OwnedRooms.Select(r => r.Key); foreach (var room in user.Rooms) { var isOwner = ownedRooms.Contains(room.Key); // Tell the people in this room that you've joined Clients.Group(room.Name).addUser(userViewModel, room.Name, isOwner); // Add the caller to the group so they receive messages Groups.Add(clientId, room.Name); if (!reconnecting) { // Add to the list of room names rooms.Add(new RoomViewModel { Name = room.Name, Private = room.Private, Closed = room.Closed }); } } if (!reconnecting) { // Initialize the chat with the rooms the user is in Clients.Caller.logOn(rooms); } } private void UpdateActivity(ChatUser user, ChatRoom room) { UpdateActivity(user); OnUpdateActivity(user, room); } private void UpdateActivity(ChatUser user) { _service.UpdateActivity(user, Context.ConnectionId, UserAgent); _repository.CommitChanges(); } private bool TryHandleCommand(string command, string room) { string clientId = Context.ConnectionId; string userId = Context.User.Identity.Name; var commandManager = new CommandManager(clientId, UserAgent, userId, room, _service, _repository, _cache, this); return commandManager.TryHandleCommand(command); } private void DisconnectClient(string clientId) { string userId = _service.DisconnectClient(clientId); if (String.IsNullOrEmpty(userId)) { return; } // To avoid the leave/join that happens when a user refreshes the page // we sleep for a second before we check the status. Thread.Sleep(_disconnectThreshold); // Query for the user to get the updated status ChatUser user = _repository.GetUserById(userId); // There's no associated user for this client id if (user == null) { return; } _repository.Reload(user); // The user will be marked as offline if all clients leave if (user.Status == (int)UserStatus.Offline) { foreach (var room in user.Rooms) { var userViewModel = new UserViewModel(user); Clients.OthersInGroup(room.Name).leave(userViewModel, room.Name); } } } private void OnUpdateActivity(ChatUser user, ChatRoom room) { var userViewModel = new UserViewModel(user); Clients.Group(room.Name).updateActivity(userViewModel, room.Name); } private void LeaveRoom(ChatUser user, ChatRoom room) { var userViewModel = new UserViewModel(user); Clients.Group(room.Name).leave(userViewModel, room.Name); foreach (var client in user.ConnectedClients) { Groups.Remove(client.Id, room.Name); } OnRoomChanged(room); } void INotificationService.LogOn(ChatUser user, string clientId) { LogOn(user, clientId, reconnecting: true); } void INotificationService.ChangePassword() { Clients.Caller.changePassword(); } void INotificationService.SetPassword() { Clients.Caller.setPassword(); } void INotificationService.KickUser(ChatUser targetUser, ChatRoom room) { foreach (var client in targetUser.ConnectedClients) { // Kick the user from this room Clients.Client(client.Id).kick(room.Name); // Remove the user from this the room group so he doesn't get the leave message Groups.Remove(client.Id, room.Name); } // Tell the room the user left LeaveRoom(targetUser, room); } void INotificationService.OnUserCreated(ChatUser user) { // Set some client state Clients.Caller.name = user.Name; Clients.Caller.id = user.Id; Clients.Caller.hash = user.Hash; // Tell the client a user was created Clients.Caller.userCreated(); } void INotificationService.JoinRoom(ChatUser user, ChatRoom room) { var userViewModel = new UserViewModel(user); var roomViewModel = new RoomViewModel { Name = room.Name, Private = room.Private, Welcome = room.Welcome ?? "", Closed = room.Closed }; var isOwner = user.OwnedRooms.Contains(room); // Tell all clients to join this room foreach (var client in user.ConnectedClients) { Clients.Client(client.Id).joinRoom(roomViewModel); } // Tell the people in this room that you've joined Clients.Group(room.Name).addUser(userViewModel, room.Name, isOwner); // Notify users of the room count change OnRoomChanged(room); foreach (var client in user.ConnectedClients) { Groups.Add(client.Id, room.Name); } } void INotificationService.AllowUser(ChatUser targetUser, ChatRoom targetRoom) { foreach (var client in targetUser.ConnectedClients) { // Tell this client it's an owner Clients.Client(client.Id).allowUser(targetRoom.Name); } // Tell the calling client the granting permission into the room was successful Clients.Caller.userAllowed(targetUser.Name, targetRoom.Name); } void INotificationService.UnallowUser(ChatUser targetUser, ChatRoom targetRoom) { // Kick the user from the room when they are unallowed ((INotificationService)this).KickUser(targetUser, targetRoom); foreach (var client in targetUser.ConnectedClients) { // Tell this client it's an owner Clients.Client(client.Id).unallowUser(targetRoom.Name); } // Tell the calling client the granting permission into the room was successful Clients.Caller.userUnallowed(targetUser.Name, targetRoom.Name); } void INotificationService.AddOwner(ChatUser targetUser, ChatRoom targetRoom) { foreach (var client in targetUser.ConnectedClients) { // Tell this client it's an owner Clients.Client(client.Id).makeOwner(targetRoom.Name); } var userViewModel = new UserViewModel(targetUser); // If the target user is in the target room. // Tell everyone in the target room that a new owner was added if (_repository.IsUserInRoom(_cache, targetUser, targetRoom)) { Clients.Group(targetRoom.Name).addOwner(userViewModel, targetRoom.Name); } // Tell the calling client the granting of ownership was successful Clients.Caller.ownerMade(targetUser.Name, targetRoom.Name); } void INotificationService.RemoveOwner(ChatUser targetUser, ChatRoom targetRoom) { foreach (var client in targetUser.ConnectedClients) { // Tell this client it's no longer an owner Clients.Client(client.Id).demoteOwner(targetRoom.Name); } var userViewModel = new UserViewModel(targetUser); // If the target user is in the target room. // Tell everyone in the target room that the owner was removed if (_repository.IsUserInRoom(_cache, targetUser, targetRoom)) { Clients.Group(targetRoom.Name).removeOwner(userViewModel, targetRoom.Name); } // Tell the calling client the removal of ownership was successful Clients.Caller.ownerRemoved(targetUser.Name, targetRoom.Name); } void INotificationService.ChangeGravatar(ChatUser user) { Clients.Caller.hash = user.Hash; // Update the calling client foreach (var client in user.ConnectedClients) { Clients.Client(client.Id).gravatarChanged(); } // Create the view model var userViewModel = new UserViewModel(user); // Tell all users in rooms to change the gravatar foreach (var room in user.Rooms) { Clients.Group(room.Name).changeGravatar(userViewModel, room.Name); } } void INotificationService.OnSelfMessage(ChatRoom room, ChatUser user, string content) { Clients.Group(room.Name).sendMeMessage(user.Name, content, room.Name); } void INotificationService.SendPrivateMessage(ChatUser fromUser, ChatUser toUser, string messageText) { // Send a message to the sender and the sendee foreach (var client in fromUser.ConnectedClients) { Clients.Client(client.Id).sendPrivateMessage(fromUser.Name, toUser.Name, messageText); } foreach (var client in toUser.ConnectedClients) { Clients.Client(client.Id).sendPrivateMessage(fromUser.Name, toUser.Name, messageText); } } void INotificationService.PostNotification(ChatRoom room, ChatUser user, string message) { foreach (var client in user.ConnectedClients) { Clients.Client(client.Id).postNotification(message, room.Name); } } void INotificationService.ListRooms(ChatUser user) { string userId = Context.User.Identity.Name; var userModel = new UserViewModel(user); Clients.Caller.showUsersRoomList(userModel, user.Rooms.Allowed(userId).Select(r => r.Name)); } void INotificationService.ListUsers() { var users = _repository.Users.Online().Select(s => s.Name).OrderBy(s => s); Clients.Caller.listUsers(users); } void INotificationService.ListUsers(IEnumerable<ChatUser> users) { Clients.Caller.listUsers(users.Select(s => s.Name)); } void INotificationService.ListUsers(ChatRoom room, IEnumerable<string> names) { Clients.Caller.showUsersInRoom(room.Name, names); } void INotificationService.LockRoom(ChatUser targetUser, ChatRoom room) { var userViewModel = new UserViewModel(targetUser); // Tell the room it's locked Clients.All.lockRoom(userViewModel, room.Name); // Tell the caller the room was successfully locked Clients.Caller.roomLocked(room.Name); // Notify people of the change OnRoomChanged(room); } void INotificationService.CloseRoom(IEnumerable<ChatUser> users, ChatRoom room) { // notify all members of room that it is now closed foreach (var user in users) { foreach (var client in user.ConnectedClients) { Clients.Client(client.Id).roomClosed(room.Name); } } } void INotificationService.UnCloseRoom(IEnumerable<ChatUser> users, ChatRoom room) { // notify all members of room that it is now re-opened foreach (var user in users) { foreach (var client in user.ConnectedClients) { Clients.Client(client.Id).roomUnClosed(room.Name); } } } void INotificationService.LogOut(ChatUser user, string clientId) { foreach (var client in user.ConnectedClients) { DisconnectClient(client.Id); Clients.Client(client.Id).logOut(); } } void INotificationService.ShowUserInfo(ChatUser user) { string userId = Context.User.Identity.Name; Clients.Caller.showUserInfo(new { Name = user.Name, OwnedRooms = user.OwnedRooms .Allowed(userId) .Where(r => !r.Closed) .Select(r => r.Name), Status = ((UserStatus)user.Status).ToString(), LastActivity = user.LastActivity, IsAfk = user.IsAfk, AfkNote = user.AfkNote, Note = user.Note, Hash = user.Hash, Rooms = user.Rooms.Allowed(userId).Select(r => r.Name) }); } void INotificationService.ShowHelp() { Clients.Caller.showCommands(); } void INotificationService.Invite(ChatUser user, ChatUser targetUser, ChatRoom targetRoom) { // Send the invite message to the sendee foreach (var client in targetUser.ConnectedClients) { Clients.Client(client.Id).sendInvite(user.Name, targetUser.Name, targetRoom.Name); } // Send the invite notification to the sender foreach (var client in user.ConnectedClients) { Clients.Client(client.Id).sendInvite(user.Name, targetUser.Name, targetRoom.Name); } } void INotificationService.NugeUser(ChatUser user, ChatUser targetUser) { // Send a nudge message to the sender and the sendee foreach (var client in targetUser.ConnectedClients) { Clients.Client(client.Id).nudge(user.Name, targetUser.Name); } foreach (var client in user.ConnectedClients) { Clients.Client(client.Id).sendPrivateMessage(user.Name, targetUser.Name, "nudged " + targetUser.Name); } } void INotificationService.NudgeRoom(ChatRoom room, ChatUser user) { Clients.Group(room.Name).nudge(user.Name); } void INotificationService.LeaveRoom(ChatUser user, ChatRoom room) { LeaveRoom(user, room); } void INotificationService.OnUserNameChanged(ChatUser user, string oldUserName, string newUserName) { // Create the view model var userViewModel = new UserViewModel(user); // Tell the user's connected clients that the name changed foreach (var client in user.ConnectedClients) { Clients.Client(client.Id).userNameChanged(userViewModel); } // Notify all users in the rooms foreach (var room in user.Rooms) { Clients.Group(room.Name).changeUserName(oldUserName, userViewModel, room.Name); } } void INotificationService.ChangeNote(ChatUser user) { bool isNoteCleared = user.Note == null; // Update the calling client foreach (var client in user.ConnectedClients) { Clients.Client(client.Id).noteChanged(user.IsAfk, isNoteCleared); } // Create the view model var userViewModel = new UserViewModel(user); // Tell all users in rooms to change the note foreach (var room in user.Rooms) { Clients.Group(room.Name).changeNote(userViewModel, room.Name); } } void INotificationService.ChangeFlag(ChatUser user) { bool isFlagCleared = String.IsNullOrWhiteSpace(user.Flag); // Create the view model var userViewModel = new UserViewModel(user); // Update the calling client foreach (var client in user.ConnectedClients) { Clients.Client(client.Id).flagChanged(isFlagCleared, userViewModel.Country); } // Tell all users in rooms to change the flag foreach (var room in user.Rooms) { Clients.Group(room.Name).changeFlag(userViewModel, room.Name); } } void INotificationService.ChangeTopic(ChatUser user, ChatRoom room) { bool isTopicCleared = String.IsNullOrWhiteSpace(room.Topic); var parsedTopic = room.Topic ?? ""; Clients.Group(room.Name).topicChanged(room.Name, isTopicCleared, parsedTopic, user.Name); // Create the view model var roomViewModel = new RoomViewModel { Name = room.Name, Topic = parsedTopic, Closed = room.Closed }; Clients.Group(room.Name).changeTopic(roomViewModel); } void INotificationService.ChangeWelcome(ChatUser user, ChatRoom room) { bool isWelcomeCleared = String.IsNullOrWhiteSpace(room.Welcome); var parsedWelcome = room.Welcome ?? ""; foreach (var client in user.ConnectedClients) { Clients.Client(client.Id).welcomeChanged(isWelcomeCleared, parsedWelcome); } } void INotificationService.AddAdmin(ChatUser targetUser) { foreach (var client in targetUser.ConnectedClients) { // Tell this client it's an owner Clients.Client(client.Id).makeAdmin(); } var userViewModel = new UserViewModel(targetUser); // Tell all users in rooms to change the admin status foreach (var room in targetUser.Rooms) { Clients.Group(room.Name).addAdmin(userViewModel, room.Name); } // Tell the calling client the granting of admin status was successful Clients.Caller.adminMade(targetUser.Name); } void INotificationService.RemoveAdmin(ChatUser targetUser) { foreach (var client in targetUser.ConnectedClients) { // Tell this client it's no longer an owner Clients.Client(client.Id).demoteAdmin(); } var userViewModel = new UserViewModel(targetUser); // Tell all users in rooms to change the admin status foreach (var room in targetUser.Rooms) { Clients.Group(room.Name).removeAdmin(userViewModel, room.Name); } // Tell the calling client the removal of admin status was successful Clients.Caller.adminRemoved(targetUser.Name); } void INotificationService.BroadcastMessage(ChatUser user, string messageText) { // Tell all users in all rooms about this message foreach (var room in _repository.Rooms) { Clients.Group(room.Name).broadcastMessage(messageText, room.Name); } } void INotificationService.ForceUpdate() { Clients.All.forceUpdate(); } private void OnRoomChanged(ChatRoom room) { var roomViewModel = new RoomViewModel { Name = room.Name, Private = room.Private, Closed = room.Closed }; // Update the room count Clients.All.updateRoomCount(roomViewModel, _repository.GetOnlineUsers(room).Count()); } private ClientState GetClientState() { // New client state var jabbrState = GetCookieValue("jabbr.state"); ClientState clientState = null; if (String.IsNullOrEmpty(jabbrState)) { clientState = new ClientState(); } else { clientState = JsonConvert.DeserializeObject<ClientState>(jabbrState); } return clientState; } private string GetCookieValue(string key) { Cookie cookie; Context.RequestCookies.TryGetValue(key, out cookie); string value = cookie != null ? cookie.Value : null; return value != null ? Uri.UnescapeDataString(value) : null; } void INotificationService.BanUser(ChatUser targetUser) { var rooms = targetUser.Rooms.Select(x => x.Name); foreach (var room in rooms) { foreach (var client in targetUser.ConnectedClients) { // Kick the user from this room Clients.Client(client.Id).kick(room); // Remove the user from this the room group so he doesn't get the leave message Groups.Remove(client.Id, room); } } Clients.Client(targetUser.ConnectedClients.First().Id).logOut(rooms); } protected override void Dispose(bool disposing) { if (disposing) { _repository.Dispose(); } base.Dispose(disposing); } } }
// 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.Collections.Immutable; using System.Linq; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines { /// <summary> /// CA2225: Operator overloads have named alternates /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class OperatorOverloadsHaveNamedAlternatesAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA2225"; internal const string DiagnosticKindText = "DiagnosticKind"; internal const string AddAlternateText = "AddAlternate"; internal const string FixVisibilityText = "FixVisibility"; internal const string IsTrueText = "IsTrue"; private const string OpTrueText = "op_True"; private const string OpFalseText = "op_False"; private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.OperatorOverloadsHaveNamedAlternatesTitle), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); private static readonly LocalizableString s_localizableMessageDefault = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.OperatorOverloadsHaveNamedAlternatesMessageDefault), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); private static readonly LocalizableString s_localizableMessageProperty = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.OperatorOverloadsHaveNamedAlternatesMessageProperty), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); private static readonly LocalizableString s_localizableMessageMultiple = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.OperatorOverloadsHaveNamedAlternatesMessageMultiple), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); private static readonly LocalizableString s_localizableMessageVisibility = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.OperatorOverloadsHaveNamedAlternatesMessageVisibility), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.OperatorOverloadsHaveNamedAlternatesDescription), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); internal static DiagnosticDescriptor DefaultRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessageDefault, DiagnosticCategory.Usage, RuleLevel.Disabled, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static DiagnosticDescriptor PropertyRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessageProperty, DiagnosticCategory.Usage, RuleLevel.Disabled, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static DiagnosticDescriptor MultipleRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessageMultiple, DiagnosticCategory.Usage, RuleLevel.Disabled, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static DiagnosticDescriptor VisibilityRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessageVisibility, DiagnosticCategory.Usage, RuleLevel.Disabled, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(DefaultRule, PropertyRule, MultipleRule, VisibilityRule); public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.Method); } private static void AnalyzeSymbol(SymbolAnalysisContext symbolContext) { var methodSymbol = (IMethodSymbol)symbolContext.Symbol; // FxCop compat: only analyze externally visible symbols by default. // Note all the descriptors/rules for this analyzer have the same ID and category and hence // will always have identical configured visibility. if (!symbolContext.Options.MatchesConfiguredVisibility(DefaultRule, methodSymbol, symbolContext.Compilation, symbolContext.CancellationToken)) { return; } if (methodSymbol.ContainingSymbol is ITypeSymbol typeSymbol && (methodSymbol.MethodKind == MethodKind.UserDefinedOperator || methodSymbol.MethodKind == MethodKind.Conversion)) { string operatorName = methodSymbol.Name; if (IsPropertyExpected(operatorName) && operatorName != OpFalseText) { // don't report a diagnostic on the `op_False` method because then the user would see two diagnostics for what is really one error // special-case looking for `IsTrue` instance property // named properties can't be overloaded so there will only ever be 0 or 1 IPropertySymbol property = typeSymbol.GetMembers(IsTrueText).OfType<IPropertySymbol>().FirstOrDefault(); if (property == null || property.Type.SpecialType != SpecialType.System_Boolean) { symbolContext.ReportDiagnostic(CreateDiagnostic(PropertyRule, GetSymbolLocation(methodSymbol), AddAlternateText, IsTrueText, operatorName)); } else if (!property.IsPublic()) { symbolContext.ReportDiagnostic(CreateDiagnostic(VisibilityRule, GetSymbolLocation(property), FixVisibilityText, IsTrueText, operatorName)); } } else { ExpectedAlternateMethodGroup? expectedGroup = GetExpectedAlternateMethodGroup(operatorName, methodSymbol.ReturnType, methodSymbol.Parameters.FirstOrDefault()?.Type); if (expectedGroup == null) { // no alternate methods required return; } var matchedMethods = new List<IMethodSymbol>(); var unmatchedMethods = new HashSet<string>() { expectedGroup.AlternateMethod1 }; if (expectedGroup.AlternateMethod2 != null) { unmatchedMethods.Add(expectedGroup.AlternateMethod2); } foreach (IMethodSymbol candidateMethod in typeSymbol.GetMembers().OfType<IMethodSymbol>()) { if (candidateMethod.Name == expectedGroup.AlternateMethod1 || candidateMethod.Name == expectedGroup.AlternateMethod2) { // found an appropriately-named method matchedMethods.Add(candidateMethod); unmatchedMethods.Remove(candidateMethod.Name); } } // only one public method match is required if (matchedMethods.Any(m => m.IsPublic())) { // at least one public alternate method was found, do nothing } else { // either we found at least one method that should be public or we didn't find anything IMethodSymbol notPublicMethod = matchedMethods.FirstOrDefault(m => !m.IsPublic()); if (notPublicMethod != null) { // report error for improper visibility directly on the method itself symbolContext.ReportDiagnostic(CreateDiagnostic(VisibilityRule, GetSymbolLocation(notPublicMethod), FixVisibilityText, notPublicMethod.Name, operatorName)); } else { // report error for missing methods on the operator overload if (expectedGroup.AlternateMethod2 == null) { // only one alternate expected symbolContext.ReportDiagnostic(CreateDiagnostic(DefaultRule, GetSymbolLocation(methodSymbol), AddAlternateText, expectedGroup.AlternateMethod1, operatorName)); } else { // one of two alternates expected symbolContext.ReportDiagnostic(CreateDiagnostic(MultipleRule, GetSymbolLocation(methodSymbol), AddAlternateText, expectedGroup.AlternateMethod1, expectedGroup.AlternateMethod2, operatorName)); } } } } } } private static Location GetSymbolLocation(ISymbol symbol) { return symbol.OriginalDefinition.Locations.First(); } private static Diagnostic CreateDiagnostic(DiagnosticDescriptor descriptor, Location location, string kind, params string[] messageArgs) { return Diagnostic.Create(descriptor, location, ImmutableDictionary.Create<string, string>().Add(DiagnosticKindText, kind), messageArgs); } internal static bool IsPropertyExpected(string operatorName) { return operatorName switch { OpTrueText or OpFalseText => true, _ => false, }; } internal static ExpectedAlternateMethodGroup? GetExpectedAlternateMethodGroup(string operatorName, ITypeSymbol returnType, ITypeSymbol? parameterType) { // list of operator alternate names: https://docs.microsoft.com/visualstudio/code-quality/ca2225 // the most common case; create a static method with the already specified types static ExpectedAlternateMethodGroup createSingle(string methodName) => new(methodName); return operatorName switch { "op_Addition" or "op_AdditonAssignment" => createSingle("Add"), "op_BitwiseAnd" or "op_BitwiseAndAssignment" => createSingle("BitwiseAnd"), "op_BitwiseOr" or "op_BitwiseOrAssignment" => createSingle("BitwiseOr"), "op_Decrement" => createSingle("Decrement"), "op_Division" or "op_DivisionAssignment" => createSingle("Divide"), "op_Equality" or "op_Inequality" => createSingle("Equals"), "op_ExclusiveOr" or "op_ExclusiveOrAssignment" => createSingle("Xor"), "op_GreaterThan" or "op_GreaterThanOrEqual" or "op_LessThan" or "op_LessThanOrEqual" => new ExpectedAlternateMethodGroup(alternateMethod1: "CompareTo", alternateMethod2: "Compare"), "op_Increment" => createSingle("Increment"), "op_LeftShift" or "op_LeftShiftAssignment" => createSingle("LeftShift"), "op_LogicalAnd" => createSingle("LogicalAnd"), "op_LogicalOr" => createSingle("LogicalOr"), "op_LogicalNot" => createSingle("LogicalNot"), "op_Modulus" or "op_ModulusAssignment" => new ExpectedAlternateMethodGroup(alternateMethod1: "Mod", alternateMethod2: "Remainder"), "op_MultiplicationAssignment" or "op_Multiply" => createSingle("Multiply"), "op_OnesComplement" => createSingle("OnesComplement"), "op_RightShift" or "op_RightShiftAssignment" or "op_SignedRightShift" or "op_UnsignedRightShift" or "op_UnsignedRightShiftAssignment" => createSingle("RightShift"), "op_Subtraction" or "op_SubtractionAssignment" => createSingle("Subtract"), "op_UnaryNegation" => createSingle("Negate"), "op_UnaryPlus" => createSingle("Plus"), "op_Implicit" or "op_Explicit" => new ExpectedAlternateMethodGroup(alternateMethod1: $"To{GetTypeName(returnType)}", alternateMethod2: parameterType != null ? $"From{GetTypeName(parameterType)}" : null), _ => null, }; static string GetTypeName(ITypeSymbol typeSymbol) { if (typeSymbol.TypeKind != TypeKind.Array) { return typeSymbol.Name; } var elementType = typeSymbol; do { elementType = ((IArrayTypeSymbol)elementType).ElementType; } while (elementType.TypeKind == TypeKind.Array); return elementType.Name + "Array"; } } internal class ExpectedAlternateMethodGroup { public string AlternateMethod1 { get; } public string? AlternateMethod2 { get; } public ExpectedAlternateMethodGroup(string alternateMethod1, string? alternateMethod2 = null) { AlternateMethod1 = alternateMethod1; AlternateMethod2 = alternateMethod2; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; #pragma warning disable 67 namespace ExampleAssembly { /// <summary> /// A class. /// </summary> public class ExampleClass : IExampleContravariantInterface<ExampleClass>, IExampleCovariantInterface<string> { /// <summary> /// A no-arg constructor. /// </summary> public ExampleClass() { } /// <summary> /// A one-arg constructor. /// </summary> /// <param name="id">The ID.</param> /// <remarks><para>These remarks reference parameter <paramref name="id"/> /// at the end of a line.</para><para>These remarks reference parameter /// <paramref name="id"/> at the start of a line.</para></remarks> public ExampleClass(string id) { } /// <summary> /// A static lifetime field. /// </summary> public static readonly ExampleClass Default = new ExampleClass(); /// <summary> /// A static lifetime property. /// </summary> public static ExampleClass Instance { get; } = new ExampleClass(); /// <summary> /// A static lifetime method. /// </summary> public static ExampleClass Create() { throw new NotImplementedException(); } /// <summary> /// Another static lifetime method. /// </summary> public static ExampleClass Create(string id) { throw new NotImplementedException(); } /// <summary> /// A read-only property. /// </summary> /// <value>The ID.</value> public string Id { get; } = BlankId; /// <summary> /// A read-write property with a much-longer than expected summary to see /// if there is any word wrapping in the member name. /// </summary> public double Weight { get; set; } /// <summary> /// A static read-only field. /// </summary> public static readonly double DefaultWeight = 1.0; /// <summary> /// A static field. /// </summary> public static int GlobalVariable; /// <summary> /// A constant field. /// </summary> public const string BlankId = ""; /// <summary> /// A static read-only property. /// </summary> public static double MinWeight { get; } = 0.0; /// <summary> /// A static read-write property. /// </summary> public static double MaxWeight { get; set; } /// <summary> /// An event. /// </summary> public event EventHandler? WeightChanged; /// <summary> /// A static event. /// </summary> public static event EventHandler? MaxWeightChanged; /// <summary> /// A virtual method. /// </summary> public virtual void Jump() { } /// <summary> /// A boring static method. It has a really long summary because things get interesting when /// table cells have to wrap. Also, we should probably cut the summary off at some point, since /// some documenters tend to put way more in the summary than would generally be expected. /// </summary> public static void JumpAll() { } /// <summary> /// A public field. /// </summary> public bool IsBadIdea; /// <summary> /// An overloaded method. /// </summary> /// <typeparam name="T">The type parameter.</typeparam> /// <param name="x">The parameter.</param> /// <remarks>We can put special characters in <c>&lt;c&gt;</c> elements, /// <c>like | and ` and &amp;#x21;</c>.</remarks> public T Overloaded<T>(string x) { return default!; } /// <summary> /// An overloaded method. /// </summary> /// <typeparam name="T">The type parameter.</typeparam> /// <typeparam name="U">The second type parameter.</typeparam> /// <param name="x">The parameter.</param> /// <param name="y">The second parameter.</param> public void Overloaded<T, U>(T x, U y) where T : class where U : struct { } /// <summary> /// An overloaded method. /// </summary> /// <typeparam name="T">The type parameter.</typeparam> /// <param name="x">The parameter.</param> public void Overloaded<T>(T x) { } /// <summary> /// An overloaded method. /// </summary> /// <typeparam name="T">The type parameter.</typeparam> public T Overloaded<T>() { return default!; } /// <summary> /// An overloaded method. /// </summary> /// <param name="x">The parameter.</param> public void Overloaded(string x) { } /// <summary> /// An overloaded method. /// </summary> public void Overloaded() { } /// <summary> /// An overloaded method. /// </summary> /// <param name="x">The parameter.</param> public void Overloaded(int x) { } /// <summary> /// A method with default parameters. /// </summary> public void DefaultParameters<T>(bool @bool = true, bool? no = false, bool? maybe = null, byte @byte = byte.MaxValue, sbyte @sbyte = sbyte.MaxValue, char @char = '\u1234', decimal @decimal = 3.14m, double @double = double.NaN, float @float = float.NegativeInfinity, int @int = -42, uint @uint = 42, long @long = long.MinValue, ulong @ulong = long.MaxValue, object? @object = null, short @short = short.MinValue, ushort @ushort = ushort.MaxValue, string @string = "hi\0'\"\\\a\b\f\n\r\t\v\u0001\uABCD", T? t = default, DateTime @virtual = default(DateTime), ExampleEnum @enum = ExampleEnum.One, ExampleFlagsEnum flags = ExampleFlagsEnum.Second | ExampleFlagsEnum.Third) { } /// <summary> /// A method with a really long name. /// </summary> public void LongMethodNameWithTemplateParametersAndMethodParameters<T>(T t) { } /// <summary> /// A method whose summary references <paramref name="value"/>. /// </summary> /// <param name="value">The value</param> public void ParameterReference(int value) { } /// <summary> /// A method whose summary references <typeparamref name="T"/>. /// </summary> /// <param name="value">The value of type <typeparamref name="T"/>.</param> public void TypeParameterReference<T>(T value) { } /// <summary> /// A method that tries to get a value. /// </summary> /// <param name="value">The value.</param> public bool TryGetValue(out object? value) { value = default; return false; } /// <summary> /// A method that tries to get a value. /// </summary> /// <param name="value">The value of type <typeparamref name="T"/>.</param> public bool TryGetValue<T>(out T value) { value = default!; return false; } /// <summary> /// A method that edits a value. /// </summary> /// <param name="value">The value to edit.</param> public void EditValue(ref object value) { } /// <summary> /// A method that edits a value. /// </summary> /// <param name="value">The value to edit of type <typeparamref name="T"/>.</param> public void EditValue<T>(ref T value) { } /// <summary> /// A method with parameters. /// </summary> /// <param name="parameters">The parameters.</param> public void HasParams(params string[] parameters) { } /// <summary> /// A method that uses caller info. /// </summary> public void UsesCallerInfo([CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { } /// <summary> /// A method whose docs have <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a">hyperlinks</a>. /// </summary> /// <remarks>Visit <see href="https://ejball.com/" /> for <see href="https://ejball.com/">more info</see>.</remarks> public void HasHyperlinks() { } /// <summary> /// An obsolete method. /// </summary> [Obsolete("This method is old and busted.")] public void OldAndBusted() { } /// <summary> /// An unbrowsable method. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public void UnbrowsableMethod() { } /// <summary> /// A method with tuples. /// </summary> /// <param name="tuples">The tuples.</param> public void Tuples(params (string Key, object? Value)[] tuples) { } /// <summary> /// A method with a long tuple. /// </summary> public ((int A1, int A2) A, int B, int C, int, int, int D, int E, (int F1, int F2) F)? EightTuple() { return null; } /// <summary> /// A method with a nested tuple. /// </summary> public void NestedTuple(Dictionary<((int A, int B) C, IList<(int D, int E)> F), (int G, int H)> dictionary) { } /// <summary> /// A method with nullable references. /// </summary> public void NullableReferences<T>(string? a, (string B1, string? B2, string B3) b, Dictionary<string, string?> c, string[]? d, string?[] e, (T F1, T? F2) f) { } } }
namespace android.view { [global::MonoJavaBridge.JavaClass()] public sealed partial class MotionEvent : java.lang.Object, android.os.Parcelable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal MotionEvent(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public sealed override global::java.lang.String toString() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.view.MotionEvent.staticClass, "toString", "()Ljava/lang/String;", ref global::android.view.MotionEvent._m0) as java.lang.String; } public new float Size { get { return getSize(); } } private static global::MonoJavaBridge.MethodId _m1; public float getSize() { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.view.MotionEvent.staticClass, "getSize", "()F", ref global::android.view.MotionEvent._m1); } private static global::MonoJavaBridge.MethodId _m2; public float getSize(int arg0) { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.view.MotionEvent.staticClass, "getSize", "(I)F", ref global::android.view.MotionEvent._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m3; public float getY(int arg0) { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.view.MotionEvent.staticClass, "getY", "(I)F", ref global::android.view.MotionEvent._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new float Y { get { return getY(); } } private static global::MonoJavaBridge.MethodId _m4; public float getY() { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.view.MotionEvent.staticClass, "getY", "()F", ref global::android.view.MotionEvent._m4); } private static global::MonoJavaBridge.MethodId _m5; public float getX(int arg0) { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.view.MotionEvent.staticClass, "getX", "(I)F", ref global::android.view.MotionEvent._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new float X { get { return getX(); } } private static global::MonoJavaBridge.MethodId _m6; public float getX() { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.view.MotionEvent.staticClass, "getX", "()F", ref global::android.view.MotionEvent._m6); } public new long EventTime { get { return getEventTime(); } } private static global::MonoJavaBridge.MethodId _m7; public long getEventTime() { return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::android.view.MotionEvent.staticClass, "getEventTime", "()J", ref global::android.view.MotionEvent._m7); } private static global::MonoJavaBridge.MethodId _m8; public static global::android.view.MotionEvent obtain(long arg0, long arg1, int arg2, float arg3, float arg4, int arg5) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.view.MotionEvent._m8.native == global::System.IntPtr.Zero) global::android.view.MotionEvent._m8 = @__env.GetStaticMethodIDNoThrow(global::android.view.MotionEvent.staticClass, "obtain", "(JJIFFI)Landroid/view/MotionEvent;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.view.MotionEvent>(@__env.CallStaticObjectMethod(android.view.MotionEvent.staticClass, global::android.view.MotionEvent._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5))) as android.view.MotionEvent; } private static global::MonoJavaBridge.MethodId _m9; public static global::android.view.MotionEvent obtain(long arg0, long arg1, int arg2, int arg3, float arg4, float arg5, float arg6, float arg7, int arg8, float arg9, float arg10, int arg11, int arg12) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.view.MotionEvent._m9.native == global::System.IntPtr.Zero) global::android.view.MotionEvent._m9 = @__env.GetStaticMethodIDNoThrow(global::android.view.MotionEvent.staticClass, "obtain", "(JJIIFFFFIFFII)Landroid/view/MotionEvent;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.view.MotionEvent>(@__env.CallStaticObjectMethod(android.view.MotionEvent.staticClass, global::android.view.MotionEvent._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg8), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg9), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg10), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg11), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg12))) as android.view.MotionEvent; } private static global::MonoJavaBridge.MethodId _m10; public static global::android.view.MotionEvent obtain(long arg0, long arg1, int arg2, float arg3, float arg4, float arg5, float arg6, int arg7, float arg8, float arg9, int arg10, int arg11) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.view.MotionEvent._m10.native == global::System.IntPtr.Zero) global::android.view.MotionEvent._m10 = @__env.GetStaticMethodIDNoThrow(global::android.view.MotionEvent.staticClass, "obtain", "(JJIFFFFIFFII)Landroid/view/MotionEvent;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.view.MotionEvent>(@__env.CallStaticObjectMethod(android.view.MotionEvent.staticClass, global::android.view.MotionEvent._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg8), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg9), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg10), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg11))) as android.view.MotionEvent; } private static global::MonoJavaBridge.MethodId _m11; public static global::android.view.MotionEvent obtain(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.view.MotionEvent._m11.native == global::System.IntPtr.Zero) global::android.view.MotionEvent._m11 = @__env.GetStaticMethodIDNoThrow(global::android.view.MotionEvent.staticClass, "obtain", "(Landroid/view/MotionEvent;)Landroid/view/MotionEvent;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.view.MotionEvent>(@__env.CallStaticObjectMethod(android.view.MotionEvent.staticClass, global::android.view.MotionEvent._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MotionEvent; } private static global::MonoJavaBridge.MethodId _m12; public void recycle() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.MotionEvent.staticClass, "recycle", "()V", ref global::android.view.MotionEvent._m12); } private static global::MonoJavaBridge.MethodId _m13; public void writeToParcel(android.os.Parcel arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.MotionEvent.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V", ref global::android.view.MotionEvent._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m14; public int describeContents() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.MotionEvent.staticClass, "describeContents", "()I", ref global::android.view.MotionEvent._m14); } public new int Action { get { return getAction(); } set { setAction(value); } } private static global::MonoJavaBridge.MethodId _m15; public int getAction() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.MotionEvent.staticClass, "getAction", "()I", ref global::android.view.MotionEvent._m15); } private static global::MonoJavaBridge.MethodId _m16; public void setAction(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.MotionEvent.staticClass, "setAction", "(I)V", ref global::android.view.MotionEvent._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int MetaState { get { return getMetaState(); } } private static global::MonoJavaBridge.MethodId _m17; public int getMetaState() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.MotionEvent.staticClass, "getMetaState", "()I", ref global::android.view.MotionEvent._m17); } public new long DownTime { get { return getDownTime(); } } private static global::MonoJavaBridge.MethodId _m18; public long getDownTime() { return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::android.view.MotionEvent.staticClass, "getDownTime", "()J", ref global::android.view.MotionEvent._m18); } public new int DeviceId { get { return getDeviceId(); } } private static global::MonoJavaBridge.MethodId _m19; public int getDeviceId() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.MotionEvent.staticClass, "getDeviceId", "()I", ref global::android.view.MotionEvent._m19); } private static global::MonoJavaBridge.MethodId _m20; public static global::android.view.MotionEvent obtainNoHistory(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.view.MotionEvent._m20.native == global::System.IntPtr.Zero) global::android.view.MotionEvent._m20 = @__env.GetStaticMethodIDNoThrow(global::android.view.MotionEvent.staticClass, "obtainNoHistory", "(Landroid/view/MotionEvent;)Landroid/view/MotionEvent;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.view.MotionEvent>(@__env.CallStaticObjectMethod(android.view.MotionEvent.staticClass, global::android.view.MotionEvent._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MotionEvent; } public new int ActionMasked { get { return getActionMasked(); } } private static global::MonoJavaBridge.MethodId _m21; public int getActionMasked() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.MotionEvent.staticClass, "getActionMasked", "()I", ref global::android.view.MotionEvent._m21); } public new int ActionIndex { get { return getActionIndex(); } } private static global::MonoJavaBridge.MethodId _m22; public int getActionIndex() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.MotionEvent.staticClass, "getActionIndex", "()I", ref global::android.view.MotionEvent._m22); } public new float Pressure { get { return getPressure(); } } private static global::MonoJavaBridge.MethodId _m23; public float getPressure() { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.view.MotionEvent.staticClass, "getPressure", "()F", ref global::android.view.MotionEvent._m23); } private static global::MonoJavaBridge.MethodId _m24; public float getPressure(int arg0) { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.view.MotionEvent.staticClass, "getPressure", "(I)F", ref global::android.view.MotionEvent._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int PointerCount { get { return getPointerCount(); } } private static global::MonoJavaBridge.MethodId _m25; public int getPointerCount() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.MotionEvent.staticClass, "getPointerCount", "()I", ref global::android.view.MotionEvent._m25); } private static global::MonoJavaBridge.MethodId _m26; public int getPointerId(int arg0) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.MotionEvent.staticClass, "getPointerId", "(I)I", ref global::android.view.MotionEvent._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m27; public int findPointerIndex(int arg0) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.MotionEvent.staticClass, "findPointerIndex", "(I)I", ref global::android.view.MotionEvent._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new float RawX { get { return getRawX(); } } private static global::MonoJavaBridge.MethodId _m28; public float getRawX() { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.view.MotionEvent.staticClass, "getRawX", "()F", ref global::android.view.MotionEvent._m28); } public new float RawY { get { return getRawY(); } } private static global::MonoJavaBridge.MethodId _m29; public float getRawY() { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.view.MotionEvent.staticClass, "getRawY", "()F", ref global::android.view.MotionEvent._m29); } public new float XPrecision { get { return getXPrecision(); } } private static global::MonoJavaBridge.MethodId _m30; public float getXPrecision() { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.view.MotionEvent.staticClass, "getXPrecision", "()F", ref global::android.view.MotionEvent._m30); } public new float YPrecision { get { return getYPrecision(); } } private static global::MonoJavaBridge.MethodId _m31; public float getYPrecision() { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.view.MotionEvent.staticClass, "getYPrecision", "()F", ref global::android.view.MotionEvent._m31); } public new int HistorySize { get { return getHistorySize(); } } private static global::MonoJavaBridge.MethodId _m32; public int getHistorySize() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.MotionEvent.staticClass, "getHistorySize", "()I", ref global::android.view.MotionEvent._m32); } private static global::MonoJavaBridge.MethodId _m33; public long getHistoricalEventTime(int arg0) { return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::android.view.MotionEvent.staticClass, "getHistoricalEventTime", "(I)J", ref global::android.view.MotionEvent._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m34; public float getHistoricalX(int arg0, int arg1) { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.view.MotionEvent.staticClass, "getHistoricalX", "(II)F", ref global::android.view.MotionEvent._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m35; public float getHistoricalX(int arg0) { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.view.MotionEvent.staticClass, "getHistoricalX", "(I)F", ref global::android.view.MotionEvent._m35, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m36; public float getHistoricalY(int arg0) { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.view.MotionEvent.staticClass, "getHistoricalY", "(I)F", ref global::android.view.MotionEvent._m36, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m37; public float getHistoricalY(int arg0, int arg1) { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.view.MotionEvent.staticClass, "getHistoricalY", "(II)F", ref global::android.view.MotionEvent._m37, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m38; public float getHistoricalPressure(int arg0) { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.view.MotionEvent.staticClass, "getHistoricalPressure", "(I)F", ref global::android.view.MotionEvent._m38, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m39; public float getHistoricalPressure(int arg0, int arg1) { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.view.MotionEvent.staticClass, "getHistoricalPressure", "(II)F", ref global::android.view.MotionEvent._m39, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m40; public float getHistoricalSize(int arg0, int arg1) { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.view.MotionEvent.staticClass, "getHistoricalSize", "(II)F", ref global::android.view.MotionEvent._m40, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m41; public float getHistoricalSize(int arg0) { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.view.MotionEvent.staticClass, "getHistoricalSize", "(I)F", ref global::android.view.MotionEvent._m41, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int EdgeFlags { get { return getEdgeFlags(); } set { setEdgeFlags(value); } } private static global::MonoJavaBridge.MethodId _m42; public int getEdgeFlags() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.MotionEvent.staticClass, "getEdgeFlags", "()I", ref global::android.view.MotionEvent._m42); } private static global::MonoJavaBridge.MethodId _m43; public void setEdgeFlags(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.MotionEvent.staticClass, "setEdgeFlags", "(I)V", ref global::android.view.MotionEvent._m43, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m44; public void offsetLocation(float arg0, float arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.MotionEvent.staticClass, "offsetLocation", "(FF)V", ref global::android.view.MotionEvent._m44, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m45; public void setLocation(float arg0, float arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.MotionEvent.staticClass, "setLocation", "(FF)V", ref global::android.view.MotionEvent._m45, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m46; public void addBatch(long arg0, float arg1, float arg2, float arg3, float arg4, int arg5) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.MotionEvent.staticClass, "addBatch", "(JFFFFI)V", ref global::android.view.MotionEvent._m46, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5)); } public static int ACTION_MASK { get { return 255; } } public static int ACTION_DOWN { get { return 0; } } public static int ACTION_UP { get { return 1; } } public static int ACTION_MOVE { get { return 2; } } public static int ACTION_CANCEL { get { return 3; } } public static int ACTION_OUTSIDE { get { return 4; } } public static int ACTION_POINTER_DOWN { get { return 5; } } public static int ACTION_POINTER_UP { get { return 6; } } public static int ACTION_POINTER_INDEX_MASK { get { return 65280; } } public static int ACTION_POINTER_INDEX_SHIFT { get { return 8; } } public static int ACTION_POINTER_1_DOWN { get { return 5; } } public static int ACTION_POINTER_2_DOWN { get { return 261; } } public static int ACTION_POINTER_3_DOWN { get { return 517; } } public static int ACTION_POINTER_1_UP { get { return 6; } } public static int ACTION_POINTER_2_UP { get { return 262; } } public static int ACTION_POINTER_3_UP { get { return 518; } } public static int ACTION_POINTER_ID_MASK { get { return 65280; } } public static int ACTION_POINTER_ID_SHIFT { get { return 8; } } public static int EDGE_TOP { get { return 1; } } public static int EDGE_BOTTOM { get { return 2; } } public static int EDGE_LEFT { get { return 4; } } public static int EDGE_RIGHT { get { return 8; } } internal static global::MonoJavaBridge.FieldId _CREATOR5650; public static global::android.os.Parcelable_Creator CREATOR { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.os.Parcelable_Creator>(@__env.GetStaticObjectField(global::android.view.MotionEvent.staticClass, _CREATOR5650)) as android.os.Parcelable_Creator; } } static MotionEvent() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.MotionEvent.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/MotionEvent")); global::android.view.MotionEvent._CREATOR5650 = @__env.GetStaticFieldIDNoThrow(global::android.view.MotionEvent.staticClass, "CREATOR", "Landroid/os/Parcelable$Creator;"); } } }
// 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.IO; using System.Linq; using System.Reflection.Tests; using System.Runtime.CompilerServices; 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 { [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("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); } [Fact] public void EntryPoint_ExecutingAssembly_IsNull() { Assert.Null(Helpers.ExecutingAssembly.EntryPoint); } 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] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "On desktop, XUnit hosts in an appdomain in such a way that GetEntryAssembly() returns null")] public void GetEntryAssembly() { Assert.NotNull(Assembly.GetEntryAssembly()); string assembly = Assembly.GetEntryAssembly().ToString(); bool correct = assembly.IndexOf("xunit.console.netcore", StringComparison.OrdinalIgnoreCase) != -1 || assembly.IndexOf("XUnit.Runner.Uap", StringComparison.OrdinalIgnoreCase) != -1; Assert.True(correct, $"Unexpected assembly name {assembly}"); } 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); } } 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) }; } [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] 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] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "CodeBase is not supported on UapAot")] public void CodeBase() { Assert.NotEmpty(Helpers.ExecutingAssembly.CodeBase); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "ImageRuntimeVersion is not supported on UapAot.")] 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[]> 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)); } [Fact] public void CreateQualifiedName() { string assemblyName = Helpers.ExecutingAssembly.ToString(); Assert.Equal(typeof(AssemblyTests).FullName + ", " + assemblyName, Assembly.CreateQualifiedName(assemblyName, typeof(AssemblyTests).FullName)); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "GetReferencedAssemblies is not supported on UapAot.")] 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 IEnumerable<object[]> ToString_TestData() { yield return new object[] { Helpers.ExecutingAssembly, "System.Reflection.Tests" }; yield return new object[] { Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), "PublicKeyToken=" }; } [Theory] public void ToString(Assembly assembly, string expected) { Assert.Contains(expected, assembly.ToString()); Assert.Equal(assembly.ToString(), assembly.FullName); } 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)); ; } } 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) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Linq.Expressions.Tests { public static class TernaryTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryBoolTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; bool[] array2 = new bool[] { true, false }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyBool(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryByteTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; byte[] array2 = new byte[] { 0, 1, byte.MaxValue }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyByte(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryCustomTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; C[] array2 = new C[] { null, new C(), new D(), new D(0), new D(5) }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyCustom(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryCharTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; char[] array2 = new char[] { '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyChar(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryCustom2Test(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; D[] array2 = new D[] { null, new D(), new D(0), new D(5) }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyCustom2(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryDecimalTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; decimal[] array2 = new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyDecimal(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryDelegateTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; Delegate[] array2 = new Delegate[] { null, (Func<object>)delegate () { return null; }, (Func<int, int>)delegate (int i) { return i + 1; }, (Action<object>)delegate { } }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyDelegate(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryDoubleTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; double[] array2 = new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyDouble(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryEnumTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; E[] array2 = new E[] { (E)0, E.A, E.B, (E)int.MaxValue, (E)int.MinValue }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyEnum(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryEnumLongTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; El[] array2 = new El[] { (El)0, El.A, El.B, (El)long.MaxValue, (El)long.MinValue }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyEnumLong(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryFloatTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; float[] array2 = new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyFloat(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryFuncOfObjectTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; Func<object>[] array2 = new Func<object>[] { null, (Func<object>)delegate () { return null; } }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyFuncOfObject(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryInterfaceTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; I[] array2 = new I[] { null, new C(), new D(), new D(0), new D(5) }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyInterface(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryIEquatableOfCustomTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; IEquatable<C>[] array2 = new IEquatable<C>[] { null, new C(), new D(), new D(0), new D(5) }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyIEquatableOfCustom(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryIEquatableOfCustom2Test(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; IEquatable<D>[] array2 = new IEquatable<D>[] { null, new D(), new D(0), new D(5) }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyIEquatableOfCustom2(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryIntTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; int[] array2 = new int[] { 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyInt(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryLongTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; long[] array2 = new long[] { 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyLong(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryObjectTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; object[] array2 = new object[] { null, new object(), new C(), new D(3) }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyObject(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryStructTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; S[] array2 = new S[] { default(S), new S() }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyStruct(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernarySByteTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; sbyte[] array2 = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifySByte(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryStructWithStringTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; Sc[] array2 = new Sc[] { default(Sc), new Sc(), new Sc(null) }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyStructWithString(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryStructWithStringAndFieldTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; Scs[] array2 = new Scs[] { default(Scs), new Scs(), new Scs(null, new S()) }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyStructWithStringAndField(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryShortTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; short[] array2 = new short[] { 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyShort(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryStructWithTwoValuesTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; Sp[] array2 = new Sp[] { default(Sp), new Sp(), new Sp(5, 5.0) }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyStructWithTwoValues(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryStructWithValueTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; Ss[] array2 = new Ss[] { default(Ss), new Ss(), new Ss(new S()) }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyStructWithValue(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryStringTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; string[] array2 = new string[] { null, "", "a", "foo" }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyString(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryUIntTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; uint[] array2 = new uint[] { 0, 1, uint.MaxValue }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyUInt(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryULongTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; ulong[] array2 = new ulong[] { 0, 1, ulong.MaxValue }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyULong(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryUShortTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; ushort[] array2 = new ushort[] { 0, 1, ushort.MaxValue }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyUShort(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryGenericWithCustomTest(bool useInterpreter) { CheckTernaryGenericHelper<C>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryGenericWithEnumTest(bool useInterpreter) { CheckTernaryGenericHelper<E>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryGenericWithObjectTest(bool useInterpreter) { CheckTernaryGenericHelper<object>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryGenericWithStructTest(bool useInterpreter) { CheckTernaryGenericHelper<S>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryGenericWithStructWithStringAndFieldTest(bool useInterpreter) { CheckTernaryGenericHelper<Scs>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryGenericWithClassRestrictionWithCustomTest(bool useInterpreter) { CheckTernaryGenericWithClassRestrictionHelper<C>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryGenericWithClassRestrictionWithObjectTest(bool useInterpreter) { CheckTernaryGenericWithClassRestrictionHelper<object>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryGenericWithSubClassRestrictionWithCustomTest(bool useInterpreter) { CheckTernaryGenericWithSubClassRestrictionHelper<C>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryGenericWithClassAndNewRestrictionWithCustomTest(bool useInterpreter) { CheckTernaryGenericWithClassAndNewRestrictionHelper<C>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryGenericWithClassAndNewRestrictionWithObjectTest(bool useInterpreter) { CheckTernaryGenericWithClassAndNewRestrictionHelper<object>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryGenericWithSubClassAndNewRestrictionWithCustomTest(bool useInterpreter) { CheckTernaryGenericWithSubClassAndNewRestrictionHelper<C>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryGenericWithStructRestrictionWithEnumTest(bool useInterpreter) { CheckTernaryGenericWithStructRestrictionHelper<E>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryGenericWithStructRestrictionWithStructTest(bool useInterpreter) { CheckTernaryGenericWithStructRestrictionHelper<S>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryGenericWithStructRestrictionWithStructWithStringAndFieldTest(bool useInterpreter) { CheckTernaryGenericWithStructRestrictionHelper<Scs>(useInterpreter); } #endregion #region Generic helpers private static void CheckTernaryGenericHelper<T>(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; T[] array2 = new T[] { default(T) }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyGeneric<T>(array1[i], array2[j], array2[k], useInterpreter); } } } } private static void CheckTernaryGenericWithClassRestrictionHelper<Tc>(bool useInterpreter) where Tc : class { bool[] array1 = new bool[] { false, true }; Tc[] array2 = new Tc[] { null, default(Tc) }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyGenericWithClassRestriction<Tc>(array1[i], array2[j], array2[k], useInterpreter); } } } } private static void CheckTernaryGenericWithSubClassRestrictionHelper<TC>(bool useInterpreter) where TC : C { bool[] array1 = new bool[] { false, true }; TC[] array2 = new TC[] { null, default(TC), (TC)new C() }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyGenericWithSubClassRestriction<TC>(array1[i], array2[j], array2[k], useInterpreter); } } } } private static void CheckTernaryGenericWithClassAndNewRestrictionHelper<Tcn>(bool useInterpreter) where Tcn : class, new() { bool[] array1 = new bool[] { false, true }; Tcn[] array2 = new Tcn[] { null, default(Tcn), new Tcn() }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyGenericWithClassAndNewRestriction<Tcn>(array1[i], array2[j], array2[k], useInterpreter); } } } } private static void CheckTernaryGenericWithSubClassAndNewRestrictionHelper<TCn>(bool useInterpreter) where TCn : C, new() { bool[] array1 = new bool[] { false, true }; TCn[] array2 = new TCn[] { null, default(TCn), new TCn(), (TCn)new C() }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyGenericWithSubClassAndNewRestriction<TCn>(array1[i], array2[j], array2[k], useInterpreter); } } } } private static void CheckTernaryGenericWithStructRestrictionHelper<Ts>(bool useInterpreter) where Ts : struct { bool[] array1 = new bool[] { false, true }; Ts[] array2 = new Ts[] { default(Ts), new Ts() }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyGenericWithStructRestriction<Ts>(array1[i], array2[j], array2[k], useInterpreter); } } } } #endregion #region Test verifiers private static void VerifyBool(bool condition, bool a, bool b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(bool)), Expression.Constant(b, typeof(bool))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyByte(bool condition, byte a, byte b, bool useInterpreter) { Expression<Func<byte>> e = Expression.Lambda<Func<byte>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(byte)), Expression.Constant(b, typeof(byte))), Enumerable.Empty<ParameterExpression>()); Func<byte> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyCustom(bool condition, C a, C b, bool useInterpreter) { Expression<Func<C>> e = Expression.Lambda<Func<C>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(C)), Expression.Constant(b, typeof(C))), Enumerable.Empty<ParameterExpression>()); Func<C> f = e.Compile(useInterpreter); Assert.Same(condition ? a : b, f()); } private static void VerifyChar(bool condition, char a, char b, bool useInterpreter) { Expression<Func<char>> e = Expression.Lambda<Func<char>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(char)), Expression.Constant(b, typeof(char))), Enumerable.Empty<ParameterExpression>()); Func<char> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyCustom2(bool condition, D a, D b, bool useInterpreter) { Expression<Func<D>> e = Expression.Lambda<Func<D>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(D)), Expression.Constant(b, typeof(D))), Enumerable.Empty<ParameterExpression>()); Func<D> f = e.Compile(useInterpreter); Assert.Same(condition ? a : b, f()); } private static void VerifyDecimal(bool condition, decimal a, decimal b, bool useInterpreter) { Expression<Func<decimal>> e = Expression.Lambda<Func<decimal>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(decimal)), Expression.Constant(b, typeof(decimal))), Enumerable.Empty<ParameterExpression>()); Func<decimal> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyDelegate(bool condition, Delegate a, Delegate b, bool useInterpreter) { Expression<Func<Delegate>> e = Expression.Lambda<Func<Delegate>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(Delegate)), Expression.Constant(b, typeof(Delegate))), Enumerable.Empty<ParameterExpression>()); Func<Delegate> f = e.Compile(useInterpreter); Assert.Same(condition ? a : b, f()); } private static void VerifyDouble(bool condition, double a, double b, bool useInterpreter) { Expression<Func<double>> e = Expression.Lambda<Func<double>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(double)), Expression.Constant(b, typeof(double))), Enumerable.Empty<ParameterExpression>()); Func<double> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyEnum(bool condition, E a, E b, bool useInterpreter) { Expression<Func<E>> e = Expression.Lambda<Func<E>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(E)), Expression.Constant(b, typeof(E))), Enumerable.Empty<ParameterExpression>()); Func<E> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyEnumLong(bool condition, El a, El b, bool useInterpreter) { Expression<Func<El>> e = Expression.Lambda<Func<El>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(El)), Expression.Constant(b, typeof(El))), Enumerable.Empty<ParameterExpression>()); Func<El> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyFloat(bool condition, float a, float b, bool useInterpreter) { Expression<Func<float>> e = Expression.Lambda<Func<float>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(float)), Expression.Constant(b, typeof(float))), Enumerable.Empty<ParameterExpression>()); Func<float> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyFuncOfObject(bool condition, Func<object> a, Func<object> b, bool useInterpreter) { Expression<Func<Func<object>>> e = Expression.Lambda<Func<Func<object>>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(Func<object>)), Expression.Constant(b, typeof(Func<object>))), Enumerable.Empty<ParameterExpression>()); Func<Func<object>> f = e.Compile(useInterpreter); Assert.Same(condition ? a : b, f()); } private static void VerifyInterface(bool condition, I a, I b, bool useInterpreter) { Expression<Func<I>> e = Expression.Lambda<Func<I>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(I)), Expression.Constant(b, typeof(I))), Enumerable.Empty<ParameterExpression>()); Func<I> f = e.Compile(useInterpreter); Assert.Same(condition ? a : b, f()); } private static void VerifyIEquatableOfCustom(bool condition, IEquatable<C> a, IEquatable<C> b, bool useInterpreter) { Expression<Func<IEquatable<C>>> e = Expression.Lambda<Func<IEquatable<C>>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(IEquatable<C>)), Expression.Constant(b, typeof(IEquatable<C>))), Enumerable.Empty<ParameterExpression>()); Func<IEquatable<C>> f = e.Compile(useInterpreter); Assert.Same(condition ? a : b, f()); } private static void VerifyIEquatableOfCustom2(bool condition, IEquatable<D> a, IEquatable<D> b, bool useInterpreter) { Expression<Func<IEquatable<D>>> e = Expression.Lambda<Func<IEquatable<D>>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(IEquatable<D>)), Expression.Constant(b, typeof(IEquatable<D>))), Enumerable.Empty<ParameterExpression>()); Func<IEquatable<D>> f = e.Compile(useInterpreter); Assert.Same(condition ? a : b, f()); } private static void VerifyInt(bool condition, int a, int b, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(int)), Expression.Constant(b, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyLong(bool condition, long a, long b, bool useInterpreter) { Expression<Func<long>> e = Expression.Lambda<Func<long>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(long)), Expression.Constant(b, typeof(long))), Enumerable.Empty<ParameterExpression>()); Func<long> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyObject(bool condition, object a, object b, bool useInterpreter) { Expression<Func<object>> e = Expression.Lambda<Func<object>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(object)), Expression.Constant(b, typeof(object))), Enumerable.Empty<ParameterExpression>()); Func<object> f = e.Compile(useInterpreter); Assert.Same(condition ? a : b, f()); } private static void VerifyStruct(bool condition, S a, S b, bool useInterpreter) { Expression<Func<S>> e = Expression.Lambda<Func<S>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(S)), Expression.Constant(b, typeof(S))), Enumerable.Empty<ParameterExpression>()); Func<S> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifySByte(bool condition, sbyte a, sbyte b, bool useInterpreter) { Expression<Func<sbyte>> e = Expression.Lambda<Func<sbyte>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(sbyte)), Expression.Constant(b, typeof(sbyte))), Enumerable.Empty<ParameterExpression>()); Func<sbyte> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyStructWithString(bool condition, Sc a, Sc b, bool useInterpreter) { Expression<Func<Sc>> e = Expression.Lambda<Func<Sc>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(Sc)), Expression.Constant(b, typeof(Sc))), Enumerable.Empty<ParameterExpression>()); Func<Sc> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyStructWithStringAndField(bool condition, Scs a, Scs b, bool useInterpreter) { Expression<Func<Scs>> e = Expression.Lambda<Func<Scs>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(Scs)), Expression.Constant(b, typeof(Scs))), Enumerable.Empty<ParameterExpression>()); Func<Scs> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyShort(bool condition, short a, short b, bool useInterpreter) { Expression<Func<short>> e = Expression.Lambda<Func<short>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(short)), Expression.Constant(b, typeof(short))), Enumerable.Empty<ParameterExpression>()); Func<short> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyStructWithTwoValues(bool condition, Sp a, Sp b, bool useInterpreter) { Expression<Func<Sp>> e = Expression.Lambda<Func<Sp>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(Sp)), Expression.Constant(b, typeof(Sp))), Enumerable.Empty<ParameterExpression>()); Func<Sp> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyStructWithValue(bool condition, Ss a, Ss b, bool useInterpreter) { Expression<Func<Ss>> e = Expression.Lambda<Func<Ss>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(Ss)), Expression.Constant(b, typeof(Ss))), Enumerable.Empty<ParameterExpression>()); Func<Ss> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyString(bool condition, string a, string b, bool useInterpreter) { Expression<Func<string>> e = Expression.Lambda<Func<string>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(string)), Expression.Constant(b, typeof(string))), Enumerable.Empty<ParameterExpression>()); Func<string> f = e.Compile(useInterpreter); Assert.Same(condition ? a : b, f()); } private static void VerifyUInt(bool condition, uint a, uint b, bool useInterpreter) { Expression<Func<uint>> e = Expression.Lambda<Func<uint>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(uint)), Expression.Constant(b, typeof(uint))), Enumerable.Empty<ParameterExpression>()); Func<uint> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyULong(bool condition, ulong a, ulong b, bool useInterpreter) { Expression<Func<ulong>> e = Expression.Lambda<Func<ulong>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(ulong)), Expression.Constant(b, typeof(ulong))), Enumerable.Empty<ParameterExpression>()); Func<ulong> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyUShort(bool condition, ushort a, ushort b, bool useInterpreter) { Expression<Func<ushort>> e = Expression.Lambda<Func<ushort>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(ushort)), Expression.Constant(b, typeof(ushort))), Enumerable.Empty<ParameterExpression>()); Func<ushort> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyGeneric<T>(bool condition, T a, T b, bool useInterpreter) { Expression<Func<T>> e = Expression.Lambda<Func<T>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(T)), Expression.Constant(b, typeof(T))), Enumerable.Empty<ParameterExpression>()); Func<T> f = e.Compile(useInterpreter); if (default(T) == null) Assert.Same((object)(condition ? a : b), (object)f()); else Assert.Equal(condition ? a : b, f()); } private static void VerifyGenericWithClassRestriction<Tc>(bool condition, Tc a, Tc b, bool useInterpreter) where Tc : class { Expression<Func<Tc>> e = Expression.Lambda<Func<Tc>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(Tc)), Expression.Constant(b, typeof(Tc))), Enumerable.Empty<ParameterExpression>()); Func<Tc> f = e.Compile(useInterpreter); Assert.Same(condition ? a : b, f()); } private static void VerifyGenericWithSubClassRestriction<TC>(bool condition, TC a, TC b, bool useInterpreter) where TC : class { Expression<Func<TC>> e = Expression.Lambda<Func<TC>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(TC)), Expression.Constant(b, typeof(TC))), Enumerable.Empty<ParameterExpression>()); Func<TC> f = e.Compile(useInterpreter); Assert.Same(condition ? a : b, f()); } private static void VerifyGenericWithClassAndNewRestriction<Tcn>(bool condition, Tcn a, Tcn b, bool useInterpreter) where Tcn : class { Expression<Func<Tcn>> e = Expression.Lambda<Func<Tcn>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(Tcn)), Expression.Constant(b, typeof(Tcn))), Enumerable.Empty<ParameterExpression>()); Func<Tcn> f = e.Compile(useInterpreter); Assert.Same(condition ? a : b, f()); } private static void VerifyGenericWithSubClassAndNewRestriction<TCn>(bool condition, TCn a, TCn b, bool useInterpreter) where TCn : class { Expression<Func<TCn>> e = Expression.Lambda<Func<TCn>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(TCn)), Expression.Constant(b, typeof(TCn))), Enumerable.Empty<ParameterExpression>()); Func<TCn> f = e.Compile(useInterpreter); Assert.Same(condition ? a : b, f()); } private static void VerifyGenericWithStructRestriction<Ts>(bool condition, Ts a, Ts b, bool useInterpreter) { Expression<Func<Ts>> e = Expression.Lambda<Func<Ts>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(Ts)), Expression.Constant(b, typeof(Ts))), Enumerable.Empty<ParameterExpression>()); Func<Ts> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsAzureSpecials { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// ApiVersionDefaultOperations operations. /// </summary> internal partial class ApiVersionDefaultOperations : IServiceOperations<AutoRestAzureSpecialParametersTestClient>, IApiVersionDefaultOperations { /// <summary> /// Initializes a new instance of the ApiVersionDefaultOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ApiVersionDefaultOperations(AutoRestAzureSpecialParametersTestClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestAzureSpecialParametersTestClient /// </summary> public AutoRestAzureSpecialParametersTestClient Client { get; private set; } /// <summary> /// GET method with api-version modeled in global settings. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> GetMethodGlobalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetMethodGlobalValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/method/string/none/query/global/2015-07-01-preview").ToString(); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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> /// GET method with api-version modeled in global settings. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> GetMethodGlobalNotProvidedValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetMethodGlobalNotProvidedValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/method/string/none/query/globalNotProvided/2015-07-01-preview").ToString(); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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> /// GET method with api-version modeled in global settings. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> GetPathGlobalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetPathGlobalValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/path/string/none/query/global/2015-07-01-preview").ToString(); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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> /// GET method with api-version modeled in global settings. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> GetSwaggerGlobalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetSwaggerGlobalValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/swagger/string/none/query/global/2015-07-01-preview").ToString(); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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; } } }
#region Using Directives #endregion namespace SPALM.SPSF.Library.Actions { using System.IO; using System.Windows.Forms; using System.Xml; using EnvDTE; using Microsoft.Practices.ComponentModel; using Microsoft.Practices.RecipeFramework; using Microsoft.Practices.RecipeFramework.Services; /// <summary> /// Add a new item to a given folder /// </summary> [ServiceDependency(typeof(DTE))] public class EnableWorkflowFoundation : ConfigurableAction { [Input(Required = true)] public Project Project { get { return this.project; } set { this.project = value; } } private Project project; protected string GetBasePath() { return base.GetService<IConfigurationService>(true).BasePath; } protected string GetPackageGuid() { return base.GetService<IConfigurationService>(true).CurrentPackage.Guid; } protected string GetPackageCaption() { return base.GetService<IConfigurationService>(true).CurrentPackage.Caption; } private string GetTemplateBasePath() { return new DirectoryInfo(this.GetBasePath() + @"\Templates").FullName; } public void SetProjectTypeGuids(Project proj) { string templatesDir = Path.Combine(GetTemplateBasePath(), "Items.Cache"); //Helpers.EnsureGaxPackageRegistration("{14822709-B5A1-4724-98CA-57A101D1B079}", GetPackageGuid(), templatesDir, GetPackageCaption()); Helpers.EnsureGaxPackageRegistration("{14822709-B5A1-4724-98CA-57A101D1B079}", "{14822709-B5A1-4724-98CA-57A101D1B079}", templatesDir, GetPackageCaption()); string projectTypeGuids = ""; object service = null; Microsoft.VisualStudio.Shell.Interop.IVsSolution solution = null; Microsoft.VisualStudio.Shell.Interop.IVsHierarchy hierarchy = null; Microsoft.VisualStudio.Shell.Interop.IVsAggregatableProject aggregatableProject = null; int result = 0; service = GetService(typeof(Microsoft.VisualStudio.Shell.Interop.IVsSolution)); solution = (Microsoft.VisualStudio.Shell.Interop.IVsSolution)service; result = solution.GetProjectOfUniqueName(proj.UniqueName, out hierarchy); if (result == 0) { aggregatableProject = (Microsoft.VisualStudio.Shell.Interop.IVsAggregatableProject)hierarchy; result = aggregatableProject.GetAggregateProjectTypeGuids(out projectTypeGuids); //workflows if (!projectTypeGuids.ToUpper().Contains("{14822709-B5A1-4724-98CA-57A101D1B079}")) { if (projectTypeGuids == "") { projectTypeGuids = "{14822709-B5A1-4724-98CA-57A101D1B079}"; } else { projectTypeGuids = "{14822709-B5A1-4724-98CA-57A101D1B079}" + ";" + projectTypeGuids; } } //csharp if (!projectTypeGuids.ToUpper().Contains("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}")) { if (projectTypeGuids != "") { projectTypeGuids += ";"; } projectTypeGuids += "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"; } aggregatableProject.SetAggregateProjectTypeGuids(projectTypeGuids); } } public override void Execute() { SetProjectTypeGuids(project); //add import statement //<Import Project="$(MSBuildToolsPath)\Workflow.Targets" /> DTE service = (DTE)this.GetService(typeof(DTE)); string fileName = project.FullName; Helpers.SelectProject(project); if (service.SuppressUI || MessageBox.Show("The project file of project " + project.Name + " must be updated. Can SPSF save and unload the project?", "Unloading project", MessageBoxButtons.YesNo) == DialogResult.Yes) { service.Documents.CloseAll(vsSaveChanges.vsSaveChangesPrompt); try { Helpers.LogMessage(project.DTE, this, "Updating csproj file"); service.ExecuteCommand("File.SaveAll", string.Empty); service.ExecuteCommand("Project.UnloadProject", string.Empty); MigrateFile(fileName); service.ExecuteCommand("Project.ReloadProject", string.Empty); } catch { Helpers.LogMessage(project.DTE, this, "Could not update project file. Add following statement manually:"); Helpers.LogMessage(project.DTE, this, "<Import Project=\"$(MSBuildToolsPath)\\Workflow.Targets\" />"); } } } private void MigrateFile(string path) { XmlDocument csprojfile = new XmlDocument(); csprojfile.Load(path); XmlNamespaceManager newnsmgr = new XmlNamespaceManager(csprojfile.NameTable); newnsmgr.AddNamespace("ns", "http://schemas.microsoft.com/developer/msbuild/2003"); XmlNode nodeProject = csprojfile.SelectSingleNode("/ns:Project", newnsmgr); //check for nodeimport CheckImportNode(csprojfile, nodeProject, @"$(MSBuildToolsPath)\Workflow.Targets", ""); csprojfile.Save(path); } private void CheckImportNode(XmlDocument csprojfile, XmlNode nodeProject, string projectString, string conditionString) { Helpers.LogMessage((DTE)this.GetService(typeof(DTE)), this, "Adding new Import node"); XmlNamespaceManager newnsmgr = new XmlNamespaceManager(csprojfile.NameTable); newnsmgr.AddNamespace("ns", "http://schemas.microsoft.com/developer/msbuild/2003"); XmlNode nodeImport = csprojfile.SelectSingleNode("/ns:Project/ns:Import[@Project='" + projectString + "']", newnsmgr); if (nodeImport == null) { //ok, die 1. node ist noch nicht da XmlElement importNode = csprojfile.CreateElement("Import", "http://schemas.microsoft.com/developer/msbuild/2003"); nodeProject.AppendChild(importNode); XmlAttribute importAttribute = csprojfile.CreateAttribute("Project"); //, "http://schemas.microsoft.com/developer/msbuild/2003"); importAttribute.Value = projectString; importNode.Attributes.Append(importAttribute); if (conditionString != "") { XmlAttribute condiAttribute = csprojfile.CreateAttribute("Condition"); //, "http://schemas.microsoft.com/developer/msbuild/2003"); condiAttribute.Value = conditionString; importNode.Attributes.Append(condiAttribute); } } else { if (conditionString != "") { //ok, die node ist da, ist aber auch die condition richtig? if ((nodeImport.Attributes["Condition"] != null) && (nodeImport.Attributes["Condition"].Value.Trim() == conditionString)) { //ok, alles ist korrekt, wir machen nix } else { //ok, wenn condition da, dann wert setzen, ansonsten Conditionattribute erzeugen if (nodeImport.Attributes["Condition"] != null) { nodeImport.Attributes["Condition"].Value = conditionString; } else { XmlAttribute condiAttribute = csprojfile.CreateAttribute("Condition"); //, "http://schemas.microsoft.com/developer/msbuild/2003"); condiAttribute.Value = conditionString; nodeImport.Attributes.Append(condiAttribute); } } } } } /// <summary> /// Removes the previously added reference, if it was created /// </summary> public override void Undo() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Transactions.Tests { // Ported from Mono public class EnlistTest { #region Vol1_Dur0 /* Single volatile resource, SPC happens */ [Fact] public void Vol1_Dur0() { IntResourceManager irm = new IntResourceManager(1); irm.UseSingle = true; using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; scope.Complete(); } irm.CheckSPC("irm"); } [Fact] public void Vol1_Dur0_2PC() { IntResourceManager irm = new IntResourceManager(1); using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; scope.Complete(); } irm.Check2PC("irm"); } /* Single volatile resource, SPC happens */ [Fact] public void Vol1_Dur0_Fail1() { IntResourceManager irm = new IntResourceManager(1); irm.UseSingle = true; using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; /* Not completing this.. scope.Complete ();*/ } irm.Check(0, 0, 0, 1, 0, 0, 0, "irm"); } [Fact] public void Vol1_Dur0_Fail2() { Assert.Throws<TransactionAbortedException>(() => { IntResourceManager irm = new IntResourceManager(1); irm.FailPrepare = true; using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; scope.Complete(); } }); } [Fact] public void Vol1_Dur0_Fail3() { Assert.Throws<TransactionAbortedException>(() => { IntResourceManager irm = new IntResourceManager(1); irm.UseSingle = true; irm.FailSPC = true; using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; scope.Complete(); } }); } #endregion #region Vol2_Dur0 /* >1 volatile, 2PC */ [Fact] public void Vol2_Dur0_SPC() { IntResourceManager irm = new IntResourceManager(1); IntResourceManager irm2 = new IntResourceManager(3); irm.UseSingle = true; irm2.UseSingle = true; using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; irm2.Value = 6; scope.Complete(); } irm.Check2PC("irm"); irm2.Check2PC("irm2"); } #endregion #region Vol0_Dur1 /* 1 durable */ [Fact] public void Vol0_Dur1() { IntResourceManager irm = new IntResourceManager(1); irm.Type = ResourceManagerType.Durable; irm.UseSingle = true; using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; scope.Complete(); } irm.CheckSPC("irm"); } /* We support only 1 durable with 2PC * On .net, this becomes a distributed transaction */ [ActiveIssue("Distributed transactions are not supported.")] [Fact] public void Vol0_Dur1_2PC() { IntResourceManager irm = new IntResourceManager(1); /* Durable resource enlisted with a IEnlistedNotification * object */ irm.Type = ResourceManagerType.Durable; using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; scope.Complete(); } } [Fact] public void Vol0_Dur1_Fail() { IntResourceManager irm = new IntResourceManager(1); /* Durable resource enlisted with a IEnlistedNotification * object */ irm.Type = ResourceManagerType.Durable; irm.FailSPC = true; irm.UseSingle = true; Assert.Throws<TransactionAbortedException>(() => { using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; scope.Complete(); } }); irm.Check(1, 0, 0, 0, 0, 0, 0, "irm"); } #endregion #region Vol2_Dur1 /* >1vol + 1 durable */ [Fact] public void Vol2_Dur1() { IntResourceManager[] irm = new IntResourceManager[4]; irm[0] = new IntResourceManager(1); irm[1] = new IntResourceManager(3); irm[2] = new IntResourceManager(5); irm[3] = new IntResourceManager(7); irm[0].Type = ResourceManagerType.Durable; for (int i = 0; i < 4; i++) irm[i].UseSingle = true; using (TransactionScope scope = new TransactionScope()) { irm[0].Value = 2; irm[1].Value = 6; irm[2].Value = 10; irm[3].Value = 14; scope.Complete(); } irm[0].CheckSPC("irm [0]"); /* Volatile RMs get 2PC */ for (int i = 1; i < 4; i++) irm[i].Check2PC("irm [" + i + "]"); } /* >1vol + 1 durable * Durable fails SPC */ [Fact] public void Vol2_Dur1_Fail1() { IntResourceManager[] irm = new IntResourceManager[4]; irm[0] = new IntResourceManager(1); irm[1] = new IntResourceManager(3); irm[2] = new IntResourceManager(5); irm[3] = new IntResourceManager(7); irm[0].Type = ResourceManagerType.Durable; irm[0].FailSPC = true; for (int i = 0; i < 4; i++) irm[i].UseSingle = true; /* Durable RM irm[0] does Abort on SPC, so * all volatile RMs get Rollback */ Assert.Throws<TransactionAbortedException>(() => { using (TransactionScope scope = new TransactionScope()) { irm[0].Value = 2; irm[1].Value = 6; irm[2].Value = 10; irm[3].Value = 14; scope.Complete(); } }); irm[0].CheckSPC("irm [0]"); /* Volatile RMs get 2PC Prepare, and then get rolled back */ for (int i = 1; i < 4; i++) irm[i].Check(0, 1, 0, 1, 0, 0, 0, "irm [" + i + "]"); } /* >1vol + 1 durable * Volatile fails Prepare */ [Fact] public void Vol2_Dur1_Fail3() { IntResourceManager[] irm = new IntResourceManager[4]; irm[0] = new IntResourceManager(1); irm[1] = new IntResourceManager(3); irm[2] = new IntResourceManager(5); irm[3] = new IntResourceManager(7); irm[0].Type = ResourceManagerType.Durable; irm[2].FailPrepare = true; for (int i = 0; i < 4; i++) irm[i].UseSingle = true; /* Durable RM irm[2] does on SPC, so * all volatile RMs get Rollback */ Assert.Throws<TransactionAbortedException>(() => { using (TransactionScope scope = new TransactionScope()) { irm[0].Value = 2; irm[1].Value = 6; irm[2].Value = 10; irm[3].Value = 14; scope.Complete(); } }); irm[0].Check(0, 0, 0, 1, 0, 0, 0, "irm [0]"); /* irm [1] & [2] get prepare, * [2] -> ForceRollback, * [1] & [3] get rollback, * [0](durable) gets rollback */ irm[1].Check(0, 1, 0, 1, 0, 0, 0, "irm [1]"); irm[2].Check(0, 1, 0, 0, 0, 0, 0, "irm [2]"); irm[3].Check(0, 0, 0, 1, 0, 0, 0, "irm [3]"); } [Fact] public void Vol2_Dur1_Fail4() { IntResourceManager[] irm = new IntResourceManager[2]; irm[0] = new IntResourceManager(1); irm[1] = new IntResourceManager(3); irm[0].Type = ResourceManagerType.Durable; irm[0].FailSPC = true; irm[0].FailWithException = true; for (int i = 0; i < 2; i++) irm[i].UseSingle = true; /* Durable RM irm[2] does on SPC, so * all volatile RMs get Rollback */ TransactionAbortedException e = Assert.Throws<TransactionAbortedException>(() => { using (TransactionScope scope = new TransactionScope()) { irm[0].Value = 2; irm[1].Value = 6; scope.Complete(); } }); Assert.IsType<NotSupportedException>(e.InnerException); irm[0].Check(1, 0, 0, 0, 0, 0, 0, "irm [0]"); irm[1].Check(0, 1, 0, 1, 0, 0, 0, "irm [1]"); } [Fact] public void Vol2_Dur1_Fail5() { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager[] irm = new IntResourceManager[2]; irm[0] = new IntResourceManager(1); irm[1] = new IntResourceManager(3); Transaction.Current = ct; irm[0].Type = ResourceManagerType.Durable; irm[0].FailSPC = true; irm[0].FailWithException = true; for (int i = 0; i < 2; i++) irm[i].UseSingle = true; /* Durable RM irm[2] does on SPC, so * all volatile RMs get Rollback */ using (TransactionScope scope = new TransactionScope()) { irm[0].Value = 2; irm[1].Value = 6; scope.Complete(); } TransactionAbortedException tae = Assert.Throws<TransactionAbortedException>(() => ct.Commit()); Assert.IsType<NotSupportedException>(tae.InnerException); irm[0].Check(1, 0, 0, 0, 0, 0, 0, "irm [0]"); irm[1].Check(0, 1, 0, 1, 0, 0, 0, "irm [1]"); InvalidOperationException ioe = Assert.Throws<InvalidOperationException>(() => ct.Commit()); Assert.Null(ioe.InnerException); Transaction.Current = null; } #endregion #region Promotable Single Phase Enlistment [Fact] public void Vol0_Dur0_Pspe1() { IntResourceManager irm = new IntResourceManager(1); irm.Type = ResourceManagerType.Promotable; using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; scope.Complete(); } irm.Check(1, 0, 0, 0, 0, 1, 0, "irm"); } [Fact] public void Vol1_Dur0_Pspe1() { IntResourceManager irm0 = new IntResourceManager(1); IntResourceManager irm1 = new IntResourceManager(1); irm1.Type = ResourceManagerType.Promotable; using (TransactionScope scope = new TransactionScope()) { irm0.Value = 2; irm1.Value = 8; scope.Complete(); } irm1.Check(1, 0, 0, 0, 0, 1, 0, "irm1"); } [Fact] public void Vol0_Dur1_Pspe1() { IntResourceManager irm0 = new IntResourceManager(1); IntResourceManager irm1 = new IntResourceManager(1); irm0.Type = ResourceManagerType.Durable; irm0.UseSingle = true; irm1.Type = ResourceManagerType.Promotable; using (TransactionScope scope = new TransactionScope()) { irm0.Value = 8; irm1.Value = 2; Assert.Equal(0, irm1.NumEnlistFailed); } // TODO: Technically this is not correct. A call to EnlistPromotableSinglePhase is called AFTER a // DurableEnlist for a given transaction will return "false", which should probably be considered // an enlistment failure. An exception is not thrown, but the PSPE still "failed" } [Fact] public void Vol0_Dur0_Pspe2() { IntResourceManager irm0 = new IntResourceManager(1); IntResourceManager irm1 = new IntResourceManager(1); irm0.Type = ResourceManagerType.Promotable; irm1.Type = ResourceManagerType.Promotable; using (TransactionScope scope = new TransactionScope()) { irm0.Value = 8; irm1.Value = 2; Assert.Equal(0, irm1.NumEnlistFailed); } // TODO: Technically this is not correct. A call to EnlistPromotableSinglePhase is called AFTER a // successful EnlistPromotableSinglePhase for a given transaction will return "false", which should // probably be considered an enlistment failure. An exception is not thrown, but the second PSPE still "failed". } #endregion #region Others /* >1vol * > 1 durable, On .net this becomes a distributed transaction * We don't support this in mono yet. */ [ActiveIssue("Distributed transactions are not supported.")] [Fact] public void Vol0_Dur2() { IntResourceManager[] irm = new IntResourceManager[2]; irm[0] = new IntResourceManager(1); irm[1] = new IntResourceManager(3); irm[0].Type = ResourceManagerType.Durable; irm[1].Type = ResourceManagerType.Durable; for (int i = 0; i < 2; i++) irm[i].UseSingle = true; using (TransactionScope scope = new TransactionScope()) { irm[0].Value = 2; irm[1].Value = 6; scope.Complete(); } } [Fact] public void TransactionDispose() { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); irm.Type = ResourceManagerType.Durable; ct.Dispose(); irm.Check(0, 0, 0, 0, "Dispose transaction"); } [Fact] public void TransactionDispose2() { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); Transaction.Current = ct; irm.Value = 5; try { ct.Dispose(); } finally { Transaction.Current = null; } irm.Check(0, 0, 1, 0, "Dispose transaction"); Assert.Equal(1, irm.Value); } [Fact] public void TransactionDispose3() { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); try { Transaction.Current = ct; irm.Value = 5; ct.Commit(); ct.Dispose(); } finally { Transaction.Current = null; } irm.Check(1, 1, 0, 0, "Dispose transaction"); Assert.Equal(5, irm.Value); } #endregion #region TransactionCompleted [Fact] public void TransactionCompleted_Committed() { bool called = false; using (var ts = new TransactionScope()) { var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => called = true; ts.Complete(); } Assert.True(called, "TransactionCompleted event handler not called!"); } [Fact] public void TransactionCompleted_Rollback() { bool called = false; using (var ts = new TransactionScope()) { var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => called = true; // Not calling ts.Complete() on purpose.. } Assert.True(called, "TransactionCompleted event handler not called!"); } #endregion #region Success/Failure behavior tests #region Success/Failure behavior Vol1_Dur0 Cases [Fact] public void Vol1SPC_Committed() { bool called = false; TransactionStatus status = TransactionStatus.Active; var rm = new IntResourceManager(1) { UseSingle = true, Type = ResourceManagerType.Volatile }; using (var ts = new TransactionScope()) { rm.Value = 2; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; ts.Complete(); } rm.Check(1, 0, 0, 0, 0, 0, 0, "rm"); Assert.True(called, "TransactionCompleted event handler not called!"); Assert.Equal(TransactionStatus.Committed, status); } [Fact] public void Vol1_Committed() { bool called = false; TransactionStatus status = TransactionStatus.Active; var rm = new IntResourceManager(1) { Type = ResourceManagerType.Volatile, }; using (var ts = new TransactionScope()) { rm.Value = 2; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; ts.Complete(); } rm.Check(0, 1, 1, 0, 0, 0, 0, "rm"); Assert.True(called, "TransactionCompleted event handler not called!"); Assert.Equal(TransactionStatus.Committed, status); } [Fact] public void Vol1_Rollback() { bool called = false; TransactionStatus status = TransactionStatus.Active; var rm = new IntResourceManager(1) { Type = ResourceManagerType.Volatile, }; using (var ts = new TransactionScope()) { rm.Value = 2; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; // Not calling ts.Complete() on purpose.. } rm.Check(0, 0, 0, 1, 0, 0, 0, "rm"); Assert.True(called, "TransactionCompleted event handler not called!"); Assert.Equal(TransactionStatus.Aborted, status); } [Fact] public void Vol1SPC_Throwing_On_Commit() { bool called = false; Exception ex = null; TransactionStatus status = TransactionStatus.Active; var rm = new IntResourceManager(1) { UseSingle = true, FailSPC = true, FailWithException = true, Type = ResourceManagerType.Volatile }; try { using (var ts = new TransactionScope()) { rm.Value = 2; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; ts.Complete(); } } catch (Exception _ex) { ex = _ex; } rm.Check(1, 0, 0, 0, 0, 0, 0, "rm"); Assert.True(called, "TransactionCompleted event handler not called!"); Assert.Equal(TransactionStatus.Aborted, status); Assert.NotNull(ex); Assert.IsType<TransactionAbortedException>(ex); Assert.NotNull(ex.InnerException); Assert.IsType<NotSupportedException>(ex.InnerException); } [Fact] public void Vol1_Throwing_On_Commit() { bool called = false; TransactionStatus status = TransactionStatus.Active; Exception ex = null; var rm = new IntResourceManager(1) { FailCommit = true, FailWithException = true, Type = ResourceManagerType.Volatile }; try { using (var ts = new TransactionScope()) { rm.Value = 2; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; ts.Complete(); } } catch (Exception _ex) { ex = _ex; } rm.Check(0, 1, 1, 0, 0, 0, 0, "rm"); // MS.NET wont call TransactionCompleted event in this particular case. Assert.False(called, "TransactionCompleted event handler _was_ called!?!?!"); Assert.IsType<NotSupportedException>(ex); } [Fact] public void Vol1_Throwing_On_Rollback() { bool called = false; TransactionStatus status = TransactionStatus.Active; Exception ex = null; var rm = new IntResourceManager(1) { FailRollback = true, FailWithException = true, Type = ResourceManagerType.Volatile }; try { using (var ts = new TransactionScope()) { rm.Value = 2; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; // Not calling ts.Complete() on purpose.. } } catch (Exception _ex) { ex = _ex; } rm.Check(0, 0, 0, 1, 0, 0, 0, "rm"); // MS.NET wont call TransactionCompleted event in this particular case. Assert.False(called, "TransactionCompleted event handler _was_ called!?!?!"); Assert.NotNull(ex); // MS.NET will relay the exception thrown by RM instead of wrapping it on a TransactionAbortedException. Assert.IsType<NotSupportedException>(ex); } [Fact] public void Vol1_Throwing_On_Prepare() { bool called = false; TransactionStatus status = TransactionStatus.Active; Exception ex = null; var rm = new IntResourceManager(1) { FailPrepare = true, FailWithException = true, Type = ResourceManagerType.Volatile }; try { using (var ts = new TransactionScope()) { rm.Value = 2; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; ts.Complete(); } } catch (Exception _ex) { ex = _ex; } rm.Check(0, 1, 0, 0, 0, 0, 0, "rm"); Assert.True(called, "TransactionCompleted event handler not called!"); Assert.NotNull(ex); Assert.IsType<TransactionAbortedException>(ex); Assert.NotNull(ex.InnerException); Assert.IsType<NotSupportedException>(ex.InnerException); Assert.Equal(TransactionStatus.Aborted, status); } #endregion #region Success/Failure behavior Vol2_Dur0 Cases [Fact] public void Vol2SPC_Committed() { TransactionStatus status = TransactionStatus.Active; bool called = false; var rm1 = new IntResourceManager(1) { UseSingle = true, Type = ResourceManagerType.Volatile }; var rm2 = new IntResourceManager(2) { UseSingle = true, Type = ResourceManagerType.Volatile }; using (var ts = new TransactionScope()) { rm1.Value = 11; rm2.Value = 22; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; ts.Complete(); } // There can be only one *Single* PC enlistment, // so TM will downgrade both to normal enlistments. rm1.Check(0, 1, 1, 0, 0, 0, 0, "rm1"); rm2.Check(0, 1, 1, 0, 0, 0, 0, "rm2"); Assert.True(called, "TransactionCompleted event handler not called!"); Assert.Equal(TransactionStatus.Committed, status); } [Fact] public void Vol2_Committed() { TransactionStatus status = TransactionStatus.Active; bool called = false; var rm1 = new IntResourceManager(1) { Type = ResourceManagerType.Volatile }; var rm2 = new IntResourceManager(1) { Type = ResourceManagerType.Volatile }; using (var ts = new TransactionScope()) { rm1.Value = 11; rm2.Value = 22; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; ts.Complete(); } rm1.Check(0, 1, 1, 0, 0, 0, 0, "rm1"); rm2.Check(0, 1, 1, 0, 0, 0, 0, "rm2"); Assert.True(called, "TransactionCompleted event handler not called!"); Assert.Equal(TransactionStatus.Committed, status); } [Fact] public void Vol2_Rollback() { TransactionStatus status = TransactionStatus.Active; bool called = false; var rm1 = new IntResourceManager(1) { Type = ResourceManagerType.Volatile }; var rm2 = new IntResourceManager(1) { Type = ResourceManagerType.Volatile }; using (var ts = new TransactionScope()) { rm1.Value = 11; rm2.Value = 22; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; // Not calling ts.Complete() on purpose.. } rm1.Check(0, 0, 0, 1, 0, 0, 0, "rm1"); rm2.Check(0, 0, 0, 1, 0, 0, 0, "rm2"); Assert.True(called, "TransactionCompleted event handler not called!"); Assert.Equal(TransactionStatus.Aborted, status); } [Fact] public void Vol2SPC_Throwing_On_Commit() { TransactionStatus status = TransactionStatus.Active; bool called = false; Exception ex = null; var rm1 = new IntResourceManager(1) { UseSingle = true, FailCommit = true, FailWithException = true, ThrowThisException = new InvalidOperationException("rm1"), Type = ResourceManagerType.Volatile, }; var rm2 = new IntResourceManager(2) { UseSingle = true, Type = ResourceManagerType.Volatile, }; try { using (var ts = new TransactionScope()) { rm1.Value = 11; rm2.Value = 22; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; ts.Complete(); } } catch (Exception _ex) { ex = _ex; } // There can be only one *Single* PC enlistment, // so TM will downgrade both to normal enlistments. rm1.Check(0, 1, 1, 0, 0, 0, 0, "rm1"); rm2.Check(0, 1, 0, 0, 0, 0, 0, "rm2"); // MS.NET wont call TransactionCompleted event in this particular case. Assert.False(called, "TransactionCompleted event handler _was_ called!?!?!"); Assert.NotNull(ex); Assert.Equal(rm1.ThrowThisException, ex); } [Fact] public void Vol2_Throwing_On_Commit() { bool called = false; Exception ex = null; var rm1 = new IntResourceManager(1) { FailCommit = true, FailWithException = true, ThrowThisException = new InvalidOperationException("rm1"), Type = ResourceManagerType.Volatile }; var rm2 = new IntResourceManager(2) { Type = ResourceManagerType.Volatile }; try { using (var ts = new TransactionScope()) { rm1.Value = 11; rm2.Value = 22; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => called = true; ts.Complete(); } } catch (Exception _ex) { ex = _ex; } rm1.Check(0, 1, 1, 0, 0, 0, 0, "rm1"); rm2.Check(0, 1, 0, 0, 0, 0, 0, "rm2"); // MS.NET wont call TransactionCompleted event in this particular case. Assert.False(called, "TransactionCompleted event handler _was_ called!?!?!"); Assert.NotNull(ex); Assert.Equal(rm1.ThrowThisException, ex); } [Fact] public void Vol2_Throwing_On_Rollback() { bool called = false; Exception ex = null; var rm1 = new IntResourceManager(1) { FailRollback = true, FailWithException = true, ThrowThisException = new InvalidOperationException("rm1"), Type = ResourceManagerType.Volatile }; var rm2 = new IntResourceManager(2) { Type = ResourceManagerType.Volatile }; try { using (var ts = new TransactionScope()) { rm1.Value = 11; rm2.Value = 22; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => called = true; // Not calling ts.Complete() on purpose.. } } catch (Exception _ex) { ex = _ex; } rm1.Check(0, 0, 0, 1, 0, 0, 0, "rm1"); rm2.Check(0, 0, 0, 0, 0, 0, 0, "rm2"); // MS.NET wont call TransactionCompleted event in this particular case. Assert.False(called, "TransactionCompleted event handler _was_ called!?!?!"); Assert.NotNull(ex); // MS.NET will relay the exception thrown by RM instead of wrapping it on a TransactionAbortedException. Assert.Equal(rm1.ThrowThisException, ex); } [Fact] public void Vol2_Throwing_On_First_Prepare() { TransactionStatus status = TransactionStatus.Active; bool called = false; Exception ex = null; var rm1 = new IntResourceManager(1) { FailPrepare = true, FailWithException = true, ThrowThisException = new InvalidOperationException("rm1"), Type = ResourceManagerType.Volatile }; var rm2 = new IntResourceManager(2) { Type = ResourceManagerType.Volatile }; try { using (var ts = new TransactionScope()) { rm1.Value = 11; rm2.Value = 22; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; ts.Complete(); } } catch (Exception _ex) { ex = _ex; } rm1.Check(0, 1, 0, 0, 0, 0, 0, "rm1"); rm2.Check(0, 0, 0, 1, 0, 0, 0, "rm2"); Assert.True(called, "TransactionCompleted event handler not called!"); Assert.NotNull(ex); Assert.IsType<TransactionAbortedException>(ex); Assert.NotNull(ex.InnerException); Assert.IsType<InvalidOperationException>(ex.InnerException); Assert.Equal(TransactionStatus.Aborted, status); } [Fact] public void Vol2_Throwing_On_Second_Prepare() { TransactionStatus status = TransactionStatus.Active; bool called = false; Exception ex = null; var rm1 = new IntResourceManager(1) { Type = ResourceManagerType.Volatile }; var rm2 = new IntResourceManager(2) { FailPrepare = true, FailWithException = true, Type = ResourceManagerType.Volatile }; try { using (var ts = new TransactionScope()) { rm1.Value = 11; rm2.Value = 22; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; ts.Complete(); } } catch (Exception _ex) { ex = _ex; } rm1.Check(0, 1, 0, 1, 0, 0, 0, "rm1"); rm2.Check(0, 1, 0, 0, 0, 0, 0, "rm2"); Assert.True(called, "TransactionCompleted event handler not called!"); Assert.NotNull(ex); Assert.IsType<TransactionAbortedException>(ex); Assert.NotNull(ex.InnerException); Assert.IsType<NotSupportedException>(ex.InnerException); Assert.Equal(TransactionStatus.Aborted, status); } [Fact] public void Vol2_Throwing_On_First_Prepare_And_Second_Rollback() { TransactionStatus status = TransactionStatus.Active; bool called = false; Exception ex = null; var rm1 = new IntResourceManager(1) { FailPrepare = true, FailWithException = true, ThrowThisException = new InvalidOperationException("rm1"), Type = ResourceManagerType.Volatile }; var rm2 = new IntResourceManager(2) { FailRollback = true, FailWithException = true, ThrowThisException = new InvalidOperationException("rm2"), Type = ResourceManagerType.Volatile }; try { using (var ts = new TransactionScope()) { rm1.Value = 11; rm2.Value = 22; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; ts.Complete(); } } catch (Exception _ex) { ex = _ex; } rm1.Check(0, 1, 0, 0, 0, 0, 0, "rm1"); rm2.Check(0, 0, 0, 1, 0, 0, 0, "rm2"); // MS.NET wont call TransactionCompleted event in this particular case. Assert.False(called, "TransactionCompleted event handler _was_ called!?!?!"); Assert.NotNull(ex); Assert.Equal(rm2.ThrowThisException, ex); } [Fact] public void Vol2_Throwing_On_First_Rollback_And_Second_Prepare() { TransactionStatus status = TransactionStatus.Active; bool called = false; Exception ex = null; var rm1 = new IntResourceManager(1) { FailRollback = true, FailWithException = true, ThrowThisException = new InvalidOperationException("rm1"), Type = ResourceManagerType.Volatile }; var rm2 = new IntResourceManager(2) { FailPrepare = true, FailWithException = true, ThrowThisException = new InvalidOperationException("rm2"), Type = ResourceManagerType.Volatile }; try { using (var ts = new TransactionScope()) { rm1.Value = 11; rm2.Value = 22; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; ts.Complete(); } } catch (Exception _ex) { ex = _ex; } rm1.Check(0, 1, 0, 1, 0, 0, 0, "rm1"); rm2.Check(0, 1, 0, 0, 0, 0, 0, "rm2"); // MS.NET wont call TransactionCompleted event in this particular case. Assert.False(called, "TransactionCompleted event handler _was_ called!?!?!"); Assert.NotNull(ex); Assert.Equal(rm1.ThrowThisException, ex); } #endregion #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void CompareEqualUInt16() { var test = new SimpleBinaryOpTest__CompareEqualUInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareEqualUInt16 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(UInt16); private const int Op2ElementCount = VectorSize / sizeof(UInt16); private const int RetElementCount = VectorSize / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static Vector128<UInt16> _clsVar1; private static Vector128<UInt16> _clsVar2; private Vector128<UInt16> _fld1; private Vector128<UInt16> _fld2; private SimpleBinaryOpTest__DataTable<UInt16, UInt16, UInt16> _dataTable; static SimpleBinaryOpTest__CompareEqualUInt16() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__CompareEqualUInt16() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<UInt16, UInt16, UInt16>(_data1, _data2, new UInt16[RetElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.CompareEqual( Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.CompareEqual( Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.CompareEqual( Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareEqual), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareEqual), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareEqual), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.CompareEqual( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr); var result = Sse2.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__CompareEqualUInt16(); var result = Sse2.CompareEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.CompareEqual(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<UInt16> left, Vector128<UInt16> right, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "") { if (result[0] != ((left[0] == right[0]) ? unchecked((ushort)(-1)) : 0)) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((left[i] == right[i]) ? unchecked((ushort)(-1)) : 0)) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.CompareEqual)}<UInt16>(Vector128<UInt16>, Vector128<UInt16>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Reflection; using System.IO; namespace Microsoft.Scripting.Metadata { internal sealed class MetadataImport { private readonly MemoryBlock _image; private const int TableCount = (int)MetadataRecordType.GenericParamConstraint + 1; internal MetadataImport(MemoryBlock image) { _image = image; try { ReadPEFileLevelData(); ReadCORModuleLevelData(); ReadMetadataLevelData(); } catch (ArgumentOutOfRangeException) { throw new BadImageFormatException(); } } #region PE File private int _numberOfSections; private OptionalHeaderDirectoryEntries _optionalHeaderDirectoryEntries; private SectionHeader[] _sectionHeaders; // private MemoryBlock _win32ResourceBlock; private void ReadOptionalHeaderDirectoryEntries(MemoryReader memReader) { // ExportTableDirectory // ImportTableDirectory memReader.SeekRelative(2 * 2 * sizeof(uint)); _optionalHeaderDirectoryEntries.ResourceTableDirectory.RelativeVirtualAddress = memReader.ReadUInt32(); _optionalHeaderDirectoryEntries.ResourceTableDirectory.Size = memReader.ReadUInt32(); // ExceptionTableDirectory // CertificateTableDirectory // BaseRelocationTableDirectory // DebugTableDirectory // CopyrightTableDirectory // GlobalPointerTableDirectory // ThreadLocalStorageTableDirectory // LoadConfigTableDirectory // BoundImportTableDirectory // ImportAddressTableDirectory // DelayImportTableDirectory memReader.SeekRelative(11 * 2 * sizeof(uint)); _optionalHeaderDirectoryEntries.COR20HeaderTableDirectory.RelativeVirtualAddress = memReader.ReadUInt32(); _optionalHeaderDirectoryEntries.COR20HeaderTableDirectory.Size = memReader.ReadUInt32(); // ReservedDirectory memReader.SeekRelative(1 * 2 * sizeof(uint)); } private void ReadSectionHeaders(MemoryReader memReader) { if (memReader.RemainingBytes < _numberOfSections * PEFileConstants.SizeofSectionHeader) { throw new BadImageFormatException(); } _sectionHeaders = new SectionHeader[_numberOfSections]; SectionHeader[] sectionHeaderArray = _sectionHeaders; for (int i = 0; i < _numberOfSections; i++) { memReader.SeekRelative(PEFileConstants.SizeofSectionName); sectionHeaderArray[i].VirtualSize = memReader.ReadUInt32(); sectionHeaderArray[i].VirtualAddress = memReader.ReadUInt32(); sectionHeaderArray[i].SizeOfRawData = memReader.ReadUInt32(); sectionHeaderArray[i].OffsetToRawData = memReader.ReadUInt32(); //sectionHeaderArray[i].RVAToRelocations = memReader.ReadInt32(); //sectionHeaderArray[i].PointerToLineNumbers = memReader.ReadInt32(); //sectionHeaderArray[i].NumberOfRelocations = memReader.ReadUInt16(); //sectionHeaderArray[i].NumberOfLineNumbers = memReader.ReadUInt16(); //sectionHeaderArray[i].SectionCharacteristics = (SectionCharacteristics)memReader.ReadUInt32(); memReader.SeekRelative(2 * sizeof(int) + 2 * sizeof(ushort) + sizeof(uint)); } } private void ReadPEFileLevelData() { if (_image.Length < PEFileConstants.BasicPEHeaderSize) { throw new BadImageFormatException(); } MemoryReader memReader = new MemoryReader(_image); // Look for DOS Signature "MZ" ushort dosSig = _image.ReadUInt16(0); if (dosSig != PEFileConstants.DosSignature) { throw new BadImageFormatException(); } // Skip the DOS Header int ntHeaderOffset = _image.ReadInt32(PEFileConstants.PESignatureOffsetLocation); memReader.Seek(ntHeaderOffset); // Look for PESignature "PE\0\0" uint signature = memReader.ReadUInt32(); if (signature != PEFileConstants.PESignature) { throw new BadImageFormatException(); } // Read the COFF Header _numberOfSections = memReader.Block.ReadUInt16(memReader.Position + sizeof(ushort)); memReader.SeekRelative(PEFileConstants.SizeofCOFFFileHeader); // Read the magic to determine if its PE or PE+ switch ((PEMagic)memReader.ReadUInt16()) { case PEMagic.PEMagic32: memReader.SeekRelative(PEFileConstants.SizeofOptionalHeaderStandardFields32 - sizeof(ushort)); memReader.SeekRelative(PEFileConstants.SizeofOptionalHeaderNTAdditionalFields32); break; case PEMagic.PEMagic64: memReader.SeekRelative(PEFileConstants.SizeofOptionalHeaderStandardFields64 - sizeof(ushort)); memReader.SeekRelative(PEFileConstants.SizeofOptionalHeaderNTAdditionalFields64); break; default: throw new BadImageFormatException(); } ReadOptionalHeaderDirectoryEntries(memReader); ReadSectionHeaders(memReader); // _win32ResourceBlock = DirectoryToMemoryBlock(_optionalHeaderDirectoryEntries.ResourceTableDirectory); } internal MemoryBlock RvaToMemoryBlock(uint rva, uint size) { foreach (SectionHeader section in _sectionHeaders) { uint relativeOffset; if (rva >= section.VirtualAddress && (relativeOffset = rva - section.VirtualAddress) < section.VirtualSize) { uint maxSize; if (size > (maxSize = section.VirtualSize - relativeOffset)) { throw new BadImageFormatException(); } return _image.GetRange( unchecked((int)(section.OffsetToRawData + relativeOffset)), unchecked((int)(size == 0 ? maxSize : size)) ); } } throw new BadImageFormatException(); } private MemoryBlock DirectoryToMemoryBlock(DirectoryEntry directory) { if (directory.RelativeVirtualAddress == 0 || directory.Size == 0) { return null; } return RvaToMemoryBlock(directory.RelativeVirtualAddress, directory.Size); } #endregion #region COR Module private COR20Header _cor20Header; private StorageHeader _storageHeader; private StreamHeader[] _streamHeaders; private MemoryBlock _stringStream; private MemoryBlock _blobStream; private MemoryBlock _guidStream; private MemoryBlock _userStringStream; private MetadataStreamKind _metadataStreamKind; private MemoryBlock _metadataTableStream; // private MemoryBlock _resourceMemoryBlock; // private MemoryBlock _strongNameSignatureBlock; private void ReadCOR20Header() { MemoryBlock memBlock = DirectoryToMemoryBlock(_optionalHeaderDirectoryEntries.COR20HeaderTableDirectory); if (memBlock == null || memBlock.Length < _optionalHeaderDirectoryEntries.COR20HeaderTableDirectory.Size) { throw new BadImageFormatException(); } MemoryReader memReader = new MemoryReader(memBlock); // CountBytes = memReader.ReadInt32(); // MajorRuntimeVersion = memReader.ReadUInt16(); // MinorRuntimeVersion = memReader.ReadUInt16(); memReader.SeekRelative(sizeof(int) + 2 * sizeof(short)); _cor20Header.MetaDataDirectory.RelativeVirtualAddress = memReader.ReadUInt32(); _cor20Header.MetaDataDirectory.Size = memReader.ReadUInt32(); // COR20Header.COR20Flags = (COR20Flags)memReader.ReadUInt32(); // COR20Header.EntryPointTokenOrRVA = memReader.ReadUInt32(); memReader.SeekRelative(2 * sizeof(uint)); _cor20Header.ResourcesDirectory.RelativeVirtualAddress = memReader.ReadUInt32(); _cor20Header.ResourcesDirectory.Size = memReader.ReadUInt32(); _cor20Header.StrongNameSignatureDirectory.RelativeVirtualAddress = memReader.ReadUInt32(); _cor20Header.StrongNameSignatureDirectory.Size = memReader.ReadUInt32(); // CodeManagerTableDirectory // VtableFixupsDirectory // ExportAddressTableJumpsDirectory // ManagedNativeHeaderDirectory memReader.SeekRelative(4 * 2 * sizeof(uint)); } private void ReadMetadataHeader(MemoryReader memReader) { uint signature = memReader.ReadUInt32(); if (signature != COR20Constants.COR20MetadataSignature) { throw new BadImageFormatException(); } // MajorVersion = memReader.ReadUInt16(); // MinorVersion = memReader.ReadUInt16(); memReader.SeekRelative(2 * sizeof(ushort)); uint reserved = memReader.ReadUInt32(); if (reserved != 0) { throw new BadImageFormatException(); } int versionStringSize = memReader.ReadInt32(); memReader.SeekRelative(versionStringSize); } private void ReadStorageHeader(MemoryReader memReader) { _storageHeader.Flags = memReader.ReadUInt16(); _storageHeader.NumberOfStreams = memReader.ReadUInt16(); } private void ReadStreamHeaders(MemoryReader memReader) { int numberOfStreams = _storageHeader.NumberOfStreams; _streamHeaders = new StreamHeader[numberOfStreams]; StreamHeader[] streamHeaders = _streamHeaders; for (int i = 0; i < numberOfStreams; i++) { if (memReader.RemainingBytes < COR20Constants.MinimumSizeofStreamHeader) { throw new BadImageFormatException(); } streamHeaders[i].Offset = memReader.ReadUInt32(); streamHeaders[i].Size = memReader.ReadUInt32(); streamHeaders[i].Name = memReader.ReadAscii(32); memReader.Align(4); } } private void ProcessAndCacheStreams(MemoryBlock metadataRoot) { _metadataStreamKind = MetadataStreamKind.Illegal; foreach (StreamHeader streamHeader in _streamHeaders) { if ((long)streamHeader.Offset + streamHeader.Size > metadataRoot.Length) { throw new BadImageFormatException(); } MemoryBlock block = metadataRoot.GetRange((int)streamHeader.Offset, (int)streamHeader.Size); switch (streamHeader.Name) { case COR20Constants.StringStreamName: if (_stringStream != null) { throw new BadImageFormatException(); } // the first and the last byte of the heap must be zero: if (block.Length == 0 || block.ReadByte(0) != 0 || block.ReadByte(block.Length - 1) != 0) { throw new BadImageFormatException(); } _stringStream = block; break; case COR20Constants.BlobStreamName: if (_blobStream != null) { throw new BadImageFormatException(); } _blobStream = block; break; case COR20Constants.GUIDStreamName: if (_guidStream != null) { throw new BadImageFormatException(); } _guidStream = block; break; case COR20Constants.UserStringStreamName: if (_userStringStream != null) { throw new BadImageFormatException(); } _userStringStream = block; break; case COR20Constants.CompressedMetadataTableStreamName: if (_metadataStreamKind != MetadataStreamKind.Illegal) { throw new BadImageFormatException(); } _metadataStreamKind = MetadataStreamKind.Compressed; _metadataTableStream = block; break; case COR20Constants.UncompressedMetadataTableStreamName: if (_metadataStreamKind != MetadataStreamKind.Illegal) { throw new BadImageFormatException(); } _metadataStreamKind = MetadataStreamKind.UnCompressed; _metadataTableStream = block; break; default: throw new BadImageFormatException(); } } // mandatory streams: if (_stringStream == null || _guidStream == null || _metadataStreamKind == MetadataStreamKind.Illegal) { throw new BadImageFormatException(); } } private void ReadCORModuleLevelData() { ReadCOR20Header(); MemoryBlock metadataRoot = DirectoryToMemoryBlock(_cor20Header.MetaDataDirectory); if (metadataRoot == null || metadataRoot.Length < _cor20Header.MetaDataDirectory.Size) { throw new BadImageFormatException(); } MemoryReader memReader = new MemoryReader(metadataRoot); ReadMetadataHeader(memReader); ReadStorageHeader(memReader); ReadStreamHeaders(memReader); ProcessAndCacheStreams(metadataRoot); // _resourceMemoryBlock = DirectoryToMemoryBlock(_cor20Header.ResourcesDirectory); // _strongNameSignatureBlock = DirectoryToMemoryBlock(_cor20Header.StrongNameSignatureDirectory); } #endregion Methods [CORModule] #region Metadata private MetadataTableHeader _metadataTableHeader; private int[] _tableRowCounts; internal ModuleTable ModuleTable; internal TypeRefTable TypeRefTable; internal TypeDefTable TypeDefTable; internal FieldPtrTable FieldPtrTable; internal FieldTable FieldTable; internal MethodPtrTable MethodPtrTable; internal MethodTable MethodTable; internal ParamPtrTable ParamPtrTable; internal ParamTable ParamTable; internal InterfaceImplTable InterfaceImplTable; internal MemberRefTable MemberRefTable; internal ConstantTable ConstantTable; internal CustomAttributeTable CustomAttributeTable; internal FieldMarshalTable FieldMarshalTable; internal DeclSecurityTable DeclSecurityTable; internal ClassLayoutTable ClassLayoutTable; internal FieldLayoutTable FieldLayoutTable; internal StandAloneSigTable StandAloneSigTable; internal EventMapTable EventMapTable; internal EventPtrTable EventPtrTable; internal EventTable EventTable; internal PropertyMapTable PropertyMapTable; internal PropertyPtrTable PropertyPtrTable; internal PropertyTable PropertyTable; internal MethodSemanticsTable MethodSemanticsTable; internal MethodImplTable MethodImplTable; internal ModuleRefTable ModuleRefTable; internal TypeSpecTable TypeSpecTable; internal ImplMapTable ImplMapTable; internal FieldRVATable FieldRVATable; internal EnCLogTable EnCLogTable; internal EnCMapTable EnCMapTable; internal AssemblyTable AssemblyTable; internal AssemblyProcessorTable AssemblyProcessorTable; internal AssemblyOSTable AssemblyOSTable; internal AssemblyRefTable AssemblyRefTable; internal AssemblyRefProcessorTable AssemblyRefProcessorTable; internal AssemblyRefOSTable AssemblyRefOSTable; internal FileTable FileTable; internal ExportedTypeTable ExportedTypeTable; internal ManifestResourceTable ManifestResourceTable; internal NestedClassTable NestedClassTable; internal GenericParamTable GenericParamTable; internal MethodSpecTable MethodSpecTable; internal GenericParamConstraintTable GenericParamConstraintTable; internal bool IsManifestModule { get { return AssemblyTable.NumberOfRows == 1; } } internal bool UseFieldPtrTable { get { return FieldPtrTable.NumberOfRows > 0; } } internal bool UseMethodPtrTable { get { return MethodPtrTable.NumberOfRows > 0; } } internal bool UseParamPtrTable { get { return ParamPtrTable.NumberOfRows > 0; } } internal bool UseEventPtrTable { get { return EventPtrTable.NumberOfRows > 0; } } internal bool UsePropertyPtrTable { get { return PropertyPtrTable.NumberOfRows > 0; } } private void ReadMetadataTableInformation(MemoryReader memReader) { if (memReader.RemainingBytes < MetadataStreamConstants.SizeOfMetadataTableHeader) { throw new BadImageFormatException(); } // Reserved memReader.SeekRelative(sizeof(uint)); _metadataTableHeader.MajorVersion = memReader.ReadByte(); _metadataTableHeader.MinorVersion = memReader.ReadByte(); _metadataTableHeader.HeapSizeFlags = (HeapSizeFlag)memReader.ReadByte(); // Rid memReader.SeekRelative(sizeof(byte)); _metadataTableHeader.ValidTables = (TableMask)memReader.ReadUInt64(); _metadataTableHeader.SortedTables = (TableMask)memReader.ReadUInt64(); ulong presentTables = (ulong)_metadataTableHeader.ValidTables; ulong validTablesForVersion = 0; int version = _metadataTableHeader.MajorVersion << 8 | _metadataTableHeader.MinorVersion; switch (version) { case 0x0100: validTablesForVersion = (ulong)TableMask.V1_0_TablesMask; break; case 0x0101: validTablesForVersion = (ulong)TableMask.V1_1_TablesMask; break; case 0x0200: validTablesForVersion = (ulong)TableMask.V2_0_TablesMask; break; default: throw new BadImageFormatException(); } if ((presentTables & ~validTablesForVersion) != 0) { throw new BadImageFormatException(); } if (_metadataStreamKind == MetadataStreamKind.Compressed && (presentTables & (ulong)TableMask.CompressedStreamNotAllowedMask) != 0) { throw new BadImageFormatException(); } ulong requiredSortedTables = presentTables & validTablesForVersion & (ulong)TableMask.SortedTablesMask; if ((requiredSortedTables & (ulong)_metadataTableHeader.SortedTables) != requiredSortedTables) { throw new BadImageFormatException(); } int numberOfTables = _metadataTableHeader.GetNumberOfTablesPresent(); if (memReader.RemainingBytes < numberOfTables * sizeof(Int32)) { throw new BadImageFormatException(); } int[] metadataTableRowCount = _metadataTableHeader.CompressedMetadataTableRowCount = new int[numberOfTables]; for (int i = 0; i < numberOfTables; i++) { uint rowCount = memReader.ReadUInt32(); if (rowCount > 0x00ffffff) { throw new BadImageFormatException(); } metadataTableRowCount[i] = (int)rowCount; } } private static int ComputeCodedTokenSize(int largeRowSize, int[] rowCountArray, TableMask tablesReferenced) { bool isAllReferencedTablesSmall = true; ulong tablesReferencedMask = (ulong)tablesReferenced; for (int tableIndex = 0; tableIndex < TableCount; tableIndex++) { if ((tablesReferencedMask & 0x0000000000000001UL) != 0) { isAllReferencedTablesSmall &= (rowCountArray[tableIndex] < largeRowSize); } tablesReferencedMask >>= 1; } return isAllReferencedTablesSmall ? 2 : 4; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmaintainableCode")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] private void ProcessAndCacheMetadataTableBlocks(MemoryBlock metadataTablesMemoryBlock) { int[] rowCountArray = _tableRowCounts = new int[TableCount]; int[] rowRefSizeArray = new int[TableCount]; int[] rowCountCompressedArray = _metadataTableHeader.CompressedMetadataTableRowCount; ulong validTables = (ulong)_metadataTableHeader.ValidTables; // Fill in the row count and table reference sizes... for (int tableIndex = 0, arrayIndex = 0; tableIndex < rowRefSizeArray.Length; tableIndex++) { if ((validTables & 0x0000000000000001UL) != 0) { int rowCount = rowCountCompressedArray[arrayIndex++]; rowCountArray[tableIndex] = rowCount; rowRefSizeArray[tableIndex] = rowCount < MetadataStreamConstants.LargeTableRowCount ? 2 : 4; } else { rowRefSizeArray[tableIndex] = 2; } validTables >>= 1; } // Compute ref sizes for tables that can have pointer tables for it int fieldRefSize = rowRefSizeArray[FieldPtrTable.TableIndex] > 2 ? 4 : rowRefSizeArray[FieldPtrTable.TableIndex]; int methodRefSize = rowRefSizeArray[MethodPtrTable.TableIndex] > 2 ? 4 : rowRefSizeArray[MethodPtrTable.TableIndex]; int paramRefSize = rowRefSizeArray[ParamPtrTable.TableIndex] > 2 ? 4 : rowRefSizeArray[ParamPtrTable.TableIndex]; int eventRefSize = rowRefSizeArray[EventPtrTable.TableIndex] > 2 ? 4 : rowRefSizeArray[EventPtrTable.TableIndex]; int propertyRefSize = rowRefSizeArray[PropertyPtrTable.TableIndex] > 2 ? 4 : rowRefSizeArray[PropertyPtrTable.TableIndex]; // Compute the coded token ref sizes int typeDefOrRefRefSize = ComputeCodedTokenSize(TypeDefOrRefTag.LargeRowSize, rowCountArray, TypeDefOrRefTag.TablesReferenced); int hasConstantRefSize = ComputeCodedTokenSize(HasConstantTag.LargeRowSize, rowCountArray, HasConstantTag.TablesReferenced); int hasCustomAttributeRefSize = ComputeCodedTokenSize(HasCustomAttributeTag.LargeRowSize, rowCountArray, HasCustomAttributeTag.TablesReferenced); int hasFieldMarshalRefSize = ComputeCodedTokenSize(HasFieldMarshalTag.LargeRowSize, rowCountArray, HasFieldMarshalTag.TablesReferenced); int hasDeclSecurityRefSize = ComputeCodedTokenSize(HasDeclSecurityTag.LargeRowSize, rowCountArray, HasDeclSecurityTag.TablesReferenced); int memberRefParentRefSize = ComputeCodedTokenSize(MemberRefParentTag.LargeRowSize, rowCountArray, MemberRefParentTag.TablesReferenced); int hasSemanticsRefSize = ComputeCodedTokenSize(HasSemanticsTag.LargeRowSize, rowCountArray, HasSemanticsTag.TablesReferenced); int methodDefOrRefRefSize = ComputeCodedTokenSize(MethodDefOrRefTag.LargeRowSize, rowCountArray, MethodDefOrRefTag.TablesReferenced); int memberForwardedRefSize = ComputeCodedTokenSize(MemberForwardedTag.LargeRowSize, rowCountArray, MemberForwardedTag.TablesReferenced); int implementationRefSize = ComputeCodedTokenSize(ImplementationTag.LargeRowSize, rowCountArray, ImplementationTag.TablesReferenced); int customAttributeTypeRefSize = ComputeCodedTokenSize(CustomAttributeTypeTag.LargeRowSize, rowCountArray, CustomAttributeTypeTag.TablesReferenced); int resolutionScopeRefSize = ComputeCodedTokenSize(ResolutionScopeTag.LargeRowSize, rowCountArray, ResolutionScopeTag.TablesReferenced); int typeOrMethodDefRefSize = ComputeCodedTokenSize(TypeOrMethodDefTag.LargeRowSize, rowCountArray, TypeOrMethodDefTag.TablesReferenced); // Compute HeapRef Sizes int stringHeapRefSize = (_metadataTableHeader.HeapSizeFlags & HeapSizeFlag.StringHeapLarge) == HeapSizeFlag.StringHeapLarge ? 4 : 2; int guidHeapRefSize = (_metadataTableHeader.HeapSizeFlags & HeapSizeFlag.GUIDHeapLarge) == HeapSizeFlag.GUIDHeapLarge ? 4 : 2; int blobHeapRefSize = (_metadataTableHeader.HeapSizeFlags & HeapSizeFlag.BlobHeapLarge) == HeapSizeFlag.BlobHeapLarge ? 4 : 2; // Populate the Table blocks int totalRequiredSize = 0; int currentTableSize = 0; int currentPointer = 0; ModuleTable = new ModuleTable(rowCountArray[ModuleTable.TableIndex], stringHeapRefSize, guidHeapRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = ModuleTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; TypeRefTable = new TypeRefTable(rowCountArray[TypeRefTable.TableIndex], resolutionScopeRefSize, stringHeapRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = TypeRefTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; TypeDefTable = new TypeDefTable(rowCountArray[TypeDefTable.TableIndex], fieldRefSize, methodRefSize, typeDefOrRefRefSize, stringHeapRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = TypeDefTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; FieldPtrTable = new FieldPtrTable(rowCountArray[FieldPtrTable.TableIndex], rowRefSizeArray[FieldPtrTable.TableIndex], currentPointer, metadataTablesMemoryBlock); currentTableSize = FieldPtrTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; FieldTable = new FieldTable(rowCountArray[FieldTable.TableIndex], stringHeapRefSize, blobHeapRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = FieldTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; MethodPtrTable = new MethodPtrTable(rowCountArray[MethodPtrTable.TableIndex], rowRefSizeArray[MethodPtrTable.TableIndex], currentPointer, metadataTablesMemoryBlock); currentTableSize = MethodPtrTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; MethodTable = new MethodTable(rowCountArray[MethodTable.TableIndex], paramRefSize, stringHeapRefSize, blobHeapRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = MethodTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; ParamPtrTable = new ParamPtrTable(rowCountArray[ParamPtrTable.TableIndex], rowRefSizeArray[ParamPtrTable.TableIndex], currentPointer, metadataTablesMemoryBlock); currentTableSize = ParamPtrTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; ParamTable = new ParamTable(rowCountArray[ParamTable.TableIndex], stringHeapRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = ParamTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; InterfaceImplTable = new InterfaceImplTable(rowCountArray[InterfaceImplTable.TableIndex], rowRefSizeArray[InterfaceImplTable.TableIndex], typeDefOrRefRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = InterfaceImplTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; MemberRefTable = new MemberRefTable(rowCountArray[MemberRefTable.TableIndex], memberRefParentRefSize, stringHeapRefSize, blobHeapRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = MemberRefTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; ConstantTable = new ConstantTable(rowCountArray[ConstantTable.TableIndex], hasConstantRefSize, blobHeapRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = ConstantTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; CustomAttributeTable = new CustomAttributeTable(rowCountArray[CustomAttributeTable.TableIndex], hasCustomAttributeRefSize, customAttributeTypeRefSize, blobHeapRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = CustomAttributeTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; FieldMarshalTable = new FieldMarshalTable(rowCountArray[FieldMarshalTable.TableIndex], hasFieldMarshalRefSize, blobHeapRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = FieldMarshalTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; DeclSecurityTable = new DeclSecurityTable(rowCountArray[DeclSecurityTable.TableIndex], hasDeclSecurityRefSize, blobHeapRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = DeclSecurityTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; ClassLayoutTable = new ClassLayoutTable(rowCountArray[ClassLayoutTable.TableIndex], rowRefSizeArray[ClassLayoutTable.TableIndex], currentPointer, metadataTablesMemoryBlock); currentTableSize = ClassLayoutTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; FieldLayoutTable = new FieldLayoutTable(rowCountArray[FieldLayoutTable.TableIndex], rowRefSizeArray[FieldLayoutTable.TableIndex], currentPointer, metadataTablesMemoryBlock); currentTableSize = FieldLayoutTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; StandAloneSigTable = new StandAloneSigTable(rowCountArray[StandAloneSigTable.TableIndex], blobHeapRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = StandAloneSigTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; EventMapTable = new EventMapTable(rowCountArray[EventMapTable.TableIndex], rowRefSizeArray[EventMapTable.TableIndex], eventRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = EventMapTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; EventPtrTable = new EventPtrTable(rowCountArray[EventPtrTable.TableIndex], rowRefSizeArray[EventPtrTable.TableIndex], currentPointer, metadataTablesMemoryBlock); currentTableSize = EventPtrTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; EventTable = new EventTable(rowCountArray[EventTable.TableIndex], typeDefOrRefRefSize, stringHeapRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = EventTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; PropertyMapTable = new PropertyMapTable(rowCountArray[PropertyMapTable.TableIndex], rowRefSizeArray[PropertyMapTable.TableIndex], propertyRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = PropertyMapTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; PropertyPtrTable = new PropertyPtrTable(rowCountArray[PropertyPtrTable.TableIndex], rowRefSizeArray[PropertyPtrTable.TableIndex], currentPointer, metadataTablesMemoryBlock); currentTableSize = PropertyPtrTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; PropertyTable = new PropertyTable(rowCountArray[PropertyTable.TableIndex], stringHeapRefSize, blobHeapRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = PropertyTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; MethodSemanticsTable = new MethodSemanticsTable(rowCountArray[MethodSemanticsTable.TableIndex], rowRefSizeArray[MethodSemanticsTable.TableIndex], hasSemanticsRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = MethodSemanticsTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; MethodImplTable = new MethodImplTable(rowCountArray[MethodImplTable.TableIndex], rowRefSizeArray[MethodImplTable.TableIndex], methodDefOrRefRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = MethodImplTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; ModuleRefTable = new ModuleRefTable(rowCountArray[ModuleRefTable.TableIndex], stringHeapRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = ModuleRefTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; TypeSpecTable = new TypeSpecTable(rowCountArray[TypeSpecTable.TableIndex], blobHeapRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = TypeSpecTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; ImplMapTable = new ImplMapTable(rowCountArray[ImplMapTable.TableIndex], rowRefSizeArray[ImplMapTable.TableIndex], memberForwardedRefSize, stringHeapRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = ImplMapTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; FieldRVATable = new FieldRVATable(rowCountArray[FieldRVATable.TableIndex], rowRefSizeArray[FieldRVATable.TableIndex], currentPointer, metadataTablesMemoryBlock); currentTableSize = FieldRVATable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; EnCLogTable = new EnCLogTable(rowCountArray[EnCLogTable.TableIndex], currentPointer, metadataTablesMemoryBlock); currentTableSize = EnCLogTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; EnCMapTable = new EnCMapTable(rowCountArray[EnCMapTable.TableIndex], currentPointer, metadataTablesMemoryBlock); currentTableSize = EnCMapTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; AssemblyTable = new AssemblyTable(rowCountArray[AssemblyTable.TableIndex], stringHeapRefSize, blobHeapRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = AssemblyTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; AssemblyProcessorTable = new AssemblyProcessorTable(rowCountArray[AssemblyProcessorTable.TableIndex], currentPointer, metadataTablesMemoryBlock); currentTableSize = AssemblyProcessorTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; AssemblyOSTable = new AssemblyOSTable(rowCountArray[AssemblyOSTable.TableIndex], currentPointer, metadataTablesMemoryBlock); currentTableSize = AssemblyOSTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; AssemblyRefTable = new AssemblyRefTable(rowCountArray[AssemblyRefTable.TableIndex], stringHeapRefSize, blobHeapRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = AssemblyRefTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; AssemblyRefProcessorTable = new AssemblyRefProcessorTable(rowCountArray[AssemblyRefProcessorTable.TableIndex], rowRefSizeArray[AssemblyRefProcessorTable.TableIndex], currentPointer, metadataTablesMemoryBlock); currentTableSize = AssemblyRefProcessorTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; AssemblyRefOSTable = new AssemblyRefOSTable(rowCountArray[AssemblyRefOSTable.TableIndex], rowRefSizeArray[AssemblyRefOSTable.TableIndex], currentPointer, metadataTablesMemoryBlock); currentTableSize = AssemblyRefOSTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; FileTable = new FileTable(rowCountArray[FileTable.TableIndex], stringHeapRefSize, blobHeapRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = FileTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; ExportedTypeTable = new ExportedTypeTable(rowCountArray[ExportedTypeTable.TableIndex], implementationRefSize, stringHeapRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = ExportedTypeTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; ManifestResourceTable = new ManifestResourceTable(rowCountArray[ManifestResourceTable.TableIndex], implementationRefSize, stringHeapRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = ManifestResourceTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; NestedClassTable = new NestedClassTable(rowCountArray[NestedClassTable.TableIndex], rowRefSizeArray[NestedClassTable.TableIndex], currentPointer, metadataTablesMemoryBlock); currentTableSize = NestedClassTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; GenericParamTable = new GenericParamTable(rowCountArray[GenericParamTable.TableIndex], typeOrMethodDefRefSize, stringHeapRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = GenericParamTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; MethodSpecTable = new MethodSpecTable(rowCountArray[MethodSpecTable.TableIndex], methodDefOrRefRefSize, blobHeapRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = MethodSpecTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; GenericParamConstraintTable = new GenericParamConstraintTable(rowCountArray[GenericParamConstraintTable.TableIndex], rowRefSizeArray[GenericParamConstraintTable.TableIndex], typeDefOrRefRefSize, currentPointer, metadataTablesMemoryBlock); currentTableSize = GenericParamConstraintTable.Table.Length; totalRequiredSize += currentTableSize; currentPointer += currentTableSize; } private void ReadMetadataLevelData() { MemoryReader memReader = new MemoryReader(_metadataTableStream); ReadMetadataTableInformation(memReader); ProcessAndCacheMetadataTableBlocks(memReader.GetRemainingBlock()); if (ModuleTable.NumberOfRows != 1) { throw new BadImageFormatException(); } } #endregion #region Blobs and User Strings internal byte[] GetBlob(uint blob) { int dataOffset = GetBlobDataOffset(blob, out int size); var result = new byte[size]; _blobStream.Read(dataOffset, result); return result; } internal MemoryBlock GetBlobBlock(uint blob) { int dataOffset = GetBlobDataOffset(blob, out int size); return _blobStream.GetRange(dataOffset, size); } internal int GetBlobDataOffset(uint blob, out int size) { if (_blobStream == null || blob >= _blobStream.Length) { throw new BadImageFormatException(); } int offset = (int)blob; size = _blobStream.ReadCompressedInt32(offset, out int bytesRead); if (offset > _blobStream.Length - bytesRead - size) { throw new BadImageFormatException(); } return offset + bytesRead; } internal object GetBlobValue(uint blob, ElementType type) { int offset = GetBlobDataOffset(blob, out int size); if (size < GetMinTypeSize(type)) { throw new BadImageFormatException(); } switch (type) { case ElementType.Boolean: return _blobStream.ReadByte(offset) != 0; case ElementType.Char: return (char)_blobStream.ReadUInt16(offset); case ElementType.Int8: return _blobStream.ReadSByte(offset); case ElementType.UInt8: return _blobStream.ReadByte(offset); case ElementType.Int16: return _blobStream.ReadInt16(offset); case ElementType.UInt16: return _blobStream.ReadUInt16(offset); case ElementType.Int32: return _blobStream.ReadInt32(offset); case ElementType.UInt32: return _blobStream.ReadUInt32(offset); case ElementType.Int64: return _blobStream.ReadInt64(offset); case ElementType.UInt64: return _blobStream.ReadUInt64(offset); case ElementType.Single: return _blobStream.ReadSingle(offset); case ElementType.Double: return _blobStream.ReadDouble(offset); case ElementType.String: return _blobStream.ReadUtf16(offset, size); case ElementType.Class: if (_blobStream.ReadUInt32(offset) != 0) { throw new BadImageFormatException(); } return null; case ElementType.Void: return DBNull.Value; default: throw new BadImageFormatException(); } } private static int GetMinTypeSize(ElementType type) { switch (type) { case ElementType.Boolean: case ElementType.Int8: case ElementType.UInt8: return 1; case ElementType.Char: case ElementType.Int16: case ElementType.UInt16: return 2; case ElementType.Int32: case ElementType.UInt32: case ElementType.Single: case ElementType.Class: return 2; case ElementType.Int64: case ElementType.UInt64: case ElementType.Double: return 8; case ElementType.String: case ElementType.Void: return 0; } return Int32.MaxValue; } internal Guid GetGuid(uint blob) { if (blob - 1 > _guidStream.Length - 16) { throw new BadImageFormatException(); } if (blob == 0) { return Guid.Empty; } return _guidStream.ReadGuid((int)(blob - 1)); } #endregion #region Table Enumeration internal int GetFieldRange(int typeDefRid, out int count) { Debug.Assert(typeDefRid <= TypeDefTable.NumberOfRows); int numberOfFieldRows = UseFieldPtrTable ? FieldPtrTable.NumberOfRows : FieldTable.NumberOfRows; uint start = TypeDefTable.GetFirstFieldRid(typeDefRid); uint nextStart = (typeDefRid == TypeDefTable.NumberOfRows) ? (uint)numberOfFieldRows + 1 : TypeDefTable.GetFirstFieldRid(typeDefRid + 1); count = GetRangeCount(numberOfFieldRows, start, nextStart); return (int)start; } internal int GetMethodRange(int typeDefRid, out int count) { Debug.Assert(typeDefRid <= TypeDefTable.NumberOfRows); int numberOfMethodRows = UseMethodPtrTable ? MethodPtrTable.NumberOfRows : MethodTable.NumberOfRows; uint start = TypeDefTable.GetFirstMethodRid(typeDefRid); uint nextStart = (typeDefRid == TypeDefTable.NumberOfRows) ? (uint)numberOfMethodRows + 1 : TypeDefTable.GetFirstMethodRid(typeDefRid + 1); count = GetRangeCount(numberOfMethodRows, start, nextStart); return (int)start; } internal int GetEventRange(int typeDefRid, out int count) { Debug.Assert(typeDefRid <= TypeDefTable.NumberOfRows); int eventMapRid = EventMapTable.FindEventMapRowIdFor(typeDefRid); if (eventMapRid == 0) { count = 0; return 0; } int numberOfEventRows = UseEventPtrTable ? EventPtrTable.NumberOfRows : EventTable.NumberOfRows; uint start = EventMapTable.GetEventListStartFor(eventMapRid); uint nextStart = (eventMapRid == EventMapTable.NumberOfRows) ? (uint)numberOfEventRows + 1 : EventMapTable.GetEventListStartFor(eventMapRid + 1); count = GetRangeCount(numberOfEventRows, start, nextStart); return (int)start; } internal int GetPropertyRange(int typeDefRid, out int count) { Debug.Assert(typeDefRid <= TypeDefTable.NumberOfRows); int propertyMapRid = PropertyMapTable.FindPropertyMapRowIdFor(typeDefRid); if (propertyMapRid == 0) { count = 0; return 0; } int numberOfPropertyRows = UsePropertyPtrTable ? PropertyPtrTable.NumberOfRows : PropertyTable.NumberOfRows; uint start = PropertyMapTable.GetFirstPropertyRid(propertyMapRid); uint nextStart = (propertyMapRid == PropertyMapTable.NumberOfRows) ? (uint)numberOfPropertyRows + 1 : PropertyMapTable.GetFirstPropertyRid(propertyMapRid + 1); count = GetRangeCount(numberOfPropertyRows, start, nextStart); return (int)start; } private int GetRangeCount(int rowCount, uint start, uint nextStart) { if (start == 0) { return 0; } if (start > rowCount + 1 || nextStart > rowCount + 1 || start > nextStart) { throw new BadImageFormatException(); } return (int)(nextStart - start); } internal int GetParamRange(int methodDefRid, out int count) { Debug.Assert(methodDefRid <= MethodTable.NumberOfRows); int numberOfParamRows = UseParamPtrTable ? ParamPtrTable.NumberOfRows : ParamTable.NumberOfRows; uint start = MethodTable.GetFirstParamRid(methodDefRid); uint nextStart = (methodDefRid == MethodTable.NumberOfRows) ? (uint)numberOfParamRows + 1 : MethodTable.GetFirstParamRid(methodDefRid + 1); count = GetRangeCount(numberOfParamRows, start, nextStart); return (int)start; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] internal EnumerationIndirection GetEnumeratorRange(MetadataTokenType type, MetadataToken parent, out int startRid, out int count) { Debug.Assert(IsValidToken(parent)); switch (type) { case MetadataTokenType.MethodDef: if (parent.IsNull) { count = MethodTable.NumberOfRows; startRid = 1; } else { Debug.Assert(parent.IsTypeDef); startRid = GetMethodRange(parent.Rid, out count); } return UseParamPtrTable ? EnumerationIndirection.Method : EnumerationIndirection.None; case MetadataTokenType.Property: if (parent.IsNull) { count = PropertyTable.NumberOfRows; startRid = 1; } else { Debug.Assert(parent.IsTypeDef); startRid = GetPropertyRange(parent.Rid, out count); } return UsePropertyPtrTable ? EnumerationIndirection.Property : EnumerationIndirection.None; case MetadataTokenType.Event: if (parent.IsNull) { count = EventTable.NumberOfRows; startRid = 1; } else { Debug.Assert(parent.IsTypeDef); startRid = GetEventRange(parent.Rid, out count); } return UseEventPtrTable ? EnumerationIndirection.Event : EnumerationIndirection.None; case MetadataTokenType.FieldDef: if (parent.IsNull) { count = FieldTable.NumberOfRows; startRid = 1; } else { Debug.Assert(parent.IsTypeDef); startRid = GetFieldRange(parent.Rid, out count); } return UseFieldPtrTable ? EnumerationIndirection.Field : EnumerationIndirection.None; case MetadataTokenType.ParamDef: if (parent.IsNull) { count = ParamTable.NumberOfRows; startRid = 1; } else { Debug.Assert(parent.IsMethodDef); startRid = GetParamRange(parent.Rid, out count); } return UseParamPtrTable ? EnumerationIndirection.Param : EnumerationIndirection.None; case MetadataTokenType.CustomAttribute: if (parent.IsNull) { count = CustomAttributeTable.NumberOfRows; startRid = 1; } else { startRid = CustomAttributeTable.FindCustomAttributesForToken(parent, out count); } return EnumerationIndirection.None; case MetadataTokenType.InterfaceImpl: if (parent.IsNull) { count = InterfaceImplTable.NumberOfRows; startRid = 1; } else { Debug.Assert(parent.IsTypeDef); startRid = InterfaceImplTable.FindInterfaceImplForType(parent.Rid, out count); } return EnumerationIndirection.None; case MetadataTokenType.GenericPar: if (parent.IsNull) { count = GenericParamTable.NumberOfRows; startRid = 1; } else if (parent.IsTypeDef) { startRid = GenericParamTable.FindGenericParametersForType(parent.Rid, out count); } else { Debug.Assert(parent.IsMethodDef); startRid = GenericParamTable.FindGenericParametersForMethod(parent.Rid, out count); } return EnumerationIndirection.None; case MetadataTokenType.GenericParamConstraint: if (parent.IsNull) { count = GenericParamConstraintTable.NumberOfRows; startRid = 1; } else { Debug.Assert(parent.IsGenericParam); startRid = GenericParamConstraintTable.FindConstraintForGenericParam(parent.Rid, out count); } return EnumerationIndirection.None; case MetadataTokenType.AssemblyRef: case MetadataTokenType.ModuleRef: case MetadataTokenType.File: case MetadataTokenType.TypeDef: case MetadataTokenType.TypeSpec: case MetadataTokenType.TypeRef: case MetadataTokenType.NestedClass: case MetadataTokenType.ExportedType: case MetadataTokenType.MethodSpec: case MetadataTokenType.MemberRef: case MetadataTokenType.Signature: case MetadataTokenType.ManifestResource: Debug.Assert(parent.IsNull); count = _tableRowCounts[(int)type >> 24]; startRid = 1; return EnumerationIndirection.None; default: Debug.Assert(false); throw new InvalidOperationException(); } } #endregion internal bool IsValidToken(MetadataToken token) { int tableIndex = (int)token.RecordType; if (tableIndex < _tableRowCounts.Length) { return token.Rid <= _tableRowCounts[tableIndex]; } switch (tableIndex) { case (int)MetadataTokenType.String >> 24: return token.Rid < _stringStream.Length; case (int)MetadataTokenType.Name >> 24: return _userStringStream != null && token.Rid < _userStringStream.Length; } return false; } internal int GetRowCount(int tableIndex) { return _tableRowCounts[tableIndex]; } internal MetadataName GetMetadataName(uint blob) { return _stringStream.ReadName(blob); } internal object GetDefaultValue(MetadataToken token) { int constantRid = ConstantTable.GetConstantRowId(token); if (constantRid == 0) { return Missing.Value; } uint blob = ConstantTable.GetValue(constantRid, out ElementType type); return GetBlobValue(blob, type); } #region Test Support internal MemoryBlock Image { get { return _image; } } #endregion #region Dump #if DEBUG public unsafe void Dump(TextWriter output) { output.WriteLine("Image:"); output.WriteLine(" {0}", _image.Length); output.WriteLine(); output.WriteLine("COFF header:"); output.WriteLine(" NumberOfSections {0}", _numberOfSections); output.WriteLine(); output.WriteLine("Directories"); output.WriteLine(" ResourceTableDirectory +{0:X8} {1}", _optionalHeaderDirectoryEntries.ResourceTableDirectory.RelativeVirtualAddress, _optionalHeaderDirectoryEntries.ResourceTableDirectory.Size); output.WriteLine(" COR20HeaderTableDirectory +{0:X8} {1}", _optionalHeaderDirectoryEntries.COR20HeaderTableDirectory.RelativeVirtualAddress, _optionalHeaderDirectoryEntries.COR20HeaderTableDirectory.Size); output.WriteLine(); foreach (var section in _sectionHeaders) { output.WriteLine("Section"); output.WriteLine(" VirtualAddress {0}", section.VirtualAddress); output.WriteLine(" VirtualSize {0}", section.VirtualSize); output.WriteLine(" SizeOfRawData {0}", section.SizeOfRawData); output.WriteLine(" OffsetToRawData {0}", section.OffsetToRawData); } //output.WriteLine(); //output.WriteLine("Win32Resources:"); //output.WriteLine(" +{0:X8} {1}", _win32ResourceBlock.Pointer - _image.Pointer, _win32ResourceBlock.Length); output.WriteLine(); output.WriteLine("COR20 Header:"); output.WriteLine(" MetaDataDirectory @{0:X8} {1}", _cor20Header.MetaDataDirectory.RelativeVirtualAddress, _cor20Header.MetaDataDirectory.Size); output.WriteLine(" ResourcesDirectory @{0:X8} {1}", _cor20Header.ResourcesDirectory.RelativeVirtualAddress, _cor20Header.ResourcesDirectory.Size); output.WriteLine(" StrongNameSignatureDirectory @{0:X8} {1}", _cor20Header.StrongNameSignatureDirectory.RelativeVirtualAddress, _cor20Header.StrongNameSignatureDirectory.Size); output.WriteLine(); output.WriteLine("StorageHeader:"); output.WriteLine(" Flags {0}", _storageHeader.Flags); output.WriteLine(" NumberOfStreams {0}", _storageHeader.NumberOfStreams); output.WriteLine(); output.WriteLine("Streams:"); foreach (var stream in _streamHeaders) { output.WriteLine(" {0,-10} {1:X8} {2}", "'" + stream.Name + "'", stream.Offset, stream.Size); } output.WriteLine(); output.WriteLine("StringStream: +{0:X8}", _stringStream.Pointer - _image.Pointer); output.WriteLine("BlobStream: +{0:X8}", _blobStream != null ? (_blobStream.Pointer - _image.Pointer) : 0); output.WriteLine("GUIDStream: +{0:X8}", _guidStream.Pointer - _image.Pointer); output.WriteLine("UserStringStream: +{0:X8}", _userStringStream != null ? (_userStringStream.Pointer - _image.Pointer) : 0); output.WriteLine("MetadataTableStream: +{0:X8}", _metadataTableStream.Pointer - _image.Pointer); //output.WriteLine("ResourceMemoryReader: +{0:X8}", _resourceMemoryBlock != null ? (_resourceMemoryBlock.Pointer - _image.Pointer) : 0); output.WriteLine(); output.WriteLine("Misc:"); output.WriteLine(" MetadataStreamKind {0}", _metadataStreamKind); } #endif #endregion } }
/* | Version 10.1.84 | Copyright 2013 Esri | | 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.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Windows; using System.Windows.Data; using System.Windows.Media; using System.Windows.Threading; using ESRI.ArcLogistics.App.Controls; using ESRI.ArcLogistics.DomainObjects; using ESRI.ArcLogistics.Geocoding; using Xceed.Wpf.DataGrid; using Xceed.Wpf.DataGrid.Views; using Point = System.Windows.Point; namespace ESRI.ArcLogistics.App.GridHelpers { /// <summary> /// Class for managing popup which should point at cell with invalid item. /// </summary> internal class ValidationCalloutController { #region Constructor /// <summary> /// Constructor. /// </summary> /// <param name="dataGrid">DataGridControlEx.</param> /// public ValidationCalloutController(DataGridControlEx dataGrid) { // Check input parameter. Debug.Assert(dataGrid != null); // Init fields. _dataGrid = dataGrid; var context = DataGridControl.GetDataGridContext(_dataGrid); _collection = context.Items; // When page loaded - do validation and subscribe to events. dataGrid.Loaded += (sender, args) => { // Do initial validation. _Validate(); // Subscribe to events. _InitEventHandlers(); }; // When page unloaded - close callout and unsubscribe from events. dataGrid.Unloaded += (sender, args) => { // Close popup. _ClosePopup(false); // Unsubscribe from events. _UnsubscribeFromEvents(); }; // Init timer, which will hide callout. _InitTimer(); } #endregion #region Private Properties /// <summary> /// Popup, which will be shown near error cell. /// Use this property instead of '_callout' field. /// </summary> private Callout _Callout { get { if (_callout == null) _callout = new Callout(); return _callout; } } /// <summary> /// Invalid item. /// Use this property instead of "_invalidItem" field. /// </summary> /// <remarks>When setting new value trying to unsubscribe /// from previous item's property changed event.</remarks> private IDataErrorInfo _InvalidItem { get { return _invalidItem; } set { // Unsubscribe from property changed event. if (_invalidItem as INotifyPropertyChanged != null) (_invalidItem as INotifyPropertyChanged).PropertyChanged -= new PropertyChangedEventHandler(_InvalidItemPropertyChanged); // Set new value. _invalidItem = value; } } #endregion #region Private Methods /// <summary> /// Subscribe to events. /// </summary> private void _InitEventHandlers() { // If datagrid items source exists - subscribe to its events. if (_dataGrid.ItemsSource is DataGridCollectionView) _SubscribeToItemsSourceEvents(); // Subscribe to data grid events. _dataGrid.OnItemSourceChanged += new EventHandler(_DataGridOnItemSourceChanged); _dataGrid.InitializingInsertionRow += new EventHandler<InitializingInsertionRowEventArgs> (_DataGridInitializingInsertionRow); _dataGrid.MouseMove += new System.Windows.Input.MouseEventHandler(_dataGridMouseMove); // Subscribe to window events. _SubscribeToWindowEvents(); // Subscribe to UI manager events. App.Current.UIManager.Locked += new EventHandler(_UIManagerLocked); App.Current.UIManager.UnLocked += new EventHandler(_UIManagerUnLocked); } /// <summary> /// Unsubscribe from all events. /// </summary> private void _UnsubscribeFromEvents() { if (_dataGrid.ItemsSource is DataGridCollectionView) _UnsubscribeFromItemsSourceEvents(); _dataGrid.InitializingInsertionRow -= new EventHandler<InitializingInsertionRowEventArgs> (_DataGridInitializingInsertionRow); _dataGrid.OnItemSourceChanged -= new EventHandler(_DataGridOnItemSourceChanged); _dataGrid.MouseMove -= new System.Windows.Input.MouseEventHandler(_dataGridMouseMove); _UnsubscribeFromWindowEvents(); _StopTimer(); } /// <summary> /// Subscribe to grid's items source events. /// </summary> private void _SubscribeToItemsSourceEvents() { // If data grid items source was set to null // we don't need to subscribe to events. if (_dataGrid.ItemsSource == null) return; // Remember collection to unsubscribe from its items in future. _dataGridCollectionView = _dataGrid.ItemsSource as DataGridCollectionView; // Check that collection's type. Debug.Assert(_dataGridCollectionView != null); // Subscribing to data grid source collection events. (_dataGridCollectionView as INotifyCollectionChanged).CollectionChanged += new NotifyCollectionChangedEventHandler(_SourceItemsCollectionChanged); // If user is adding new item we need to close popup and subscribe to // property changed event. _dataGridCollectionView.NewItemCreated += new EventHandler<DataGridItemEventArgs> (_CollectionViewSourceCreatingNewItem); // If user is editing existence item, need to close popup, subscribe to // property changed event and open popup for item invalid property. _dataGridCollectionView.BeginningEdit += new EventHandler<DataGridItemCancelEventArgs> (_CollectionViewSourceBeginningEdit); // When user finish/editing item, we need // to re-validate data grid's source collection. _dataGridCollectionView.NewItemCommitted += new EventHandler<DataGridItemEventArgs> (_CollectionViewSourceNewItemFinishEdit); _dataGridCollectionView.NewItemCanceled += new EventHandler<DataGridItemEventArgs> (_CollectionViewSourceNewItemFinishEdit); _dataGridCollectionView.CommittingEdit += new EventHandler<DataGridItemCancelEventArgs> (_CollectionViewSourceFinishEdit); _dataGridCollectionView.CancelingEdit += new EventHandler<DataGridItemHandledEventArgs> (_CollectionViewSourceFinishEdit); } /// <summary> /// Unsubscribe from grid's items source events. /// </summary> private void _UnsubscribeFromItemsSourceEvents() { // If data grid items source is null // dont need to unsubscibe from events. if (_dataGridCollectionView == null) return; (_dataGridCollectionView as INotifyCollectionChanged).CollectionChanged -= new NotifyCollectionChangedEventHandler(_SourceItemsCollectionChanged); _dataGridCollectionView.NewItemCreated -= new EventHandler<DataGridItemEventArgs> (_CollectionViewSourceCreatingNewItem); _dataGridCollectionView.BeginningEdit -= new EventHandler<DataGridItemCancelEventArgs> (_CollectionViewSourceBeginningEdit); _dataGridCollectionView.NewItemCommitted -= new EventHandler<DataGridItemEventArgs> (_CollectionViewSourceNewItemFinishEdit); _dataGridCollectionView.NewItemCanceled -= new EventHandler<DataGridItemEventArgs> (_CollectionViewSourceNewItemFinishEdit); _dataGridCollectionView.CommittingEdit -= new EventHandler<DataGridItemCancelEventArgs> (_CollectionViewSourceFinishEdit); _dataGridCollectionView.CancelingEdit -= new EventHandler<DataGridItemHandledEventArgs> (_CollectionViewSourceFinishEdit); } /// <summary> /// Gets parent window of Xceed Grid. /// </summary> /// <returns></returns> private Window _GetXceedGridParentWindow() { Window window = null; FrameworkElement parentElement = _dataGrid; Debug.Assert(parentElement != null); // Find grid's parent window. while (parentElement != null && !(parentElement is Window)) { parentElement = (FrameworkElement)VisualTreeHelper.GetParent(parentElement); } if (parentElement != null) window = parentElement as Window; else window = App.Current.MainWindow; return window; } /// <summary> /// Find grid's window and subscribe to it's events. /// </summary> private void _SubscribeToWindowEvents() { // Get parent window of Xceed Grid. _window = _GetXceedGridParentWindow(); // Subscribe to window's events. _window.Deactivated += new EventHandler(_WindowDeactivated); _window.LocationChanged += new EventHandler(_WindowLocationChanged); _window.SizeChanged += new SizeChangedEventHandler(_WindowSizeChanged); _window.StateChanged += new EventHandler(_WindowStateChanged); } /// <summary> /// Unsubscribe from grid's parent window events. /// </summary> private void _UnsubscribeFromWindowEvents() { _window.Deactivated -= new EventHandler(_WindowDeactivated); _window.LocationChanged -= new EventHandler(_WindowLocationChanged); _window.SizeChanged -= new SizeChangedEventHandler(_WindowSizeChanged); _window.StateChanged -= new EventHandler(_WindowStateChanged); } /// <summary> /// Unsubscribe from events. /// </summary> /// <param name="item">Edited item.</param> private void _UnsubscribeFromEditingEvents(object item) { (item as INotifyPropertyChanged).PropertyChanged -= new PropertyChangedEventHandler(_EditedItemPropertyChanged); DataRow row = _dataGrid.GetContainerFromItem(item) as DataRow; if (row == null) row = _dataGrid.InsertionRow; // When grid view is TableFlow, here can come null row. if (row != null) foreach (var cell in row.Cells) cell.PropertyChanged -= new PropertyChangedEventHandler(_CellPropertyChanged); } /// <summary> /// Init timer, which will hide callout. /// </summary> private void _InitTimer() { _timer = new DispatcherTimer(); _timer.Interval = new TimeSpan(0, 0, SECONDS_AFTER_CALLOUT_WILL_BE_HIDED); _timer.Tick += delegate { _timer.Stop(); _showCallout = false; _Callout.Close(true); }; } /// <summary> /// Close popup, unsubscribe from callout events. /// </summary> /// <param name="animate">Animate closing or not.</param> private void _DeactivatePopup(bool animate) { if (_InvalidItem as INotifyPropertyChanged != null) { (_InvalidItem as INotifyPropertyChanged).PropertyChanged -= new PropertyChangedEventHandler(_InvalidItemPropertyChanged); } _ClosePopup(animate); } /// <summary> /// Find ScrollViewer from cell and subscribe to it scroll changed event. /// </summary> /// <param name="cell">Cell.</param> private void _SubscribeOnScroller(Cell cell) { _scrollViewer = XceedVisualTreeHelper.FindScrollViewer(cell); if (_scrollViewer != null) _scrollViewer.ScrollChanged += new System.Windows.Controls. ScrollChangedEventHandler(_ScrollViewerScrollChanged); } /// <summary> /// If item has error in visible properies - show first of them. /// </summary> /// <param name="objectToValidate">IDataErrorInfo implementation.</param> private void _ShowCalloutOnInvalidItem(IDataErrorInfo objectToValidate) { // If there is nothing to validate - do nothing. if (objectToValidate == null) return; // Find column, corresponding to invalid property. Column column = _GetColumnWithError(objectToValidate); if (column != null) { _InvalidItem = objectToValidate; _InitCallout(column); } } /// <summary> /// Close current popup, set new popup to _callout field. /// </summary> /// <param name="animate">Animate closing or not.</param> private void _ClosePopup(bool animate) { _Callout.Close(animate); _callout = new Callout(); } /// <summary> /// Check that all items in collection are valid. /// </summary> private void _Validate() { if (App.Current.UIManager.IsLocked || !_dataGrid.IsVisible) return; // Need to stop timer. _StopTimer(); // Enable showing callout. _showCallout = true; // For all items in data grid source collection. foreach (var item in _collection) // If item isn't valid. if ((item is IDataErrorInfo) && !(string.IsNullOrEmpty((item as IDataErrorInfo).Error))) { // Cast item to IDataErrorInfo. var dataObject = item as IDataErrorInfo; // Find first visible column with error. Column column = _GetColumnWithError(dataObject); if (column != null) { // Remeber data object as invalid item. _InvalidItem = dataObject; // If row with this item isn't shown in grid - show it. if (_IsItemVisible(dataObject)) _dataGrid.BringItemIntoView(dataObject); // Set grid's current item on invalid item. // There must be so much invoking, because grid is working async. _dataGrid.Dispatcher.BeginInvoke(new Action(delegate() { _dataGrid.CurrentItem = dataObject; // Show column with wrong property. _dataGrid.Dispatcher.BeginInvoke(new Action(delegate() { _dataGrid.CurrentColumn = column; // Show callout. _dataGrid.Dispatcher.BeginInvoke(new Action(delegate() { _InitCallout(column); _StartTimerSubscribeToEvent(); } ), DispatcherPriority.ContextIdle); }), DispatcherPriority.ContextIdle); }), DispatcherPriority.ContextIdle); // If we found invalid item - stop searching. return; } } } /// <summary> /// Return first visible column with error for this item. /// </summary> /// <param name="itemToCheck">Item, which property must be checked.</param> /// <returns>First visible column with error.</returns> private Column _GetColumnWithError(IDataErrorInfo itemToCheck) { // For each grid visible column. foreach (var column in _dataGrid.GetVisibleColumns()) { // Find error message for corresponding property. string error = itemToCheck[column.FieldName]; // If error message isn't empty. if (!string.IsNullOrEmpty(error)) return column; } // If we come here - there is no invalid columns. return null; } /// <summary> /// Check that row is shown in current grid layout. /// </summary> /// <param name="dataObject">Data object, which row must be checked.</param> /// <returns>'True' if row is shown, 'false' otherwise.</returns> private bool _IsItemVisible(IDataErrorInfo dataObject) { // Get row for this item. var row = _dataGrid.GetContainerFromItem(dataObject) as Row; if (row != null) { // Check that row is shown. var point = row.PointToScreen(new System.Windows.Point(0, row.Height)); return _IsPointInsideGrid(row, point); } return false; } /// <summary> /// Check that point is inside of the grid. /// </summary> /// <param name="row">Row with point.</param> /// <param name="point">Point to check.</param> /// <returns>'True' if point is inside visible part of the grid, 'false' otherwise.</returns> private bool _IsPointInsideGrid(Row row, Point point) { if (_dataGrid.InsertionRow == row && _dataGrid.IsBeingEdited) return _IsPointInsideGridOnVerticalHorizontalAxis(point, false); else return _IsPointInsideGridOnVerticalHorizontalAxis(point, true); } /// <summary> /// Check that point is inside visible part of grid. /// </summary> /// <param name="point">Point to check. It's coordinate must /// be in device-independent units.</param> /// <param name="checkVertical">If 'false' there is no need to check is point /// inside grid on </param> /// <returns>'True' if point is inside visible part, 'false' otherwise.</returns> /// <remarks>Do not use this method directly. Use _IsPointInsideGrid instead.</remarks> private bool _IsPointInsideGridOnVerticalHorizontalAxis(Point point, bool checkVertical) { // Find grid top left, and lower right visible points. var minPoint = _dataGrid.PointToScreen(new Point(0, 0)); var maxPoint = _dataGrid.PointToScreen( new Point(_dataGrid.ActualWidth, _dataGrid.ActualHeight)); // Check, that point is inside grid on Y axis. // If we are adding new item then point is definitely visible on Y axis. // Otherwise point must be lower then grid's header. if (checkVertical && (!(point.Y > minPoint.Y + _gridHeadingRowAndInsertionRowHeight && point.Y < maxPoint.Y))) return false; // Check, that point is inside grid on X axis. if (!(point.X > minPoint.X && point.X <= maxPoint.X)) return false; return true; } /// <summary> /// Show callout in proper position. /// </summary> /// <param name="column">Collumn with invalid property.</param> private void _InitCallout(ColumnBase column) { // Remember column with invalid property. _column = column; // Show callout in right place. _SetPopupPosition(); } /// <summary> /// Start timer that will hide callout and subscribe to invalid item /// and grid invalid cells events. /// </summary> private void _StartTimerSubscribeToEvent() { // Start timer. _timer.Start(); // When invalid item's property changed - need to re-validate all items in table. (_InvalidItem as INotifyPropertyChanged).PropertyChanged += new PropertyChangedEventHandler(_InvalidItemPropertyChanged); } /// <summary> /// Stop timer. /// </summary> private void _StopTimer() { _timer.Stop(); // Need to unsubscribe from invalid item's property changed event. if(_InvalidItem != null) (_InvalidItem as INotifyPropertyChanged).PropertyChanged -= new PropertyChangedEventHandler(_InvalidItemPropertyChanged); } /// <summary> /// Get cell with error. /// </summary> /// <returns><c>Xceed.Wpf.DataGrid.Cell</c>.</returns> private Cell _FindCellWithError(Row row) { // If row is null - return null. if (row != null) { // Get cell with invalid property. var cell = (row as Row).Cells[_column]; // If we havent found scroll viever - do find it. if (_scrollViewer == null) _SubscribeOnScroller(cell); // If this cell is visible - return it. if (cell != null && cell.IsVisible) return cell; } // If we come here - cell couldnt be found. return null; } /// <summary> /// Get cell with error. /// </summary> /// <returns><c>Xceed.Wpf.DataGrid.Cell</c>.</returns> private Row _FindRowWithError() { // Check that invalid item is not empty and that collumn is still displayed. if (_InvalidItem != null && _column != null) { // Get the row with invalid item. var row = _dataGrid.GetContainerFromItem(_InvalidItem); // If row is null - then get insertion row. if (row == null && _dataGrid.IsNewItemBeingAdded) row = _dataGrid.InsertionRow; return row as Row; } // Callout cannot be displayed so return "bad" point. return null; } /// <summary> /// Updating popup position. /// </summary> private void _SetPopupPosition() { // Check that there are invalid item and column with error if (_InvalidItem == null || _column == null) return; // If grid isnt in editing state and // we cannot show callout - do not show. if (!_dataGrid.IsBeingEdited && !_showCallout && !_Callout.IsOpen) return; var invalidItemError = _InvalidItem[_column.FieldName]; // Set popup text. _Callout.DataContext = invalidItemError; // Detect error cell. var row = _FindRowWithError(); var cell = _FindCellWithError(row); if (cell != null && !string.IsNullOrEmpty(invalidItemError)) { // Get visible part of the cell. Rect placementRect = _GetCellVisibleRectangle(cell, row); if (placementRect != Rect.Empty ) { // Init callout. _Callout.PlacementRectangle = placementRect; _Callout.Placement = System.Windows.Controls.Primitives.PlacementMode.Custom; _Callout.IsOpen = true; } else if (_Callout.IsOpen) _ClosePopup(false); } else _ClosePopup(false); } /// <summary> /// Get visible part of the cell. /// </summary> /// <param name="cell">Cell with error.</param> /// <param name="row">Row with error.</param> /// <returns>Rect, representing visible part of the cell.</returns> private Rect _GetCellVisibleRectangle(Cell cell, Row row) { // Get top left and bottom right points of the cell. var topLeft = cell.PointToScreen(new Point(0, 0)); var bottomRight = cell.PointToScreen(new Point(cell.ActualWidth, cell.ActualHeight)); // If both points isnt inside of the grid, thath mean that cell isnt visible. if (!_IsPointInsideGrid(row, topLeft) && !_IsPointInsideGrid(row, bottomRight)) return Rect.Empty; // Calculate vertical offset. double verticalOffset; // If cell is in insertion row or if grid have no insertion row - // offset is equal to the height of the grid heading row. if (row == _dataGrid.InsertionRow || _dataGrid.InsertionRow == null) verticalOffset = HEADING_ROW_HEIGHT; else verticalOffset = _gridHeadingRowAndInsertionRowHeight; // Detect grid first row top left point. var gridTopLeftPoint = _dataGrid.PointToScreen(new Point(0, verticalOffset)); // Translate this point to cell coordinate. var cellGridTopLeftPoint = cell.PointFromScreen(gridTopLeftPoint); // Correct cell visible rectangle if necessary. if (cellGridTopLeftPoint.X > 0) topLeft.X = gridTopLeftPoint.X; if (cellGridTopLeftPoint.Y > 0) topLeft.Y = gridTopLeftPoint.Y; // Detect grid bottom right point. var gridRightEdge = _dataGrid.PointToScreen( new Point(_dataGrid.ActualWidth, _dataGrid.ActualHeight)); // Translate this point to cell coordinate. var cellGridRightEdge = cell.PointFromScreen(gridRightEdge); // Correct cell visible rectangle if necessary. if (cellGridRightEdge.X < cell.ActualWidth) bottomRight.X = gridRightEdge.X; if (cellGridRightEdge.Y < cell.ActualHeight) bottomRight.Y = gridRightEdge.Y; return new Rect(topLeft, bottomRight); } /// <summary> /// Return first column from address scope. /// </summary> /// <returns>First visible address column or false if it wasnt found.</returns> private ColumnBase _GetFirstAddressColumn() { foreach (var column in _dataGrid.GetVisibleColumns()) if (Address.IsAddressPropertyName(column.FieldName)) return column; return null; } #endregion #region Private Event Handlers /// <summary> /// Occure when UI interface is unlocked. /// </summary> /// <param name="sender">Ignored.</param> /// <param name="e">Ignored.</param> private void _UIManagerUnLocked(object sender, EventArgs e) { _Validate(); } /// <summary> /// Occure when UI interface is locked. /// </summary> /// <param name="sender">Ignored.</param> /// <param name="e">Ignored.</param> private void _UIManagerLocked(object sender, EventArgs e) { _ClosePopup(false); } /// <summary> /// When mouse move in invalid cell - show corresponding popup. /// </summary> /// <param name="sender">Ignored.</param> /// <param name="e">Ignored.</param> private void _dataGridMouseMove(object sender, System.Windows.Input.MouseEventArgs e) { // Find cell on which mouse moved. Cell cell = XceedVisualTreeHelper.GetCellByEventArgs(e); // If cell has error, grid isnt in editing state and timer is running - show callout. if (cell != null && cell.HasValidationError && !_timer.IsEnabled && !_dataGrid.IsBeingEdited && !(_dataGrid.InsertionRow != null && _dataGrid.InsertionRow.IsBeingEdited)) { _showCallout = true; // Detect current column and item. Show callout. IDataErrorInfo currentItem = _dataGrid.GetItemFromContainer(cell) as IDataErrorInfo; var columns = _dataGrid.GetVisibleColumns(); _column = columns.FirstOrDefault(x => x.FieldName == cell.FieldName); _InvalidItem = currentItem; _SetPopupPosition(); _showCallout = false; // When mouse leave current cell - callout must be hided. cell.MouseLeave += new System.Windows.Input.MouseEventHandler(_MouseLeaveCellWithInvalidProperty); } } /// <summary> /// When mouse leave invalid cell - close popup. /// </summary> /// <param name="sender">Ignored.</param> /// <param name="e">Ignored.</param> private void _MouseLeaveCellWithInvalidProperty(object sender, System.Windows.Input.MouseEventArgs e) { // Unsubscribe from this event. (sender as Cell).MouseLeave -= new System.Windows.Input. MouseEventHandler(_MouseLeaveCellWithInvalidProperty); // If grid isnt edited and if timer isnt running - close callout. if (!_dataGrid.IsBeingEdited && !_timer.IsEnabled) _ClosePopup(true); } /// <summary> /// When some of the error item's property changed we need to re-validate /// all items in grid source collection. /// </summary> /// <param name="sender">Ignored.</param> /// <param name="e">Ignored.</param> private void _InvalidItemPropertyChanged(object sender, PropertyChangedEventArgs e) { if (_GetInvalidColumns(_invalidItem).Contains(_column)) return; // Need to close old popup. _DeactivatePopup(true); // Start new validation. _Validate(); } /// <summary> /// Return first visible column with error for this item. /// </summary> /// <param name="itemToCheck">Item, which property must be checked.</param> /// <returns>First visible column with error.</returns> private List<Column> _GetInvalidColumns(IDataErrorInfo itemToCheck) { List<Column> columns = new List<Column>(); // For each grid visible column. foreach (var column in _dataGrid.GetVisibleColumns()) { // Find error message for corresponding property. string error = itemToCheck[column.FieldName]; // If error message isn't empty. if (!string.IsNullOrEmpty(error)) columns.Add(column); } // If we come here - there is no invalid columns. return columns; } /// <summary> /// If window state changed - update callout. /// </summary> /// <param name="sender">Ignore.</param> /// <param name="e">Ignore.</param> private void _WindowStateChanged(object sender, EventArgs e) { // If window was restored - show callout. if (_window.WindowState == WindowState.Normal || _window.WindowState == WindowState.Maximized) if (!_dataGrid.IsBeingEdited) _Validate(); else _ShowCalloutOnInvalidItem(_InvalidItem); // If window was minimized - close callout. else _DeactivatePopup(false); } /// <summary> /// If window size changed - update callout position. /// </summary> /// <param name="sender">Ignore.</param> /// <param name="e">Ignore.</param> private void _WindowSizeChanged(object sender, SizeChangedEventArgs e) { _SetPopupPosition(); } /// <summary> /// If window location changed - update callout position. /// </summary> /// <param name="sender">Ignore.</param> /// <param name="e">Ignore.</param> private void _WindowLocationChanged(object sender, EventArgs e) { // Close callout if it is open. if (_Callout.IsOpen) _DeactivatePopup(true); } /// <summary> /// When window deactivated - need to hide callout. /// </summary> /// <param name="sender">Ignore.</param> /// <param name="e">Ignore.</param> private void _WindowDeactivated(object sender, EventArgs e) { _DeactivatePopup(false); } /// <summary> /// If another collection was used as grid's source - subscribe to it's /// collection changed event. /// </summary> /// <param name="sender">Ignore.</param> /// <param name="e">Ignore.</param> private void _DataGridOnItemSourceChanged(object sender, EventArgs e) { _UnsubscribeFromItemsSourceEvents(); _SubscribeToItemsSourceEvents(); } /// <summary> /// If collection changed - need to re-init callout. /// </summary> /// <param name="sender">Ignore.</param> /// <param name="e">Ignore.</param> private void _SourceItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { // Deactivate popup and do validation for whole collection. if (e.Action == NotifyCollectionChangedAction.Remove || e.Action == NotifyCollectionChangedAction.Reset) { _DeactivatePopup(true); _Validate(); } } /// <summary> /// Subscribe to cell property changed events. Doing so we will know when user change active cell. /// </summary> /// <param name="sender">Ignore.</param> /// <param name="e">Ignore.</param> private void _DataGridInitializingInsertionRow(object sender, InitializingInsertionRowEventArgs e) { DataRow row = _dataGrid.InsertionRow; foreach (var cell in row.Cells) cell.PropertyChanged += new PropertyChangedEventHandler(_CellPropertyChanged); } /// <summary> /// Starting editing of new item. /// </summary> /// <param name="sender">Ignore.</param> /// <param name="e">DataGridItemEventArgs.</param> private void _CollectionViewSourceCreatingNewItem(object sender, DataGridItemEventArgs e) { // Stop timer and unsubscribe from mouse move events. _StopTimer(); // Turn off geocoding validation. if (e.Item is IGeocodable) (e.Item as IGeocodable).IsAddressValidationEnabled = false; // Close popup. _DeactivatePopup(true); // Remember edited item and subscribe to it's property changed event. _InvalidItem = e.Item as IDataErrorInfo; (e.Item as INotifyPropertyChanged).PropertyChanged += new PropertyChangedEventHandler (_EditedItemPropertyChanged); // If new item already has errors - show callout. _dataGrid.Dispatcher.BeginInvoke(new Action(delegate() { var column = _GetColumnWithError(_InvalidItem); if (column != null) _InitCallout(column); }), DispatcherPriority.ApplicationIdle); } /// <summary> /// If user scrolled grid - need to change callout position. /// </summary> /// <param name="sender">Ignore.</param> /// <param name="e">Ignore.</param> private void _ScrollViewerScrollChanged(object sender, System.Windows.Controls. ScrollChangedEventArgs e) { _dataGrid.Dispatcher.BeginInvoke(new Action(delegate() { _SetPopupPosition(); }), DispatcherPriority.ApplicationIdle); } /// <summary> /// Need to close current popup and open popup if current item has invalid property. /// </summary> /// <param name="sender">Ignored.</param> /// <param name="e">DataGridItemCancelEventArgs.</param> private void _CollectionViewSourceBeginningEdit(object sender, DataGridItemCancelEventArgs e) { // Do not show callout, when pointing on invalid cell. _StopTimer(); // If callout pointing at another item - close it. if (_InvalidItem != e.Item && _Callout.IsOpen) { _ClosePopup(true); _callout = new Callout(); } // Remember edited item and subscribe to it's property changed event. _InvalidItem = e.Item as IDataErrorInfo; (e.Item as INotifyPropertyChanged).PropertyChanged += new PropertyChangedEventHandler (_EditedItemPropertyChanged); // If current column have error. if (_dataGrid.CurrentColumn != null && !string.IsNullOrEmpty((e.Item as IDataErrorInfo)[_dataGrid.CurrentColumn.FieldName])) { // If callout is pointing at another column - close it. if (_column != _dataGrid.CurrentColumn) { _ClosePopup(true); _callout = new Callout(); } // If callout closed - open it and point at current cell. if (!_Callout.IsOpen) { // Detect column to show callout. var column = _dataGrid.CurrentColumn; if (Address.IsAddressPropertyName(column.FieldName)) column = _GetFirstAddressColumn(); _InitCallout(column); } } // If callout closed - seek for item's invalid properties. else if (!_Callout.IsOpen && !string.IsNullOrEmpty(_InvalidItem.Error)) _ShowCalloutOnInvalidItem(e.Item as IDataErrorInfo); // Subscribe to cell property changed events. Doing so we will know when user change active cell. DataRow row = _dataGrid.GetContainerFromItem(e.Item) as DataRow; // If grid view is table flow - even in editing state row can be null. if (row != null) foreach (var cell in row.Cells) cell.PropertyChanged += new PropertyChangedEventHandler(_CellPropertyChanged); } /// <summary> /// When editing item property changed need to check its properties for errors. /// </summary> /// <param name="sender">IDataErrorInfo implementation.</param> /// <param name="e">Ignored.</param> private void _EditedItemPropertyChanged(object sender, PropertyChangedEventArgs e) { // Detect current column. var column = _dataGrid.CurrentColumn; // If grid view is table flow - current column can be null. if (column == null) return; // Edited property is address property - do not check anything. if (Address.IsAddressPropertyName(_dataGrid.CurrentColumn.FieldName)) return; // Set currently editing item as invalid item. _InvalidItem = sender as IDataErrorInfo; // If currently edited property is invalid - point callout at it. if (!string.IsNullOrEmpty(_InvalidItem[column.FieldName])) { // If current callout doesnt point at this cell - close callout // and open it on right place. if (_column != column) { _ClosePopup(true); _InitCallout(column); } // If callout closed - show it. else if (!_callout.IsOpen) _InitCallout(column); } // If currently edited property became valid or // if property on which callout is pointing became valid - // close callout and seek for another invalid property to point at. else if (_column == _dataGrid.CurrentColumn || (_column != null && string.IsNullOrEmpty(_InvalidItem[_column.FieldName]))) { _ClosePopup(true); _ShowCalloutOnInvalidItem(sender as IDataErrorInfo); } // If currently edited item has no errors - close popup. else if (string.IsNullOrEmpty((sender as IDataErrorInfo).Error)) _ClosePopup(true); } /// <summary> /// Editing in grid finished, need check for validation. /// </summary> /// <param name="sender">Ignored.</param> /// <param name="e">Ignored.</param> private void _CollectionViewSourceFinishEdit(object sender, DataGridItemEventArgs e) { // Unsubscribe from events. _UnsubscribeFromEditingEvents(e.Item); // If there are no cell with error on edited item - do validation for whole collection. if (_GetInvalidColumns(e.Item as IDataErrorInfo).Count == 0) _Validate(); // Start timer and subscribe to item's, cells events. _StartTimerSubscribeToEvent(); } /// <summary> /// Editing new item in grid finished, need check for validation. /// </summary> /// <param name="sender">Ignored.</param> /// <param name="e">Ignored.</param> private void _CollectionViewSourceNewItemFinishEdit(object sender, DataGridItemEventArgs e) { // Close callout. _ClosePopup(false); // Enable geocoding validation. if (e.Item is IGeocodable) (e.Item as IGeocodable).IsAddressValidationEnabled = true; // Unsubscribe from events. _UnsubscribeFromEditingEvents(e.Item); // We need to do invoking, to wait while new item will be comitted to the view. _dataGrid.Dispatcher.BeginInvoke(new Action(delegate() { _Validate(); }), DispatcherPriority.ApplicationIdle); } /// <summary> /// If another cell become active, check corresponding property for errors. /// </summary> /// <param name="sender">Ignored.</param> /// <param name="e">PropertyChangedEventArgs.</param> private void _CellPropertyChanged(object sender, PropertyChangedEventArgs e) { // If last column was address column and current // is address column - do not move callout. if (_column != null && Address.IsAddressPropertyName(_dataGrid.CurrentColumn.FieldName) && Address.IsAddressPropertyName(_column.FieldName)) return; // If this cell become active, check that corresponding property has error. if (e.PropertyName == IS_CELL_EDITOR_DISPLAYED_PROPERTY_NAME) if (!string.IsNullOrEmpty(_InvalidItem[_dataGrid.CurrentColumn.FieldName]) && _column != _dataGrid.CurrentColumn) { _ClosePopup(true); // If this is address property - point callout to first address column. if (Address.IsAddressPropertyName(_dataGrid.CurrentColumn.FieldName)) _InitCallout(_GetFirstAddressColumn()); // If it is any other property - point callout to it. else _InitCallout(_dataGrid.CurrentColumn); } } #endregion #region Private Constant Fields /// <summary> /// Default row height resource name. /// </summary> private const string DEFAULT_ROW_HEIGHT = "XceedRowDefaultHeight"; /// <summary> /// Is cell editor displayed property name. /// </summary> private const string IS_CELL_EDITOR_DISPLAYED_PROPERTY_NAME = "IsCellEditorDisplayed"; /// <summary> /// At least 10 px of row with invalid item must be visible to show callout. /// </summary> private const int HEADING_ROW_HEIGHT = 10; /// <summary> /// Time after which callout will be hided. In seconds. /// </summary> private const int SECONDS_AFTER_CALLOUT_WILL_BE_HIDED = 5; #endregion #region Private Static field /// <summary> /// Height of the table header: row with column names and insertion row. /// </summary> private static double _gridHeadingRowAndInsertionRowHeight = HEADING_ROW_HEIGHT + (double)System.Windows.Application.Current.FindResource(DEFAULT_ROW_HEIGHT); #endregion #region Private Fields /// <summary> /// Grid wich needs to be validated. /// </summary> private DataGridControlEx _dataGrid; /// <summary> /// Collection which needs to validate. /// </summary> private CollectionView _collection; /// <summary> /// Popup, which will be shown near error cell. /// </summary> private Callout _callout; /// <summary> /// Invalid item. /// </summary> private IDataErrorInfo _invalidItem; /// <summary> /// Column corresponding to invalid property. /// </summary> private ColumnBase _column; /// <summary> /// Grid's scroller. /// </summary> private TableViewScrollViewer _scrollViewer; /// <summary> /// Grid's parent window. /// </summary> private Window _window; /// <summary> /// Data grid collection source. Need for unsubscribing from old collection. /// </summary> private DataGridCollectionView _dataGridCollectionView; /// <summary> /// Timer, which hide callout after some time. /// </summary> private DispatcherTimer _timer; /// <summary> /// If this flag set to 'false' callout wouldn't be shown /// on next scrolling/window activating. /// </summary> private bool _showCallout = true; #endregion } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Stream ** ** <OWNER>gpaperin</OWNER> ** ** ** Purpose: Abstract base class for all Streams. Provides ** default implementations of asynchronous reads & writes, in ** terms of the synchronous reads & writes (and vice versa). ** ** ===========================================================*/ using System; using System.Threading; #if FEATURE_ASYNC_IO using System.Threading.Tasks; #endif using System.Runtime; using System.Runtime.InteropServices; #if NEW_EXPERIMENTAL_ASYNC_IO using System.Runtime.CompilerServices; #endif using System.Runtime.ExceptionServices; using System.Security; using System.Security.Permissions; using System.Diagnostics.Contracts; using System.Reflection; namespace System.IO { [Serializable] [ComVisible(true)] #if CONTRACTS_FULL [ContractClass(typeof(StreamContract))] #endif #if FEATURE_REMOTING public abstract class Stream : MarshalByRefObject, IDisposable { #else // FEATURE_REMOTING public abstract class Stream : IDisposable { #endif // FEATURE_REMOTING public static readonly Stream Null = new NullStream(); //We pick a value that is the largest multiple of 4096 that is still smaller than the large object heap threshold (85K). // The CopyTo/CopyToAsync buffer is short-lived and is likely to be collected at Gen0, and it offers a significant // improvement in Copy performance. private const int _DefaultCopyBufferSize = 81920; #if NEW_EXPERIMENTAL_ASYNC_IO // To implement Async IO operations on streams that don't support async IO [NonSerialized] private ReadWriteTask _activeReadWriteTask; [NonSerialized] private SemaphoreSlim _asyncActiveSemaphore; internal SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized() { // Lazily-initialize _asyncActiveSemaphore. As we're never accessing the SemaphoreSlim's // WaitHandle, we don't need to worry about Disposing it. return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1)); } #endif public abstract bool CanRead { [Pure] get; } // If CanSeek is false, Position, Seek, Length, and SetLength should throw. public abstract bool CanSeek { [Pure] get; } [ComVisible(false)] public virtual bool CanTimeout { [Pure] get { return false; } } public abstract bool CanWrite { [Pure] get; } public abstract long Length { get; } public abstract long Position { get; set; } [ComVisible(false)] public virtual int ReadTimeout { get { Contract.Ensures(Contract.Result<int>() >= 0); throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported")); } set { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported")); } } [ComVisible(false)] public virtual int WriteTimeout { get { Contract.Ensures(Contract.Result<int>() >= 0); throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported")); } set { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported")); } } #if FEATURE_ASYNC_IO [HostProtection(ExternalThreading = true)] [ComVisible(false)] public Task CopyToAsync(Stream destination) { return CopyToAsync(destination, _DefaultCopyBufferSize); } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public Task CopyToAsync(Stream destination, Int32 bufferSize) { return CopyToAsync(destination, bufferSize, CancellationToken.None); } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public virtual Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) { if (destination == null) throw new ArgumentNullException("destination"); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); if (!CanRead && !CanWrite) throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_StreamClosed")); if (!destination.CanRead && !destination.CanWrite) throw new ObjectDisposedException("destination", Environment.GetResourceString("ObjectDisposed_StreamClosed")); if (!CanRead) throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream")); if (!destination.CanWrite) throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnwritableStream")); Contract.EndContractBlock(); return CopyToAsyncInternal(destination, bufferSize, cancellationToken); } private async Task CopyToAsyncInternal(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) { Contract.Requires(destination != null); Contract.Requires(bufferSize > 0); Contract.Requires(CanRead); Contract.Requires(destination.CanWrite); byte[] buffer = new byte[bufferSize]; int bytesRead; while ((bytesRead = await ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0) { await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false); } } #endif // FEATURE_ASYNC_IO // Reads the bytes from the current stream and writes the bytes to // the destination stream until all bytes are read, starting at // the current position. public void CopyTo(Stream destination) { if (destination == null) throw new ArgumentNullException("destination"); if (!CanRead && !CanWrite) throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_StreamClosed")); if (!destination.CanRead && !destination.CanWrite) throw new ObjectDisposedException("destination", Environment.GetResourceString("ObjectDisposed_StreamClosed")); if (!CanRead) throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream")); if (!destination.CanWrite) throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnwritableStream")); Contract.EndContractBlock(); InternalCopyTo(destination, _DefaultCopyBufferSize); } public void CopyTo(Stream destination, int bufferSize) { if (destination == null) throw new ArgumentNullException("destination"); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); if (!CanRead && !CanWrite) throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_StreamClosed")); if (!destination.CanRead && !destination.CanWrite) throw new ObjectDisposedException("destination", Environment.GetResourceString("ObjectDisposed_StreamClosed")); if (!CanRead) throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream")); if (!destination.CanWrite) throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnwritableStream")); Contract.EndContractBlock(); InternalCopyTo(destination, bufferSize); } private void InternalCopyTo(Stream destination, int bufferSize) { Contract.Requires(destination != null); Contract.Requires(CanRead); Contract.Requires(destination.CanWrite); Contract.Requires(bufferSize > 0); byte[] buffer = new byte[bufferSize]; int read; while ((read = Read(buffer, 0, buffer.Length)) != 0) destination.Write(buffer, 0, read); } // Stream used to require that all cleanup logic went into Close(), // which was thought up before we invented IDisposable. However, we // need to follow the IDisposable pattern so that users can write // sensible subclasses without needing to inspect all their base // classes, and without worrying about version brittleness, from a // base class switching to the Dispose pattern. We're moving // Stream to the Dispose(bool) pattern - that's where all subclasses // should put their cleanup starting in V2. public virtual void Close() { /* These are correct, but we'd have to fix PipeStream & NetworkStream very carefully. Contract.Ensures(CanRead == false); Contract.Ensures(CanWrite == false); Contract.Ensures(CanSeek == false); */ Dispose(true); GC.SuppressFinalize(this); } public void Dispose() { /* These are correct, but we'd have to fix PipeStream & NetworkStream very carefully. Contract.Ensures(CanRead == false); Contract.Ensures(CanWrite == false); Contract.Ensures(CanSeek == false); */ Close(); } protected virtual void Dispose(bool disposing) { // Note: Never change this to call other virtual methods on Stream // like Write, since the state on subclasses has already been // torn down. This is the last code to run on cleanup for a stream. } public abstract void Flush(); #if FEATURE_ASYNC_IO [HostProtection(ExternalThreading=true)] [ComVisible(false)] public Task FlushAsync() { return FlushAsync(CancellationToken.None); } [HostProtection(ExternalThreading=true)] [ComVisible(false)] public virtual Task FlushAsync(CancellationToken cancellationToken) { return Task.Factory.StartNew(state => ((Stream)state).Flush(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } #endif // FEATURE_ASYNC_IO [Obsolete("CreateWaitHandle will be removed eventually. Please use \"new ManualResetEvent(false)\" instead.")] protected virtual WaitHandle CreateWaitHandle() { Contract.Ensures(Contract.Result<WaitHandle>() != null); return new ManualResetEvent(false); } [HostProtection(ExternalThreading=true)] public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { Contract.Ensures(Contract.Result<IAsyncResult>() != null); return BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: false); } [HostProtection(ExternalThreading = true)] internal IAsyncResult BeginReadInternal(byte[] buffer, int offset, int count, AsyncCallback callback, Object state, bool serializeAsynchronously) { Contract.Ensures(Contract.Result<IAsyncResult>() != null); if (!CanRead) __Error.ReadNotSupported(); #if !NEW_EXPERIMENTAL_ASYNC_IO return BlockingBeginRead(buffer, offset, count, callback, state); #else // Mango did not do Async IO. if(CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { return BlockingBeginRead(buffer, offset, count, callback, state); } // To avoid a race with a stream's position pointer & generating ---- // conditions with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread if it does a second IO request until the first one completes. var semaphore = EnsureAsyncActiveSemaphoreInitialized(); Task semaphoreTask = null; if (serializeAsynchronously) { semaphoreTask = semaphore.WaitAsync(); } else { semaphore.Wait(); } // Create the task to asynchronously do a Read. This task serves both // as the asynchronous work item and as the IAsyncResult returned to the user. var asyncResult = new ReadWriteTask(true /*isRead*/, delegate { // The ReadWriteTask stores all of the parameters to pass to Read. // As we're currently inside of it, we can get the current task // and grab the parameters from it. var thisTask = Task.InternalCurrent as ReadWriteTask; Contract.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask"); // Do the Read and return the number of bytes read var bytesRead = thisTask._stream.Read(thisTask._buffer, thisTask._offset, thisTask._count); thisTask.ClearBeginState(); // just to help alleviate some memory pressure return bytesRead; }, state, this, buffer, offset, count, callback); // Schedule it if (semaphoreTask != null) RunReadWriteTaskWhenReady(semaphoreTask, asyncResult); else RunReadWriteTask(asyncResult); return asyncResult; // return it #endif } public virtual int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException("asyncResult"); Contract.Ensures(Contract.Result<int>() >= 0); Contract.EndContractBlock(); #if !NEW_EXPERIMENTAL_ASYNC_IO return BlockingEndRead(asyncResult); #else // Mango did not do async IO. if(CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { return BlockingEndRead(asyncResult); } var readTask = _activeReadWriteTask; if (readTask == null) { throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple")); } else if (readTask != asyncResult) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple")); } else if (!readTask._isRead) { throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple")); } try { return readTask.GetAwaiter().GetResult(); // block until completion, then get result / propagate any exception } finally { _activeReadWriteTask = null; Contract.Assert(_asyncActiveSemaphore != null, "Must have been initialized in order to get here."); _asyncActiveSemaphore.Release(); } #endif } #if FEATURE_ASYNC_IO [HostProtection(ExternalThreading = true)] [ComVisible(false)] public Task<int> ReadAsync(Byte[] buffer, int offset, int count) { return ReadAsync(buffer, offset, count, CancellationToken.None); } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public virtual Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { // If cancellation was requested, bail early with an already completed task. // Otherwise, return a task that represents the Begin/End methods. return cancellationToken.IsCancellationRequested ? Task.FromCancellation<int>(cancellationToken) : BeginEndReadAsync(buffer, offset, count); } private Task<Int32> BeginEndReadAsync(Byte[] buffer, Int32 offset, Int32 count) { return TaskFactory<Int32>.FromAsyncTrim( this, new ReadWriteParameters { Buffer = buffer, Offset = offset, Count = count }, (stream, args, callback, state) => stream.BeginRead(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler (stream, asyncResult) => stream.EndRead(asyncResult)); // cached by compiler } private struct ReadWriteParameters // struct for arguments to Read and Write calls { internal byte[] Buffer; internal int Offset; internal int Count; } #endif //FEATURE_ASYNC_IO [HostProtection(ExternalThreading=true)] public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { Contract.Ensures(Contract.Result<IAsyncResult>() != null); return BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: false); } [HostProtection(ExternalThreading = true)] internal IAsyncResult BeginWriteInternal(byte[] buffer, int offset, int count, AsyncCallback callback, Object state, bool serializeAsynchronously) { Contract.Ensures(Contract.Result<IAsyncResult>() != null); if (!CanWrite) __Error.WriteNotSupported(); #if !NEW_EXPERIMENTAL_ASYNC_IO return BlockingBeginWrite(buffer, offset, count, callback, state); #else // Mango did not do Async IO. if(CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { return BlockingBeginWrite(buffer, offset, count, callback, state); } // To avoid a race with a stream's position pointer & generating ---- // conditions with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread if it does a second IO request until the first one completes. var semaphore = EnsureAsyncActiveSemaphoreInitialized(); Task semaphoreTask = null; if (serializeAsynchronously) { semaphoreTask = semaphore.WaitAsync(); // kick off the asynchronous wait, but don't block } else { semaphore.Wait(); // synchronously wait here } // Create the task to asynchronously do a Write. This task serves both // as the asynchronous work item and as the IAsyncResult returned to the user. var asyncResult = new ReadWriteTask(false /*isRead*/, delegate { // The ReadWriteTask stores all of the parameters to pass to Write. // As we're currently inside of it, we can get the current task // and grab the parameters from it. var thisTask = Task.InternalCurrent as ReadWriteTask; Contract.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask"); // Do the Write thisTask._stream.Write(thisTask._buffer, thisTask._offset, thisTask._count); thisTask.ClearBeginState(); // just to help alleviate some memory pressure return 0; // not used, but signature requires a value be returned }, state, this, buffer, offset, count, callback); // Schedule it if (semaphoreTask != null) RunReadWriteTaskWhenReady(semaphoreTask, asyncResult); else RunReadWriteTask(asyncResult); return asyncResult; // return it #endif } #if NEW_EXPERIMENTAL_ASYNC_IO private void RunReadWriteTaskWhenReady(Task asyncWaiter, ReadWriteTask readWriteTask) { Contract.Assert(readWriteTask != null); // Should be Contract.Requires, but CCRewrite is doing a poor job with // preconditions in async methods that await. Mike & Manuel are aware. (10/6/2011, bug 290222) Contract.Assert(asyncWaiter != null); // Ditto // If the wait has already complete, run the task. if (asyncWaiter.IsCompleted) { Contract.Assert(asyncWaiter.IsRanToCompletion, "The semaphore wait should always complete successfully."); RunReadWriteTask(readWriteTask); } else // Otherwise, wait for our turn, and then run the task. { asyncWaiter.ContinueWith((t, state) => { Contract.Assert(t.IsRanToCompletion, "The semaphore wait should always complete successfully."); var tuple = (Tuple<Stream,ReadWriteTask>)state; tuple.Item1.RunReadWriteTask(tuple.Item2); // RunReadWriteTask(readWriteTask); }, Tuple.Create<Stream,ReadWriteTask>(this, readWriteTask), default(CancellationToken), TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } } private void RunReadWriteTask(ReadWriteTask readWriteTask) { Contract.Requires(readWriteTask != null); Contract.Assert(_activeReadWriteTask == null, "Expected no other readers or writers"); // Schedule the task. ScheduleAndStart must happen after the write to _activeReadWriteTask to avoid a race. // Internally, we're able to directly call ScheduleAndStart rather than Start, avoiding // two interlocked operations. However, if ReadWriteTask is ever changed to use // a cancellation token, this should be changed to use Start. _activeReadWriteTask = readWriteTask; // store the task so that EndXx can validate it's given the right one readWriteTask.m_taskScheduler = TaskScheduler.Default; readWriteTask.ScheduleAndStart(needsProtection: false); } #endif public virtual void EndWrite(IAsyncResult asyncResult) { if (asyncResult==null) throw new ArgumentNullException("asyncResult"); Contract.EndContractBlock(); #if !NEW_EXPERIMENTAL_ASYNC_IO BlockingEndWrite(asyncResult); #else // Mango did not do Async IO. if(CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { BlockingEndWrite(asyncResult); return; } var writeTask = _activeReadWriteTask; if (writeTask == null) { throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple")); } else if (writeTask != asyncResult) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple")); } else if (writeTask._isRead) { throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple")); } try { writeTask.GetAwaiter().GetResult(); // block until completion, then propagate any exceptions Contract.Assert(writeTask.Status == TaskStatus.RanToCompletion); } finally { _activeReadWriteTask = null; Contract.Assert(_asyncActiveSemaphore != null, "Must have been initialized in order to get here."); _asyncActiveSemaphore.Release(); } #endif } #if NEW_EXPERIMENTAL_ASYNC_IO // Task used by BeginRead / BeginWrite to do Read / Write asynchronously. // A single instance of this task serves four purposes: // 1. The work item scheduled to run the Read / Write operation // 2. The state holding the arguments to be passed to Read / Write // 3. The IAsyncResult returned from BeginRead / BeginWrite // 4. The completion action that runs to invoke the user-provided callback. // This last item is a bit tricky. Before the AsyncCallback is invoked, the // IAsyncResult must have completed, so we can't just invoke the handler // from within the task, since it is the IAsyncResult, and thus it's not // yet completed. Instead, we use AddCompletionAction to install this // task as its own completion handler. That saves the need to allocate // a separate completion handler, it guarantees that the task will // have completed by the time the handler is invoked, and it allows // the handler to be invoked synchronously upon the completion of the // task. This all enables BeginRead / BeginWrite to be implemented // with a single allocation. private sealed class ReadWriteTask : Task<int>, ITaskCompletionAction { internal readonly bool _isRead; internal Stream _stream; internal byte [] _buffer; internal int _offset; internal int _count; private AsyncCallback _callback; private ExecutionContext _context; internal void ClearBeginState() // Used to allow the args to Read/Write to be made available for GC { _stream = null; _buffer = null; } [SecuritySafeCritical] // necessary for EC.Capture [MethodImpl(MethodImplOptions.NoInlining)] public ReadWriteTask( bool isRead, Func<object,int> function, object state, Stream stream, byte[] buffer, int offset, int count, AsyncCallback callback) : base(function, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach) { Contract.Requires(function != null); Contract.Requires(stream != null); Contract.Requires(buffer != null); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; // Store the arguments _isRead = isRead; _stream = stream; _buffer = buffer; _offset = offset; _count = count; // If a callback was provided, we need to: // - Store the user-provided handler // - Capture an ExecutionContext under which to invoke the handler // - Add this task as its own completion handler so that the Invoke method // will run the callback when this task completes. if (callback != null) { _callback = callback; _context = ExecutionContext.Capture(ref stackMark, ExecutionContext.CaptureOptions.OptimizeDefaultCase | ExecutionContext.CaptureOptions.IgnoreSyncCtx); base.AddCompletionAction(this); } } [SecurityCritical] // necessary for CoreCLR private static void InvokeAsyncCallback(object completedTask) { var rwc = (ReadWriteTask)completedTask; var callback = rwc._callback; rwc._callback = null; callback(rwc); } [SecurityCritical] // necessary for CoreCLR private static ContextCallback s_invokeAsyncCallback; [SecuritySafeCritical] // necessary for ExecutionContext.Run void ITaskCompletionAction.Invoke(Task completingTask) { // Get the ExecutionContext. If there is none, just run the callback // directly, passing in the completed task as the IAsyncResult. // If there is one, process it with ExecutionContext.Run. var context = _context; if (context == null) { var callback = _callback; _callback = null; callback(completingTask); } else { _context = null; var invokeAsyncCallback = s_invokeAsyncCallback; if (invokeAsyncCallback == null) s_invokeAsyncCallback = invokeAsyncCallback = InvokeAsyncCallback; // benign ---- using(context) ExecutionContext.Run(context, invokeAsyncCallback, this, true); } } } #endif #if FEATURE_ASYNC_IO [HostProtection(ExternalThreading = true)] [ComVisible(false)] public Task WriteAsync(Byte[] buffer, int offset, int count) { return WriteAsync(buffer, offset, count, CancellationToken.None); } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public virtual Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { // If cancellation was requested, bail early with an already completed task. // Otherwise, return a task that represents the Begin/End methods. return cancellationToken.IsCancellationRequested ? Task.FromCancellation(cancellationToken) : BeginEndWriteAsync(buffer, offset, count); } private Task BeginEndWriteAsync(Byte[] buffer, Int32 offset, Int32 count) { return TaskFactory<VoidTaskResult>.FromAsyncTrim( this, new ReadWriteParameters { Buffer=buffer, Offset=offset, Count=count }, (stream, args, callback, state) => stream.BeginWrite(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler (stream, asyncResult) => // cached by compiler { stream.EndWrite(asyncResult); return default(VoidTaskResult); }); } #endif // FEATURE_ASYNC_IO public abstract long Seek(long offset, SeekOrigin origin); public abstract void SetLength(long value); public abstract int Read([In, Out] byte[] buffer, int offset, int count); // Reads one byte from the stream by calling Read(byte[], int, int). // Will return an unsigned byte cast to an int or -1 on end of stream. // This implementation does not perform well because it allocates a new // byte[] each time you call it, and should be overridden by any // subclass that maintains an internal buffer. Then, it can help perf // significantly for people who are reading one byte at a time. #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public virtual int ReadByte() { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < 256); byte[] oneByteArray = new byte[1]; int r = Read(oneByteArray, 0, 1); if (r==0) return -1; return oneByteArray[0]; } public abstract void Write(byte[] buffer, int offset, int count); // Writes one byte from the stream by calling Write(byte[], int, int). // This implementation does not perform well because it allocates a new // byte[] each time you call it, and should be overridden by any // subclass that maintains an internal buffer. Then, it can help perf // significantly for people who are writing one byte at a time. public virtual void WriteByte(byte value) { byte[] oneByteArray = new byte[1]; oneByteArray[0] = value; Write(oneByteArray, 0, 1); } [HostProtection(Synchronization=true)] public static Stream Synchronized(Stream stream) { if (stream==null) throw new ArgumentNullException("stream"); Contract.Ensures(Contract.Result<Stream>() != null); Contract.EndContractBlock(); if (stream is SyncStream) return stream; return new SyncStream(stream); } #if !FEATURE_PAL || MONO // This method shouldn't have been exposed in Dev10 (we revised object invariants after locking down). [Obsolete("Do not call or override this method.")] protected virtual void ObjectInvariant() { } #endif internal IAsyncResult BlockingBeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { Contract.Ensures(Contract.Result<IAsyncResult>() != null); // To avoid a race with a stream's position pointer & generating ---- // conditions with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread and do the IO synchronously. // This can't perform well - use a different approach. SynchronousAsyncResult asyncResult; try { int numRead = Read(buffer, offset, count); asyncResult = new SynchronousAsyncResult(numRead, state); } catch (IOException ex) { asyncResult = new SynchronousAsyncResult(ex, state, isWrite: false); } if (callback != null) { callback(asyncResult); } return asyncResult; } internal static int BlockingEndRead(IAsyncResult asyncResult) { Contract.Ensures(Contract.Result<int>() >= 0); return SynchronousAsyncResult.EndRead(asyncResult); } internal IAsyncResult BlockingBeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { Contract.Ensures(Contract.Result<IAsyncResult>() != null); // To avoid a race with a stream's position pointer & generating ---- // conditions with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread and do the IO synchronously. // This can't perform well - use a different approach. SynchronousAsyncResult asyncResult; try { Write(buffer, offset, count); asyncResult = new SynchronousAsyncResult(state); } catch (IOException ex) { asyncResult = new SynchronousAsyncResult(ex, state, isWrite: true); } if (callback != null) { callback(asyncResult); } return asyncResult; } internal static void BlockingEndWrite(IAsyncResult asyncResult) { SynchronousAsyncResult.EndWrite(asyncResult); } [Serializable] private sealed class NullStream : Stream { internal NullStream() {} public override bool CanRead { [Pure] get { return true; } } public override bool CanWrite { [Pure] get { return true; } } public override bool CanSeek { [Pure] get { return true; } } public override long Length { get { return 0; } } public override long Position { get { return 0; } set {} } protected override void Dispose(bool disposing) { // Do nothing - we don't want NullStream singleton (static) to be closable } public override void Flush() { } #if FEATURE_ASYNC_IO [ComVisible(false)] public override Task FlushAsync(CancellationToken cancellationToken) { return cancellationToken.IsCancellationRequested ? Task.FromCancellation(cancellationToken) : Task.CompletedTask; } #endif // FEATURE_ASYNC_IO [HostProtection(ExternalThreading = true)] public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { if (!CanRead) __Error.ReadNotSupported(); return BlockingBeginRead(buffer, offset, count, callback, state); } public override int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException("asyncResult"); Contract.EndContractBlock(); return BlockingEndRead(asyncResult); } [HostProtection(ExternalThreading = true)] public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { if (!CanWrite) __Error.WriteNotSupported(); return BlockingBeginWrite(buffer, offset, count, callback, state); } public override void EndWrite(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException("asyncResult"); Contract.EndContractBlock(); BlockingEndWrite(asyncResult); } public override int Read([In, Out] byte[] buffer, int offset, int count) { return 0; } #if FEATURE_ASYNC_IO [ComVisible(false)] public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { var nullReadTask = s_nullReadTask; if (nullReadTask == null) s_nullReadTask = nullReadTask = new Task<int>(false, 0, (TaskCreationOptions)InternalTaskOptions.DoNotDispose, CancellationToken.None); // benign ---- return nullReadTask; } private static Task<int> s_nullReadTask; #endif //FEATURE_ASYNC_IO public override int ReadByte() { return -1; } public override void Write(byte[] buffer, int offset, int count) { } #if FEATURE_ASYNC_IO [ComVisible(false)] public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return cancellationToken.IsCancellationRequested ? Task.FromCancellation(cancellationToken) : Task.CompletedTask; } #endif // FEATURE_ASYNC_IO public override void WriteByte(byte value) { } public override long Seek(long offset, SeekOrigin origin) { return 0; } public override void SetLength(long length) { } } /// <summary>Used as the IAsyncResult object when using asynchronous IO methods on the base Stream class.</summary> internal sealed class SynchronousAsyncResult : IAsyncResult { private readonly Object _stateObject; private readonly bool _isWrite; private ManualResetEvent _waitHandle; private ExceptionDispatchInfo _exceptionInfo; private bool _endXxxCalled; private Int32 _bytesRead; internal SynchronousAsyncResult(Int32 bytesRead, Object asyncStateObject) { _bytesRead = bytesRead; _stateObject = asyncStateObject; //_isWrite = false; } internal SynchronousAsyncResult(Object asyncStateObject) { _stateObject = asyncStateObject; _isWrite = true; } internal SynchronousAsyncResult(Exception ex, Object asyncStateObject, bool isWrite) { _exceptionInfo = ExceptionDispatchInfo.Capture(ex); _stateObject = asyncStateObject; _isWrite = isWrite; } public bool IsCompleted { // We never hand out objects of this type to the user before the synchronous IO completed: get { return true; } } public WaitHandle AsyncWaitHandle { get { return LazyInitializer.EnsureInitialized(ref _waitHandle, () => new ManualResetEvent(true)); } } public Object AsyncState { get { return _stateObject; } } public bool CompletedSynchronously { get { return true; } } internal void ThrowIfError() { if (_exceptionInfo != null) _exceptionInfo.Throw(); } internal static Int32 EndRead(IAsyncResult asyncResult) { SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult; if (ar == null || ar._isWrite) __Error.WrongAsyncResult(); if (ar._endXxxCalled) __Error.EndReadCalledTwice(); ar._endXxxCalled = true; ar.ThrowIfError(); return ar._bytesRead; } internal static void EndWrite(IAsyncResult asyncResult) { SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult; if (ar == null || !ar._isWrite) __Error.WrongAsyncResult(); if (ar._endXxxCalled) __Error.EndWriteCalledTwice(); ar._endXxxCalled = true; ar.ThrowIfError(); } } // class SynchronousAsyncResult // SyncStream is a wrapper around a stream that takes // a lock for every operation making it thread safe. [Serializable] internal sealed class SyncStream : Stream, IDisposable { private Stream _stream; [NonSerialized] private bool? _overridesBeginRead; [NonSerialized] private bool? _overridesBeginWrite; internal SyncStream(Stream stream) { if (stream == null) throw new ArgumentNullException("stream"); Contract.EndContractBlock(); _stream = stream; } public override bool CanRead { [Pure] get { return _stream.CanRead; } } public override bool CanWrite { [Pure] get { return _stream.CanWrite; } } public override bool CanSeek { [Pure] get { return _stream.CanSeek; } } [ComVisible(false)] public override bool CanTimeout { [Pure] get { return _stream.CanTimeout; } } public override long Length { get { lock(_stream) { return _stream.Length; } } } public override long Position { get { lock(_stream) { return _stream.Position; } } set { lock(_stream) { _stream.Position = value; } } } [ComVisible(false)] public override int ReadTimeout { get { return _stream.ReadTimeout; } set { _stream.ReadTimeout = value; } } [ComVisible(false)] public override int WriteTimeout { get { return _stream.WriteTimeout; } set { _stream.WriteTimeout = value; } } // In the off chance that some wrapped stream has different // semantics for Close vs. Dispose, let's preserve that. public override void Close() { lock(_stream) { try { _stream.Close(); } finally { base.Dispose(true); } } } protected override void Dispose(bool disposing) { lock(_stream) { try { // Explicitly pick up a potentially methodimpl'ed Dispose if (disposing) ((IDisposable)_stream).Dispose(); } finally { base.Dispose(disposing); } } } public override void Flush() { lock(_stream) _stream.Flush(); } public override int Read([In, Out]byte[] bytes, int offset, int count) { lock(_stream) return _stream.Read(bytes, offset, count); } public override int ReadByte() { lock(_stream) return _stream.ReadByte(); } private static bool OverridesBeginMethod(Stream stream, string methodName) { Contract.Requires(stream != null, "Expected a non-null stream."); Contract.Requires(methodName == "BeginRead" || methodName == "BeginWrite", "Expected BeginRead or BeginWrite as the method name to check."); // Get all of the methods on the underlying stream var methods = stream.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance); // If any of the methods have the desired name and are defined on the base Stream // Type, then the method was not overridden. If none of them were defined on the // base Stream, then it must have been overridden. foreach (var method in methods) { if (method.DeclaringType == typeof(Stream) && method.Name == methodName) { return false; } } return true; } [HostProtection(ExternalThreading=true)] public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { // Lazily-initialize whether the wrapped stream overrides BeginRead if (_overridesBeginRead == null) { _overridesBeginRead = OverridesBeginMethod(_stream, "BeginRead"); } lock (_stream) { // If the Stream does have its own BeginRead implementation, then we must use that override. // If it doesn't, then we'll use the base implementation, but we'll make sure that the logic // which ensures only one asynchronous operation does so with an asynchronous wait rather // than a synchronous wait. A synchronous wait will result in a deadlock condition, because // the EndXx method for the outstanding async operation won't be able to acquire the lock on // _stream due to this call blocked while holding the lock. return _overridesBeginRead.Value ? _stream.BeginRead(buffer, offset, count, callback, state) : _stream.BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: true); } } public override int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException("asyncResult"); Contract.Ensures(Contract.Result<int>() >= 0); Contract.EndContractBlock(); lock(_stream) return _stream.EndRead(asyncResult); } public override long Seek(long offset, SeekOrigin origin) { lock(_stream) return _stream.Seek(offset, origin); } public override void SetLength(long length) { lock(_stream) _stream.SetLength(length); } public override void Write(byte[] bytes, int offset, int count) { lock(_stream) _stream.Write(bytes, offset, count); } public override void WriteByte(byte b) { lock(_stream) _stream.WriteByte(b); } [HostProtection(ExternalThreading=true)] public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { // Lazily-initialize whether the wrapped stream overrides BeginWrite if (_overridesBeginWrite == null) { _overridesBeginWrite = OverridesBeginMethod(_stream, "BeginWrite"); } lock (_stream) { // If the Stream does have its own BeginWrite implementation, then we must use that override. // If it doesn't, then we'll use the base implementation, but we'll make sure that the logic // which ensures only one asynchronous operation does so with an asynchronous wait rather // than a synchronous wait. A synchronous wait will result in a deadlock condition, because // the EndXx method for the outstanding async operation won't be able to acquire the lock on // _stream due to this call blocked while holding the lock. return _overridesBeginWrite.Value ? _stream.BeginWrite(buffer, offset, count, callback, state) : _stream.BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: true); } } public override void EndWrite(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException("asyncResult"); Contract.EndContractBlock(); lock(_stream) _stream.EndWrite(asyncResult); } } } #if CONTRACTS_FULL [ContractClassFor(typeof(Stream))] internal abstract class StreamContract : Stream { public override long Seek(long offset, SeekOrigin origin) { Contract.Ensures(Contract.Result<long>() >= 0); throw new NotImplementedException(); } public override void SetLength(long value) { throw new NotImplementedException(); } public override int Read(byte[] buffer, int offset, int count) { Contract.Ensures(Contract.Result<int>() >= 0); Contract.Ensures(Contract.Result<int>() <= count); throw new NotImplementedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotImplementedException(); } public override long Position { get { Contract.Ensures(Contract.Result<long>() >= 0); throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public override void Flush() { throw new NotImplementedException(); } public override bool CanRead { get { throw new NotImplementedException(); } } public override bool CanWrite { get { throw new NotImplementedException(); } } public override bool CanSeek { get { throw new NotImplementedException(); } } public override long Length { get { Contract.Ensures(Contract.Result<long>() >= 0); throw new NotImplementedException(); } } } #endif // CONTRACTS_FULL }
using Cake.Common.Diagnostics; using Cake.Npm; using Cake.Yarn; using Cake.Npm.RunScript; using CK.Text; using CSemVer; using Newtonsoft.Json.Linq; using System; using System.Linq; using System.Text; using SimpleGitVersion; namespace CodeCake { /// <summary> /// Basic (unpublished) NPM project. /// </summary> public class YarnProject { protected YarnProject( StandardGlobalInfo globalInfo, YarnSolution npmSolution, YarnSimplePackageJsonFile json, NormalizedPath outputPath ) { DirectoryPath = json.JsonFilePath.RemoveLastPart(); PackageJson = json; OutputPath = outputPath; NPMRCPath = DirectoryPath.AppendPart( ".npmrc" ); GlobalInfo = globalInfo; NpmSolution = npmSolution; } protected static YarnProject CreateYarnProject( StandardGlobalInfo globalInfo, YarnSolution npmSolution, YarnSimplePackageJsonFile json, NormalizedPath outputPath ) { return new YarnProject( globalInfo, npmSolution, json, outputPath ); } public StandardGlobalInfo GlobalInfo { get; } public YarnSolution NpmSolution { get; } public virtual bool IsPublished => false; public NormalizedPath DirectoryPath { get; } public YarnSimplePackageJsonFile PackageJson { get; } public NormalizedPath OutputPath { get; } public NormalizedPath NPMRCPath { get; } /// <summary> /// Runs "yarn install --frozen-lockfile" (instead of "npm ci") on this project. /// See https://docs.npmjs.com/cli/ci.html. /// </summary> /// <param name="globalInfo">The global information object.</param> public virtual void RunYarnCi() { GlobalInfo.Cake.Information( $"Running 'yarn install --immutable' in {DirectoryPath.Path}" ); GlobalInfo.Cake.Yarn().Install(settings => { settings.WithArgument( "--immutable" ); settings.WorkingDirectory = DirectoryPath.Path; } ); } /// <summary> /// Gets whether this package has a named script entry. /// </summary> /// <param name="name">Script name.</param> /// <returns>Whether the script exists.</returns> public bool HasScript( string name ) => PackageJson.Scripts.Contains( name ); /// <summary> /// Finds either "baseName-debug", "baseName-release" depending on <see cref="ICommitBuildInfo.BuildConfiguration"/> /// and falls back to baseName if specific scripts don't exist. /// By default, at least 'baseName' must exist otherwise an InvalidOperationException is thrown. /// </summary> /// <param name="baseName">Base name to look for.</param> /// <param name="checkBaseNameExist"> /// By default, at least baseName must exist otherwise an InvalidOperationException is thrown. /// When false, no check is done for baseName that is returned as-is. /// When null (and baseName cannot be found), null is returned. /// </param> /// <returns>The best script (or null if it doesn't exist and <paramref name="checkBaseNameExist"/> is null).</returns> public string FindBestScript( string baseName, bool? checkBaseNameExist = true ) { string n = baseName + '-' + GlobalInfo.BuildInfo.BuildConfiguration; if( HasScript( n ) ) return n; if( checkBaseNameExist == null ) { return HasScript( baseName ) ? baseName : null; } else if( checkBaseNameExist == true ) { if( HasScript( baseName ) ) return baseName; throw new InvalidOperationException( $"Missing script '{baseName}' in {PackageJson.JsonFilePath}." ); } return baseName; } /// <summary> /// Finds either "name-debug", "name-release" depending on <see cref="StandardGlobalInfo.IsRelease"/> /// and falls back to "name". By default if no script is found an <see cref="InvalidOperationException"/> /// is thrown. To emit a Cake warning (and return null) if the script can't be found, /// let <paramref name="scriptMustExist"/> be false. /// </summary> /// <param name="globalInfo">The global info object.</param> /// <param name="name">Base script name to look for.</param> /// <param name="scriptMustExist"> /// False to emit a warning and return null if the script doesn't exist. /// By default if no script is found an <see cref="InvalidOperationException"/> is thrown. /// </param> /// <returns>The best script (or null if it doesn't exist and <paramref name="scriptMustExist"/> is false).</returns> public string FindBestScript( string name, bool scriptMustExist = true ) { string n = FindBestScript( name, scriptMustExist ? (bool?)true : null ); if( n == null ) { GlobalInfo.Cake.Warning( $"Missing script '{name}' in '{PackageJson.JsonFilePath}'." ); } return n; } /// <summary> /// Run clean script (that must exist, see <see cref="FindBestScript(string, bool)"/>). /// </summary> /// <param name="cleanScriptName">Clean script name.</param> /// <returns></returns> public virtual void RunClean() { RunScript( "clean", false, true ); } /// <summary> /// Runs the 'name-debug', 'name-release' or 'name' script (see <see cref="FindBestScript(string, bool)"/>). /// </summary> /// <param name="scriptMustExist"> /// False to only emit a warning and return false if the script doesn't exist instead of /// throwing an exception. /// </param> /// <param name="runInBuildDirectory">Whether the script should be run in <see cref="OutputPath"/> or <see cref="DirectoryPath"/> if false.</param> /// <returns>False if the script doesn't exist (<paramref name="scriptMustExist"/> is false), otherwise true.</returns> public bool RunScript( string name, bool runInBuildDirectory, bool scriptMustExist ) { string n = FindBestScript( name, scriptMustExist ); if( n == null ) return false; DoRunScript( n, runInBuildDirectory ); return true; } /// <summary> /// Run a npm script. /// </summary> /// <param name="scriptName">The npm script to run.</param> /// <param name="runInBuildDirectory">Whether the script should be run in <see cref="OutputPath"/> or <see cref="DirectoryPath"/> if false.</param> private protected virtual void DoRunScript( string scriptName, bool runInBuildDirectory ) { GlobalInfo.Cake.Yarn().RunScript( scriptName, settings => { settings.WorkingDirectory = runInBuildDirectory ? OutputPath.Path : DirectoryPath.Path; } ); } /// <summary> /// Runs "build" script: see <see cref="RunScript(string, bool)"/>. /// </summary> /// <param name="globalInfo">The global information object.</param> /// <param name="scriptMustExist"> /// False to only emit a warning and return false if the script doesn't exist instead of /// throwing an exception. /// </param> /// <returns>False if the script doesn't exist (<paramref name="scriptMustExist"/> is false), otherwise true.</returns> public bool RunBuild( bool scriptMustExist = true ) => RunScript( "build", false, scriptMustExist ); /// <summary> /// Runs "test" script: see <see cref="RunScript(string, bool)"/>. /// </summary> /// <param name="globalInfo">The global information object.</param> /// <param name="scriptMustExist"> /// False to only emit a warning and return false if the script doesn't exist instead of /// throwing an exception. /// </param> /// <returns>False if the script doesn't exist (<paramref name="scriptMustExist"/> is false), otherwise true.</returns> public void RunTest() { var key = DirectoryPath.AppendPart( "test" ); if( !GlobalInfo.CheckCommitMemoryKey( key ) ) { RunScript( "test", false, true ); GlobalInfo.WriteCommitMemoryKey( key ); } } private protected IDisposable TemporarySetPackageVersion( SVersion version, bool targetOutputPath = false ) { return YarnTempFileTextModification.TemporaryReplacePackageVersion( !targetOutputPath ? PackageJson.JsonFilePath : OutputPath.AppendPart( "package.json" ), version ); } private protected IDisposable TemporaryPrePack( SVersion version, Action<JObject> packageJsonPreProcessor, bool ckliLocalFeedMode ) { return YarnTempFileTextModification.TemporaryReplaceDependenciesVersion( NpmSolution, OutputPath.AppendPart( "package.json" ), ckliLocalFeedMode, version, packageJsonPreProcessor ); } #region .npmrc configuration public IDisposable TemporarySetPushTargetAndTokenLogin( string pushUri, string token ) { return YarnTempFileTextModification.TemporaryInjectNPMToken( NPMRCPath, pushUri, PackageJson.Scope, ( npmrc, u ) => npmrc.Add( u + ":_authToken=" + token ) ); } public IDisposable TemporarySetPushTargetAndPasswordLogin( string pushUri, string password ) { return YarnTempFileTextModification.TemporaryInjectNPMToken( NPMRCPath, pushUri, PackageJson.Scope, ( npmrc, u ) => { npmrc.Add( u + ":username=CodeCakeBuilder" ); npmrc.Add( u + ":_password=" + password ); } ); } public IDisposable TemporarySetPushTargetAndAzurePatLogin( string pushUri, string pat ) { var pwd = Convert.ToBase64String( Encoding.UTF8.GetBytes( pat ) ); return TemporarySetPushTargetAndPasswordLogin( pushUri, pwd ); } #endregion } }
// $Id: mxCodec.cs,v 1.26 2010-09-20 06:21:37 gaudenz Exp $ // Copyright (c) 2007-2008, Gaudenz Alder using System; using System.Collections.Generic; using System.Text; using System.Xml; namespace com.mxgraph { /// <summary> /// XML codec for .NET object graphs. In order to resolve forward references /// when reading files the XML document that contains the data must be passed /// to the constructor. /// </summary> public class mxCodec { /// <summary> /// Holds the owner document of the codec. /// </summary> protected XmlDocument document; /// <summary> /// Maps from IDs to objects. /// </summary> protected Dictionary<string, object> objects = new Dictionary<string, Object>(); /// <summary> /// Specifies if default values should be encoded. Default is false. /// </summary> protected bool encodeDefaults = false; /// <summary> /// Constructs an XML encoder/decoder with a new owner document. /// </summary> public mxCodec() : this(mxUtils.CreateDocument()) { } /// <summary> /// Constructs an XML encoder/decoder for the specified owner document. The document is /// required to resolve forward ID references. This means if you parse a graphmodel that /// is represented in XML you must also pass the document that contains the XML to the /// constructor, otherwise forward references will not be resolved. /// </summary> /// <param name="document">Optional XML document that contains the data. If no document /// is specified then a new document is created using mxUtils.createDocument</param> public mxCodec(XmlDocument document) { if (document == null) { document = mxUtils.CreateDocument(); } this.document = document; } /// <summary> /// Sets or returns the owner document of the codec. /// </summary> /// <returns>Returns the owner document.</returns> public XmlDocument Document { get { return document; } set { document = value; } } /// <summary> /// Sets or returns if default values of member variables should be encoded. /// </summary> public bool IsEncodeDefaults { get { return encodeDefaults; } set { encodeDefaults = value; } } /// <summary> /// Returns the object lookup table. /// </summary> public Dictionary<string, object> Objects { get { return objects; } } /// <summary> /// Assoiates the given object with the given ID. /// </summary> /// <param name="id">ID for the object to be associated with.</param> /// <param name="obj">Object to be associated with the ID.</param> /// <returns>Returns the given object.</returns> public Object PutObject(string id, Object obj) { return objects[id] = obj; } /// <summary> /// Returns the decoded object for the element with the specified ID in /// document. If the object is not known then lookup is used to find an /// object. If no object is found, then the element with the respective ID /// from the document is parsed using decode. /// </summary> /// <param name="id">ID of the object to be returned.</param> /// <returns>Returns the object for the given ID.</returns> public Object GetObject(string id) { Object obj = null; if (id != null) { obj = (objects.ContainsKey(id)) ? objects[id] : null; if (obj == null) { obj = Lookup(id); if (obj == null) { XmlNode node = GetElementById(id); if (node != null) { obj = Decode(node); } } } } return obj; } /// <summary> /// Hook for subclassers to implement a custom lookup mechanism for cell IDs. /// This implementation always returns null. /// </summary> /// <param name="id">ID of the object to be returned.</param> /// <returns>Returns the object for the given ID.</returns> public Object Lookup(string id) { return null; } /// <summary> /// Returns the element with the given ID from the document. /// </summary> /// <param name="id">ID of the element to be returned.</param> /// <returns>Returns the element for the given ID.</returns> public XmlNode GetElementById(string id) { return GetElementById(id, null); } /// <summary> /// Returns the element with the given ID from document. The optional attr /// argument specifies the name of the ID attribute. Default is id. The /// XPath expression used to find the element is //*[\@id='arg'] where id /// is the name of the ID attribute (attributeName) and arg is the given id. /// </summary> /// <param name="id">ID of the element to be returned.</param> /// <param name="attributeName">Optional string for the attributename. Default is id.</param> /// <returns>Returns the element for the given ID.</returns> public XmlNode GetElementById(string id, string attributeName) { if (attributeName == null) { attributeName = "id"; } string expr = "//*[@" + attributeName + "='" + id + "']"; return mxUtils.SelectSingleNode(document, expr); } /// <summary> /// Returns the ID of the specified object. This implementation calls /// reference first and if that returns null handles the object as an /// mxCell by returning their IDs using mxCell.getId. If no ID exists for /// the given cell, then an on-the-fly ID is generated using /// mxCellPath.create. /// </summary> /// <param name="obj">Object to return the ID for.</param> /// <returns>Returns the ID for the given object.</returns> public string GetId(Object obj) { string id = null; if (obj != null) { id = Reference(obj); if (id == null && obj is mxICell) { id = ((mxICell)obj).Id; if (id == null) { // Uses an on-the-fly Id id = mxCellPath.Create((mxICell)obj); if (id.Length == 0) { id = "root"; } } } } return id; } /// <summary> /// Hook for subclassers to implement a custom method for retrieving IDs from /// objects. This implementation always returns null. /// </summary> /// <param name="obj">Object whose ID should be returned.</param> /// <returns>Returns the ID for the given object.</returns> public string Reference(Object obj) { return null; } /// <summary> /// Encodes the specified object and returns the resulting XML node. /// </summary> /// <param name="obj">Object to be encoded.</param> /// <returns>Returns an XML node that represents the given object.</returns> public XmlNode Encode(Object obj) { XmlNode node = null; if (obj != null) { string name = mxCodecRegistry.GetName(obj); mxObjectCodec enc = mxCodecRegistry.GetCodec(name); if (enc != null) { node = enc.Encode(this, obj); } else { if (obj is XmlNode) { node = ((XmlNode)obj).CloneNode(true); } else { Console.WriteLine("No codec for " + name); } } } return node; } /// <summary> /// Decodes the given XML node using decode(XmlNode, Object). /// </summary> /// <param name="node">XML node to be decoded.</param> /// <returns>Returns an object that represents the given node.</returns> public Object Decode(XmlNode node) { return Decode(node, null); } /// <summary> /// Decodes the given XML node. The optional "into" argument specifies an /// existing object to be used. If no object is given, then a new /// instance is created using the constructor from the codec. /// The function returns the passed in object or the new instance if no /// object was given. /// </summary> /// <param name="node">XML node to be decoded.</param> /// <param name="into">Optional object to be decodec into.</param> /// <returns>Returns an object that represents the given node.</returns> public Object Decode(XmlNode node, Object into) { Object obj = null; if (node != null && node.NodeType == XmlNodeType.Element) { mxObjectCodec codec = mxCodecRegistry.GetCodec(node.Name); try { if (codec != null) { obj = codec.Decode(this, node, into); } else { obj = node.CloneNode(true); ((XmlElement)obj).RemoveAttribute("as"); } } catch (Exception e) { Console.WriteLine("Cannot decode " + node.Name + ": " + e.Message); } } return obj; } /// <summary> /// Encoding of cell hierarchies is built-into the core, but is a /// higher-level function that needs to be explicitely used by the /// respective object encoders (eg. mxModelCodec, mxChildChangeCodec /// and mxRootChangeCodec). This implementation writes the given cell /// and its children as a (flat) sequence into the given node. The /// children are not encoded if the optional includeChildren is false. /// The function is in charge of adding the result into the given node /// and has no return value. /// </summary> /// <param name="cell">mxCell to be encoded.</param> /// <param name="node">Parent XML node to add the encoded cell into.</param> /// <param name="includeChildren">Boolean indicating if the method should /// include all descendents</param> public void EncodeCell(mxICell cell, XmlNode node, bool includeChildren) { node.AppendChild(Encode(cell)); if (includeChildren) { int childCount = cell.ChildCount(); for (int i = 0; i < childCount; i++) { EncodeCell(cell.GetChildAt(i), node, includeChildren); } } } /// <summary> /// Decodes cells that have been encoded using inversion, ie. where the /// user object is the enclosing node in the XML, and restores the group /// and graph structure in the cells. Returns a new mxCell instance /// that represents the given node. /// </summary> /// <param name="node">XML node that contains the cell data.</param> /// <param name="restoreStructures">Boolean indicating whether the graph /// structure should be restored by calling insert and insertEdge on the /// parent and terminals, respectively. /// </param> /// <returns>Graph cell that represents the given node.</returns> public mxICell DecodeCell(XmlNode node, bool restoreStructures) { mxICell cell = null; if (node != null && node.NodeType == XmlNodeType.Element) { // Tries to find a codec for the given node name. If that does // not return a codec then the node is the user object (an XML node // that contains the mxCell, aka inversion). mxObjectCodec decoder = mxCodecRegistry.GetCodec(node.Name); // Tries to find the codec for the cell inside the user object. // This assumes all node names inside the user object are either // not registered or they correspond to a class for cells. if (decoder == null) { XmlNode child = node.FirstChild; while (child != null && !(decoder is mxCellCodec)) { decoder = mxCodecRegistry.GetCodec(child.Name); child = child.NextSibling; } } if (!(decoder is mxCellCodec)) { decoder = mxCodecRegistry.GetCodec("mxCell"); } cell = (mxICell)decoder.Decode(this, node); if (restoreStructures) { InsertIntoGraph(cell); } } return cell; } /// <summary> /// Inserts the given cell into its parent and terminal cells. /// </summary> /// <param name="cell"></param> public void InsertIntoGraph(mxICell cell) { mxICell parent = cell.Parent; mxICell source = cell.GetTerminal(true); mxICell target = cell.GetTerminal(false); // Fixes possible inconsistencies during insert into graph cell.SetTerminal(null, false); cell.SetTerminal(null, true); cell.Parent = null; if (parent != null) { parent.Insert(cell); } if (source != null) { source.InsertEdge(cell, true); } if (target != null) { target.InsertEdge(cell, false); } } /// <summary> /// Sets the attribute on the specified node to value. This is a /// helper method that makes sure the attribute and value arguments /// are not null. /// </summary> /// <param name="node">XML node to set the attribute for.</param> /// <param name="attribute">Attributename to be set.</param> /// <param name="value">New value of the attribute.</param> public static void SetAttribute(XmlNode node, string attribute, Object value) { if (node.NodeType == XmlNodeType.Element && attribute != null && value != null) { ((XmlElement)node).SetAttribute(attribute, value.ToString()); } } } }
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 DeveloperInterviewProject.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// 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; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Xml; using System.Xml.Linq; using System.Xml.Schema; using System.Xml.Serialization; using System.IO; using System.Text; using System.Reflection; using System.Threading.Tasks; using System.Runtime.Serialization.Json; namespace SerializationTypes { public class TypeWithDateTimeStringProperty { public string DateTimeString; public DateTime CurrentDateTime; public TypeWithDateTimeStringProperty() { } } public class SimpleType { public string P1 { get; set; } public int P2 { get; set; } public static bool AreEqual(SimpleType x, SimpleType y) { if (x == null) { return y == null; } else if (y == null) { return x == null; } else { return (x.P1 == y.P1) && (x.P2 == y.P2); } } } public class TypeWithGetSetArrayMembers { public SimpleType[] F1; public int[] F2; public SimpleType[] P1 { get; set; } public int[] P2 { get; set; } } public class TypeWithGetOnlyArrayProperties { private SimpleType[] _p1 = new SimpleType[2]; private int[] _p2 = new int[2]; public SimpleType[] P1 { get { return _p1; } } public int[] P2 { get { return _p2; } } } public struct StructNotSerializable { public int value; public override int GetHashCode() { return value; } } public class MyCollection<T> : ICollection<T> { private List<T> _items = new List<T>(); public MyCollection() { } public MyCollection(params T[] values) { _items.AddRange(values); } public void Add(T item) { _items.Add(item); } public void Clear() { _items.Clear(); } public bool Contains(T item) { return _items.Contains(item); } public void CopyTo(T[] array, int arrayIndex) { _items.CopyTo(array, arrayIndex); } public int Count { get { return _items.Count; } } public bool IsReadOnly { get { return ((ICollection<T>)_items).IsReadOnly; } } public bool Remove(T item) { return _items.Remove(item); } public IEnumerator<T> GetEnumerator() { return ((ICollection<T>)_items).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_items).GetEnumerator(); } } public class TypeWithMyCollectionField { public MyCollection<string> Collection; } public class TypeWithReadOnlyMyCollectionProperty { private MyCollection<string> _ro = new MyCollection<string>(); public MyCollection<string> Collection { get { return _ro; } } } public class MyList : IList { private List<object> _items = new List<object>(); public MyList() { } public MyList(params object[] values) { _items.AddRange(values); } public int Add(object value) { return ((IList)_items).Add(value); } public void Clear() { throw new NotImplementedException(); } public bool Contains(object value) { return _items.Contains(value); } public int IndexOf(object value) { throw new NotImplementedException(); } public void Insert(int index, object value) { throw new NotImplementedException(); } public bool IsFixedSize { get { throw new NotImplementedException(); } } public bool IsReadOnly { get { throw new NotImplementedException(); } } public void Remove(object value) { throw new NotImplementedException(); } public void RemoveAt(int index) { throw new NotImplementedException(); } public object this[int index] { get { return _items[index]; } set { throw new NotImplementedException(); } } public void CopyTo(Array array, int index) { throw new NotImplementedException(); } public int Count { get { return _items.Count; } } public bool IsSynchronized { get { throw new NotImplementedException(); } } public object SyncRoot { get { throw new NotImplementedException(); } } public IEnumerator GetEnumerator() { return ((IEnumerable)_items).GetEnumerator(); } } public enum MyEnum { [EnumMember] One, Two, [EnumMember] Three } public class TypeWithEnumMembers { public MyEnum F1; public MyEnum P1 { get; set; } } [DataContract] public struct DCStruct { [DataMember] public string Data; public DCStruct(bool init) { Data = "Data"; } } [DataContract] public class DCClassWithEnumAndStruct { [DataMember] public DCStruct MyStruct; [DataMember] public MyEnum MyEnum1; public DCClassWithEnumAndStruct() { } public DCClassWithEnumAndStruct(bool init) { MyStruct = new DCStruct(init); } } public class BuiltInTypes { public byte[] ByteArray { get; set; } } public class TypeA { public string Name; } public class TypeB { public string Name; public static implicit operator TypeA(TypeB i) { return new TypeA { Name = i.Name }; } public static implicit operator TypeB(TypeA i) { return new TypeB { Name = i.Name }; } } public class TypeHasArrayOfASerializedAsB { public TypeA[] Items; public TypeHasArrayOfASerializedAsB() { } public TypeHasArrayOfASerializedAsB(bool init) { Items = new TypeA[] { new TypeA { Name = "typeAValue" }, new TypeB { Name = "typeBValue" }, }; } } public class __TypeNameWithSpecialCharacters\u6F22\u00F1 { public string PropertyNameWithSpecialCharacters\u6F22\u00F1 { get; set; } } public class BaseClassWithSamePropertyName { [DataMember] public string StringProperty; [DataMember] public int IntProperty; [DataMember] public DateTime DateTimeProperty; [DataMember] public List<string> ListProperty; } public class DerivedClassWithSameProperty : BaseClassWithSamePropertyName { [DataMember] public new string StringProperty; [DataMember] public new int IntProperty; [DataMember] public new DateTime DateTimeProperty; [DataMember] public new List<string> ListProperty; } public class DerivedClassWithSameProperty2 : DerivedClassWithSameProperty { [DataMember] public new DateTime DateTimeProperty; [DataMember] public new List<string> ListProperty; } public class TypeWithDateTimePropertyAsXmlTime { DateTime _value; [XmlText(DataType = "time")] public DateTime Value { get { return _value; } set { _value = value; } } } public class TypeWithByteArrayAsXmlText { [XmlText(DataType = "base64Binary")] public byte[] Value; } [DataContract(IsReference = false)] public class SimpleDC { [DataMember] public string Data; public SimpleDC() { } public SimpleDC(bool init) { Data = DateTime.MaxValue.ToString("T", CultureInfo.InvariantCulture); } } [XmlRoot(Namespace = "http://schemas.xmlsoap.org/ws/2005/04/discovery", IsNullable = false)] public class TypeWithXmlTextAttributeOnArray { [XmlText] public string[] Text; } [Flags] public enum EnumFlags { [EnumMember] One = 0x01, [EnumMember] Two = 0x02, [EnumMember] Three = 0x04, [EnumMember] Four = 0x08 } public interface IBaseInterface { string ClassID { get; } string DisplayName { get; set; } string Id { get; set; } bool IsLoaded { get; set; } } [DataContract] public class ClassImplementsInterface : IBaseInterface { public virtual string ClassID { get; set; } [DataMember] public string DisplayName { get; set; } [DataMember] public string Id { get; set; } public bool IsLoaded { get; set; } } #region XmlSerializer specific public class WithStruct { public SomeStruct Some { get; set; } } public struct SomeStruct { public int A; public int B; } public class WithEnums { public IntEnum Int { get; set; } public ShortEnum Short { get; set; } } public class WithNullables { public IntEnum? Optional { get; set; } public IntEnum? Optionull { get; set; } public int? OptionalInt { get; set; } public Nullable<int> OptionullInt { get; set; } public SomeStruct? Struct1 { get; set; } public SomeStruct? Struct2 { get; set; } } public enum ByteEnum : byte { Option0, Option1, Option2 } public enum SByteEnum : sbyte { Option0, Option1, Option2 } public enum ShortEnum : short { Option0, Option1, Option2 } public enum IntEnum { Option0, Option1, Option2 } public enum UIntEnum : uint { Option0, Option1, Option2 } public enum LongEnum : long { Option0, Option1, Option2 } public enum ULongEnum : ulong { Option0, Option1, Option2 } [XmlRoot(DataType = "XmlSerializerAttributes", ElementName = "AttributeTesting", IsNullable = false)] [XmlInclude(typeof(ItemChoiceType))] public class XmlSerializerAttributes { public XmlSerializerAttributes() { XmlElementProperty = 1; XmlAttributeProperty = 2; XmlArrayProperty = new string[] { "one", "two", "three" }; EnumType = ItemChoiceType.Word; MyChoice = "String choice value"; XmlIncludeProperty = ItemChoiceType.DecimalNumber; XmlEnumProperty = new ItemChoiceType[] { ItemChoiceType.DecimalNumber, ItemChoiceType.Number, ItemChoiceType.Word, ItemChoiceType.None }; XmlTextProperty = "<xml>Hello XML</xml>"; XmlNamespaceDeclarationsProperty = "XmlNamespaceDeclarationsPropertyValue"; } [XmlElement(DataType = "int", ElementName = "XmlElementPropertyNode", Namespace = "http://element", Type = typeof(int))] public int XmlElementProperty { get; set; } [XmlAttribute(AttributeName = "XmlAttributeName")] public int XmlAttributeProperty { get; set; } [XmlArray(ElementName = "CustomXmlArrayProperty", Namespace = "http://mynamespace")] [XmlArrayItem(typeof(string))] public object[] XmlArrayProperty { get; set; } [XmlChoiceIdentifier("EnumType")] [XmlElement("Word", typeof(string))] [XmlElement("Number", typeof(int))] [XmlElement("DecimalNumber", typeof(double))] public object MyChoice; // Don't serialize this field. The EnumType field contains the enumeration value that corresponds to the MyChoice field value. [XmlIgnore] public ItemChoiceType EnumType; [XmlElement] public object XmlIncludeProperty; [XmlEnum("EnumProperty")] public ItemChoiceType[] XmlEnumProperty; [XmlText] public string XmlTextProperty; [XmlNamespaceDeclarations] public string XmlNamespaceDeclarationsProperty; } [XmlType(IncludeInSchema = false)] public enum ItemChoiceType { None, Word, Number, DecimalNumber } public class TypeWithAnyAttribute { public string Name; [XmlAttribute] public int IntProperty { get; set; } [XmlAnyAttribute] public XmlAttribute[] Attributes { get; set; } } public class KnownTypesThroughConstructor { public object EnumValue; public object SimpleTypeValue; } public class SimpleKnownTypeValue { public string StrProperty { get; set; } } public class ClassImplementingIXmlSerialiable : IXmlSerializable { public static bool WriteXmlInvoked = false; public static bool ReadXmlInvoked = false; public string StringValue { get; set; } private bool BoolValue { get; set; } public ClassImplementingIXmlSerialiable() { BoolValue = true; } public bool GetPrivateMember() { return BoolValue; } public System.Xml.Schema.XmlSchema GetSchema() { return null; } public void ReadXml(System.Xml.XmlReader reader) { ReadXmlInvoked = true; reader.MoveToContent(); StringValue = reader.GetAttribute("StringValue"); BoolValue = bool.Parse(reader.GetAttribute("BoolValue")); } public void WriteXml(System.Xml.XmlWriter writer) { WriteXmlInvoked = true; writer.WriteAttributeString("StringValue", StringValue); writer.WriteAttributeString("BoolValue", BoolValue.ToString()); } } public class TypeWithPropertyNameSpecified { public string MyField; [XmlIgnore] public bool MyFieldSpecified; public int MyFieldIgnored; [XmlIgnore] public bool MyFieldIgnoredSpecified; } [XmlType(Namespace = ""), XmlRoot(Namespace = "", IsNullable = true)] public class TypeWithXmlSchemaFormAttribute { [XmlArray(Form = XmlSchemaForm.Unqualified)] public List<int> UnqualifiedSchemaFormListProperty { get; set; } [XmlArray(Form = XmlSchemaForm.None), XmlArrayItem("NoneParameter", Form = XmlSchemaForm.None, IsNullable = false)] public List<string> NoneSchemaFormListProperty { get; set; } [XmlArray(Form = XmlSchemaForm.Qualified), XmlArrayItem("QualifiedParameter", Form = XmlSchemaForm.Qualified, IsNullable = false)] public List<bool> QualifiedSchemaFormListProperty { get; set; } } [XmlType(TypeName = "MyXmlType")] public class TypeWithTypeNameInXmlTypeAttribute { [XmlAttribute(Form = XmlSchemaForm.Qualified)] public string XmlAttributeForm; } [XmlType(AnonymousType = true)] public class TypeWithSchemaFormInXmlAttribute { [XmlAttribute(Form = XmlSchemaForm.Qualified, Namespace = "http://test.com")] public string TestProperty; } #endregion public class TypeWithNonPublicDefaultConstructor { private static string s_prefix; static TypeWithNonPublicDefaultConstructor() { s_prefix = "Mr. "; } private TypeWithNonPublicDefaultConstructor() { Name = s_prefix + "FooName"; } public string Name { get; set; } } // Comes from app: The Weather Channel. See bug 1101076 for details public class ServerSettings { public string DS2Root { get; set; } public string MetricConfigUrl { get; set; } } [DataContract] public class TypeWithXmlQualifiedName { [DataMember(IsRequired = true, EmitDefaultValue = false)] public XmlQualifiedName Value { get; set; } } public class TypeWith2DArrayProperty2 { [System.Xml.Serialization.XmlArrayItemAttribute("SimpleType", typeof(SimpleType[]), IsNullable = false)] public SimpleType[][] TwoDArrayOfSimpleType; } public class TypeWithPropertiesHavingDefaultValue { [DefaultValue("")] public string EmptyStringProperty { get; set; } = ""; [DefaultValue("DefaultString")] public string StringProperty { get; set; } = "DefaultString"; [DefaultValue(11)] public int IntProperty { get; set; } = 11; [DefaultValue('m')] public char CharProperty { get; set; } = 'm'; } public class TypeWithEnumPropertyHavingDefaultValue { [DefaultValue(1)] public IntEnum EnumProperty { get; set; } = IntEnum.Option1; } public class TypeWithEnumFlagPropertyHavingDefaultValue { [DefaultValue(EnumFlags.One | EnumFlags.Four)] public EnumFlags EnumProperty { get; set; } = EnumFlags.One | EnumFlags.Four; } public class TypeWithShouldSerializeMethod { private static readonly string DefaultFoo = "default"; public string Foo { get; set; } = DefaultFoo; public bool ShouldSerializeFoo() { return Foo != DefaultFoo; } } public class KnownTypesThroughConstructorWithArrayProperties { public object StringArrayValue; public object IntArrayValue; } public class KnownTypesThroughConstructorWithValue { public object Value; } public class TypeWithTypesHavingCustomFormatter { [XmlElement(DataType = "dateTime")] public DateTime DateTimeContent; [XmlElement(DataType = "QName")] public XmlQualifiedName QNameContent; // The case where DataType = "date" is verified by Xml_TypeWithDateTimePropertyAsXmlTime. [XmlElement(DataType = "date")] public DateTime DateContent; [XmlElement(DataType = "Name")] public string NameContent; [XmlElement(DataType = "NCName")] public string NCNameContent; [XmlElement(DataType = "NMTOKEN")] public string NMTOKENContent; [XmlElement(DataType = "NMTOKENS")] public string NMTOKENSContent; [XmlElement(DataType = "base64Binary")] public byte[] Base64BinaryContent; [XmlElement(DataType = "hexBinary")] public byte[] HexBinaryContent; } public class TypeWithArrayPropertyHavingChoice { // The ManyChoices field can contain an array // of choices. Each choice must be matched to // an array item in the ChoiceArray field. [XmlChoiceIdentifier("ChoiceArray")] [XmlElement("Item", typeof(string))] [XmlElement("Amount", typeof(int))] public object[] ManyChoices; // TheChoiceArray field contains the enumeration // values, one for each item in the ManyChoices array. [XmlIgnore] public MoreChoices[] ChoiceArray; } public enum MoreChoices { None, Item, Amount } public class TypeWithFieldsOrdered { [XmlElement(Order = 0)] public int IntField1; [XmlElement(Order = 1)] public int IntField2; [XmlElement(Order = 3)] public string StringField1; [XmlElement(Order = 2)] public string StringField2; } [KnownType(typeof(List<SimpleType>))] [KnownType(typeof(SimpleType[]))] [DataContract] public class TypeWithKnownTypesOfCollectionsWithConflictingXmlName { [DataMember] public object Value1 = new List<SimpleType>(); [DataMember] public object Value2 = new SimpleType[1]; } } public class TypeWithXmlElementProperty { [XmlAnyElement] public XmlElement[] Elements; } public class TypeWithXmlDocumentProperty { public XmlDocument Document; } public class TypeWithBinaryProperty { [XmlElement(DataType = "hexBinary")] public byte[] BinaryHexContent { get; set; } [XmlElement(DataType = "base64Binary")] public byte[] Base64Content { get; set; } } public class TypeWithTimeSpanProperty { public TimeSpan TimeSpanProperty; } public class TypeWithDefaultTimeSpanProperty { public TypeWithDefaultTimeSpanProperty() { TimeSpanProperty = GetDefaultValue("TimeSpanProperty"); TimeSpanProperty2 = GetDefaultValue("TimeSpanProperty2"); } [DefaultValue(typeof(TimeSpan), "00:01:00")] public TimeSpan TimeSpanProperty { get; set; } [DefaultValue(typeof(TimeSpan), "00:00:01")] public TimeSpan TimeSpanProperty2 { get; set; } public TimeSpan GetDefaultValue(string propertyName) { var property = this.GetType().GetProperty(propertyName); var attribute = property.GetCustomAttribute(typeof(DefaultValueAttribute)) as DefaultValueAttribute; if (attribute != null) { return (TimeSpan)attribute.Value; } else { return new TimeSpan(0, 0, 0); } } } public class TypeWithByteProperty { public byte ByteProperty; } [XmlRoot()] public class TypeWithXmlNodeArrayProperty { [XmlText] public XmlNode[] CDATA { get; set; } } public class Animal { public int Age; public string Name; } public class Dog : Animal { public DogBreed Breed; } public enum DogBreed { GermanShepherd, LabradorRetriever } public class Group { public string GroupName; public Vehicle GroupVehicle; } public class Vehicle { public string LicenseNumber; } [DataContract(Namespace = "www.msn.com/Examples/")] public class Employee { [DataMember] public string EmployeeName; [DataMember] private string ID = string.Empty; } public class SerializeIm : XmlSerializerImplementation { public override XmlSerializer GetSerializer(Type type) { return new XmlSerializer(type); } } [XmlInclude(typeof(DerivedClass))] public class BaseClass { public string value { get; set; } public string Value; } public class DerivedClass : BaseClass { public new string value; public new string Value { get; set; } } [XmlRootAttribute("PurchaseOrder", Namespace = "http://www.contoso1.com", IsNullable = false)] public class PurchaseOrder { public Address ShipTo; public string OrderDate; [XmlArrayAttribute("Items")] public OrderedItem[] OrderedItems; public decimal SubTotal; public decimal ShipCost; public decimal TotalCost; public static PurchaseOrder CreateInstance() { PurchaseOrder po = new PurchaseOrder(); Address billAddress = new Address(); billAddress.Name = "John Doe"; billAddress.Line1 = "1 Main St."; billAddress.City = "AnyTown"; billAddress.State = "WA"; billAddress.Zip = "00000"; po.ShipTo = billAddress; po.OrderDate = new DateTime(2017, 4, 10).ToString("D", CultureInfo.InvariantCulture); OrderedItem item = new OrderedItem(); item.ItemName = "Widget S"; item.Description = "Small widget"; item.UnitPrice = (decimal)5.23; item.Quantity = 3; item.Calculate(); OrderedItem[] items = { item }; po.OrderedItems = items; decimal subTotal = new decimal(); foreach (OrderedItem oi in items) { subTotal += oi.LineTotal; } po.SubTotal = subTotal; po.ShipCost = (decimal)12.51; po.TotalCost = po.SubTotal + po.ShipCost; return po; } } public class Address { [XmlAttribute] public string Name; public string Line1; [XmlElementAttribute(IsNullable = false)] public string City; public string State; public string Zip; public static void CreateInstance() { Address obj = new Address(); obj.City = "Pune"; obj.State = "WA"; obj.Zip = "98052"; } } public class OrderedItem { public string ItemName; public string Description; public decimal UnitPrice; public int Quantity; public decimal LineTotal; public void Calculate() { LineTotal = UnitPrice * Quantity; } } [XmlType("AliasedTestType")] public class AliasedTestType { [XmlElement("X", typeof(List<int>))] [XmlElement("Y", typeof(List<string>))] [XmlElement("Z", typeof(List<double>))] public object Aliased { get; set; } } public class BaseClass1 { [XmlElement] public MyCollection1 Prop; } public class DerivedClass1 : BaseClass1 { [XmlElement] public new MyCollection1 Prop; } public class MyCollection1 : IEnumerable<DateTime>, IEnumerable { private List<DateTime> _values = new List<DateTime>(); public void Add(DateTime value) { _values.Add(value); } IEnumerator<DateTime> IEnumerable<DateTime>.GetEnumerator() { return _values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _values.GetEnumerator(); } } public static class Outer { public class Person { public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } } } public class Orchestra { public Instrument[] Instruments; } public class Instrument { public string Name; } public class Brass : Instrument { public bool IsValved; } public class Trumpet : Brass { public char Modulation; } public class Pet { [DefaultValueAttribute("Dog")] public string Animal; [XmlIgnoreAttribute] public string Comment; public string Comment2; } public class TypeWithVirtualGenericProperty<T> { public virtual T Value { get; set; } } public class TypeWithVirtualGenericPropertyDerived<T> : TypeWithVirtualGenericProperty<T> { public override T Value { get; set; } } public class DefaultValuesSetToNaN { [DefaultValue(double.NaN)] public double DoubleProp { get; set; } [DefaultValue(float.NaN)] public float FloatProp { get; set; } [DefaultValue(double.NaN)] public double DoubleField; [DefaultValue(float.NaN)] public float SingleField; public override bool Equals(object obj) { var other = obj as DefaultValuesSetToNaN; return other == null ? false : other.DoubleProp == this.DoubleProp && other.FloatProp == this.FloatProp && other.DoubleField == this.DoubleField && other.SingleField == this.SingleField; } public override int GetHashCode() { return this.DoubleProp.GetHashCode() ^ this.FloatProp.GetHashCode() ^ this.DoubleField.GetHashCode() ^ this.SingleField.GetHashCode(); } } public class DefaultValuesSetToPositiveInfinity { [DefaultValue(double.PositiveInfinity)] public double DoubleProp { get; set; } [DefaultValue(float.PositiveInfinity)] public float FloatProp { get; set; } [DefaultValue(double.PositiveInfinity)] public double DoubleField; [DefaultValue(float.PositiveInfinity)] public float SingleField; public override bool Equals(object obj) { var other = obj as DefaultValuesSetToPositiveInfinity; return other == null ? false : other.DoubleProp == this.DoubleProp && other.FloatProp == this.FloatProp && other.DoubleField == this.DoubleField && other.SingleField == this.SingleField; } public override int GetHashCode() { return this.DoubleProp.GetHashCode() ^ this.FloatProp.GetHashCode() ^ this.DoubleField.GetHashCode() ^ this.SingleField.GetHashCode(); } } public class DefaultValuesSetToNegativeInfinity { [DefaultValue(double.NegativeInfinity)] public double DoubleProp { get; set; } [DefaultValue(float.NegativeInfinity)] public float FloatProp { get; set; } [DefaultValue(double.NegativeInfinity)] public double DoubleField; [DefaultValue(float.NegativeInfinity)] public float SingleField; public override bool Equals(object obj) { var other = obj as DefaultValuesSetToNegativeInfinity; return other == null ? false : other.DoubleProp == this.DoubleProp && other.FloatProp == this.FloatProp && other.DoubleField == this.DoubleField && other.SingleField == this.SingleField; } public override int GetHashCode() { return this.DoubleProp.GetHashCode() ^ this.FloatProp.GetHashCode() ^ this.DoubleField.GetHashCode() ^ this.SingleField.GetHashCode(); } } [XmlRoot("RootElement")] public class TypeWithMismatchBetweenAttributeAndPropertyType { private int _intValue = 120; [DefaultValue(true), XmlAttribute("IntValue")] public int IntValue { get { return _intValue; } set { _intValue = value; } } } [DataContract(IsReference = true)] public class TypeWithLinkedProperty { [DataMember] public TypeWithLinkedProperty Child { get; set; } [DataMember] public List<TypeWithLinkedProperty> Children { get; set; } } [Serializable()] [System.Xml.Serialization.XmlType("MsgDocumentType", Namespace = "http://example.com")] [System.Xml.Serialization.XmlRoot("Document", Namespace = "http://example.com")] public partial class MsgDocumentType { [System.Xml.Serialization.XmlAttribute("id", DataType = "ID")] public string Id { get; set; } [System.Xml.Serialization.XmlAttribute("refs", DataType = "IDREFS")] public string[] Refs { get; set; } } public class RootClass { [XmlArray] public List<Parameter> Parameters { get; set; } } [XmlInclude(typeof(Parameter<string>))] public class Parameter { [XmlAttribute] public string Name { get; set; } } public class Parameter<T> : Parameter { public T Value { get; set; } }
using OrchardCore.ResourceManagement; namespace OrchardCore.Resources { public class ResourceManifest : IResourceManifestProvider { public void BuildManifests(IResourceManifestBuilder builder) { var manifest = builder.Add(); manifest .DefineScript("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/jquery.min.js", "~/OrchardCore.Resources/Scripts/jquery.js") .SetCdn("https://code.jquery.com/jquery-3.5.1.min.js", "https://code.jquery.com/jquery-3.5.1.js") .SetCdnIntegrity("sha384-ZvpUoO/+PpLXR1lu4jmpXWu80pZlYUAfxl5NsBMWOEPSjUn/6Z/hRTt8+pR6L4N2", "sha384-/LjQZzcpTzaYn7qWqRIWYC5l8FWEZ2bIHIz0D73Uzba4pShEcdLdZyZkI4Kv676E") .SetVersion("3.5.1"); manifest .DefineScript("jQuery.slim") .SetUrl("~/OrchardCore.Resources/Scripts/jquery.slim.min.js", "~/OrchardCore.Resources/Scripts/jquery.slim.js") .SetCdn("https://code.jquery.com/jquery-3.5.1.slim.min.js", "https://code.jquery.com/jquery-3.5.1.slim.js") .SetCdnIntegrity("sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj", "sha384-x6NENSfxadikq2gB4e6/qompriNc+y1J3eqWg3hAAMNBs4dFU303XMTcU3uExJgZ") .SetVersion("3.5.1"); manifest .DefineScript("jQuery") .SetUrl("~/OrchardCore.Resources/Vendor/jquery-3.4.1/jquery.min.js", "~/OrchardCore.Resources/Vendor/jquery-3.4.1/jquery.js") .SetCdn("https://code.jquery.com/jquery-3.4.1.min.js", "https://code.jquery.com/jquery-3.4.1.js") .SetCdnIntegrity("sha384-vk5WoKIaW/vJyUAd9n/wmopsmNhiy+L2Z+SBxGYnUkunIxVxAv/UtMOhba/xskxh", "sha384-mlceH9HlqLp7GMKHrj5Ara1+LvdTZVMx4S1U43/NxCvAkzIo8WJ0FE7duLel3wVo") .SetVersion("3.4.1"); manifest .DefineScript("jQuery.slim") .SetUrl("~/OrchardCore.Resources/Vendor/jquery-3.4.1/jquery.slim.min.js", "~/OrchardCore.Resources/Vendor/jquery-3.4.1/jquery.slim.js") .SetCdn("https://code.jquery.com/jquery-3.4.1.slim.min.js", "https://code.jquery.com/jquery-3.4.1.slim.js") .SetCdnIntegrity("sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n", "sha384-teRaFq/YbXOM/9FZ1qTavgUgTagWUPsk6xapwcjkrkBHoWvKdZZuAeV8hhaykl+G") .SetVersion("3.4.1"); manifest .DefineScript("jQuery.easing") .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/jquery.easing.min.js", "~/OrchardCore.Resources/Scripts/jquery.easing.js") .SetCdn("https://cdn.jsdelivr.net/npm/jquery.easing@1.4.1/jquery.easing.min.js", "https://cdn.jsdelivr.net/npm/jquery.easing@1.4.1/jquery.easing.js") .SetCdnIntegrity("sha384-leGYpHE9Tc4N9OwRd98xg6YFpB9shlc/RkilpFi0ljr3QD4tFoFptZvgnnzzwG4Q", "sha384-fwPA0FyfPOiDsglgAC4ZWmBGwpXSZNkq9IG+cM9HL4CkpNQo4xgCDkOIPdWypLMX") .SetVersion("1.4.1"); manifest .DefineScript("jQuery-ui") .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/jquery-ui.min.js", "~/OrchardCore.Resources/Scripts/jquery-ui.js") .SetCdn("https://code.jquery.com/ui/1.12.1/jquery-ui.min.js", "https://code.jquery.com/ui/1.12.1/jquery-ui.js") .SetCdnIntegrity("sha384-Dziy8F2VlJQLMShA6FHWNul/veM9bCkRUaLqr199K94ntO5QUrLJBEbYegdSkkqX", "sha384-JPbtLYL10d/Z1crlc6GGGGM3PavCzzoUJ1UxH0bXHOfguWHQ6XAWrIzW+MBGGXe5") .SetVersion("1.12.1"); manifest .DefineStyle("jQuery-ui") .SetUrl("~/OrchardCore.Resources/Styles/jquery-ui.min.css", "~/OrchardCore.Resources/Styles/jquery-ui.css") .SetCdn("https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.min.css", "https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css") .SetCdnIntegrity("sha384-kcAOn9fN4XSd+TGsNu2OQKSuV5ngOwt7tg73O4EpaD91QXvrfgvf0MR7/2dUjoI6", "sha384-xewr6kSkq3dBbEtB6Z/3oFZmknWn7nHqhLVLrYgzEFRbU/DHSxW7K3B44yWUN60D") .SetVersion("1.12.1"); manifest .DefineScript("jQuery-ui-i18n") .SetDependencies("jQuery-ui") .SetUrl("~/OrchardCore.Resources/Scripts/jquery-ui-i18n.min.js", "~/OrchardCore.Resources/Scripts/jquery-ui-i18n.js") .SetCdn("https://code.jquery.com/ui/1.7.2/i18n/jquery-ui-i18n.min.js", "https://code.jquery.com/ui/1.7.2/i18n/jquery-ui-i18n.min.js") .SetCdnIntegrity("sha384-0rV7y4NH7acVmq+7Y9GM6evymvReojk9li+7BYb/ug61uqPSsXJ4uIScVY+N9qtd", "sha384-0rV7y4NH7acVmq+7Y9GM6evymvReojk9li+7BYb/ug61uqPSsXJ4uIScVY+N9qtd") .SetVersion("1.7.2"); manifest .DefineScript("bootstrap") .SetDependencies("jQuery") .SetCdn("https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js", "https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.js") .SetCdnIntegrity("sha384-vhJnz1OVIdLktyixHY4Uk3OHEwdQqPppqYR8+5mjsauETgLOcEynD9oPHhhz18Nw", "sha384-it0Suwx+VjMafDIVf5t+ozEbrflmNjEddSX5LstI/Xdw3nv4qP/a4e8K4k5hH6l4") .SetVersion("3.4.0"); manifest .DefineStyle("bootstrap") .SetCdn("https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css", "https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.css") .SetCdnIntegrity("sha384-PmY9l28YgO4JwMKbTvgaS7XNZJ30MK9FAZjjzXtlqyZCqBY6X6bXIkM++IkyinN+", "sha384-/5bQ8UYbZnrNY3Mfy6zo9QLgIQD/0CximLKk733r8/pQnXn2mgvhvKhcy43gZtJV") .SetVersion("3.4.0"); manifest .DefineStyle("bootstrap-theme") .SetCdn("https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap-theme.min.css", "https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap-theme.css") .SetCdnIntegrity("sha384-jzngWsPS6op3fgRCDTESqrEJwRKck+CILhJVO5VvaAZCq8JYf8HsR/HPpBOOPZfR", "sha384-RtiWe5OsslAYZ9AVyorBziI2VQL7E27rzWygBJh7wrZuVPyK5jeQLLytnJIpJqfD") .SetVersion("3.4.0"); manifest .DefineScript("popper") .SetUrl("~/OrchardCore.Resources/Scripts/popper.min.js", "~/OrchardCore.Resources/Scripts/popper.js") .SetCdn("https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js", "https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.js") .SetCdnIntegrity("sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN", "sha384-cpSm/ilDFOWiMuF2bj03ZzJinb48NO9IGCXcYDtUzdP5y64Ober65chnoOj1XFoA") .SetVersion("1.16.1"); manifest .DefineScript("bootstrap") .SetDependencies("jQuery", "popper") .SetUrl("~/OrchardCore.Resources/Scripts/bootstrap.min.js", "~/OrchardCore.Resources/Scripts/bootstrap.js") .SetCdn("https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js", "https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.js") .SetCdnIntegrity("sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV", "sha384-PR/NM91PuT7DlZx1yQeKVnw+YgwW1GBT9jWtx05MZ1362zoFpXKl4Bh5ib8q9KYi") .SetVersion("4.5.2"); manifest .DefineScript("bootstrap-bundle") .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/bootstrap.bundle.min.js", "~/OrchardCore.Resources/Scripts/bootstrap.bundle.js") .SetCdn("https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js", "https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.js") .SetCdnIntegrity("sha384-LtrjvnR4Twt/qOuYxE721u19sVFLVSA4hf/rRt6PrZTmiPltdZcI7q7PXQBYTKyf", "sha384-Va0QamZVgxahbos902mvpvqxVvLn9ZwNj4NWN05Amy+8nWzFVfAwInsMtZ32FBW2") .SetVersion("4.5.2"); manifest .DefineStyle("bootstrap") .SetUrl("~/OrchardCore.Resources/Styles/bootstrap.min.css", "~/OrchardCore.Resources/Styles/bootstrap.css") .SetCdn("https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css", "https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.css") .SetCdnIntegrity("sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z", "sha384-89E3APJ9A7cFtt/qxlncRQEy9GnrOMoZTRVChFWLmpFhVJ0/t4uL4lhd4xzSJT/M") .SetVersion("4.5.2"); manifest .DefineStyle("bootstrap-select") .SetUrl("~/OrchardCore.Resources/Styles/bootstrap-select.min.css", "~/OrchardCore.Resources/Styles/bootstrap-select.css") .SetCdn("https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.18/dist/css/bootstrap-select.min.css", "https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.18/dist/css/bootstrap-select.css") .SetCdnIntegrity("sha384-dTqTc7d5t+FKhTIaMmda32pZNoXY/Y0ui0hRl5GzDQp4aARfEzbP1jzX6+KRuGKg", "sha384-OlTrhEtwZzUzVXapTUO8s6QryXzpD8mFyNVA8kyAi8KMgfOKSJYvielvExM+dNPR") .SetVersion("1.13.18"); manifest .DefineScript("bootstrap-select") .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/bootstrap-select.min.js", "~/OrchardCore.Resources/Scripts/bootstrap-select.js") .SetCdn("https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.18/dist/js/bootstrap-select.min.js", "https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.18/dist/js/bootstrap-select.js") .SetCdnIntegrity("sha384-x8fxIWvLdZnkRaCvkDXOlxd6UP+qga975FjnbRp6NRpL9jjXjY9TwF9y7z4AccxS", "sha384-6BZTOUHC4e3nWcy5gveLqAu52vwy5TX8zBIvvfZFVDzIjYDgprdXRMK/hsypxdpQ") .SetVersion("1.13.18"); manifest .DefineStyle("bootstrap-slider") .SetUrl("~/OrchardCore.Resources/Styles/bootstrap-slider.min.css", "~/OrchardCore.Resources/Styles/bootstrap-slider.css") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/11.0.2/css/bootstrap-slider.min.css", "https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/11.0.2/css/bootstrap-slider.css") .SetCdnIntegrity("sha384-Ot7O5p8Ws9qngwQOA1DP7acHuGIfK63cYbVJRYzrrMXhT3syEYhEsg+uqPsPpRhZ", "sha384-x1BbAB1QrM4/ZjT+vJzuI/NdvRo4tINKqg7lTN9jCq0bWrr/nelp9KfroZWd3UJu") .SetVersion("11.0.2"); manifest .DefineScript("bootstrap-slider") .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/bootstrap-slider.min.js", "~/OrchardCore.Resources/Scripts/bootstrap-slider.js") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/11.0.2/bootstrap-slider.min.js", "https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/11.0.2/bootstrap-slider.js") .SetCdnIntegrity("sha384-lZLZ1uMNIkCnScGXQrJ+PzUR2utC/FgaxJLMMrQD3Fbra1AwGXvshEIedqCmqXTM", "sha384-3kfvdN8W/a8p/9S6Gy69uVsacwuNxyvFVJXxZa/Qe00tkNfZw63n/4snM1u646YU") .SetVersion("11.0.2"); manifest .DefineStyle("codemirror") .SetUrl("~/OrchardCore.Resources/Styles/codemirror/codemirror.min.css", "~/OrchardCore.Resources/Styles/codemirror/codemirror.css") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/codemirror.min.css", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/codemirror.css") .SetCdnIntegrity("sha384-K/FfhVUneW5TdId1iTRDHsOHhLGHoJekcX6UThyJhMRctwRxlL3XmSnTeWX2k3Qe", "sha384-KsbK45E17r4hdzdJB8hf/poBTYi0oDktKdCAyP67Uc9lE9Amf83NF+Vf6VJZ6mRK") .SetVersion("5.58.0"); manifest .DefineStyle("codemirror-addon-display-fullscreen") .SetUrl("~/OrchardCore.Resources/Styles/codemirror/addon/display/fullscreen.css", "~/OrchardCore.Resources/Styles/codemirror/addon/display/fullscreen.css") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/addon/display/fullscreen.min.css", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/addon/display/fullscreen.css") .SetCdnIntegrity("sha384-uuIczW2AGKADJpvg6YiNBJQWE7duDkgQDkndYEsbUGaLm8SPJZzlly6hcEo0aTlW", "sha384-+glu1jsbG+T5ocmkeMvIYh5w07IXKxmJZaCdkNbVfpEr3xi+M0gopFSR/oLKXxio") .SetVersion("5.58.0"); manifest .DefineStyle("codemirror-addon-hint-show-hint") .SetUrl("~/OrchardCore.Resources/Styles/codemirror/addon/hint/show-hint.min.css", "~/OrchardCore.Resources/Styles/codemirror/addon/hint/show-hint.css") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/addon/hint/show-hint.min.css", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/addon/hint/show-hint.css") .SetCdnIntegrity("sha384-qqTWkykzuDLx4yDYa7bVrwNwBHuqVvklDUMVaU4eezgNUEgGbP8Zv6i3u8OmtuWg", "sha384-ZZbLvEvLoXKrHo3Tkh7W8amMgoHFkDzWe8IAm1ZgxsG5y35H+fJCVMWwr0YBAEGA") .SetVersion("5.58.0"); manifest .DefineScript("codemirror") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/codemirror.min.js", "~/OrchardCore.Resources/Scripts/codemirror/codemirror.js") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/codemirror.min.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/codemirror.js") .SetCdnIntegrity("sha384-MCaZNN0tRoN3lWByTquAyxWBS/0wrHU9NMKw0CIWNJWXkYTeusXLdDNwabsW8IG6", "sha384-UDuTjzyPkNH6K+A+nd0fjKvdgjh5dPuKk15tBaWwUDWdPr1qzALnBHLJXNWFjeth") .SetVersion("5.58.0"); manifest .DefineScript("codemirror-addon-selection-active-line") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/selection/active-line.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/selection/active-line.js") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/addon/selection/active-line.min.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/addon/selection/active-line.min.js") .SetCdnIntegrity("sha384-a1C6GgT4/STEs5Df0Ko1uzqijvgtY7MvVv7Z4uuyk+N4llXey69UU0QxXy6L007K", "sha384-kKz13r+qZMgTNgXROGNHQ0/0/J1FtvIvRZ9yjOHo1YLUCd+KF8r9R+su/B+f6C0U") .SetVersion("5.58.0"); manifest .DefineScript("codemirror-addon-display-autorefresh") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/display/autorefresh.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/display/autorefresh.js") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/addon/display/autorefresh.min.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/addon/display/autorefresh.js") .SetCdnIntegrity("sha384-pn83o6MtS8kicn/sV6AhRaBqXQ5tau8NzA2ovcobkcc1uRFP7D8CMhRx231QwKST", "sha384-5wrQkkCzj5dJInF+DDDYjE1itTGaIxO+TL6gMZ2eZBo9OyWLczkjolFX8kixX/9X") .SetVersion("5.58.0"); manifest .DefineScript("codemirror-addon-display-fullscreen") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/display/fullscreen.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/display/fullscreen.js") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/addon/display/fullscreen.min.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/addon/display/fullscreen.js") .SetCdnIntegrity("sha384-QWNlxQIqNTw1WRsFEBoyGSFItEfal64eVEm0CU8KVFq6P5KnKOggFNp9aQgmDA9U", "sha384-kuwHYEheDAp0NlPye2VXyxJ6J54CeVky9tH+e0mn6/gP4PJ50MF4FGKkrGAxIyCW") .SetVersion("5.58.0"); manifest .DefineScript("codemirror-addon-edit-closetag") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/edit/closetag.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/display/fullscreen.js") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/addon/edit/closetag.min.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/addon/edit/closetag.js") .SetCdnIntegrity("sha384-JqEk/xYh2w3m+IwV7QlyAJI+nLEISeQQzipKvsXonJCTFrAerFYuxnl/UcaYtImK", "sha384-7U8y7U7Dit7biOcvavud1w0ihUHjWoWv8Fp1JmgbDkADBCu2EqQ27uzZ595vlX7g") .SetVersion("5.58.0"); manifest .DefineScript("codemirror-addon-hint-show-hint") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/hint/show-hint.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/hint/show-hint.js") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/addon/hint/show-hint.min.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/addon/hint/show-hint.js") .SetCdnIntegrity("sha384-Q95dPnF5hO9lv8VMNgPsksbevLpBpg8kA3oX09iL/csWh/Vtd96a0k3U8k2cpLNw", "sha384-VIjTLfyf8TDATLORaNeFgbAzeAy9ZbmWEkjdQhJc5JyrdrnBbiTrixhYCizHe7vL") .SetVersion("5.58.0"); manifest .DefineScript("codemirror-addon-hint-sql-hint") .SetDependencies("codemirror-addon-hint-show-hint") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/hint/sql-hint.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/hint/sql-hint.js") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/addon/hint/sql-hint.min.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/addon/hint/sql-hint.js") .SetCdnIntegrity("sha384-o9FqqjYhfbrB9mOsxV07kYRhlQJh/upT6krVNSXfLseRob05IXVudSBmY9sG3lEj", "sha384-cPhM7+ID++Q4c4eAXovBSrwnBb/sIg0Cuci0iyMjAaTor/JEJ3lee3SdBFbKa8wC") .SetVersion("5.58.0"); manifest .DefineScript("codemirror-addon-mode-multiplex") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/mode/multiplex.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/mode/multiplex.js") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/addon/mode/multiplex.min.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/addon/mode/multiplex.js") .SetCdnIntegrity("sha384-sTw3lU1fIEXG/qNbuuh7lpitFgxSwaReQLtKo8gVCzKz/j3yOk8whDk4NiG5Cnvs", "sha384-xF886YuXgjqY02JjHuoV+B+SZYB4DYq7YUniuin/yCqJdxYpXomTlOfmiSoSNpwQ") .SetVersion("5.58.0"); manifest .DefineScript("codemirror-addon-mode-simple") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/mode/simple.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/mode/simple.js") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/addon/mode/simple.min.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/addon/mode/simple.js") .SetCdnIntegrity("sha384-DbFZlXwgV4md0LMM7aSVdbUaCldkPh4QXILJ/kbD9ZZiC3gQ+E9SjHG++B3PvCr1", "sha384-ntjFEzI50GYBTbLGaOVgBt97cxp74jfCqMDmZYlGWk8ZZp2leFMJYOp85T3tOeG9") .SetVersion("5.58.0"); manifest .DefineScript("codemirror-mode-css") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/mode/css/css.min.js", "~/OrchardCore.Resources/Scripts/codemirror/mode/css/css.js") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/mode/css/css.min.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/mode/css/css.js") .SetCdnIntegrity("sha384-7qjHTracYtl04dp9noesILoIDudLA8736YHkui0kBKTAEm6j/XOJ7laasgFKCmcw", "sha384-KQnueJAsHUDvm95nlrdIDwvnB3ziHU858LJB2fsrs/r1/gDX84NAVyUIJ7MSyABv") .SetVersion("5.58.0"); manifest .DefineScript("codemirror-mode-htmlmixed") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/mode/htmlmixed/htmlmixed.min.js", "~/OrchardCore.Resources/Scripts/codemirror/mode/htmlmixed/htmlmixed.js") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/mode/htmlmixed/htmlmixed.min.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/mode/htmlmixed/htmlmixed.js") .SetCdnIntegrity("sha384-sbLNpMWktagHnz1dYX5ffxjnU0+k5cGjZTg2QDE64Gi/fZ28b0USo6CZvaEjyKKl", "sha384-fxS517EbIB2hObIbibF9AuQAFnAlwZgIsy2zpeCqpw4yIkJRfNOLSe0JHu7H7ULE") .SetVersion("5.58.0"); manifest .DefineScript("codemirror-mode-javascript") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/mode/javascript/javascript.min.js", "~/OrchardCore.Resources/Scripts/codemirror/mode/javascript/javascript.js") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/mode/javascript/javascript.min.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/mode/javascript/javascript.js") .SetCdnIntegrity("sha384-FuCGRyDVxBCEoXaFRf2fvIsvCvyFlAPfJpr+RE/yt16pRj0/nHA1kDpQFrWE8jAX", "sha384-9BowMxIRNf7gbVLczrUIg0cGcovpADtOdn45yCZ5e9NCfSgePO6DvEzw0Yx0G8yt") .SetVersion("5.58.0"); manifest .DefineScript("codemirror-mode-sql") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/mode/sql/sql.min.js", "~/OrchardCore.Resources/Scripts/codemirror/mode/sql/sql.js") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/mode/sql/sql.min.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/mode/sql/sql.js") .SetCdnIntegrity("sha384-86IcFNbXZf+LKDhAwqi2Rvj//vHEiIK6AzJ0j2m5OzgIWSOsCcPWzTu1VA61Xo8H", "sha384-D+uYw7olvmCEyME9PHzGRne1Sh8+XTk84/JZinlhDTutXBH45AdThw4uLAAt4vIm") .SetVersion("5.58.0"); manifest .DefineScript("codemirror-mode-xml") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/mode/xml/xml.min.js", "~/OrchardCore.Resources/Scripts/codemirror/mode/xml/xml.js") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/mode/xml/xml.min.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.0/mode/xml/xml.js") .SetCdnIntegrity("sha384-27kgmf2cIJ9bclpvyUN4SgnnYnW7Wu0MiGYpm+fmNQhcREFI7mq0C9ehuxYuwqgy", "sha384-z8O1dAcb8dxGYbhmbzbJ41xAUlle9jfZpok46e8s9+Tyu9bKxx742hiNqVJ0D6cL") .SetVersion("5.58.0"); manifest .DefineStyle("font-awesome") .SetUrl("~/OrchardCore.Resources/Styles/font-awesome.min.css", "~/OrchardCore.Resources/Styles/font-awesome.css") .SetCdn("https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css", "https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css") .SetCdnIntegrity("sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN", "sha384-FckWOBo7yuyMS7In0aXZ0aoVvnInlnFMwCv77x9sZpFgOonQgnBj1uLwenWVtsEj") .SetVersion("4.7.0"); manifest .DefineStyle("font-awesome") .SetUrl("~/OrchardCore.Resources/Vendor/fontawesome-free/css/all.min.css", "~/OrchardCore.Resources/Vendor/fontawesome-free/css/all.css") .SetCdn("https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.0/css/all.min.css", "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.0/css/all.css") .SetCdnIntegrity("sha384-OLYO0LymqQ+uHXELyx93kblK5YIS3B2ZfLGBmsJaUyor7CpMTBsahDHByqSuWW+q", "sha384-xE3JwGuHzCWTnY4GeD2mMe5HCe2ZhO940RfNZ3n0EX3sow3wPU8azcmYu4pjZNB5") .SetVersion("5.15.0"); manifest .DefineScript("font-awesome") .SetUrl("~/OrchardCore.Resources/Vendor/fontawesome-free/js/all.min.js", "~/OrchardCore.Resources/Vendor/fontawesome-free/js/all.js") .SetCdn("https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.0/js/all.min.js", "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.0/js/all.js") .SetCdnIntegrity("sha384-zba7TI5RCX7zpVqdwxLFYtstiHCUSJQr2nGo0dJFhnzfrubNU4zeM/ZUK4nLMNBo", "sha384-eBamUk6IWpBzyIQ4iJw2UsR/ZG0UyrLumXPXtmPzneoytyY6dOK3XnIU4ePKiOR7") .SetVersion("5.15.0"); manifest .DefineScript("font-awesome-v4-shims") .SetUrl("~/OrchardCore.Resources/Vendor/fontawesome-free/js/v4-shims.min.js", "~/OrchardCore.Resources/Vendor/fontawesome-free/js/v4-shims.js") .SetCdn("https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.0/js/v4-shims.min.js", "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.0/js/v4-shims.js") .SetCdnIntegrity("sha384-jbTS0QJVDF3EaYdDpNNCtSmF1sFiNTWlnF7gKxvVKe+uVJmiHUbyRlnB962qLcXp", "sha384-wAL2KymHV2I64Q7XAQRBh5tUv35Nz1bCA86FD4Kc18VAxP2Te0RgHQLHO+ynRY5f") .SetVersion("5.15.0"); manifest .DefineScript("jquery-resizable") .SetDependencies("resizable-resolveconflict") .SetUrl("~/OrchardCore.Resources/Scripts/jquery-resizable.min.js", "~/OrchardCore.Resources/Scripts/jquery-resizable.js") .SetCdn("https://cdn.jsdelivr.net/npm/jquery-resizable-dom@0.35.0/dist/jquery-resizable.min.js") .SetCdnIntegrity("sha384-1LMjDEezsSgzlRgsyFIAvLW7FWSdFIHqBGjUa+ad5EqtK1FORC8XpTJ/pahxj5GB", "sha384-0yk9X0IG0cXxuN9yTTkps/3TNNI9ZcaKKhh8dgqOEAWGXxIYS5xaY2as6b32Ov3P") .SetVersion("0.35.0"); manifest .DefineScript("resizable-resolveconflict") .SetDependencies("jQuery-ui") .SetUrl("~/OrchardCore.Resources/Scripts/resizable-resolveconflict.min.js", "~/OrchardCore.Resources/Scripts/resizable-resolveconflict.js") .SetVersion("2.21.0"); manifest .DefineStyle("trumbowyg") .SetUrl("~/OrchardCore.Resources/Styles/trumbowyg.min.css", "~/OrchardCore.Resources/Styles/trumbowyg.css") .SetCdn("https://cdn.jsdelivr.net/npm/trumbowyg@2.21.0/dist/ui/trumbowyg.min.css", "https://cdn.jsdelivr.net/npm/trumbowyg@2.21.0/dist/ui/trumbowyg.css") .SetCdnIntegrity("sha384-/QRP5MyK1yCOLeUwO9+YXKUDNFKRuzDjVDW+U8RnsI/9I3+p538CduXmiLfzWUY4", "sha384-helPIukt/ukxd7K8G/hg2Hgi5Zt2V5khBjNiQjpRUPE/mV/7I3Cym7fVGwol5PzR") .SetVersion("2.21.0"); manifest .DefineScript("trumbowyg") .SetDependencies("jquery-resizable") .SetUrl("~/OrchardCore.Resources/Scripts/trumbowyg.js", "~/OrchardCore.Resources/Scripts/trumbowyg.js") .SetCdn("https://cdn.jsdelivr.net/npm/trumbowyg@2.21.0/dist/trumbowyg.min.js", "https://cdn.jsdelivr.net/npm/trumbowyg@2.21.0/dist/trumbowyg.js") .SetCdnIntegrity("sha384-XrYMLffzTUgFmXcXtkSWBUpAzHQzzDOXM96+7pKkOIde9oUDWNb72Ij7K06zsLTV", "sha384-I0b1bxE3gmTi8+HE5xlvTLLehif/97lNC+tk2dGrln7dtdQ/FasdZRDbXAg3rBus") .SetVersion("2.21.0"); manifest .DefineScript("trumbowyg-shortcodes") .SetDependencies("trumbowyg") .SetUrl("~/OrchardCore.Resources/Scripts/trumbowyg.shortcodes.js", "~/OrchardCore.Resources/Scripts/trumbowyg.shortcodes.min.js") .SetVersion("1.0.0"); manifest .DefineStyle("trumbowyg-plugins") .SetDependencies("trumbowyg") .SetUrl("~/OrchardCore.Resources/Styles/trumbowyg-plugins.min.css", "~/OrchardCore.Resources/Styles/trumbowyg-plugins.css") .SetVersion("2.21.0"); manifest .DefineScript("trumbowyg-plugins") .SetDependencies("trumbowyg") .SetUrl("~/OrchardCore.Resources/Scripts/trumbowyg-plugins.js", "~/OrchardCore.Resources/Scripts/trumbowyg-plugins.js") .SetVersion("2.21.0"); manifest .DefineScript("vuejs") .SetUrl("~/OrchardCore.Resources/Scripts/vue.min.js", "~/OrchardCore.Resources/Scripts/vue.js") .SetCdn("https://cdn.jsdelivr.net/npm/vue@2.6.11/dist/vue.min.js", "https://cdn.jsdelivr.net/npm/vue@2.6.11/dist/vue.js") .SetCdnIntegrity("sha384-OZmxTjkv7EQo5XDMPAmIkkvywVeXw59YyYh6zq8UKfkbor13jS+5p8qMTBSA1q+F", "sha384-+jvb+jCJ37FkNjPyYLI3KJzQeD8pPFXUra3B/QJFqQ3txYrUPIP1eOfxK4h3cKZP") .SetVersion("2.6.11"); manifest .DefineScript("vue-multiselect") .SetDependencies("vuejs") .SetUrl("~/OrchardCore.Resources/Scripts/vue-multiselect.min.js", "~/OrchardCore.Resources/Scripts/vue-multiselect.min.js") .SetCdn("https://cdn.jsdelivr.net/npm/vue-multiselect@2.1.6/dist/vue-multiselect.min.js", "https://cdn.jsdelivr.net/npm/vue-multiselect@2.1.6/dist/vue-multiselect.min.js") .SetCdnIntegrity("sha384-a4eXewRTYCwYdFtSnMCZTNtiXrfdul6aQdueRgHPAx2y1Ldp0QaFdCTpOx0ycsXU", "sha384-a4eXewRTYCwYdFtSnMCZTNtiXrfdul6aQdueRgHPAx2y1Ldp0QaFdCTpOx0ycsXU") .SetVersion("2.1.6"); manifest .DefineStyle("vue-multiselect") .SetUrl("~/OrchardCore.Resources/Styles/vue-multiselect.min.css", "~/OrchardCore.Resources/Styles/vue-multiselect.min.css") .SetCdn("https://cdn.jsdelivr.net/npm/vue-multiselect@2.1.6/dist/vue-multiselect.min.css", "https://cdn.jsdelivr.net/npm/vue-multiselect@2.1.6/dist/vue-multiselect.min.css") .SetCdnIntegrity("sha384-PPH/T7V86Z1+B4eMPef4FJXLD5fsTpObWoCoK3CiNtSX7aji+5qxpOCn1f2TDYAM", "sha384-PPH/T7V86Z1+B4eMPef4FJXLD5fsTpObWoCoK3CiNtSX7aji+5qxpOCn1f2TDYAM") .SetVersion("2.1.6"); manifest .DefineScript("Sortable") .SetUrl("~/OrchardCore.Resources/Scripts/Sortable.min.js", "~/OrchardCore.Resources/Scripts/Sortable.js") .SetCdn("https://cdn.jsdelivr.net/npm/sortablejs@1.10.2/Sortable.min.js", "https://cdn.jsdelivr.net/npm/sortablejs@1.10.2/Sortable.js") .SetCdnIntegrity("sha384-6qM1TfKo1alBw3Uw9AWXnaY5h0G3ScEjxtUm4TwRJm7HRmDX8UfiDleTAEEg5vIe", "sha384-lNRluF0KgEfw4KyH2cJAoBAMzRHZVp5bgBGAzRxHeXoFqb5admHjitlZ2dmspHmC") .SetVersion("1.10.2"); manifest .DefineScript("vuedraggable") .SetDependencies("vuejs", "Sortable") .SetUrl("~/OrchardCore.Resources/Scripts/vuedraggable.umd.min.js", "~/OrchardCore.Resources/Scripts/vuedraggable.umd.js") .SetCdn("https://cdn.jsdelivr.net/npm/vuedraggable@2.24.1/dist/vuedraggable.umd.min.js", "https://cdn.jsdelivr.net/npm/vuedraggable@2.24.1/dist/vuedraggable.umd.js") .SetCdnIntegrity("sha384-95XQBb8XRK8jN1TR3CjE7Shlbm1m/8JNzMu/ACCsnWu/yFvMTkCjDHVXbOVl7Moi", "sha384-10hAGRrbDQC4KS+gdeuUtzyGr+4JdQ4PFfU58+1uy+D7WkEgCcI9xlUPBa10fdf7") .SetVersion("2.24.1"); manifest .DefineScript("jscookie") .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/js.cookie.min.js", "~/OrchardCore.Resources/Scripts/js.cookie.js") .SetVersion("2.1.4"); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using NeedDotNet.Web.Areas.HelpPage.ModelDescriptions; using NeedDotNet.Web.Areas.HelpPage.Models; namespace NeedDotNet.Web.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
/* ** $Id: lundump.c,v 2.7.1.4 2008/04/04 19:51:41 roberto Exp $ ** load precompiled Lua chunks ** See Copyright Notice in lua.h */ using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.Serialization; namespace SharpLua { using TValue = Lua.lua_TValue; using lua_Number = System.Double; using lu_byte = System.Byte; using StkId = Lua.lua_TValue; using Instruction = System.UInt32; using ZIO = Lua.Zio; public partial class Lua { /* for header of binary files -- this is Lua 5.1 */ public const int LUAC_VERSION = 0x51; /* for header of binary files -- this is the official format */ public const int LUAC_FORMAT = 0; /* size of header of binary files */ public const int LUAC_HEADERSIZE = 12; public class LoadState{ public LuaState L; public ZIO Z; public Mbuffer b; public CharPtr name; }; //#ifdef LUAC_TRUST_BINARIES //#define IF(c,s) //#define error(S,s) //#else //#define IF(c,s) if (c) error(S,s) public static void IF(int c, string s) { } public static void IF(bool c, string s) { } static void error(LoadState S, CharPtr why) { luaO_pushfstring(S.L,"%s: %s in precompiled chunk",S.name,why); luaD_throw(S.L,LUA_ERRSYNTAX); } //#endif public static object LoadMem(LoadState S, Type t) { #if WindowsCE // under CE, sizeof(char) is 2, not 1! int size = (t == typeof(char)) ? 1 : Marshal.SizeOf(t); #else int size = Marshal.SizeOf(t); #endif CharPtr str = new char[size]; LoadBlock(S, str, size); byte[] bytes = new byte[str.chars.Length]; for (int i = 0; i < str.chars.Length; i++) bytes[i] = (byte)str.chars[i]; GCHandle pinnedPacket = GCHandle.Alloc(bytes, GCHandleType.Pinned); object b = Marshal.PtrToStructure(pinnedPacket.AddrOfPinnedObject(), t); pinnedPacket.Free(); return b; } public static object LoadMem(LoadState S, Type t, int n) { #if SILVERLIGHT List<object> array = new List<object>(); for (int i = 0; i < n; i++) array.Add(LoadMem(S, t)); return array.ToArray(); #else ArrayList array = new ArrayList(); for (int i=0; i<n; i++) array.Add(LoadMem(S, t)); return array.ToArray(t); #endif } public static lu_byte LoadByte(LoadState S) {return (lu_byte)LoadChar(S);} public static object LoadVar(LoadState S, Type t) { return LoadMem(S, t); } public static object LoadVector(LoadState S, Type t, int n) {return LoadMem(S, t, n);} private static void LoadBlock(LoadState S, CharPtr b, int size) { uint r=luaZ_read(S.Z, b, (uint)size); IF (r!=0, "unexpected end"); } private static int LoadChar(LoadState S) { return (char)LoadVar(S, typeof(char)); } private static int LoadInt(LoadState S) { int x = (int)LoadVar(S, typeof(int)); IF (x<0, "bad integer"); return x; } private static lua_Number LoadNumber(LoadState S) { return (lua_Number)LoadVar(S, typeof(lua_Number)); } private static TString LoadString(LoadState S) { uint size = (uint)LoadVar(S, typeof(uint)); if (size==0) return null; else { CharPtr s=luaZ_openspace(S.L,S.b,size); LoadBlock(S, s, (int)size); return luaS_newlstr(S.L,s,size-1); /* remove trailing '\0' */ } } private static void LoadCode(LoadState S, Proto f) { int n=LoadInt(S); f.code = luaM_newvector<Instruction>(S.L, n); f.sizecode=n; f.code = (Instruction[])LoadVector(S, typeof(Instruction), n); } private static void LoadConstants(LoadState S, Proto f) { int i,n; n=LoadInt(S); f.k = luaM_newvector<TValue>(S.L, n); f.sizek=n; for (i=0; i<n; i++) setnilvalue(f.k[i]); for (i=0; i<n; i++) { TValue o=f.k[i]; int t=LoadChar(S); switch (t) { case LUA_TNIL: setnilvalue(o); break; case LUA_TBOOLEAN: setbvalue(o, LoadChar(S)); break; case LUA_TNUMBER: setnvalue(o, LoadNumber(S)); break; case LUA_TSTRING: setsvalue2n(S.L, o, LoadString(S)); break; default: error(S,"bad constant"); break; } } n=LoadInt(S); f.p=luaM_newvector<Proto>(S.L,n); f.sizep=n; for (i=0; i<n; i++) f.p[i]=null; for (i=0; i<n; i++) f.p[i]=LoadFunction(S,f.source); } private static void LoadDebug(LoadState S, Proto f) { int i,n; n=LoadInt(S); f.lineinfo=luaM_newvector<int>(S.L,n); f.sizelineinfo=n; f.lineinfo = (int[])LoadVector(S, typeof(int), n); n=LoadInt(S); f.locvars=luaM_newvector<LocVar>(S.L,n); f.sizelocvars=n; for (i=0; i<n; i++) f.locvars[i].varname=null; for (i=0; i<n; i++) { f.locvars[i].varname=LoadString(S); f.locvars[i].startpc=LoadInt(S); f.locvars[i].endpc=LoadInt(S); } n=LoadInt(S); f.upvalues=luaM_newvector<TString>(S.L, n); f.sizeupvalues=n; for (i=0; i<n; i++) f.upvalues[i]=null; for (i=0; i<n; i++) f.upvalues[i]=LoadString(S); } private static Proto LoadFunction(LoadState S, TString p) { Proto f; if (++S.L.nCcalls > LUAI_MAXCCALLS) error(S,"code too deep"); f=luaF_newproto(S.L); setptvalue2s(S.L,S.L.top,f); incr_top(S.L); f.source=LoadString(S); if (f.source==null) f.source=p; f.linedefined=LoadInt(S); f.lastlinedefined=LoadInt(S); f.nups=LoadByte(S); f.numparams=LoadByte(S); f.is_vararg=LoadByte(S); f.maxstacksize=LoadByte(S); LoadCode(S,f); LoadConstants(S,f); LoadDebug(S,f); IF (luaG_checkcode(f)==0 ? 1 : 0, "bad code"); StkId.dec(ref S.L.top); S.L.nCcalls--; return f; } private static void LoadHeader(LoadState S) { CharPtr h = new char[LUAC_HEADERSIZE]; CharPtr s = new char[LUAC_HEADERSIZE]; luaU_header(h); LoadBlock(S, s, LUAC_HEADERSIZE); IF (memcmp(h, s, LUAC_HEADERSIZE)!=0, "bad header"); } /* ** load precompiled chunk */ public static Proto luaU_undump (LuaState L, ZIO Z, Mbuffer buff, CharPtr name) { LoadState S = new LoadState(); if (name[0] == '@' || name[0] == '=') S.name = name+1; else if (name[0]==LUA_SIGNATURE[0]) S.name="binary string"; else S.name=name; S.L=L; S.Z=Z; S.b=buff; LoadHeader(S); return LoadFunction(S,luaS_newliteral(L,"=?")); } /* * make header */ public static void luaU_header(CharPtr h) { h = new CharPtr(h); int x=1; memcpy(h, LUA_SIGNATURE, LUA_SIGNATURE.Length); h = h.add(LUA_SIGNATURE.Length); h[0] = (char)LUAC_VERSION; h.inc(); h[0] = (char)LUAC_FORMAT; h.inc(); //*h++=(char)*(char*)&x; /* endianness */ h[0] = (char)x; /* endianness */ h.inc(); h[0] = (char)sizeof(int); h.inc(); h[0] = (char)sizeof(uint); h.inc(); h[0] = (char)sizeof(Instruction); h.inc(); h[0] = (char)sizeof(lua_Number); h.inc(); //(h++)[0] = ((lua_Number)0.5 == 0) ? 0 : 1; /* is lua_Number integral? */ h[0] = (char)0; // always 0 on this build } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Netcode; using Pathoschild.Stardew.Common; using Pathoschild.Stardew.Common.Items.ItemData; using Pathoschild.Stardew.Common.Utilities; using Pathoschild.Stardew.TractorMod.Framework.Attachments; using StardewModdingAPI; using StardewValley; using StardewValley.Locations; using StardewValley.Objects; using StardewValley.TerrainFeatures; using StardewValley.Tools; using xTile.Dimensions; using Rectangle = Microsoft.Xna.Framework.Rectangle; using SObject = StardewValley.Object; namespace Pathoschild.Stardew.TractorMod.Framework { /// <summary>The base class for tool implementations.</summary> internal abstract class BaseAttachment : IAttachment { /********* ** Fields *********/ /// <summary>Fetches metadata about loaded mods.</summary> protected IModRegistry ModRegistry { get; } /// <summary>Simplifies access to private code.</summary> protected IReflectionHelper Reflection { get; } /// <summary>The millisecond game times elapsed when requested cooldowns started.</summary> private readonly IDictionary<string, long> CooldownStartTimes = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase); /// <summary>Whether the Farm Type Manager mod is installed.</summary> private readonly bool HasFarmTypeManager; /// <summary>Whether the current player found the golden scythe.</summary> private readonly Cached<bool> FoundGoldenScythe = new( getCacheKey: () => $"{Game1.uniqueIDForThisGame},{Game1.ticks / 300}", // refresh every 5 seconds fetchNew: () => Game1.player?.mailReceived?.Contains("gotGoldenScythe") == true ); /// <summary>A fake pickaxe to use for clearing dead crops to ensure consistent behavior.</summary> private readonly Lazy<Pickaxe> FakePickaxe = new(() => new Pickaxe()); /********* ** Accessors *********/ /// <summary>The minimum number of ticks between each update.</summary> public int RateLimit { get; } /********* ** Public methods *********/ /// <summary>Get whether the tool is currently enabled.</summary> /// <param name="player">The current player.</param> /// <param name="tool">The tool selected by the player (if any).</param> /// <param name="item">The item selected by the player (if any).</param> /// <param name="location">The current location.</param> public abstract bool IsEnabled(Farmer player, Tool tool, Item item, GameLocation location); /// <summary>Apply the tool to the given tile.</summary> /// <param name="tile">The tile to modify.</param> /// <param name="tileObj">The object on the tile.</param> /// <param name="tileFeature">The feature on the tile.</param> /// <param name="player">The current player.</param> /// <param name="tool">The tool selected by the player (if any).</param> /// <param name="item">The item selected by the player (if any).</param> /// <param name="location">The current location.</param> public abstract bool Apply(Vector2 tile, SObject tileObj, TerrainFeature tileFeature, Farmer player, Tool tool, Item item, GameLocation location); /// <summary>Method called when the tractor attachments have been activated for a location.</summary> /// <param name="location">The current tractor location.</param> public virtual void OnActivated(GameLocation location) { this.CooldownStartTimes.Clear(); } /********* ** Protected methods *********/ /// <summary>Construct an instance.</summary> /// <param name="modRegistry">Fetches metadata about loaded mods.</param> /// <param name="reflection">Simplifies access to private code.</param> /// <param name="rateLimit">The minimum number of ticks between each update.</param> protected BaseAttachment(IModRegistry modRegistry, IReflectionHelper reflection, int rateLimit = 0) { this.ModRegistry = modRegistry; this.Reflection = reflection; this.RateLimit = rateLimit; this.HasFarmTypeManager = modRegistry.IsLoaded("Esca.FarmTypeManager"); } /// <summary>Start a cooldown if it's not already started.</summary> /// <param name="key">An arbitrary cooldown ID to check.</param> /// <param name="delay">The cooldown time.</param> /// <returns>Returns true if the cooldown was successfully started, or false if it was already in progress.</returns> protected bool TryStartCooldown(string key, TimeSpan delay) { long currentTime = (long)Game1.currentGameTime.TotalGameTime.TotalMilliseconds; if (!this.CooldownStartTimes.TryGetValue(key, out long startTime) || (currentTime - startTime) >= delay.TotalMilliseconds) { this.CooldownStartTimes[key] = currentTime; return true; } return false; } /// <summary>Use a tool on a tile.</summary> /// <param name="tool">The tool to use.</param> /// <param name="tile">The tile to affect.</param> /// <param name="player">The current player.</param> /// <param name="location">The current location.</param> /// <returns>Returns <c>true</c> for convenience when implementing tools.</returns> protected bool UseToolOnTile(Tool tool, Vector2 tile, Farmer player, GameLocation location) { // use tool on center of tile player.lastClick = this.GetToolPixelPosition(tile); tool.DoFunction(location, (int)player.lastClick.X, (int)player.lastClick.Y, 0, player); return true; } /// <summary>Get the pixel position relative to the top-left corner of the map at which to use a tool.</summary> /// <param name="tile">The tile to affect.</param> protected Vector2 GetToolPixelPosition(Vector2 tile) { return (tile * Game1.tileSize) + new Vector2(Game1.tileSize / 2f); } /// <summary>Use a weapon on the given tile.</summary> /// <param name="weapon">The weapon to use.</param> /// <param name="tile">The tile to attack.</param> /// <param name="player">The current player.</param> /// <param name="location">The current location.</param> /// <returns>Returns whether a monster was attacked.</returns> /// <remarks>This is a simplified version of <see cref="MeleeWeapon.DoDamage"/>. This doesn't account for player bonuses (since it's hugely overpowered anyway), doesn't cause particle effects, doesn't trigger animation timers, etc.</remarks> protected bool UseWeaponOnTile(MeleeWeapon weapon, Vector2 tile, Farmer player, GameLocation location) { bool attacked = location.damageMonster( areaOfEffect: this.GetAbsoluteTileArea(tile), minDamage: weapon.minDamage.Value, maxDamage: weapon.maxDamage.Value, isBomb: false, knockBackModifier: weapon.knockback.Value, addedPrecision: weapon.addedPrecision.Value, critChance: weapon.critChance.Value, critMultiplier: weapon.critMultiplier.Value, triggerMonsterInvincibleTimer: weapon.type.Value != MeleeWeapon.dagger, who: player ); if (attacked) location.playSound(weapon.type.Value == MeleeWeapon.club ? "clubhit" : "daggerswipe"); return attacked; } /// <summary>Trigger the player action on the given tile.</summary> /// <param name="location">The location for which to trigger an action.</param> /// <param name="tile">The tile for which to trigger an action.</param> /// <param name="player">The player for which to trigger an action.</param> protected bool CheckTileAction(GameLocation location, Vector2 tile, Farmer player) { return location.checkAction(new Location((int)tile.X, (int)tile.Y), Game1.viewport, player); } /// <summary>Get whether a given object is a twig.</summary> /// <param name="obj">The world object.</param> protected bool IsTwig(SObject obj) { return obj?.ParentSheetIndex is 294 or 295; } /// <summary>Get whether a given object is a weed.</summary> /// <param name="obj">The world object.</param> protected bool IsWeed(SObject obj) { return obj is not Chest && obj?.Name == "Weeds"; } /// <summary>Remove the specified items from the player inventory.</summary> /// <param name="player">The player whose inventory to edit.</param> /// <param name="item">The item instance to deduct.</param> /// <param name="count">The number to deduct.</param> protected void ConsumeItem(Farmer player, Item item, int count = 1) { item.Stack -= 1; if (item.Stack <= 0) player.removeItemFromInventory(item); } /// <summary>Remove the specified items from the chest inventory.</summary> /// <param name="chest">The chest whose inventory to edit.</param> /// <param name="item">The item instance to deduct.</param> /// <param name="count">The number to deduct.</param> protected void ConsumeItem(Chest chest, Item item, int count = 1) { item.Stack -= 1; if (item.Stack <= 0) { for (int i = 0; i < chest.items.Count; i++) { Item slot = chest.items[i]; if (slot != null && object.ReferenceEquals(item, slot)) { chest.items[i] = null; break; } } } } /// <summary>Get a rectangle representing the tile area in absolute pixels from the map origin.</summary> /// <param name="tile">The tile position.</param> protected Rectangle GetAbsoluteTileArea(Vector2 tile) { Vector2 pos = tile * Game1.tileSize; return new Rectangle((int)pos.X, (int)pos.Y, Game1.tileSize, Game1.tileSize); } /// <summary>Get the resource clumps in a given location.</summary> /// <param name="location">The location to search.</param> private IEnumerable<ResourceClump> GetNormalResourceClumps(GameLocation location) { IEnumerable<ResourceClump> clumps = location.resourceClumps; switch (location) { case Forest { log: not null } forest: clumps = clumps.Concat(new[] { forest.log }); break; case Woods woods when woods.stumps.Any(): clumps = clumps.Concat(woods.stumps); break; } return clumps; } /// <summary>Get the resource clump which covers a given tile, if any.</summary> /// <param name="location">The location to check.</param> /// <param name="tile">The tile to check.</param> protected bool HasResourceClumpCoveringTile(GameLocation location, Vector2 tile) { return this.GetResourceClumpCoveringTile(location, tile, null, out _) != null; } /// <summary>Get the resource clump which covers a given tile, if any.</summary> /// <param name="location">The location to check.</param> /// <param name="tile">The tile to check.</param> /// <param name="player">The current player.</param> /// <param name="applyTool">Applies a tool to the resource clump.</param> protected ResourceClump GetResourceClumpCoveringTile(GameLocation location, Vector2 tile, Farmer player, out Func<Tool, bool> applyTool) { Rectangle tileArea = this.GetAbsoluteTileArea(tile); // normal resource clumps foreach (ResourceClump clump in this.GetNormalResourceClumps(location)) { if (clump.getBoundingBox(clump.tile.Value).Intersects(tileArea)) { applyTool = tool => this.UseToolOnTile(tool, tile, player, location); return clump; } } // FarmTypeManager resource clumps if (this.HasFarmTypeManager) { foreach (LargeTerrainFeature feature in location.largeTerrainFeatures) { if (feature.GetType().FullName == "FarmTypeManager.LargeResourceClump" && feature.getBoundingBox(feature.tilePosition.Value).Intersects(tileArea)) { ResourceClump clump = this.Reflection.GetField<NetRef<ResourceClump>>(feature, "Clump").GetValue().Value; applyTool = tool => feature.performToolAction(tool, 0, tile, location); return clump; } } } applyTool = null; return null; } /// <summary>Get the best target farm animal for a tool.</summary> /// <param name="tool">The tool to check.</param> /// <param name="location">The location to check.</param> /// <param name="tile">The tile to check.</param> /// <remarks>Derived from <see cref="Shears.beginUsing"/> and <see cref="Utility.GetBestHarvestableFarmAnimal"/>.</remarks> protected FarmAnimal GetBestHarvestableFarmAnimal(Tool tool, GameLocation location, Vector2 tile) { // ignore if location can't have animals if (location is not IAnimalLocation animalLocation) return null; // get best harvestable animal Vector2 useAt = this.GetToolPixelPosition(tile); FarmAnimal animal = Utility.GetBestHarvestableFarmAnimal( animals: animalLocation.Animals.Values, tool: tool, toolRect: new Rectangle((int)useAt.X, (int)useAt.Y, Game1.tileSize, Game1.tileSize) ); if (animal == null || animal.toolUsedForHarvest.Value != tool.BaseName || animal.currentProduce.Value <= 0 || animal.age.Value < animal.ageWhenMature.Value) return null; return animal; } /// <summary>Get the tilled dirt for a tile, if any.</summary> /// <param name="tileFeature">The feature on the tile.</param> /// <param name="tileObj">The object on the tile.</param> /// <param name="dirt">The tilled dirt found, if any.</param> /// <param name="isCoveredByObj">Whether there's an object placed over the tilled dirt.</param> /// <param name="pot">The indoor pot containing the dirt, if applicable.</param> /// <returns>Returns whether tilled dirt was found.</returns> protected bool TryGetHoeDirt(TerrainFeature tileFeature, SObject tileObj, out HoeDirt dirt, out bool isCoveredByObj, out IndoorPot pot) { // garden pot if (tileObj is IndoorPot foundPot) { pot = foundPot; dirt = pot.hoeDirt.Value; isCoveredByObj = false; return true; } // regular dirt if ((dirt = tileFeature as HoeDirt) != null) { pot = null; isCoveredByObj = tileObj != null; return true; } // none found pot = null; dirt = null; isCoveredByObj = false; return false; } /// <summary>Break open a container using a tool, if applicable.</summary> /// <param name="tile">The tile position</param> /// <param name="tileObj">The object on the tile.</param> /// <param name="tool">The tool selected by the player (if any).</param> /// <param name="location">The current location.</param> protected bool TryBreakContainer(Vector2 tile, SObject tileObj, Tool tool, GameLocation location) { if (tileObj is BreakableContainer) return tileObj.performToolAction(tool, location); if (tileObj?.GetItemType() == ItemType.Object && tileObj.Name == "SupplyCrate" && tileObj is not Chest && tileObj.performToolAction(tool, location)) { tileObj.performRemoveAction(tile, location); Game1.currentLocation.Objects.Remove(tile); return true; } return false; } /// <summary>Try to harvest tall grass.</summary> /// <param name="location">The location being harvested.</param> /// <param name="tile">The tile being harvested.</param> /// <param name="tileFeature">The terrain feature on the tile.</param> /// <param name="player">The current player.</param> /// <returns>Returns whether it was harvested.</returns> protected bool TryClearDeadCrop(GameLocation location, Vector2 tile, TerrainFeature tileFeature, Farmer player) { return tileFeature is HoeDirt { crop: not null } dirt && dirt.crop.dead.Value && this.UseToolOnTile(this.FakePickaxe.Value, tile, player, location); } /// <summary>Try to harvest tall grass.</summary> /// <param name="grass">The grass to harvest.</param> /// <param name="location">The location being harvested.</param> /// <param name="tile">The tile being harvested.</param> /// <returns>Returns whether it was harvested.</returns> /// <remarks>Derived from <see cref="Grass.performToolAction"/>.</remarks> protected bool TryHarvestGrass(Grass grass, GameLocation location, Vector2 tile) { if (grass == null) return false; // remove grass location.terrainFeatures.Remove(tile); // collect hay Random random = Game1.IsMultiplayer ? Game1.recentMultiplayerRandom : new Random((int)(Game1.uniqueIDForThisGame + tile.X * 1000.0 + tile.Y * 11.0)); if (random.NextDouble() < (this.FoundGoldenScythe.Value ? 0.75 : 0.5)) { if (Game1.getFarm().tryToAddHay(1) == 0) // returns number left Game1.addHUDMessage(new HUDMessage("Hay", HUDMessage.achievement_type, true, Color.LightGoldenrodYellow, new SObject(178, 1))); } return true; } /// <summary>Cancel the current player animation if it matches one of the given IDs.</summary> /// <param name="player">The player to change.</param> /// <param name="animationIds">The animation IDs to detect.</param> protected void CancelAnimation(Farmer player, params int[] animationIds) { int animationId = this.Reflection.GetField<int>(player.FarmerSprite, "currentSingleAnimation").GetValue(); foreach (int id in animationIds) { if (id == animationId) { player.completelyStopAnimatingOrDoingAction(); player.forceCanMove(); break; } } } } }
#pragma warning disable IDE0079 // Remove unnecessary suppression #pragma warning disable CS1591 // ReSharper disable InconsistentNaming // Decompiled with JetBrains decompiler // Type: Autodesk.Revit.DB.UnitSymbolType // Assembly: RevitAPI, Version=21.0.0.0, Culture=neutral, PublicKeyToken=null // MVID: E5118772-F025-44D6-A6E2-B8EDEDB90979 // Assembly location: C:\Program Files\Autodesk\Revit 2021\RevitAPI.dll using System; namespace CodeCave.Revit.Toolkit { /// <since>2014.</since> /// <summary> /// The unit symbol displayed in the formatted string representation of a number to indicate the units of the value. /// </summary> /// <remarks> /// Most unit symbols appear as suffixes after the formatted number, /// for example "mm" for millimeters. Some currency symbols appear as /// prefixes, for example "$" for dollars. /// </remarks> /// <since>2014.</since> [Obsolete("This enumeration is deprecated in Revit 2021 and may be removed in a future version of Revit. Please use the `ForgeTypeId` class instead. Use constant members of the `SymbolTypeId` class to replace uses of specific values of this enumeration.")] public enum UnitSymbolType { UST_CUSTOM = -1, // 0xFFFFFFFF UST_NONE = 0, UST_M = 1, UST_CM = 101, // 0x00000065 UST_MM = 201, // 0x000000C9 UST_LF = 301, // 0x0000012D UST_FOOT_SINGLE_QUOTE = 302, // 0x0000012E UST_FT = 303, // 0x0000012F UST_INCH_DOUBLE_QUOTE = 601, // 0x00000259 UST_IN = 602, // 0x0000025A UST_ACRES = 701, // 0x000002BD UST_HECTARES = 801, // 0x00000321 UST_CY = 1001, // 0x000003E9 UST_SF = 1101, // 0x0000044D UST_FT_SUP_2 = 1102, // 0x0000044E UST_FT_CARET_2 = 1103, // 0x0000044F UST_M_SUP_2 = 1201, // 0x000004B1 UST_M_CARET_2 = 1202, // 0x000004B2 UST_CF = 1301, // 0x00000515 UST_FT_SUP_3 = 1302, // 0x00000516 UST_FT_CARET_3 = 1303, // 0x00000517 UST_M_SUP_3 = 1401, // 0x00000579 UST_M_CARET_3 = 1402, // 0x0000057A UST_DEGREE_SYMBOL = 1501, // 0x000005DD UST_PERCENT_SIGN = 1901, // 0x0000076D UST_IN_SUP_2 = 2001, // 0x000007D1 UST_IN_CARET_2 = 2002, // 0x000007D2 UST_CM_SUP_2 = 2101, // 0x00000835 UST_CM_CARET_2 = 2102, // 0x00000836 UST_MM_SUP_2 = 2201, // 0x00000899 UST_MM_CARET_2 = 2202, // 0x0000089A UST_IN_SUP_3 = 2301, // 0x000008FD UST_IN_CARET_3 = 2302, // 0x000008FE UST_CM_SUP_3 = 2401, // 0x00000961 UST_CM_CARET_3 = 2402, // 0x00000962 UST_MM_SUP_3 = 2501, // 0x000009C5 UST_MM_CARET_3 = 2502, // 0x000009C6 UST_L = 2601, // 0x00000A29 UST_GAL = 2701, // 0x00000A8D UST_KG_PER_CU_M = 2801, // 0x00000AF1 UST_LB_MASS_PER_CU_FT = 2901, // 0x00000B55 UST_LBM_PER_CU_FT = 2902, // 0x00000B56 UST_LB_MASS_PER_CU_IN = 3001, // 0x00000BB9 UST_LBM_PER_CU_IN = 3002, // 0x00000BBA UST_BTU = 3101, // 0x00000C1D UST_CAL = 3201, // 0x00000C81 UST_KCAL = 3301, // 0x00000CE5 UST_JOULE = 3401, // 0x00000D49 UST_KWH = 3501, // 0x00000DAD UST_THERM = 3601, // 0x00000E11 UST_IN_WG_PER_100FT = 3701, // 0x00000E75 UST_PASCAL_PER_M = 3801, // 0x00000ED9 UST_WATT = 3901, // 0x00000F3D UST_KILOWATT = 4001, // 0x00000FA1 UST_BTU_PER_S = 4101, // 0x00001005 UST_BTU_PER_H = 4201, // 0x00001069 UST_CAL_PER_S = 4301, // 0x000010CD UST_KCAL_PER_S = 4401, // 0x00001131 UST_WATT_PER_SQ_FT = 4501, // 0x00001195 UST_WATT_PER_SQ_M = 4601, // 0x000011F9 UST_IN_WG = 4701, // 0x0000125D UST_PASCAL = 4801, // 0x000012C1 UST_KILOPASCAL = 4901, // 0x00001325 UST_MEGAPASCAL = 5001, // 0x00001389 UST_PSI = 5101, // 0x000013ED UST_LB_FORCE_PER_SQ_IN = 5102, // 0x000013EE UST_PSIG = 5103, // 0x000013EF UST_PSIA = 5104, // 0x000013F0 UST_LBF_PER_SQ_IN = 5105, // 0x000013F1 UST_IN_HG = 5201, // 0x00001451 UST_MM_HG = 5301, // 0x000014B5 UST_ATM = 5401, // 0x00001519 UST_BAR = 5501, // 0x0000157D UST_DEGREE_F = 5601, // 0x000015E1 UST_DEGREE_C = 5701, // 0x00001645 UST_KELVIN = 5801, // 0x000016A9 UST_DEGREE_R = 5901, // 0x0000170D UST_FT_PER_MIN = 6001, // 0x00001771 UST_FPM = 6002, // 0x00001772 UST_M_PER_S = 6101, // 0x000017D5 UST_CM_PER_MIN = 6201, // 0x00001839 UST_CU_FT_PER_MIN = 6301, // 0x0000189D UST_CFM = 6302, // 0x0000189E UST_L_PER_S = 6401, // 0x00001901 UST_LPS = 6402, // 0x00001902 UST_CU_M_PER_S = 6501, // 0x00001965 UST_CMS = 6502, // 0x00001966 UST_CU_M_PER_H = 6601, // 0x000019C9 UST_CMH = 6602, // 0x000019CA UST_GAL_PER_MIN = 6701, // 0x00001A2D UST_GPM = 6702, // 0x00001A2E UST_USGPM = 6703, // 0x00001A2F UST_GAL_PER_H = 6801, // 0x00001A91 UST_GPH = 6802, // 0x00001A92 UST_USGPH = 6803, // 0x00001A93 UST_AMPERE = 6901, // 0x00001AF5 UST_KILOAMPERE = 7001, // 0x00001B59 UST_MILLIAMPERE = 7101, // 0x00001BBD UST_VOLT = 7201, // 0x00001C21 UST_KILOVOLT = 7301, // 0x00001C85 UST_MILLIVOLT = 7401, // 0x00001CE9 UST_HZ = 7501, // 0x00001D4D UST_CPS = 7601, // 0x00001DB1 UST_LX = 7701, // 0x00001E15 UST_FC = 7801, // 0x00001E79 UST_FTC = 7802, // 0x00001E7A UST_FL = 7901, // 0x00001EDD UST_FL_LOWERCASE = 7902, // 0x00001EDE UST_FTL = 7903, // 0x00001EDF UST_CD_PER_SQ_M = 8001, // 0x00001F41 UST_CD = 8101, // 0x00001FA5 UST_LM = 8301, // 0x0000206D UST_VOLTAMPERE = 8401, // 0x000020D1 UST_KILOVOLTAMPERE = 8501, // 0x00002135 UST_HP = 8601, // 0x00002199 UST_N = 8701, // 0x000021FD UST_DA_N = 8801, // 0x00002261 UST_K_N = 8901, // 0x000022C5 UST_M_N = 9001, // 0x00002329 UST_KIP = 9101, // 0x0000238D UST_KGF = 9201, // 0x000023F1 UST_TF = 9301, // 0x00002455 UST_LB_FORCE = 9401, // 0x000024B9 UST_LBF = 9402, // 0x000024BA UST_N_PER_M = 9501, // 0x0000251D UST_DA_N_PER_M = 9601, // 0x00002581 UST_K_N_PER_M = 9701, // 0x000025E5 UST_M_N_PER_M = 9801, // 0x00002649 UST_KIP_PER_FT = 9901, // 0x000026AD UST_KGF_PER_M = 10001, // 0x00002711 UST_TF_PER_M = 10101, // 0x00002775 UST_LB_FORCE_PER_FT = 10201, // 0x000027D9 UST_LBF_PER_FT = 10202, // 0x000027DA UST_N_PER_M_SUP_2 = 10301, // 0x0000283D UST_DA_N_PER_M_SUP_2 = 10401, // 0x000028A1 UST_K_N_PER_M_SUP_2 = 10501, // 0x00002905 UST_M_N_PER_M_SUP_2 = 10601, // 0x00002969 UST_KSF = 10701, // 0x000029CD UST_KIP_PER_SQ_FT = 10702, // 0x000029CE UST_KGF_PER_M_SUP_2 = 10801, // 0x00002A31 UST_TF_PER_M_SUP_2 = 10901, // 0x00002A95 UST_PSF = 11001, // 0x00002AF9 UST_LB_FORCE_PER_SQ_FT = 11002, // 0x00002AFA UST_LBF_PER_SQ_FT = 11003, // 0x00002AFB UST_N_DASH_M = 11101, // 0x00002B5D UST_DA_N_DASH_M = 11201, // 0x00002BC1 UST_K_N_DASH_M = 11301, // 0x00002C25 UST_M_N_DASH_M = 11401, // 0x00002C89 UST_KIP_DASH_FT = 11501, // 0x00002CED UST_KGF_DASH_M = 11601, // 0x00002D51 UST_TF_DASH_M = 11701, // 0x00002DB5 UST_LB_FORCE_DASH_FT = 11801, // 0x00002E19 UST_LBF_DASH_FT = 11802, // 0x00002E1A UST_M_PER_K_N = 11901, // 0x00002E7D UST_FT_PER_KIP = 12001, // 0x00002EE1 UST_M_SUP_2_PER_K_N = 12101, // 0x00002F45 UST_FT_SUP_2_PER_KIP = 12201, // 0x00002FA9 UST_M_SUP_3_PER_K_N = 12301, // 0x0000300D UST_FT_SUP_3_PER_KIP = 12401, // 0x00003071 UST_INV_K_N = 12501, // 0x000030D5 UST_INV_KIP = 12601, // 0x00003139 UST_FTH2O_PER_100FT = 12701, // 0x0000319D UST_FT_OF_WATER_PER_100FT = 12702, // 0x0000319E UST_FEET_OF_WATER_PER_100FT = 12703, // 0x0000319F UST_FTH2O = 12801, // 0x00003201 UST_FT_OF_WATER = 12802, // 0x00003202 UST_FEET_OF_WATER = 12803, // 0x00003203 UST_PA_S = 12901, // 0x00003265 UST_LB_FORCE_PER_FT_S = 13001, // 0x000032C9 UST_LBM_PER_FT_S = 13002, // 0x000032CA UST_CP = 13101, // 0x0000332D UST_FT_PER_S = 13201, // 0x00003391 UST_FPS = 13202, // 0x00003392 UST_KSI = 13301, // 0x000033F5 UST_KIP_PER_SQ_IN = 13302, // 0x000033F6 UST_KN_PER_M_SUP_3 = 13401, // 0x00003459 UST_LB_FORCE_PER_CU_FT = 13501, // 0x000034BD UST_LBF_PER_CU_FT = 13502, // 0x000034BE UST_KIP_PER_IN_SUP_3 = 13601, // 0x00003521 UST_INV_DEGREE_F = 13701, // 0x00003585 UST_INV_DEGREE_C = 13801, // 0x000035E9 UST_N_DASH_M_PER_M = 13901, // 0x0000364D UST_DA_N_DASH_M_PER_M = 14001, // 0x000036B1 UST_K_N_DASH_M_PER_M = 14101, // 0x00003715 UST_M_N_DASH_M_PER_M = 14201, // 0x00003779 UST_KIP_DASH_FT_PER_FT = 14301, // 0x000037DD UST_KGF_DASH_M_PER_M = 14401, // 0x00003841 UST_TF_DASH_M_PER_M = 14501, // 0x000038A5 UST_LB_FORCE_DASH_FT_PER_FT = 14601, // 0x00003909 UST_LBF_DASH_FT_PER_FT = 14602, // 0x0000390A UST_LB_FORCE_PER_FT_H = 14701, // 0x0000396D UST_LBM_PER_FT_H = 14702, // 0x0000396E UST_KIPS_PER_IN = 14801, // 0x000039D1 UST_KIPS_PER_CU_FT = 14901, // 0x00003A35 UST_KIP_FT_PER_DEGREE = 15001, // 0x00003A99 UST_K_N_M_PER_DEGREE = 15101, // 0x00003AFD UST_KIP_FT_PER_DEGREE_PER_FT = 15201, // 0x00003B61 UST_K_N_M_PER_DEGREE_PER_M = 15301, // 0x00003BC5 UST_WATT_PER_SQ_M_K = 15401, // 0x00003C29 UST_BTU_PER_H_SQ_FT_DEGREE_F = 15501, // 0x00003C8D UST_CFM_PER_SQ_FT = 15601, // 0x00003CF1 UST_CFM_PER_SF = 15602, // 0x00003CF2 UST_LPS_PER_SQ_M = 15701, // 0x00003D55 UST_L_PER_S_SQ_M = 15702, // 0x00003D56 UST_COLON_10 = 15801, // 0x00003DB9 UST_COLON_12 = 15901, // 0x00003E1D UST_SLOPE_DEGREE_SYMBOL = 16001, // 0x00003E81 UST_WATT_PER_CU_FT = 16401, // 0x00004011 UST_WATT_PER_CU_M = 16501, // 0x00004075 UST_BTU_PER_H_SQ_FT = 16601, // 0x000040D9 UST_BTU_PER_H_CU_FT = 16701, // 0x0000413D UST_TON = 16801, // 0x000041A1 UST_TON_OF_REFRIGERATION = 16802, // 0x000041A2 UST_CFM_PER_CU_FT = 16901, // 0x00004205 UST_CFM_PER_CF = 16902, // 0x00004206 UST_L_PER_S_CU_M = 17001, // 0x00004269 UST_CFM_PER_TON = 17101, // 0x000042CD UST_L_PER_S_KW = 17201, // 0x00004331 UST_SQ_FT_PER_TON = 17301, // 0x00004395 UST_SF_PER_TON = 17302, // 0x00004396 UST_SQ_M_PER_KW = 17401, // 0x000043F9 UST_DOLLAR = 17501, // 0x0000445D UST_EURO_SUFFIX = 17502, // 0x0000445E UST_EURO_PREFIX = 17503, // 0x0000445F UST_POUND = 17504, // 0x00004460 UST_YEN = 17505, // 0x00004461 UST_CHINESE_HONG_KONG_SAR = 17506, // 0x00004462 UST_WON = 17507, // 0x00004463 UST_SHEQEL = 17508, // 0x00004464 UST_DONG = 17509, // 0x00004465 UST_BAHT = 17510, // 0x00004466 UST_KRONER = 17511, // 0x00004467 UST_LM_PER_W = 17601, // 0x000044C1 UST_SF_PER_MBH = 17701, // 0x00004525 UST_SF_PER_KBTU_PER_H = 17702, // 0x00004526 UST_SQ_FT_PER_MBH = 17703, // 0x00004527 UST_SQ_FT_PER_KBTU_PER_H = 17704, // 0x00004528 UST_K_N_PER_CM_SUP_2 = 17801, // 0x00004589 UST_N_PER_MM_SUP_2 = 17901, // 0x000045ED UST_K_N_PER_MM_SUP_2 = 18001, // 0x00004651 UST_ONE_COLON = 18201, // 0x00004719 UST_H_SQ_FT_DEGREE_F_PER_BTU = 18401, // 0x000047E1 UST_SQ_M_K_PER_WATT = 18501, // 0x00004845 UST_BTU_PER_F = 18601, // 0x000048A9 UST_J_PER_KELVIN = 18701, // 0x0000490D UST_KJ_PER_KELVIN = 18801, // 0x00004971 UST_KGM = 18901, // 0x000049D5 UST_TM = 19001, // 0x00004A39 UST_LB_MASS = 19101, // 0x00004A9D UST_LBM = 19102, // 0x00004A9E UST_M_PER_SQ_S = 19201, // 0x00004B01 UST_KM_PER_SQ_S = 19301, // 0x00004B65 UST_IN_PER_SQ_S = 19401, // 0x00004BC9 UST_FT_PER_SQ_S = 19501, // 0x00004C2D UST_MI_PER_SQ_S = 19601, // 0x00004C91 UST_FT_SUP_4 = 19701, // 0x00004CF5 UST_IN_SUP_4 = 19801, // 0x00004D59 UST_MM_SUP_4 = 19901, // 0x00004DBD UST_CM_SUP_4 = 20001, // 0x00004E21 UST_M_SUP_4 = 20101, // 0x00004E85 UST_FT_SUP_6 = 20201, // 0x00004EE9 UST_IN_SUP_6 = 20301, // 0x00004F4D UST_MM_SUP_6 = 20401, // 0x00004FB1 UST_CM_SUP_6 = 20501, // 0x00005015 UST_M_SUP_6 = 20601, // 0x00005079 UST_SQ_FT_PER_FT = 20701, // 0x000050DD UST_SQ_IN_PER_FT = 20801, // 0x00005141 UST_SQ_MM_PER_M = 20901, // 0x000051A5 UST_SQ_CM_PER_M = 21001, // 0x00005209 UST_SQ_M_PER_M = 21101, // 0x0000526D UST_KGM_PER_M = 21201, // 0x000052D1 UST_LB_MASS_PER_FT = 21301, // 0x00005335 UST_LBM_PER_FT = 21302, // 0x00005336 UST_RAD = 21401, // 0x00005399 UST_GRAD = 21501, // 0x000053FD UST_RAD_PER_S = 21601, // 0x00005461 UST_MS = 21701, // 0x000054C5 UST_S = 21801, // 0x00005529 UST_MIN = 21901, // 0x0000558D UST_H = 22001, // 0x000055F1 UST_KM_PER_H = 22101, // 0x00005655 UST_MI_PER_H = 22201, // 0x000056B9 UST_KJ = 22301, // 0x0000571D UST_KGM_PER_SQ_M = 22401, // 0x00005781 UST_LBM_PER_SQ_FT = 22501, // 0x000057E5 UST_WATTS_PER_METER_KELVIN = 22601, // 0x00005849 UST_J_PER_G_CELSIUS = 22701, // 0x000058AD UST_J_PER_G = 22801, // 0x00005911 UST_NG_PER_PA_S_SQ_M = 22901, // 0x00005975 UST_OHM_M = 23001, // 0x000059D9 UST_BTU_PER_H_FT_DEGREE_F = 23101, // 0x00005A3D UST_BTU_PER_LB_DEGREE_F = 23201, // 0x00005AA1 UST_BTU_PER_LB = 23301, // 0x00005B05 UST_GR_PER_H_SQ_FT_IN_HG = 23401, // 0x00005B69 UST_PER_MILLE_SIGN = 23501, // 0x00005BCD UST_DM = 23601, // 0x00005C31 UST_J_PER_KG_CELSIUS = 23701, // 0x00005C95 UST_UM_PER_M_C = 23801, // 0x00005CF9 UST_UIN_PER_IN_F = 23901, // 0x00005D5D UST_USTONNES_MASS_TONS = 24001, // 0x00005DC1 UST_USTONNES_MASS_T = 24002, // 0x00005DC2 UST_USTONNES_MASS_ST = 24003, // 0x00005DC3 UST_USTONNES_FORCE_TONSF = 24101, // 0x00005E25 UST_USTONNES_FORCE_STF = 24102, // 0x00005E26 UST_USTONNES_FORCE_AS_MASS_TONS = 24103, // 0x00005E27 UST_USTONNES_FORCE_AS_MASS_T = 24104, // 0x00005E28 UST_USTONNES_FORCE_AS_MASS_ST = 24105, // 0x00005E29 UST_L_PER_M = 24201, // 0x00005E89 UST_LPM = 24202, // 0x00005E8A UST_DEGREE_F_DIFFERENCE = 24301, // 0x00005EED UST_DELTA_DEGREE_F = 24302, // 0x00005EEE UST_DEGREE_C_DIFFERENCE = 24401, // 0x00005F51 UST_DELTA_DEGREE_C = 24402, // 0x00005F52 UST_KELVIN_DIFFERENCE = 24501, // 0x00005FB5 UST_DELTA_KELVIN = 24502, // 0x00005FB6 UST_DEGREE_R_DIFFERENCE = 24601, // 0x00006019 UST_DELTA_DEGREE_R = 24602, // 0x0000601A UST_US_SURVEY_FT = 60501, // 0x0000EC55 } }
using System; using System.Collections.Generic; using System.Linq; using Skahal.Common; using Skahal.Logging; using UnityEngine; using Buildron.Domain.Builds; namespace Buildron.Domain.Users { /// <summary> /// Domain service to user from continuous integration server. /// </summary> public class UserService : IUserService { #region Events /// <summary> /// Occurs when an user is found. /// </summary> public event EventHandler<UserFoundEventArgs> UserFound; /// <summary> /// Occurs when an user is updated. /// </summary> public event EventHandler<UserUpdatedEventArgs> UserUpdated; /// <summary> /// Occurs when an user triggered a build. /// </summary> public event EventHandler<UserTriggeredBuildEventArgs> UserTriggeredBuild; /// <summary> /// Occurs when an user is removed. /// </summary> public event EventHandler<UserRemovedEventArgs> UserRemoved; /// <summary> /// Occurs when an user authentication is completed. /// </summary> public event EventHandler<UserAuthenticationCompletedEventArgs> UserAuthenticationCompleted; #endregion #region Fields private StaticUserAvatarProvider m_userAvatarCache; private IList<IUserAvatarProvider> m_humanUserAvatarProviders; private IList<IUserAvatarProvider> m_nonHumanUserAvatarProviders; private ISHLogStrategy m_log; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Buildron.Domain.Users.UserService"/> class. /// </summary> /// <param name="humanUserAvatarProviders">Human user avatar providers.</param> /// <param name="nonHumanAvatarProviders">Non human avatar providers.</param> /// <param name="log">Log.</param> public UserService ( IUserAvatarProvider[] humanUserAvatarProviders, IUserAvatarProvider[] nonHumanAvatarProviders, ISHLogStrategy log) { Users = new List<IUser> (); // Use a StaticUserAvatarProvier as a cached user avatar providers. m_userAvatarCache = new StaticUserAvatarProvider (); m_humanUserAvatarProviders = new List<IUserAvatarProvider> (humanUserAvatarProviders); m_humanUserAvatarProviders.Insert (0, m_userAvatarCache); m_nonHumanUserAvatarProviders = new List<IUserAvatarProvider> (nonHumanAvatarProviders); m_nonHumanUserAvatarProviders.Insert (0, m_userAvatarCache); m_log = log; } #endregion #region Properties /// <summary> /// Gets the users. /// </summary> public IList<IUser> Users { get; private set; } #endregion #region Methods /// <summary> /// Initialize the service. /// </summary> /// <param name="buildsProvider">Builds provider.</param> public void Initialize (IBuildsProvider buildsProvider) { var serviceSender = typeof(UserService); var usersInLastBuildsUpdate = new List<IUser> (); buildsProvider.BuildUpdated += (sender, e) => { var user = e.Build.TriggeredBy; if (user != null) { var previousUser = Users.FirstOrDefault (f => f == user); if (previousUser == null) { // New user found. Users.Add (user); UserFound.Raise (serviceSender, new UserFoundEventArgs (user)); RaiseUserTriggeredBuildEvents (serviceSender, user, user.Builds); GetUserPhoto(user, (photo) => { user.Photo = photo; UserUpdated.Raise (serviceSender, new UserUpdatedEventArgs (user)); }); } else { var triggeredBuilds = user.Builds.Except (previousUser.Builds); RaiseUserTriggeredBuildEvents (serviceSender, user, triggeredBuilds); Users.Remove (previousUser); Users.Add (user); } UserUpdated.Raise (serviceSender, new UserUpdatedEventArgs (user)); usersInLastBuildsUpdate.Add (user); } }; buildsProvider.BuildsRefreshed += delegate { var removedUsers = Users.Except (usersInLastBuildsUpdate).ToArray (); m_log.Warning ("UserService.BuildsRefreshed: there is {0} users and {1} were refreshed. {2} will be removed", Users.Count, usersInLastBuildsUpdate.Count (), removedUsers.Length); foreach (var user in removedUsers) { Users.Remove (user); UserRemoved.Raise (typeof(BuildService), new UserRemovedEventArgs (user)); } usersInLastBuildsUpdate.Clear (); }; buildsProvider.UserAuthenticationCompleted += (sender, e) => UserAuthenticationCompleted.Raise (sender, e); } /// <summary> /// Gets the user photo. /// </summary> /// <param name="user">User.</param> /// <param name="photoReceived">Photo received callback.</param> public void GetUserPhoto (IUser user, Action<Texture2D> photoReceived) { if (user != null) { if (user.Kind == UserKind.Human) { GetUserPhoto (user, photoReceived, m_humanUserAvatarProviders); } else { GetUserPhoto (user, photoReceived, m_nonHumanUserAvatarProviders); } } } private void GetUserPhoto (IUser user, Action<Texture2D> photoReceived, IList<IUserAvatarProvider> providersChain, int providerStartIndex = 0) { if (providerStartIndex < providersChain.Count) { var currentProvider = providersChain [providerStartIndex]; currentProvider.GetUserPhoto (user, (photo) => { if (photo == null) { GetUserPhoto (user, photoReceived, providersChain, ++providerStartIndex); } else { // Add found photo to cache. if (!object.ReferenceEquals (currentProvider, m_userAvatarCache)) { m_userAvatarCache.AddPhoto (user.UserName, photo); } // Callback photo recieved. photoReceived (photo); } }); } } private void RaiseUserTriggeredBuildEvents (Type serviceSender, IUser user, IEnumerable<IBuild> triggeredBuilds) { foreach (var build in triggeredBuilds) { UserTriggeredBuild.Raise (serviceSender, new UserTriggeredBuildEventArgs (user, build)); } } #endregion } }
using System; using LanguageExt; using System.Linq; using System.Collections.Generic; using System.Threading.Tasks; using LanguageExt.DataTypes.Serialisation; using LanguageExt.TypeClasses; using LanguageExt.ClassInstances; using LanguageExt.Common; using static LanguageExt.Prelude; namespace LanguageExt { public static partial class TryAsyncT { static TryAsync<A> ToTry<A>(Func<Task<Result<A>>> ma) => new TryAsync<A>(ma); // // Collections // public static TryAsync<Arr<B>> Traverse<A, B>(this Arr<TryAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<Result<Arr<B>>> Go(Arr<TryAsync<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Try())).ConfigureAwait(false); return rb.Exists(d => d.IsFaulted) ? rb.Filter(b => b.IsFaulted).Map(b => new Result<Arr<B>>(b.Exception)).Head() : new Result<Arr<B>>(new Arr<B>(rb.Map(d => d.Value))); } } public static TryAsync<HashSet<B>> Traverse<A, B>(this HashSet<TryAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<Result<HashSet<B>>> Go(HashSet<TryAsync<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Try())).ConfigureAwait(false); return rb.Exists(d => d.IsFaulted) ? rb.Filter(b => b.IsFaulted).Map(b => new Result<HashSet<B>>(b.Exception)).Head() : new Result<HashSet<B>>(new HashSet<B>(rb.Map(d => d.Value))); } } [Obsolete("use TraverseSerial or TraverseParallel instead")] public static TryAsync<IEnumerable<B>> Traverse<A, B>(this IEnumerable<TryAsync<A>> ma, Func<A, B> f) => TraverseParallel(ma, f); public static TryAsync<IEnumerable<B>> TraverseSerial<A, B>(this IEnumerable<TryAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<Result<IEnumerable<B>>> Go(IEnumerable<TryAsync<A>> ma, Func<A, B> f) { var rb = new List<B>(); foreach (var a in ma) { var mb = await a.Try().ConfigureAwait(false); if (mb.IsFaulted) return new Result<IEnumerable<B>>(mb.Exception); rb.Add(f(mb.Value)); } return new Result<IEnumerable<B>>(rb); }; } public static TryAsync<IEnumerable<B>> TraverseParallel<A, B>(this IEnumerable<TryAsync<A>> ma, Func<A, B> f) => TraverseParallel(ma, SysInfo.DefaultAsyncSequenceParallelism, f); public static TryAsync<IEnumerable<B>> TraverseParallel<A, B>(this IEnumerable<TryAsync<A>> ma, int windowSize, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<Result<IEnumerable<B>>> Go(IEnumerable<TryAsync<A>> ma, Func<A, B> f) { var rb = await ma.Map(a => a.Map(f).Try()).WindowMap(windowSize, Prelude.identity).ConfigureAwait(false); return rb.Exists(d => d.IsFaulted) ? rb.Filter(b => b.IsFaulted).Map(b => new Result<IEnumerable<B>>(b.Exception)).Head() : new Result<IEnumerable<B>>(rb.Map(d => d.Value).ToArray()); } } [Obsolete("use TraverseSerial or TraverseParallel instead")] public static TryAsync<IEnumerable<A>> Sequence<A>(this IEnumerable<TryAsync<A>> ma) => TraverseParallel(ma, Prelude.identity); public static TryAsync<IEnumerable<A>> SequenceSerial<A>(this IEnumerable<TryAsync<A>> ma) => TraverseSerial(ma, Prelude.identity); public static TryAsync<IEnumerable<A>> SequenceParallel<A>(this IEnumerable<TryAsync<A>> ma) => TraverseParallel(ma, Prelude.identity); public static TryAsync<IEnumerable<A>> SequenceParallel<A>(this IEnumerable<TryAsync<A>> ma, int windowSize) => TraverseParallel(ma, windowSize, Prelude.identity); public static TryAsync<Lst<B>> Traverse<A, B>(this Lst<TryAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<Result<Lst<B>>> Go(Lst<TryAsync<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Try())).ConfigureAwait(false); return rb.Exists(d => d.IsFaulted) ? rb.Filter(b => b.IsFaulted).Map(b => new Result<Lst<B>>(b.Exception)).Head() : new Result<Lst<B>>(new Lst<B>(rb.Map(d => d.Value))); } } public static TryAsync<Que<B>> Traverse<A, B>(this Que<TryAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<Result<Que<B>>> Go(Que<TryAsync<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Try())).ConfigureAwait(false); return rb.Exists(d => d.IsFaulted) ? rb.Filter(b => b.IsFaulted).Map(b => new Result<Que<B>>(b.Exception)).Head() : new Result<Que<B>>(new Que<B>(rb.Map(d => d.Value))); } } [Obsolete("use TraverseSerial or TraverseParallel instead")] public static TryAsync<Seq<B>> Traverse<A, B>(this Seq<TryAsync<A>> ma, Func<A, B> f) => TraverseParallel(ma, f); public static TryAsync<Seq<B>> TraverseSerial<A, B>(this Seq<TryAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<Result<Seq<B>>> Go(Seq<TryAsync<A>> ma, Func<A, B> f) { var rb = new List<B>(); foreach (var a in ma) { var mb = await a.Try().ConfigureAwait(false); if (mb.IsFaulted) return new Result<Seq<B>>(mb.Exception); rb.Add(f(mb.Value)); } return new Result<Seq<B>>(Seq.FromArray(rb.ToArray())); }; } public static TryAsync<Seq<B>> TraverseParallel<A, B>(this Seq<TryAsync<A>> ma, Func<A, B> f) => TraverseParallel(ma, SysInfo.DefaultAsyncSequenceParallelism, f); public static TryAsync<Seq<B>> TraverseParallel<A, B>(this Seq<TryAsync<A>> ma, int windowSize, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<Result<Seq<B>>> Go(Seq<TryAsync<A>> ma, Func<A, B> f) { var rb = await ma.Map(a => a.Map(f).Try()).WindowMap(windowSize, Prelude.identity).ConfigureAwait(false); return rb.Exists(d => d.IsFaulted) ? rb.Filter(b => b.IsFaulted).Map(b => new Result<Seq<B>>(b.Exception)).Head() : new Result<Seq<B>>(Seq.FromArray(rb.Map(d => d.Value).ToArray())); } } [Obsolete("use TraverseSerial or TraverseParallel instead")] public static TryAsync<Seq<A>> Sequence<A>(this Seq<TryAsync<A>> ma) => TraverseParallel(ma, Prelude.identity); public static TryAsync<Seq<A>> SequenceSerial<A>(this Seq<TryAsync<A>> ma) => TraverseSerial(ma, Prelude.identity); public static TryAsync<Seq<A>> SequenceParallel<A>(this Seq<TryAsync<A>> ma) => TraverseParallel(ma, Prelude.identity); public static TryAsync<Seq<A>> SequenceParallel<A>(this Seq<TryAsync<A>> ma, int windowSize) => TraverseParallel(ma, windowSize, Prelude.identity); public static TryAsync<Set<B>> Traverse<A, B>(this Set<TryAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<Result<Set<B>>> Go(Set<TryAsync<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Try())).ConfigureAwait(false); return rb.Exists(d => d.IsFaulted) ? rb.Filter(b => b.IsFaulted).Map(b => new Result<Set<B>>(b.Exception)).Head() : new Result<Set<B>>(new Set<B>(rb.Map(d => d.Value))); } } public static TryAsync<Stck<B>> Traverse<A, B>(this Stck<TryAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<Result<Stck<B>>> Go(Stck<TryAsync<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Reverse().Map(a => a.Map(f).Try())).ConfigureAwait(false); return rb.Exists(d => d.IsFaulted) ? rb.Filter(b => b.IsFaulted).Map(b => new Result<Stck<B>>(b.Exception)).Head() : new Result<Stck<B>>(new Stck<B>(rb.Map(d => d.Value))); } } // // Async types // public static TryAsync<EitherAsync<L, B>> Traverse<L, A, B>(this EitherAsync<L, TryAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<Result<EitherAsync<L, B>>> Go(EitherAsync<L, TryAsync<A>> ma, Func<A, B> f) { var da = await ma.Data.ConfigureAwait(false); if (da.State == EitherStatus.IsBottom) return Result<EitherAsync<L, B>>.Bottom; if (da.State == EitherStatus.IsLeft) return new Result<EitherAsync<L,B>>(da.Left); var rb = await da.Right.Try().ConfigureAwait(false); if (rb.IsFaulted) return new Result<EitherAsync<L, B>>(rb.Exception); return new Result<EitherAsync<L, B>>(EitherAsync<L, B>.Right(f(rb.Value))); } } public static TryAsync<OptionAsync<B>> Traverse<A, B>(this OptionAsync<TryAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<Result<OptionAsync<B>>> Go(OptionAsync<TryAsync<A>> ma, Func<A, B> f) { var (isSome, value) = await ma.Data.ConfigureAwait(false); if (!isSome) return new Result<OptionAsync<B>>(OptionAsync<B>.None); var rb = await value.Try().ConfigureAwait(false); if (rb.IsFaulted) return new Result<OptionAsync<B>>(rb.Exception); return new Result<OptionAsync<B>>(OptionAsync<B>.Some(f(rb.Value))); } } public static TryAsync<TryAsync<B>> Traverse<A, B>(this TryAsync<TryAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<Result<TryAsync<B>>> Go(TryAsync<TryAsync<A>> ma, Func<A, B> f) { var ra = await ma.Try().ConfigureAwait(false); if (ra.IsFaulted) return new Result<TryAsync<B>>(TryAsync<B>(ra.Exception)); var rb = await ra.Value.Try().ConfigureAwait(false); if (rb.IsFaulted) return new Result<TryAsync<B>>(rb.Exception); return new Result<TryAsync<B>>(TryAsync<B>(f(rb.Value))); } } public static TryAsync<TryOptionAsync<B>> Traverse<A, B>(this TryOptionAsync<TryAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<Result<TryOptionAsync<B>>> Go(TryOptionAsync<TryAsync<A>> ma, Func<A, B> f) { var ra = await ma.Try().ConfigureAwait(false); if (ra.IsFaulted) return new Result<TryOptionAsync<B>>(TryOptionAsync<B>(ra.Exception)); if (ra.IsNone) return new Result<TryOptionAsync<B>>(TryOptionAsync<B>(None)); var rb = await ra.Value.Value.Try().ConfigureAwait(false); if (rb.IsFaulted) return new Result<TryOptionAsync<B>>(rb.Exception); return new Result<TryOptionAsync<B>>(TryOptionAsync<B>(f(rb.Value))); } } public static TryAsync<Task<B>> Traverse<A, B>(this Task<TryAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<Result<Task<B>>> Go(Task<TryAsync<A>> ma, Func<A, B> f) { var ra = await ma.ConfigureAwait(false); var rb = await ra.Try().ConfigureAwait(false); if (rb.IsFaulted) return new Result<Task<B>>(rb.Exception); return new Result<Task<B>>(f(rb.Value).AsTask()); } } public static TryAsync<ValueTask<B>> Traverse<A, B>(this ValueTask<TryAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f).AsTask()); async ValueTask<Result<ValueTask<B>>> Go(ValueTask<TryAsync<A>> ma, Func<A, B> f) { var ra = await ma.ConfigureAwait(false); var rb = await ra.Try().ConfigureAwait(false); if (rb.IsFaulted) return new Result<ValueTask<B>>(rb.Exception); return new Result<ValueTask<B>>(f(rb.Value).AsValueTask()); } } public static TryAsync<Aff<B>> Traverse<A, B>(this Aff<TryAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<Result<Aff<B>>> Go(Aff<TryAsync<A>> ma, Func<A, B> f) { var ra = await ma.Run().ConfigureAwait(false); if (ra.IsFail) return new Result<Aff<B>>(FailAff<B>(ra.Error)); var rb = await ra.Value.Try().ConfigureAwait(false); if (rb.IsFaulted) return new Result<Aff<B>>(rb.Exception); return new Result<Aff<B>>(SuccessAff<B>(f(rb.Value))); } } // // Sync types // public static TryAsync<Either<L, B>> Traverse<L, A, B>(this Either<L, TryAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<Result<Either<L, B>>> Go(Either<L, TryAsync<A>> ma, Func<A, B> f) { if(ma.IsBottom) return Result<Either<L, B>>.Bottom; if(ma.IsLeft) return new Result<Either<L, B>>(ma.LeftValue); var rb = await ma.RightValue.Try().ConfigureAwait(false); if(rb.IsFaulted) return new Result<Either<L, B>>(rb.Exception); return new Result<Either<L, B>>(f(rb.Value)); } } public static TryAsync<EitherUnsafe<L, B>> Traverse<L, A, B>(this EitherUnsafe<L, TryAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<Result<EitherUnsafe<L, B>>> Go(EitherUnsafe<L, TryAsync<A>> ma, Func<A, B> f) { if(ma.IsBottom) return Result<EitherUnsafe<L, B>>.Bottom; if(ma.IsLeft) return new Result<EitherUnsafe<L, B>>(ma.LeftValue); var rb = await ma.RightValue.Try().ConfigureAwait(false); if(rb.IsFaulted) return new Result<EitherUnsafe<L, B>>(rb.Exception); return new Result<EitherUnsafe<L, B>>(f(rb.Value)); } } public static TryAsync<Identity<B>> Traverse<A, B>(this Identity<TryAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<Result<Identity<B>>> Go(Identity<TryAsync<A>> ma, Func<A, B> f) { if(ma.IsBottom) return Result<Identity<B>>.Bottom; var rb = await ma.Value.Try().ConfigureAwait(false); if(rb.IsFaulted) return new Result<Identity<B>>(rb.Exception); return new Result<Identity<B>>(new Identity<B>(f(rb.Value))); } } public static TryAsync<Fin<B>> Traverse<A, B>(this Fin<TryAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<Result<Fin<B>>> Go(Fin<TryAsync<A>> ma, Func<A, B> f) { if(ma.IsFail) return new Result<Fin<B>>(ma.Cast<B>()); var rb = await ma.Value.Try().ConfigureAwait(false); if(rb.IsFaulted) return new Result<Fin<B>>(rb.Exception); return new Result<Fin<B>>(Fin<B>.Succ(f(rb.Value))); } } public static TryAsync<Option<B>> Traverse<A, B>(this Option<TryAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<Result<Option<B>>> Go(Option<TryAsync<A>> ma, Func<A, B> f) { if(ma.IsNone) return new Result<Option<B>>(None); var rb = await ma.Value.Try().ConfigureAwait(false); if(rb.IsFaulted) return new Result<Option<B>>(rb.Exception); return new Result<Option<B>>(Option<B>.Some(f(rb.Value))); } } public static TryAsync<OptionUnsafe<B>> Traverse<A, B>(this OptionUnsafe<TryAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<Result<OptionUnsafe<B>>> Go(OptionUnsafe<TryAsync<A>> ma, Func<A, B> f) { if(ma.IsNone) return new Result<OptionUnsafe<B>>(None); var rb = await ma.Value.Try().ConfigureAwait(false); if(rb.IsFaulted) return new Result<OptionUnsafe<B>>(rb.Exception); return new Result<OptionUnsafe<B>>(OptionUnsafe<B>.Some(f(rb.Value))); } } public static TryAsync<Try<B>> Traverse<A, B>(this Try<TryAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<Result<Try<B>>> Go(Try<TryAsync<A>> ma, Func<A, B> f) { var ra = ma.Try(); if (ra.IsFaulted) return new Result<Try<B>>(TryFail<B>(ra.Exception)); var rb = await ra.Value.Try().ConfigureAwait(false); if (rb.IsFaulted) return new Result<Try<B>>(rb.Exception); return new Result<Try<B>>(Try<B>(f(rb.Value))); } } public static TryAsync<TryOption<B>> Traverse<A, B>(this TryOption<TryAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<Result<TryOption<B>>> Go(TryOption<TryAsync<A>> ma, Func<A, B> f) { var ra = ma.Try(); if (ra.IsBottom) return Result<TryOption<B>>.Bottom; if (ra.IsNone) return new Result<TryOption<B>>(TryOptional<B>(None)); if (ra.IsFaulted) return new Result<TryOption<B>>(TryOptionFail<B>(ra.Exception)); var rb = await ra.Value.Value.Try().ConfigureAwait(false); if (rb.IsFaulted) return new Result<TryOption<B>>(rb.Exception); return new Result<TryOption<B>>(TryOption<B>(f(rb.Value))); } } public static TryAsync<Validation<Fail, B>> Traverse<Fail, A, B>(this Validation<Fail, TryAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<Result<Validation<Fail, B>>> Go(Validation<Fail, TryAsync<A>> ma, Func<A, B> f) { if (ma.IsFail) return new Result<Validation<Fail, B>>(Fail<Fail, B>(ma.FailValue)); var rb = await ma.SuccessValue.Try().ConfigureAwait(false); if(rb.IsFaulted) return new Result<Validation<Fail, B>>(rb.Exception); return new Result<Validation<Fail, B>>(f(rb.Value)); } } public static TryAsync<Validation<MonoidFail, Fail, B>> Traverse<MonoidFail, Fail, A, B>(this Validation<MonoidFail, Fail, TryAsync<A>> ma, Func<A, B> f) where MonoidFail : struct, Monoid<Fail>, Eq<Fail> { return ToTry(() => Go(ma, f)); async Task<Result<Validation<MonoidFail, Fail, B>>> Go(Validation<MonoidFail, Fail, TryAsync<A>> ma, Func<A, B> f) { if (ma.IsFail) return new Result<Validation<MonoidFail, Fail, B>>(Fail<MonoidFail, Fail, B>(ma.FailValue)); var rb = await ma.SuccessValue.Try().ConfigureAwait(false); if(rb.IsFaulted) return new Result<Validation<MonoidFail, Fail, B>>(rb.Exception); return new Result<Validation<MonoidFail, Fail, B>>(f(rb.Value)); } } public static TryAsync<Eff<B>> Traverse<A, B>(this Eff<TryAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<Result<Eff<B>>> Go(Eff<TryAsync<A>> ma, Func<A, B> f) { var ra = ma.Run(); if (ra.IsFail) return new Result<Eff<B>>(FailEff<B>(ra.Error)); var rb = await ra.Value.Try().ConfigureAwait(false); if (rb.IsFaulted) return new Result<Eff<B>>(rb.Exception); return new Result<Eff<B>>(SuccessEff<B>(f(rb.Value))); } } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // // Novell.Directory.Ldap.Utilclass.SchemaTokenCreator.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; namespace Novell.Directory.Ldap.Utilclass { public class SchemaTokenCreator { private string basestring; private bool cppcomments = false; // C++ style comments enabled private bool ccomments = false; // C style comments enabled private bool iseolsig = false; private bool cidtolower; private bool pushedback; private int peekchar; private sbyte[] ctype; private int linenumber = 1; private int ichar = 1; private char[] buf; private System.IO.StreamReader reader = null; private System.IO.StringReader sreader = null; private System.IO.Stream input = null; public string StringValue; public double NumberValue; public int lastttype; private void Initialise() { ctype = new sbyte[256]; buf = new char[20]; peekchar = Int32.MaxValue; WordCharacters('a', 'z'); WordCharacters('A', 'Z'); WordCharacters(128 + 32, 255); WhitespaceCharacters(0, ' '); CommentCharacter('/'); QuoteCharacter('"'); QuoteCharacter('\''); parseNumbers(); } public SchemaTokenCreator(System.IO.Stream instream) { Initialise(); if (instream == null) { throw new NullReferenceException(); } input = instream; } public SchemaTokenCreator(System.IO.StreamReader r) { Initialise(); if (r == null) { throw new NullReferenceException(); } reader = r; } public SchemaTokenCreator(System.IO.StringReader r) { Initialise(); if (r == null) { throw new NullReferenceException(); } sreader = r; } public void pushBack() { pushedback = true; } public int CurrentLine { get { return linenumber; } } public string ToStringValue() { string strval; switch (lastttype) { case (int)TokenTypes.EOF: strval = "EOF"; break; case (int)TokenTypes.EOL: strval = "EOL"; break; case (int)TokenTypes.WORD: strval = StringValue; break; case (int)TokenTypes.STRING: strval = StringValue; break; case (int)TokenTypes.NUMBER: case (int)TokenTypes.REAL: strval = "n=" + NumberValue; break; default: { if (lastttype < 256 && ((ctype[lastttype] & (sbyte)CharacterTypes.STRINGQUOTE) != 0)) { strval = StringValue; break; } char[] s = new char[3]; s[0] = s[2] = '\''; s[1] = (char)lastttype; strval = new string(s); break; } } return strval; } public void WordCharacters(int min, int max) { if (min < 0) min = 0; if (max >= ctype.Length) max = ctype.Length - 1; while (min <= max) ctype[min++] |= (sbyte)CharacterTypes.ALPHABETIC; } public void WhitespaceCharacters(int min, int max) { if (min < 0) min = 0; if (max >= ctype.Length) max = ctype.Length - 1; while (min <= max) ctype[min++] = (sbyte)CharacterTypes.WHITESPACE; } public void OrdinaryCharacters(int min, int max) { if (min < 0) min = 0; if (max >= ctype.Length) max = ctype.Length - 1; while (min <= max) ctype[min++] = 0; } public void OrdinaryCharacter(int ch) { if (ch >= 0 && ch < ctype.Length) ctype[ch] = 0; } public void CommentCharacter(int ch) { if (ch >= 0 && ch < ctype.Length) ctype[ch] = (sbyte)CharacterTypes.COMMENTCHAR; } public void InitTable() { for (int i = ctype.Length; --i >= 0;) ctype[i] = 0; } public void QuoteCharacter(int ch) { if (ch >= 0 && ch < ctype.Length) ctype[ch] = (sbyte)CharacterTypes.STRINGQUOTE; } public void parseNumbers() { for (int i = '0'; i <= '9'; i++) ctype[i] |= (sbyte)CharacterTypes.NUMERIC; ctype['.'] |= (sbyte)CharacterTypes.NUMERIC; ctype['-'] |= (sbyte)CharacterTypes.NUMERIC; } private int read() { if (sreader != null) { return sreader.Read(); } else if (reader != null) { return reader.Read(); } else if (input != null) return input.ReadByte(); else throw new Exception(); } public int nextToken() { if (pushedback) { pushedback = false; return lastttype; } StringValue = null; int curc = peekchar; if (curc < 0) curc = Int32.MaxValue; if (curc == (Int32.MaxValue - 1)) { curc = read(); if (curc < 0) return lastttype = (int)TokenTypes.EOF; if (curc == '\n') curc = Int32.MaxValue; } if (curc == Int32.MaxValue) { curc = read(); if (curc < 0) return lastttype = (int)TokenTypes.EOF; } lastttype = curc; peekchar = Int32.MaxValue; int ctype = curc < 256 ? this.ctype[curc] : (sbyte)CharacterTypes.ALPHABETIC; while ((ctype & (sbyte)CharacterTypes.WHITESPACE) != 0) { if (curc == '\r') { linenumber++; if (iseolsig) { peekchar = (Int32.MaxValue - 1); return lastttype = (int)TokenTypes.EOL; } curc = read(); if (curc == '\n') curc = read(); } else { if (curc == '\n') { linenumber++; if (iseolsig) { return lastttype = (int)TokenTypes.EOL; } } curc = read(); } if (curc < 0) return lastttype = (int)TokenTypes.EOF; ctype = curc < 256 ? this.ctype[curc] : (sbyte)CharacterTypes.ALPHABETIC; } if ((ctype & (sbyte)CharacterTypes.NUMERIC) != 0) { bool checkb = false; if (curc == '-') { curc = read(); if (curc != '.' && (curc < '0' || curc > '9')) { peekchar = curc; return lastttype = '-'; } checkb = true; } double dvar = 0; int tempvar = 0; int checkdec = 0; while (true) { if (curc == '.' && checkdec == 0) checkdec = 1; else if ('0' <= curc && curc <= '9') { dvar = dvar * 10 + (curc - '0'); tempvar += checkdec; } else break; curc = read(); } peekchar = curc; if (tempvar != 0) { double divby = 10; tempvar--; while (tempvar > 0) { divby *= 10; tempvar--; } dvar = dvar / divby; } NumberValue = checkb ? -dvar : dvar; return lastttype = (int)TokenTypes.NUMBER; } if ((ctype & (sbyte)CharacterTypes.ALPHABETIC) != 0) { int i = 0; do { if (i >= buf.Length) { char[] nb = new char[buf.Length * 2]; Array.Copy((Array)buf, 0, (Array)nb, 0, buf.Length); buf = nb; } buf[i++] = (char)curc; curc = read(); ctype = curc < 0 ? (sbyte)CharacterTypes.WHITESPACE : curc < 256 ? this.ctype[curc] : (sbyte)CharacterTypes.ALPHABETIC; } while ((ctype & ((sbyte)CharacterTypes.ALPHABETIC | (sbyte)CharacterTypes.NUMERIC)) != 0); peekchar = curc; StringValue = new string(buf, 0, i); if (cidtolower) StringValue = StringValue.ToLower(); return lastttype = (int)TokenTypes.WORD; } if ((ctype & (sbyte)CharacterTypes.STRINGQUOTE) != 0) { lastttype = curc; int i = 0; int rc = read(); while (rc >= 0 && rc != lastttype && rc != '\n' && rc != '\r') { if (rc == '\\') { curc = read(); int first = curc; if (curc >= '0' && curc <= '7') { curc = curc - '0'; int loopchar = read(); if ('0' <= loopchar && loopchar <= '7') { curc = (curc << 3) + (loopchar - '0'); loopchar = read(); if ('0' <= loopchar && loopchar <= '7' && first <= '3') { curc = (curc << 3) + (loopchar - '0'); rc = read(); } else rc = loopchar; } else rc = loopchar; } else { switch (curc) { case 'f': curc = 0xC; break; case 'a': curc = 0x7; break; case 'b': curc = '\b'; break; case 'v': curc = 0xB; break; case 'n': curc = '\n'; break; case 'r': curc = '\r'; break; case 't': curc = '\t'; break; default: break; } rc = read(); } } else { curc = rc; rc = read(); } if (i >= buf.Length) { char[] nb = new char[buf.Length * 2]; Array.Copy((Array)buf, 0, (Array)nb, 0, buf.Length); buf = nb; } buf[i++] = (char)curc; } peekchar = (rc == lastttype) ? Int32.MaxValue : rc; StringValue = new string(buf, 0, i); return lastttype; } if (curc == '/' && (cppcomments || ccomments)) { curc = read(); if (curc == '*' && ccomments) { int prevc = 0; while ((curc = read()) != '/' || prevc != '*') { if (curc == '\r') { linenumber++; curc = read(); if (curc == '\n') { curc = read(); } } else { if (curc == '\n') { linenumber++; curc = read(); } } if (curc < 0) return lastttype = (int)TokenTypes.EOF; prevc = curc; } return nextToken(); } else if (curc == '/' && cppcomments) { while ((curc = read()) != '\n' && curc != '\r' && curc >= 0) ; peekchar = curc; return nextToken(); } else { if ((this.ctype['/'] & (sbyte)CharacterTypes.COMMENTCHAR) != 0) { while ((curc = read()) != '\n' && curc != '\r' && curc >= 0) ; peekchar = curc; return nextToken(); } else { peekchar = curc; return lastttype = '/'; } } } if ((ctype & (sbyte)CharacterTypes.COMMENTCHAR) != 0) { while ((curc = read()) != '\n' && curc != '\r' && curc >= 0) ; peekchar = curc; return nextToken(); } return lastttype = curc; } } }
#pragma warning disable AV1564 #pragma warning disable AV1706 using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Dynamic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Web; using System.Web.Mvc; using System.Web.WebPages; using Foundation.React.Configuration; using Microsoft.Extensions.DependencyInjection; using React; using Sitecore; using Sitecore.Abstractions; using Sitecore.DependencyInjection; using Sitecore.Extensions.StringExtensions; using Sitecore.Mvc; using Sitecore.Mvc.Presentation; using IReactEnvironment = React.IReactEnvironment; using ReactNotInitializedException = React.Exceptions.ReactNotInitialisedException; using TinyIoCResolutionException = React.TinyIoC.TinyIoCResolutionException; namespace Foundation.React.Mvc { /// <summary> /// Represents the class used to create views that have Razor syntax. /// </summary> [ExcludeFromCodeCoverage] public class JsxView : BuildManagerCompiledView { private readonly BaseCacheManager _baseCacheManager; /// <summary>Gets the layout or master page.</summary> /// <returns>The layout or master page.</returns> public string LayoutPath { get; } /// <summary>Gets a value that indicates whether view start files should be executed before the view.</summary> /// <returns>A value that indicates whether view start files should be executed before the view.</returns> public bool RunViewStartPages { get; } internal DisplayModeProvider DisplayModeProvider { get; set; } /// <summary>Gets or sets the set of file extensions that will be used when looking up view start files.</summary> /// <returns>The set of file extensions that will be used when looking up view start files.</returns> public IEnumerable<string> ViewStartFileExtensions { get; } /// <summary>Initializes a new instance of the <see cref="T:System.Web.Mvc.RazorView" /> class.</summary> /// <param name="controllerContext">The controller context.</param> /// <param name="viewPath">The view path.</param> /// <param name="layoutPath">The layout or master page.</param> /// <param name="runViewStartPages">A value that indicates whether view start files should be executed before the view.</param> /// <param name="viewStartFileExtensions">The set of extensions that will be used when looking up view start files.</param> public JsxView(ControllerContext controllerContext, string viewPath, string layoutPath, bool runViewStartPages, IEnumerable<string> viewStartFileExtensions) : this(controllerContext, viewPath, layoutPath, runViewStartPages, viewStartFileExtensions, null) { _baseCacheManager = ServiceLocator.ServiceProvider.GetService<BaseCacheManager>(); } /// <summary>Initializes a new instance of the <see cref="T:System.Web.Mvc.RazorView" /> class using the view page activator.</summary> /// <param name="controllerContext">The controller context.</param> /// <param name="viewPath">The view path.</param> /// <param name="layoutPath">The layout or master page.</param> /// <param name="runViewStartPages">A value that indicates whether view start files should be executed before the view.</param> /// <param name="viewStartFileExtensions">The set of extensions that will be used when looking up view start files.</param> /// <param name="viewPageActivator">The view page activator.</param> public JsxView(ControllerContext controllerContext, string viewPath, string layoutPath, bool runViewStartPages, IEnumerable<string> viewStartFileExtensions, IViewPageActivator viewPageActivator) : base(controllerContext, viewPath, viewPageActivator) { LayoutPath = layoutPath ?? string.Empty; RunViewStartPages = runViewStartPages; ViewStartFileExtensions = viewStartFileExtensions ?? Enumerable.Empty<string>(); _baseCacheManager = ServiceLocator.ServiceProvider.GetService<BaseCacheManager>(); } /// <summary>Renders the specified view context by using the specified the writer object.</summary> /// <param name="viewContext">Information related to rendering a view, such as view data, temporary data, and form context.</param> /// <param name="writer">The writer object.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="viewContext" /> parameter is null.</exception> /// <exception cref="T:SInvalidOperationException">An instance of the view type could not be created.</exception> public override void Render(ViewContext viewContext, TextWriter writer) { if (viewContext == null) { throw new ArgumentNullException(nameof(viewContext)); } RenderView(viewContext, writer, null); } /// <summary>Renders the specified view context by using the specified writer and <see cref="T:System.Web.Mvc.WebViewPage" /> instance.</summary> /// <param name="viewContext">The view context.</param> /// <param name="writer">The writer that is used to render the view to the response.</param> /// <param name="instance">The <see cref="T:System.Web.Mvc.WebViewPage" /> instance.</param> protected override void RenderView(ViewContext viewContext, TextWriter writer, object instance) { if (writer == null) { throw new ArgumentNullException(nameof(writer)); } var placeholderKeys = GetPlaceholders(ViewPath); var componentName = Path.GetFileNameWithoutExtension(ViewPath)?.Replace("-", string.Empty); var props = GetProps(viewContext.ViewData.Model, placeholderKeys); var reactComponent = GetEnvironment().CreateComponent($"{componentName}", props); if (!string.IsNullOrWhiteSpace(ReactSettingsProvider.Current.ContainerClass)) { reactComponent.ContainerClass = ReactSettingsProvider.Current.ContainerClass; } var isEditingOverrideEnabled = ReactSettingsProvider.Current.DisableClientSideWhenEditing && Context.PageMode.IsExperienceEditorEditing; if (ReactSettingsProvider.Current.EnableClientSide && !isEditingOverrideEnabled) { writer.WriteLine(reactComponent.RenderHtml()); var tagBuilder = new TagBuilder("script") { InnerHtml = reactComponent.RenderJavaScript(true) }; writer.Write(Environment.NewLine); writer.Write(tagBuilder.ToString()); } else { writer.WriteLine(reactComponent.RenderHtml(renderServerOnly: true)); } } private static IReactEnvironment GetEnvironment() { try { return ReactEnvironment.Current; } catch (TinyIoCResolutionException ex) { throw new ReactNotInitializedException("ReactJS.NET has not been initialized correctly.", ex); } } protected virtual IList<string> GetPlaceholders(string viewPath) { const string noPlaceholders = "NONE"; const string placeholderSearch = @"<Placeholder\b[^>]*>"; char[] comma = { ',' }; var htmlCache = _baseCacheManager.GetHtmlCache(Context.Site); var cacheKey = $"$React.PlaceholderKeys.{viewPath}"; var keys = htmlCache?.GetHtml(cacheKey); if (!string.IsNullOrWhiteSpace(keys)) { return keys.Equals(noPlaceholders) ? new string[0] : keys.Split(comma, StringSplitOptions.RemoveEmptyEntries); } var placeholderKeys = new List<string>(); var jsxContents = File.ReadAllText(HttpContext.Current.Server.MapPath(viewPath)); if (string.IsNullOrWhiteSpace(jsxContents)) { return new string[0]; } var regex = new Regex(placeholderSearch); var matches = regex.Matches(jsxContents); foreach (Match match in matches) { AddPlaceholderKey(match, placeholderKeys); } // Make sure we set the cache with the placeholder keys. Even if there are not // any keys - this should make subsequent calls faster as they will not have to // do the regex search. htmlCache?.SetHtml(cacheKey, placeholderKeys.Any() ? string.Join(",", placeholderKeys) : noPlaceholders); return placeholderKeys; } private static void AddPlaceholderKey(Capture match, ICollection<string> placeholderKeys) { const string placeholderKey = "placeholderKey={['\"](?<name>[\\$A-Za-z0-9\\.\\-_\\ ]+)['\"]}"; const string isDynamicPlaceholder = "isDynamic=[{]?['\"]?(?<dynamic>\\w +)['\"]?[}]?"; var placeholderKeySearch = new Regex(placeholderKey); var placeholderKeyMatches = placeholderKeySearch.Matches(match.Value); if (placeholderKeyMatches.Count == 1) { // there should only ever be ONE var isDynamicPlaceholderSearch = new Regex(isDynamicPlaceholder); var isDynamicMatches = isDynamicPlaceholderSearch.Matches(match.Value); var dynamicPrefix = string.Empty; if (isDynamicMatches.Count == 1) { // there should only ever be ONE bool.TryParse(isDynamicMatches[0].Value, out var isDynamic); dynamicPrefix = isDynamic ? "$Id." : string.Empty; } placeholderKeys.Add(dynamicPrefix + placeholderKeyMatches[0].Groups["name"].Value); } } internal Rendering Rendering => RenderingContext.Current.Rendering; protected virtual IDictionary<string, object> GetProps(object viewModel, IList<string> placeholderKeys) { var props = new ExpandoObject(); var propsDictionary = (IDictionary<string, object>)props; var placeholders = new ExpandoObject(); var placeholdersDictionary = (IDictionary<string, object>)placeholders; propsDictionary["placeholder"] = placeholders; propsDictionary["data"] = viewModel; propsDictionary["isSitecore"] = true; propsDictionary["isEditing"] = Context.PageMode.IsExperienceEditor; if (!placeholderKeys.Any()) { return props; } var controlId = Rendering.Parameters["id"] ?? string.Empty; ExpandoObject placeholderId = null; foreach (var placeholderKey in placeholderKeys) { if (placeholderKey.StartsWith("$Id.")) { if (placeholderId == null) { placeholderId = new ExpandoObject(); placeholdersDictionary["$Id"] = placeholderId; } ((IDictionary<string, object>)placeholderId)[placeholderKey.Mid(3)] = PageContext.Current.HtmlHelper.Sitecore().Placeholder(controlId + placeholderKey.Mid(3)).ToString(); } else { placeholdersDictionary[placeholderKey] = PageContext.Current.HtmlHelper.Sitecore().Placeholder(placeholderKey).ToString(); } } return props; } } }
using UnityEngine; using System.Collections.Generic; using System.IO; namespace Beats2.Graphic { // Internal structures to fill and process public class FontChar { public int id = 0, x = 0, y = 0, width = 0, height = 0, xoffset = 0, yoffset = 0, xadvance = 0; public int texOffsetX, texOffsetY; public int texX, texY, texW, texH; public bool texFlipped; public bool texOverride; }; public class FontKerning { public int first = 0, second = 0, amount = 0; }; public class FontInfo { public string[] texturePaths = new string[0]; public int scaleW = 0, scaleH = 0; public int lineHeight = 0; public int numPages = 0; public List<FontChar> chars = new List<FontChar>(); public List<FontKerning> kernings = new List<FontKerning>(); }; class BMFontTextImporter { static string FindKeyValue(string[] tokens, string key) { string keyMatch = key + "="; for (int i = 0; i < tokens.Length; ++i) { if (tokens[i].Length > keyMatch.Length && tokens[i].Substring(0, keyMatch.Length) == keyMatch) return tokens[i].Substring(keyMatch.Length); } return ""; } public static FontInfo Parse(string path) { FontInfo fontInfo = new FontInfo(); StreamReader reader = new StreamReader(path); string line; while ((line = reader.ReadLine()) != null) { string[] tokens = line.Split( ' ' ); if (tokens[0] == "common") { fontInfo.lineHeight = int.Parse( FindKeyValue(tokens, "lineHeight") ); fontInfo.scaleW = int.Parse( FindKeyValue(tokens, "scaleW") ); fontInfo.scaleH = int.Parse( FindKeyValue(tokens, "scaleH") ); int pages = int.Parse( FindKeyValue(tokens, "pages") ); if (pages != 1) { Debug.LogError("Only one page supported in font. Please change the setting and re-export."); return null; } fontInfo.numPages = pages; fontInfo.texturePaths = new string[pages]; for (int i = 0 ; i < pages; ++i) fontInfo.texturePaths[i] = string.Empty; } else if (tokens[0] == "page") { int id = int.Parse(FindKeyValue(tokens, "id")); string file = FindKeyValue(tokens, "file"); if (file[0] == '"' && file[file.Length - 1] == '"') file = file.Substring(1, file.Length - 2); fontInfo.texturePaths[id] = file; } else if (tokens[0] == "char") { FontChar thisChar = new FontChar(); thisChar.id = int.Parse(FindKeyValue(tokens, "id")); thisChar.x = int.Parse(FindKeyValue(tokens, "x")); thisChar.y = int.Parse(FindKeyValue(tokens, "y")); thisChar.width = int.Parse(FindKeyValue(tokens, "width")); thisChar.height = int.Parse(FindKeyValue(tokens, "height")); thisChar.xoffset = int.Parse(FindKeyValue(tokens, "xoffset")); thisChar.yoffset = int.Parse(FindKeyValue(tokens, "yoffset")); thisChar.xadvance = int.Parse(FindKeyValue(tokens, "xadvance")); fontInfo.chars.Add(thisChar); } else if (tokens[0] == "kerning") { FontKerning thisKerning = new FontKerning(); thisKerning.first = int.Parse(FindKeyValue(tokens, "first")); thisKerning.second = int.Parse(FindKeyValue(tokens, "second")); thisKerning.amount = int.Parse(FindKeyValue(tokens, "amount")); fontInfo.kernings.Add(thisKerning); } } reader.Close(); return fontInfo; } } public static class FontBuilder { public static FontInfo ParseBMFont(string path) { FontInfo fontInfo = BMFontTextImporter.Parse(path); if (fontInfo == null || fontInfo.chars.Count == 0) { Debug.LogError("Font parsing returned 0 characters, check source bmfont file for errors"); return null; } return fontInfo; } public static bool BuildFont(FontInfo fontInfo, tk2dFontData target, float scale, int charPadX, bool dupeCaps, bool flipTextureY, Texture2D gradientTexture, int gradientCount) { float texWidth = fontInfo.scaleW; float texHeight = fontInfo.scaleH; float lineHeight = fontInfo.lineHeight; target.version = tk2dFontData.CURRENT_VERSION; target.lineHeight = lineHeight * scale; target.texelSize = new Vector2(scale, scale); // Get number of characters (lastindex + 1) int maxCharId = 0; int maxUnicodeChar = 100000; foreach (var theChar in fontInfo.chars) { if (theChar.id > maxUnicodeChar) { // in most cases the font contains unwanted characters! Debug.LogError("Unicode character id exceeds allowed limit: " + theChar.id.ToString() + ". Skipping."); continue; } if (theChar.id > maxCharId) maxCharId = theChar.id; } // decide to use dictionary if necessary // 2048 is a conservative lower floor bool useDictionary = maxCharId > 2048; Dictionary<int, tk2dFontChar> charDict = (useDictionary)?new Dictionary<int, tk2dFontChar>():null; tk2dFontChar[] chars = (useDictionary)?null:new tk2dFontChar[maxCharId + 1]; int minChar = 0x7fffffff; int maxCharWithinBounds = 0; int numLocalChars = 0; float largestWidth = 0.0f; foreach (var theChar in fontInfo.chars) { tk2dFontChar thisChar = new tk2dFontChar(); int id = theChar.id; int x = theChar.x; int y = theChar.y; int width = theChar.width; int height = theChar.height; int xoffset = theChar.xoffset; int yoffset = theChar.yoffset; int xadvance = theChar.xadvance + charPadX; // special case, if the width and height are zero, the origin doesn't need to be offset // handles problematic case highlighted here: // http://2dtoolkit.com/forum/index.php/topic,89.msg220.html if (width == 0 && height == 0) { xoffset = 0; yoffset = 0; } // precompute required data float px = xoffset * scale; float py = (lineHeight - yoffset) * scale; if (theChar.texOverride) { int w = theChar.texW; int h = theChar.texH; if (theChar.texFlipped) { h = theChar.texW; w = theChar.texH; } thisChar.p0 = new Vector3(px + theChar.texOffsetX * scale, py - theChar.texOffsetY * scale, 0); thisChar.p1 = new Vector3(px + (theChar.texOffsetX + w) * scale, py - (theChar.texOffsetY + h) * scale, 0); thisChar.uv0 = new Vector2((theChar.texX) / texWidth, (theChar.texY + theChar.texH) / texHeight); thisChar.uv1 = new Vector2((theChar.texX + theChar.texW) / texWidth, (theChar.texY) / texHeight); thisChar.flipped = theChar.texFlipped; } else { thisChar.p0 = new Vector3(px, py, 0); thisChar.p1 = new Vector3(px + width * scale, py - height * scale, 0); if (flipTextureY) { thisChar.uv0 = new Vector2(x / texWidth, y / texHeight); thisChar.uv1 = new Vector2(thisChar.uv0.x + width / texWidth, thisChar.uv0.y + height / texHeight); } else { thisChar.uv0 = new Vector2(x / texWidth, 1.0f - y / texHeight); thisChar.uv1 = new Vector2(thisChar.uv0.x + width / texWidth, thisChar.uv0.y - height / texHeight); } thisChar.flipped = false; } thisChar.advance = xadvance * scale; largestWidth = Mathf.Max(thisChar.advance, largestWidth); // Needs gradient data if (gradientTexture != null) { // build it up assuming the first gradient float x0 = (float)(0.0f / gradientCount); float x1 = (float)(1.0f / gradientCount); float y0 = 1.0f; float y1 = 0.0f; // align to glyph if necessary thisChar.gradientUv = new Vector2[4]; thisChar.gradientUv[0] = new Vector2(x0, y0); thisChar.gradientUv[1] = new Vector2(x1, y0); thisChar.gradientUv[2] = new Vector2(x0, y1); thisChar.gradientUv[3] = new Vector2(x1, y1); } if (id <= maxCharId) { maxCharWithinBounds = (id > maxCharWithinBounds) ? id : maxCharWithinBounds; minChar = (id < minChar) ? id : minChar; if (useDictionary) charDict[id] = thisChar; else chars[id] = thisChar; ++numLocalChars; } } // duplicate capitals to lower case, or vice versa depending on which ones exist if (dupeCaps) { for (int uc = 'A'; uc <= 'Z'; ++uc) { int lc = uc + ('a' - 'A'); if (useDictionary) { if (charDict.ContainsKey(uc)) charDict[lc] = charDict[uc]; else if (charDict.ContainsKey(lc)) charDict[uc] = charDict[lc]; } else { if (chars[lc] == null) chars[lc] = chars[uc]; else if (chars[uc] == null) chars[uc] = chars[lc]; } } } // share null char, same pointer var nullChar = new tk2dFontChar(); nullChar.gradientUv = new Vector2[4]; // this would be null otherwise target.largestWidth = largestWidth; if (useDictionary) { // guarantee at least the first 256 characters for (int i = 0; i < 256; ++i) { if (!charDict.ContainsKey(i)) charDict[i] = nullChar; } target.chars = null; target.SetDictionary(charDict); target.useDictionary = true; } else { target.chars = new tk2dFontChar[maxCharId + 1]; for (int i = 0; i <= maxCharId; ++i) { target.chars[i] = chars[i]; if (target.chars[i] == null) { target.chars[i] = nullChar; // zero everything, null char } } target.charDict = null; target.useDictionary = false; } // kerning target.kerning = new tk2dFontKerning[fontInfo.kernings.Count]; for (int i = 0; i < target.kerning.Length; ++i) { tk2dFontKerning kerning = new tk2dFontKerning(); kerning.c0 = fontInfo.kernings[i].first; kerning.c1 = fontInfo.kernings[i].second; kerning.amount = fontInfo.kernings[i].amount * scale; target.kerning[i] = kerning; } return true; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using TheBraverest.Areas.HelpPage.ModelDescriptions; using TheBraverest.Areas.HelpPage.Models; namespace TheBraverest.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using UnityEngine; using UnityStandardAssets.CrossPlatformInput; using UnityStandardAssets.Utility; using Random = UnityEngine.Random; namespace UnityStandardAssets.Characters.FirstPerson { [RequireComponent(typeof (CharacterController))] [RequireComponent(typeof (AudioSource))] public class FirstPersonController : MonoBehaviour { [SerializeField] private bool m_IsWalking; [SerializeField] private float m_WalkSpeed; [SerializeField] private float m_RunSpeed; [SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten; [SerializeField] private float m_JumpSpeed; [SerializeField] private float m_StickToGroundForce; [SerializeField] private float m_GravityMultiplier; [SerializeField] private MouseLook m_MouseLook; [SerializeField] private bool m_UseFovKick; [SerializeField] private FOVKick m_FovKick = new FOVKick(); [SerializeField] private bool m_UseHeadBob; [SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob(); [SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob(); [SerializeField] private float m_StepInterval; [SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from. [SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground. [SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground. private Camera m_Camera; private bool m_Jump; private float m_YRotation; private Vector2 m_Input; private Vector3 m_MoveDir = Vector3.zero; private CharacterController m_CharacterController; private CollisionFlags m_CollisionFlags; private bool m_PreviouslyGrounded; private Vector3 m_OriginalCameraPosition; private float m_StepCycle; private float m_NextStep; private bool m_Jumping; private AudioSource m_AudioSource; // Use this for initialization private void Start() { m_CharacterController = GetComponent<CharacterController>(); m_Camera = Camera.main; m_OriginalCameraPosition = m_Camera.transform.localPosition; m_FovKick.Setup(m_Camera); m_HeadBob.Setup(m_Camera, m_StepInterval); m_StepCycle = 0f; m_NextStep = m_StepCycle/2f; m_Jumping = false; m_AudioSource = GetComponent<AudioSource>(); m_MouseLook.Init(transform , m_Camera.transform); } // Update is called once per frame private void Update() { RotateView(); // the jump state needs to read here to make sure it is not missed if (!m_Jump) { m_Jump = CrossPlatformInputManager.GetButtonDown("Jump"); } if (!m_PreviouslyGrounded && m_CharacterController.isGrounded) { StartCoroutine(m_JumpBob.DoBobCycle()); PlayLandingSound(); m_MoveDir.y = 0f; m_Jumping = false; } if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded) { m_MoveDir.y = 0f; } m_PreviouslyGrounded = m_CharacterController.isGrounded; } private void PlayLandingSound() { m_AudioSource.clip = m_LandSound; m_AudioSource.Play(); m_NextStep = m_StepCycle + .5f; } private void FixedUpdate() { float speed; GetInput(out speed); // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x; // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, m_CharacterController.height/2f, ~0, QueryTriggerInteraction.Ignore); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; m_MoveDir.x = desiredMove.x*speed; m_MoveDir.z = desiredMove.z*speed; if (m_CharacterController.isGrounded) { m_MoveDir.y = -m_StickToGroundForce; if (m_Jump) { m_MoveDir.y = m_JumpSpeed; PlayJumpSound(); m_Jump = false; m_Jumping = true; } } else { m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime; } m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime); ProgressStepCycle(speed); UpdateCameraPosition(speed); m_MouseLook.UpdateCursorLock(); } private void PlayJumpSound() { m_AudioSource.clip = m_JumpSound; m_AudioSource.Play(); } private void ProgressStepCycle(float speed) { if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0)) { m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))* Time.fixedDeltaTime; } if (!(m_StepCycle > m_NextStep)) { return; } m_NextStep = m_StepCycle + m_StepInterval; PlayFootStepAudio(); } private void PlayFootStepAudio() { if (!m_CharacterController.isGrounded) { return; } // pick & play a random footstep sound from the array, // excluding sound at index 0 int n = Random.Range(1, m_FootstepSounds.Length); m_AudioSource.clip = m_FootstepSounds[n]; m_AudioSource.PlayOneShot(m_AudioSource.clip); // move picked sound to index 0 so it's not picked next time m_FootstepSounds[n] = m_FootstepSounds[0]; m_FootstepSounds[0] = m_AudioSource.clip; } private void UpdateCameraPosition(float speed) { Vector3 newCameraPosition; if (!m_UseHeadBob) { return; } if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded) { m_Camera.transform.localPosition = m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten))); newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset(); } else { newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset(); } m_Camera.transform.localPosition = newCameraPosition; } private void GetInput(out float speed) { // Read input float horizontal = CrossPlatformInputManager.GetAxis("Horizontal"); float vertical = CrossPlatformInputManager.GetAxis("Vertical"); bool waswalking = m_IsWalking; #if !MOBILE_INPUT // On standalone builds, walk/run speed is modified by a key press. // keep track of whether or not the character is walking or running m_IsWalking = !Input.GetKey(KeyCode.LeftShift); #endif // set the desired speed to be walking or running speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed; m_Input = new Vector2(horizontal, vertical); // normalize input if it exceeds 1 in combined length: if (m_Input.sqrMagnitude > 1) { m_Input.Normalize(); } // handle speed change to give an fov kick // only if the player is going to a run, is running and the fovkick is to be used if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0) { StopAllCoroutines(); StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown()); } } private void RotateView() { m_MouseLook.LookRotation (transform, m_Camera.transform); } private void OnControllerColliderHit(ControllerColliderHit hit) { Rigidbody body = hit.collider.attachedRigidbody; //dont move the rigidbody if the character is on top of it if (m_CollisionFlags == CollisionFlags.Below) { return; } if (body == null || body.isKinematic) { return; } body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse); } public void SetWalkSpeed ( float speed ) { m_WalkSpeed = speed; m_RunSpeed = speed; } public float GetWalkSpeed () { return m_WalkSpeed; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Threading.Tasks; using System.Windows.Threading; using GBLive.Common; using GBLive.GiantBomb; using GBLive.GiantBomb.Interfaces; namespace GBLive.Gui { public class MainWindowViewModel : IMainWindowViewModel, INotifyPropertyChanged, IDisposable { public event PropertyChangedEventHandler? PropertyChanged; private void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); private readonly ILog _logger; private readonly IGiantBombContext _gbContext; private DispatcherTimer? timer = null; public ISettings Settings { get; } // needed for MainWindow.xaml data-binding for FallbackImage private bool _isLive = false; public bool IsLive { get => _isLive; set { _isLive = value; OnPropertyChanged(nameof(IsLive)); } } private string _liveShowTitle = string.Empty; public string LiveShowTitle { get => _liveShowTitle; set { _liveShowTitle = value; OnPropertyChanged(nameof(LiveShowTitle)); } } private readonly ObservableCollection<IShow> _shows = new ObservableCollection<IShow>(); public IReadOnlyCollection<IShow> Shows => _shows; public MainWindowViewModel(ILog logger, IGiantBombContext gbContext, ISettings settings) { _logger = logger; _gbContext = gbContext; Settings = settings; } public async Task UpdateAsync() { await _logger.MessageAsync("update started", Severity.Debug); IResponse response = await _gbContext.UpdateAsync(); await _logger.MessageAsync($"response contains {response.Shows.Count} shows", Severity.Debug); if (response.Reason != Reason.Success) { await _logger.MessageAsync($"update failed: {response.Reason}", Severity.Warning); return; } bool wasLive = IsLive; IsLive = response.LiveNow != null; LiveShowTitle = (IsLive && (response.LiveNow != null)) ? response.LiveNow.Title : Settings.NameOfNoLiveShow; if (Settings.ShouldNotify) { if (!wasLive && IsLive) // we only want the notification once, upon changing from not-live to live { NotificationService.Send(Settings.IsLiveMessage, OpenChatPage); await _logger.MessageAsync($"GiantBomb went live ({response.LiveNow?.Title})", Severity.Information); } } AddNewRemoveOldRemoveExpired(response.Shows); await _logger.MessageAsync("update succeeded", Severity.Debug); } private void AddNewRemoveOldRemoveExpired(IEnumerable<IShow> shows) { // add events that that we don't already have, and that are in the future var toAdd = shows .Where(x => !_shows.Contains(x)) .Where(x => x.Time > DateTimeOffset.Now) .ToList(); if (toAdd.Any()) { foreach (IShow add in toAdd) { void notify() => NotificationService.Send(add.Title, OpenHomePage); add.StartCountdown(notify); _shows.Add(add); _logger.Message($"added show {add}", Severity.Debug); } } else { _logger.Message($"no shows to add", Severity.Debug); } // remove events that we have locally but that are no longer in the API response var toRemove = _shows .Where(x => !shows.Contains(x)) .ToList(); if (toRemove.Any()) { foreach (IShow remove in toRemove) { remove.StopCountdown(); _shows.Remove(remove); _logger.Message($"removed show {remove}", Severity.Debug); } } else { _logger.Message($"no shows removed", Severity.Debug); } // remove any events that the API response contains but whose time is in the past // well, 10 minutes in the past to allow for some leeway var expired = _shows .Where(x => x.Time < DateTimeOffset.Now.AddMinutes(-10d)) .ToList(); if (expired.Any()) { foreach (IShow each in expired) { each.StopCountdown(); _shows.Remove(each); _logger.Message($"removed old show {each}", Severity.Debug); } } else { _logger.Message($"no expired shows", Severity.Debug); } } public void OpenHomePage() { if (Settings.Home is Uri uri) { if (!SystemLaunch.Uri(uri)) { _logger.Message("home page () failed to open", Severity.Error); } } else { _logger.Message("home page Uri is null", Severity.Error); } } public void OpenChatPage() { if (Settings.Chat is Uri uri) { if (!SystemLaunch.Uri(uri)) { _logger.Message("chat page () failed to open", Severity.Error); } } else { _logger.Message("chat page Uri is null", Severity.Error); } } public void StartTimer() { if (timer is null) { timer = new DispatcherTimer(DispatcherPriority.ApplicationIdle) { Interval = TimeSpan.FromSeconds(Settings.UpdateIntervalInSeconds) }; timer.Tick += Timer_Tick; } if (!timer.IsEnabled) { timer.Start(); } } public void StopTimer() { if (!(timer is null)) { timer.Stop(); timer.Tick -= Timer_Tick; timer = null; } } private async void Timer_Tick(object? sender, EventArgs e) { await UpdateAsync(); } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { (_gbContext as IDisposable)?.Dispose(); } disposedValue = true; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } }
//----------------------------------------------------------------------- // <copyright file="MultiDimensionalArrayFormatter.cs" company="Sirenix IVS"> // Copyright (c) 2018 Sirenix IVS // // 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. // </copyright> //----------------------------------------------------------------------- using System.Globalization; namespace Stratus.OdinSerializer { using System; using System.Text; /// <summary> /// Formatter for all arrays with more than one dimension. /// </summary> /// <typeparam name="TArray">The type of the formatted array.</typeparam> /// <typeparam name="TElement">The element type of the formatted array.</typeparam> /// <seealso cref="BaseFormatter{TArray}" /> public sealed class MultiDimensionalArrayFormatter<TArray, TElement> : BaseFormatter<TArray> where TArray : class { private const string RANKS_NAME = "ranks"; private const char RANKS_SEPARATOR = '|'; private static readonly int ArrayRank; private static readonly Serializer<TElement> ValueReaderWriter = Serializer.Get<TElement>(); static MultiDimensionalArrayFormatter() { if (typeof(TArray).IsArray == false) { throw new ArgumentException("Type " + typeof(TArray).Name + " is not an array."); } if (typeof(TArray).GetElementType() != typeof(TElement)) { throw new ArgumentException("Array of type " + typeof(TArray).Name + " does not have the required element type of " + typeof(TElement).Name + "."); } ArrayRank = typeof(TArray).GetArrayRank(); if (ArrayRank <= 1) { throw new ArgumentException("Array of type " + typeof(TArray).Name + " only has one rank."); } } /// <summary> /// Returns null. /// </summary> /// <returns> /// A null value. /// </returns> protected override TArray GetUninitializedObject() { return null; } /// <summary> /// Provides the actual implementation for deserializing a value of type <see cref="T" />. /// </summary> /// <param name="value">The uninitialized value to serialize into. This value will have been created earlier using <see cref="BaseFormatter{T}.GetUninitializedObject" />.</param> /// <param name="reader">The reader to deserialize with.</param> protected override void DeserializeImplementation(ref TArray value, IDataReader reader) { string name; var entry = reader.PeekEntry(out name); if (entry == EntryType.StartOfArray) { long length; reader.EnterArray(out length); entry = reader.PeekEntry(out name); if (entry != EntryType.String || name != RANKS_NAME) { value = default(TArray); reader.SkipEntry(); return; } string lengthStr; reader.ReadString(out lengthStr); string[] lengthsStrs = lengthStr.Split(RANKS_SEPARATOR); if (lengthsStrs.Length != ArrayRank) { value = default(TArray); reader.SkipEntry(); return; } int[] lengths = new int[lengthsStrs.Length]; for (int i = 0; i < lengthsStrs.Length; i++) { int rankVal; if (int.TryParse(lengthsStrs[i], out rankVal)) { lengths[i] = rankVal; } else { value = default(TArray); reader.SkipEntry(); return; } } long rankTotal = lengths[0]; for (int i = 1; i < lengths.Length; i++) { rankTotal *= lengths[i]; } if (rankTotal != length) { value = default(TArray); reader.SkipEntry(); return; } value = (TArray)(object)Array.CreateInstance(typeof(TElement), lengths); // We must remember to register the array reference ourselves, since we return null in GetUninitializedObject this.RegisterReferenceID(value, reader); // There aren't any OnDeserializing callbacks on arrays. // Hence we don't invoke this.InvokeOnDeserializingCallbacks(value, reader, context); int elements = 0; try { this.IterateArrayWrite( (Array)(object)value, () => { if (reader.PeekEntry(out name) == EntryType.EndOfArray) { reader.Context.Config.DebugContext.LogError("Reached end of array after " + elements + " elements, when " + length + " elements were expected."); throw new InvalidOperationException(); } var v = ValueReaderWriter.ReadValue(reader); if (reader.IsInArrayNode == false) { reader.Context.Config.DebugContext.LogError("Reading array went wrong. Data dump: " + reader.GetDataDump()); throw new InvalidOperationException(); } elements++; return v; }); } catch (InvalidOperationException) { } catch (Exception ex) { reader.Context.Config.DebugContext.LogException(ex); } reader.ExitArray(); } else { value = default(TArray); reader.SkipEntry(); } } /// <summary> /// Provides the actual implementation for serializing a value of type <see cref="T" />. /// </summary> /// <param name="value">The value to serialize.</param> /// <param name="writer">The writer to serialize with.</param> protected override void SerializeImplementation(ref TArray value, IDataWriter writer) { var array = value as Array; try { writer.BeginArrayNode(array.LongLength); int[] lengths = new int[ArrayRank]; for (int i = 0; i < ArrayRank; i++) { lengths[i] = array.GetLength(i); } StringBuilder sb = new StringBuilder(); for (int i = 0; i < ArrayRank; i++) { if (i > 0) { sb.Append(RANKS_SEPARATOR); } sb.Append(lengths[i].ToString(CultureInfo.InvariantCulture)); } string lengthStr = sb.ToString(); writer.WriteString(RANKS_NAME, lengthStr); this.IterateArrayRead( (Array)(object)value, (v) => { ValueReaderWriter.WriteValue(v, writer); }); } finally { writer.EndArrayNode(); } } private void IterateArrayWrite(Array a, Func<TElement> write) { int[] indices = new int[ArrayRank]; this.IterateArrayWrite(a, 0, indices, write); } private void IterateArrayWrite(Array a, int rank, int[] indices, Func<TElement> write) { for (int i = 0; i < a.GetLength(rank); i++) { indices[rank] = i; if (rank + 1 < a.Rank) { this.IterateArrayWrite(a, rank + 1, indices, write); } else { a.SetValue(write(), indices); } } } private void IterateArrayRead(Array a, Action<TElement> read) { int[] indices = new int[ArrayRank]; this.IterateArrayRead(a, 0, indices, read); } private void IterateArrayRead(Array a, int rank, int[] indices, Action<TElement> read) { for (int i = 0; i < a.GetLength(rank); i++) { indices[rank] = i; if (rank + 1 < a.Rank) { this.IterateArrayRead(a, rank + 1, indices, read); } else { read((TElement)a.GetValue(indices)); } } } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if FEATURE_CORE_DLR using System.Linq.Expressions; #else using Microsoft.Scripting.Ast; #endif using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Dynamic; using Microsoft.Scripting; using Microsoft.Scripting.Runtime; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; namespace IronPython.Runtime { [PythonType("instancemethod"), DontMapGetMemberNamesToDir] public sealed partial class Method : PythonTypeSlot, IWeakReferenceable, IPythonMembersList, IDynamicMetaObjectProvider, ICodeFormattable, Binding.IFastInvokable { private readonly object _func; private readonly object _inst; private readonly object _declaringClass; private WeakRefTracker _weakref; public Method(object function, object instance, object @class) { _func = function; _inst = instance; _declaringClass = @class; } public Method(object function, object instance) { if (instance == null) { throw PythonOps.TypeError("unbound methods must have a class provided"); } _func = function; _inst = instance; } internal string Name { get { return (string)PythonOps.GetBoundAttr(DefaultContext.Default, _func, "__name__"); } } public string __doc__ { get { return PythonOps.GetBoundAttr(DefaultContext.Default, _func, "__doc__") as string; } } public object im_func { get { return _func; } } public object __func__ { get { return _func; } } public object im_self { get { return _inst; } } public object __self__ { get { return _inst; } } public object im_class { get { // we could have an OldClass (or any other object) here if the user called the ctor directly return PythonOps.ToPythonType(_declaringClass as PythonType) ?? _declaringClass; } } [SpecialName] public object Call(CodeContext/*!*/ context, params object[] args) { return PythonContext.GetContext(context).CallSplat(this, args); } [SpecialName] public object Call(CodeContext/*!*/ context, [ParamDictionary]IDictionary<object, object> kwArgs, params object[] args) { return PythonContext.GetContext(context).CallWithKeywords(this, args, kwArgs); } private Exception BadSelf(object got) { string firstArg; if (got == null) { firstArg = "nothing"; } else { firstArg = PythonOps.GetPythonTypeName(got) + " instance"; } PythonType pt = im_class as PythonType; return PythonOps.TypeError("unbound method {0}() must be called with {1} instance as first argument (got {2} instead)", Name, (pt != null) ? pt.Name : im_class, firstArg); } /// <summary> /// Validates that the current self object is usable for this method. /// </summary> internal object CheckSelf(CodeContext context, object self) { if (!PythonOps.IsInstance(context, self, im_class)) { throw BadSelf(self); } return self; } #region Object Overrides private string DeclaringClassAsString() { if (im_class == null) return "?"; PythonType dt = im_class as PythonType; if (dt != null) return dt.Name; return im_class.ToString(); } public override bool Equals(object obj) { Method other = obj as Method; if (other == null) return false; return object.ReferenceEquals(_inst, other._inst) && PythonOps.EqualRetBool(_func, other._func); } public override int GetHashCode() { if (_inst == null) return PythonOps.Hash(DefaultContext.Default, _func); return PythonOps.Hash(DefaultContext.Default, _inst) ^ PythonOps.Hash(DefaultContext.Default, _func); } #endregion #region IWeakReferenceable Members WeakRefTracker IWeakReferenceable.GetWeakRef() { return _weakref; } bool IWeakReferenceable.SetWeakRef(WeakRefTracker value) { _weakref = value; return true; } void IWeakReferenceable.SetFinalizer(WeakRefTracker value) { ((IWeakReferenceable)this).SetWeakRef(value); } #endregion #region Custom member access [SpecialName] public object GetCustomMember(CodeContext context, string name) { switch (name) { // Get the module name from the function and pass that out. Note that CPython's method has // no __module__ attribute and this value can be gotten via a call to method.__getattribute__ // there as well. case "__module__": return PythonOps.GetBoundAttr(context, _func, "__module__"); case "__name__": return PythonOps.GetBoundAttr(DefaultContext.Default, _func, "__name__"); default: object value; string symbol = name; if (TypeCache.Method.TryGetBoundMember(context, this, symbol, out value) || // look on method PythonOps.TryGetBoundAttr(context, _func, symbol, out value)) { // Forward to the func return value; } return OperationFailed.Value; } } [SpecialName] public void SetMemberAfter(CodeContext context, string name, object value) { TypeCache.Method.SetMember(context, this, name, value); } [SpecialName] public void DeleteMember(CodeContext context, string name) { TypeCache.Method.DeleteMember(context, this, name); } IList<string> IMembersList.GetMemberNames() { return PythonOps.GetStringMemberList(this); } IList<object> IPythonMembersList.GetMemberNames(CodeContext/*!*/ context) { List ret = TypeCache.Method.GetMemberNames(context); ret.AddNoLockNoDups("__module__"); PythonFunction pf = _func as PythonFunction; if (pf != null) { PythonDictionary dict = pf.__dict__; // Check the func foreach (KeyValuePair<object, object> kvp in dict) { ret.AddNoLockNoDups(kvp.Key); } } return ret; } #endregion #region PythonTypeSlot Overrides internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) { if (this.im_self == null) { if (owner == null || owner == im_class || PythonOps.IsSubClass(context, owner, im_class)) { value = new Method(_func, instance, owner); return true; } } value = this; return true; } internal override bool GetAlwaysSucceeds { get { return true; } } #endregion #region ICodeFormattable Members public string/*!*/ __repr__(CodeContext/*!*/ context) { object name; if (!PythonOps.TryGetBoundAttr(context, _func, "__name__", out name)) { name = "?"; } if (_inst != null) { return string.Format("<bound method {0}.{1} of {2}>", DeclaringClassAsString(), name, PythonOps.Repr(context, _inst)); } else { return string.Format("<unbound method {0}.{1}>", DeclaringClassAsString(), name); } } #endregion #region IDynamicMetaObjectProvider Members DynamicMetaObject/*!*/ IDynamicMetaObjectProvider.GetMetaObject(Expression/*!*/ parameter) { return new Binding.MetaMethod(parameter, BindingRestrictions.Empty, this); } #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.Collections; using System.Data.Common; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.Versioning; using System.Security; using System.Security.Principal; namespace System.Data.ProviderBase { internal abstract class DbConnectionPoolCounters { private static class CreationData { internal static readonly CounterCreationData HardConnectsPerSecond = new CounterCreationData( "HardConnectsPerSecond", "The number of actual connections per second that are being made to servers", PerformanceCounterType.RateOfCountsPerSecond32); internal static readonly CounterCreationData HardDisconnectsPerSecond = new CounterCreationData( "HardDisconnectsPerSecond", "The number of actual disconnects per second that are being made to servers", PerformanceCounterType.RateOfCountsPerSecond32); internal static readonly CounterCreationData SoftConnectsPerSecond = new CounterCreationData( "SoftConnectsPerSecond", "The number of connections we get from the pool per second", PerformanceCounterType.RateOfCountsPerSecond32); internal static readonly CounterCreationData SoftDisconnectsPerSecond = new CounterCreationData( "SoftDisconnectsPerSecond", "The number of connections we return to the pool per second", PerformanceCounterType.RateOfCountsPerSecond32); internal static readonly CounterCreationData NumberOfNonPooledConnections = new CounterCreationData( "NumberOfNonPooledConnections", "The number of connections that are not using connection pooling", PerformanceCounterType.NumberOfItems32); internal static readonly CounterCreationData NumberOfPooledConnections = new CounterCreationData( "NumberOfPooledConnections", "The number of connections that are managed by the connection pooler", PerformanceCounterType.NumberOfItems32); internal static readonly CounterCreationData NumberOfActiveConnectionPoolGroups = new CounterCreationData( "NumberOfActiveConnectionPoolGroups", "The number of unique connection strings", PerformanceCounterType.NumberOfItems32); internal static readonly CounterCreationData NumberOfInactiveConnectionPoolGroups = new CounterCreationData( "NumberOfInactiveConnectionPoolGroups", "The number of unique connection strings waiting for pruning", PerformanceCounterType.NumberOfItems32); internal static readonly CounterCreationData NumberOfActiveConnectionPools = new CounterCreationData( "NumberOfActiveConnectionPools", "The number of connection pools", PerformanceCounterType.NumberOfItems32); internal static readonly CounterCreationData NumberOfInactiveConnectionPools = new CounterCreationData( "NumberOfInactiveConnectionPools", "The number of connection pools", PerformanceCounterType.NumberOfItems32); internal static readonly CounterCreationData NumberOfActiveConnections = new CounterCreationData( "NumberOfActiveConnections", "The number of connections currently in-use", PerformanceCounterType.NumberOfItems32); internal static readonly CounterCreationData NumberOfFreeConnections = new CounterCreationData( "NumberOfFreeConnections", "The number of connections currently available for use", PerformanceCounterType.NumberOfItems32); internal static readonly CounterCreationData NumberOfStasisConnections = new CounterCreationData( "NumberOfStasisConnections", "The number of connections currently waiting to be made ready for use", PerformanceCounterType.NumberOfItems32); internal static readonly CounterCreationData NumberOfReclaimedConnections = new CounterCreationData( "NumberOfReclaimedConnections", "The number of connections we reclaim from GC'd external connections", PerformanceCounterType.NumberOfItems32); }; internal sealed class Counter { private PerformanceCounter _instance; internal Counter(string categoryName, string instanceName, string counterName, PerformanceCounterType counterType) { if (ADP.IsPlatformNT5) { try { if (!ADP.IsEmpty(categoryName) && !ADP.IsEmpty(instanceName)) { PerformanceCounter instance = new PerformanceCounter(); instance.CategoryName = categoryName; instance.CounterName = counterName; instance.InstanceName = instanceName; instance.InstanceLifetime = PerformanceCounterInstanceLifetime.Process; instance.ReadOnly = false; instance.RawValue = 0; // make sure we start out at zero _instance = instance; } } catch (InvalidOperationException e) { ADP.TraceExceptionWithoutRethrow(e); // TODO: generate Application EventLog entry about inability to find perf counter } } } internal void Decrement() { PerformanceCounter instance = _instance; if (null != instance) { instance.Decrement(); } } internal void Dispose() { // TODO: race condition, Dispose at the same time as Increment/Decrement PerformanceCounter instance = _instance; _instance = null; if (null != instance) { instance.RemoveInstance(); // should we be calling instance.Close? // if we do will it exacerbate the Dispose vs. Decrement race condition //instance.Close(); } } internal void Increment() { PerformanceCounter instance = _instance; if (null != instance) { instance.Increment(); } } }; private const int CounterInstanceNameMaxLength = 127; internal readonly Counter HardConnectsPerSecond; internal readonly Counter HardDisconnectsPerSecond; internal readonly Counter SoftConnectsPerSecond; internal readonly Counter SoftDisconnectsPerSecond; internal readonly Counter NumberOfNonPooledConnections; internal readonly Counter NumberOfPooledConnections; internal readonly Counter NumberOfActiveConnectionPoolGroups; internal readonly Counter NumberOfInactiveConnectionPoolGroups; internal readonly Counter NumberOfActiveConnectionPools; internal readonly Counter NumberOfInactiveConnectionPools; internal readonly Counter NumberOfActiveConnections; internal readonly Counter NumberOfFreeConnections; internal readonly Counter NumberOfStasisConnections; internal readonly Counter NumberOfReclaimedConnections; protected DbConnectionPoolCounters() : this(null, null) { } protected DbConnectionPoolCounters(string categoryName, string categoryHelp) { AppDomain.CurrentDomain.DomainUnload += new EventHandler(this.UnloadEventHandler); AppDomain.CurrentDomain.ProcessExit += new EventHandler(this.ExitEventHandler); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(this.ExceptionEventHandler); string instanceName = null; if (!ADP.IsEmpty(categoryName)) { if (ADP.IsPlatformNT5) { instanceName = GetInstanceName(); } } // level 0-3: hard connects/disconnects, plus basic pool/pool entry statistics string basicCategoryName = categoryName; HardConnectsPerSecond = new Counter(basicCategoryName, instanceName, CreationData.HardConnectsPerSecond.CounterName, CreationData.HardConnectsPerSecond.CounterType); HardDisconnectsPerSecond = new Counter(basicCategoryName, instanceName, CreationData.HardDisconnectsPerSecond.CounterName, CreationData.HardDisconnectsPerSecond.CounterType); NumberOfNonPooledConnections = new Counter(basicCategoryName, instanceName, CreationData.NumberOfNonPooledConnections.CounterName, CreationData.NumberOfNonPooledConnections.CounterType); NumberOfPooledConnections = new Counter(basicCategoryName, instanceName, CreationData.NumberOfPooledConnections.CounterName, CreationData.NumberOfPooledConnections.CounterType); NumberOfActiveConnectionPoolGroups = new Counter(basicCategoryName, instanceName, CreationData.NumberOfActiveConnectionPoolGroups.CounterName, CreationData.NumberOfActiveConnectionPoolGroups.CounterType); NumberOfInactiveConnectionPoolGroups = new Counter(basicCategoryName, instanceName, CreationData.NumberOfInactiveConnectionPoolGroups.CounterName, CreationData.NumberOfInactiveConnectionPoolGroups.CounterType); NumberOfActiveConnectionPools = new Counter(basicCategoryName, instanceName, CreationData.NumberOfActiveConnectionPools.CounterName, CreationData.NumberOfActiveConnectionPools.CounterType); NumberOfInactiveConnectionPools = new Counter(basicCategoryName, instanceName, CreationData.NumberOfInactiveConnectionPools.CounterName, CreationData.NumberOfInactiveConnectionPools.CounterType); NumberOfStasisConnections = new Counter(basicCategoryName, instanceName, CreationData.NumberOfStasisConnections.CounterName, CreationData.NumberOfStasisConnections.CounterType); NumberOfReclaimedConnections = new Counter(basicCategoryName, instanceName, CreationData.NumberOfReclaimedConnections.CounterName, CreationData.NumberOfReclaimedConnections.CounterType); // level 4: expensive stuff string verboseCategoryName = null; if (!ADP.IsEmpty(categoryName)) { // don't load TraceSwitch if no categoryName so that Odbc/OleDb have a chance of not loading TraceSwitch // which are also used by System.Diagnostics.PerformanceCounter.ctor & System.Transactions.get_Current TraceSwitch perfCtrSwitch = new TraceSwitch("ConnectionPoolPerformanceCounterDetail", "level of detail to track with connection pool performance counters"); if (TraceLevel.Verbose == perfCtrSwitch.Level) { verboseCategoryName = categoryName; } } SoftConnectsPerSecond = new Counter(verboseCategoryName, instanceName, CreationData.SoftConnectsPerSecond.CounterName, CreationData.SoftConnectsPerSecond.CounterType); SoftDisconnectsPerSecond = new Counter(verboseCategoryName, instanceName, CreationData.SoftDisconnectsPerSecond.CounterName, CreationData.SoftDisconnectsPerSecond.CounterType); NumberOfActiveConnections = new Counter(verboseCategoryName, instanceName, CreationData.NumberOfActiveConnections.CounterName, CreationData.NumberOfActiveConnections.CounterType); NumberOfFreeConnections = new Counter(verboseCategoryName, instanceName, CreationData.NumberOfFreeConnections.CounterName, CreationData.NumberOfFreeConnections.CounterType); } private string GetAssemblyName() { string result = null; // First try GetEntryAssembly name, then AppDomain.FriendlyName. Assembly assembly = Assembly.GetEntryAssembly(); if (null != assembly) { AssemblyName name = assembly.GetName(); if (name != null) { result = name.Name; } } return result; } // SxS: this method uses GetCurrentProcessId to construct the instance name. // TODO: remove the Resource* attributes if you do not use GetCurrentProcessId after the fix private string GetInstanceName() { string result = null; string instanceName = GetAssemblyName(); // instance perfcounter name if (ADP.IsEmpty(instanceName)) { AppDomain appDomain = AppDomain.CurrentDomain; if (null != appDomain) { instanceName = appDomain.FriendlyName; } } // TODO: If you do not use GetCurrentProcessId after fixing VSDD 534795, please remove Resource* attributes from this method int pid = SafeNativeMethods.GetCurrentProcessId(); // there are several characters which have special meaning // to PERFMON. They recommend that we translate them as shown below, to // prevent problems. result = string.Format((IFormatProvider)null, "{0}[{1}]", instanceName, pid); result = result.Replace('(', '[').Replace(')', ']').Replace('#', '_').Replace('/', '_').Replace('\\', '_'); // counter instance name cannot be greater than 127 if (result.Length > CounterInstanceNameMaxLength) { // Replacing the middle part with "[...]" // For example: if path is c:\long_path\very_(Ax200)_long__path\perftest.exe and process ID is 1234 than the resulted instance name will be: // c:\long_path\very_(AxM)[...](AxN)_long__path\perftest.exe[1234] // while M and N are adjusted to make each part before and after the [...] = 61 (making the total = 61 + 5 + 61 = 127) const string insertString = "[...]"; int firstPartLength = (CounterInstanceNameMaxLength - insertString.Length) / 2; int lastPartLength = CounterInstanceNameMaxLength - firstPartLength - insertString.Length; result = string.Format((IFormatProvider)null, "{0}{1}{2}", result.Substring(0, firstPartLength), insertString, result.Substring(result.Length - lastPartLength, lastPartLength)); Debug.Assert(result.Length == CounterInstanceNameMaxLength, string.Format((IFormatProvider)null, "wrong calculation of the instance name: expected {0}, actual: {1}", CounterInstanceNameMaxLength, result.Length)); } return result; } public void Dispose() { // ExceptionEventHandler with IsTerminiating may be called before // the Connection Close is called or the variables are initialized SafeDispose(HardConnectsPerSecond); SafeDispose(HardDisconnectsPerSecond); SafeDispose(SoftConnectsPerSecond); SafeDispose(SoftDisconnectsPerSecond); SafeDispose(NumberOfNonPooledConnections); SafeDispose(NumberOfPooledConnections); SafeDispose(NumberOfActiveConnectionPoolGroups); SafeDispose(NumberOfInactiveConnectionPoolGroups); SafeDispose(NumberOfActiveConnectionPools); SafeDispose(NumberOfActiveConnections); SafeDispose(NumberOfFreeConnections); SafeDispose(NumberOfStasisConnections); SafeDispose(NumberOfReclaimedConnections); } private void SafeDispose(Counter counter) { if (null != counter) { counter.Dispose(); } } private void ExceptionEventHandler(object sender, UnhandledExceptionEventArgs e) { if ((null != e) && e.IsTerminating) { Dispose(); } } private void ExitEventHandler(object sender, EventArgs e) { Dispose(); } private void UnloadEventHandler(object sender, EventArgs e) { Dispose(); } } internal sealed class DbConnectionPoolCountersNoCounters : DbConnectionPoolCounters { public static readonly DbConnectionPoolCountersNoCounters SingletonInstance = new DbConnectionPoolCountersNoCounters(); private DbConnectionPoolCountersNoCounters() : base() { } } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace MyCSOMAppWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
#region Copyright notice and license // Copyright 2015 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Threading; using System.Threading.Tasks; using Grpc.Core.Logging; using Grpc.Core.Profiling; using Grpc.Core.Utils; namespace Grpc.Core.Internal { /// <summary> /// Manages client side native call lifecycle. /// </summary> internal class AsyncCall<TRequest, TResponse> : AsyncCallBase<TRequest, TResponse>, IUnaryResponseClientCallback, IReceivedStatusOnClientCallback, IReceivedResponseHeadersCallback { static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCall<TRequest, TResponse>>(); readonly CallInvocationDetails<TRequest, TResponse> details; readonly INativeCall injectedNativeCall; // for testing bool registeredWithChannel; // Dispose of to de-register cancellation token registration CancellationTokenRegistration cancellationTokenRegistration; // Completion of a pending unary response if not null. TaskCompletionSource<TResponse> unaryResponseTcs; // Completion of a streaming response call if not null. TaskCompletionSource<object> streamingResponseCallFinishedTcs; // TODO(jtattermusch): this field could be lazy-initialized (only if someone requests the response headers). // Response headers set here once received. TaskCompletionSource<Metadata> responseHeadersTcs = new TaskCompletionSource<Metadata>(); // Set after status is received. Used for both unary and streaming response calls. ClientSideStatus? finishedStatus; public AsyncCall(CallInvocationDetails<TRequest, TResponse> callDetails) : base(callDetails.RequestMarshaller.ContextualSerializer, callDetails.ResponseMarshaller.ContextualDeserializer) { this.details = callDetails.WithOptions(callDetails.Options.Normalize()); this.initialMetadataSent = true; // we always send metadata at the very beginning of the call. } /// <summary> /// This constructor should only be used for testing. /// </summary> public AsyncCall(CallInvocationDetails<TRequest, TResponse> callDetails, INativeCall injectedNativeCall) : this(callDetails) { this.injectedNativeCall = injectedNativeCall; } // TODO: this method is not Async, so it shouldn't be in AsyncCall class, but // it is reusing fair amount of code in this class, so we are leaving it here. /// <summary> /// Blocking unary request - unary response call. /// </summary> public TResponse UnaryCall(TRequest msg) { var profiler = Profilers.ForCurrentThread(); using (profiler.NewScope("AsyncCall.UnaryCall")) using (CompletionQueueSafeHandle cq = CompletionQueueSafeHandle.CreateSync()) { bool callStartedOk = false; try { unaryResponseTcs = new TaskCompletionSource<TResponse>(); lock (myLock) { GrpcPreconditions.CheckState(!started); started = true; Initialize(cq); halfcloseRequested = true; readingDone = true; } using (var serializationScope = DefaultSerializationContext.GetInitializedThreadLocalScope()) using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { var payload = UnsafeSerialize(msg, serializationScope.Context); // do before metadata array? var ctx = details.Channel.Environment.BatchContextPool.Lease(); try { call.StartUnary(ctx, payload, GetWriteFlagsForCall(), metadataArray, details.Options.Flags); callStartedOk = true; var ev = cq.Pluck(ctx.Handle); bool success = (ev.success != 0); try { using (profiler.NewScope("AsyncCall.UnaryCall.HandleBatch")) { HandleUnaryResponse(success, ctx.GetReceivedStatusOnClient(), ctx.GetReceivedMessageReader(), ctx.GetReceivedInitialMetadata()); } } catch (Exception e) { Logger.Error(e, "Exception occurred while invoking completion delegate."); } } finally { ctx.Recycle(); } } } finally { if (!callStartedOk) { lock (myLock) { OnFailedToStartCallLocked(); } } } // Once the blocking call returns, the result should be available synchronously. // Note that GetAwaiter().GetResult() doesn't wrap exceptions in AggregateException. return unaryResponseTcs.Task.GetAwaiter().GetResult(); } } /// <summary> /// Starts a unary request - unary response call. /// </summary> public Task<TResponse> UnaryCallAsync(TRequest msg) { lock (myLock) { bool callStartedOk = false; try { GrpcPreconditions.CheckState(!started); started = true; Initialize(details.Channel.CompletionQueue); halfcloseRequested = true; readingDone = true; using (var serializationScope = DefaultSerializationContext.GetInitializedThreadLocalScope()) { var payload = UnsafeSerialize(msg, serializationScope.Context); unaryResponseTcs = new TaskCompletionSource<TResponse>(); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartUnary(UnaryResponseClientCallback, payload, GetWriteFlagsForCall(), metadataArray, details.Options.Flags); callStartedOk = true; } } return unaryResponseTcs.Task; } finally { if (!callStartedOk) { OnFailedToStartCallLocked(); } } } } /// <summary> /// Starts a streamed request - unary response call. /// Use StartSendMessage and StartSendCloseFromClient to stream requests. /// </summary> public Task<TResponse> ClientStreamingCallAsync() { lock (myLock) { bool callStartedOk = false; try { GrpcPreconditions.CheckState(!started); started = true; Initialize(details.Channel.CompletionQueue); readingDone = true; unaryResponseTcs = new TaskCompletionSource<TResponse>(); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartClientStreaming(UnaryResponseClientCallback, metadataArray, details.Options.Flags); callStartedOk = true; } return unaryResponseTcs.Task; } finally { if (!callStartedOk) { OnFailedToStartCallLocked(); } } } } /// <summary> /// Starts a unary request - streamed response call. /// </summary> public void StartServerStreamingCall(TRequest msg) { lock (myLock) { bool callStartedOk = false; try { GrpcPreconditions.CheckState(!started); started = true; Initialize(details.Channel.CompletionQueue); halfcloseRequested = true; using (var serializationScope = DefaultSerializationContext.GetInitializedThreadLocalScope()) { var payload = UnsafeSerialize(msg, serializationScope.Context); streamingResponseCallFinishedTcs = new TaskCompletionSource<object>(); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartServerStreaming(ReceivedStatusOnClientCallback, payload, GetWriteFlagsForCall(), metadataArray, details.Options.Flags); callStartedOk = true; } } call.StartReceiveInitialMetadata(ReceivedResponseHeadersCallback); } finally { if (!callStartedOk) { OnFailedToStartCallLocked(); } } } } /// <summary> /// Starts a streaming request - streaming response call. /// Use StartSendMessage and StartSendCloseFromClient to stream requests. /// </summary> public void StartDuplexStreamingCall() { lock (myLock) { bool callStartedOk = false; try { GrpcPreconditions.CheckState(!started); started = true; Initialize(details.Channel.CompletionQueue); streamingResponseCallFinishedTcs = new TaskCompletionSource<object>(); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartDuplexStreaming(ReceivedStatusOnClientCallback, metadataArray, details.Options.Flags); callStartedOk = true; } call.StartReceiveInitialMetadata(ReceivedResponseHeadersCallback); } finally { if (!callStartedOk) { OnFailedToStartCallLocked(); } } } } /// <summary> /// Sends a streaming request. Only one pending send action is allowed at any given time. /// </summary> public Task SendMessageAsync(TRequest msg, WriteFlags writeFlags) { return SendMessageInternalAsync(msg, writeFlags); } /// <summary> /// Receives a streaming response. Only one pending read action is allowed at any given time. /// </summary> public Task<TResponse> ReadMessageAsync() { return ReadMessageInternalAsync(); } /// <summary> /// Sends halfclose, indicating client is done with streaming requests. /// Only one pending send action is allowed at any given time. /// </summary> public Task SendCloseFromClientAsync() { lock (myLock) { GrpcPreconditions.CheckState(started); var earlyResult = CheckSendPreconditionsClientSide(); if (earlyResult != null) { return earlyResult; } if (disposed || finished) { // In case the call has already been finished by the serverside, // the halfclose has already been done implicitly, so just return // completed task here. halfcloseRequested = true; return TaskUtils.CompletedTask; } call.StartSendCloseFromClient(SendCompletionCallback); halfcloseRequested = true; streamingWriteTcs = new TaskCompletionSource<object>(); return streamingWriteTcs.Task; } } /// <summary> /// Get the task that completes once if streaming response call finishes with ok status and throws RpcException with given status otherwise. /// </summary> public Task StreamingResponseCallFinishedTask { get { return streamingResponseCallFinishedTcs.Task; } } /// <summary> /// Get the task that completes once response headers are received. /// </summary> public Task<Metadata> ResponseHeadersAsync { get { return responseHeadersTcs.Task; } } /// <summary> /// Gets the resulting status if the call has already finished. /// Throws InvalidOperationException otherwise. /// </summary> public Status GetStatus() { lock (myLock) { GrpcPreconditions.CheckState(finishedStatus.HasValue, "Status can only be accessed once the call has finished."); return finishedStatus.Value.Status; } } /// <summary> /// Gets the trailing metadata if the call has already finished. /// Throws InvalidOperationException otherwise. /// </summary> public Metadata GetTrailers() { lock (myLock) { GrpcPreconditions.CheckState(finishedStatus.HasValue, "Trailers can only be accessed once the call has finished."); return finishedStatus.Value.Trailers; } } public CallInvocationDetails<TRequest, TResponse> Details { get { return this.details; } } protected override void OnAfterReleaseResourcesLocked() { if (registeredWithChannel) { details.Channel.RemoveCallReference(this); registeredWithChannel = false; } } protected override void OnAfterReleaseResourcesUnlocked() { // If cancellation callback is in progress, this can block // so we need to do this outside of call's lock to prevent // deadlock. // See https://github.com/grpc/grpc/issues/14777 // See https://github.com/dotnet/corefx/issues/14903 cancellationTokenRegistration.Dispose(); } protected override bool IsClient { get { return true; } } protected override Exception GetRpcExceptionClientOnly() { return new RpcException(finishedStatus.Value.Status, finishedStatus.Value.Trailers); } protected override Task CheckSendAllowedOrEarlyResult() { var earlyResult = CheckSendPreconditionsClientSide(); if (earlyResult != null) { return earlyResult; } if (finishedStatus.HasValue) { // throwing RpcException if we already received status on client // side makes the most sense. // Note that this throws even for StatusCode.OK. // Writing after the call has finished is not a programming error because server can close // the call anytime, so don't throw directly, but let the write task finish with an error. var tcs = new TaskCompletionSource<object>(); tcs.SetException(new RpcException(finishedStatus.Value.Status, finishedStatus.Value.Trailers)); return tcs.Task; } return null; } private Task CheckSendPreconditionsClientSide() { GrpcPreconditions.CheckState(!halfcloseRequested, "Request stream has already been completed."); GrpcPreconditions.CheckState(streamingWriteTcs == null, "Only one write can be pending at a time."); if (cancelRequested) { // Return a cancelled task. var tcs = new TaskCompletionSource<object>(); tcs.SetCanceled(); return tcs.Task; } return null; } private void Initialize(CompletionQueueSafeHandle cq) { var call = CreateNativeCall(cq); details.Channel.AddCallReference(this); registeredWithChannel = true; InitializeInternal(call); RegisterCancellationCallback(); } private void OnFailedToStartCallLocked() { ReleaseResources(); // We need to execute the hook that disposes the cancellation token // registration, but it cannot be done from under a lock. // To make things simple, we just schedule the unregistering // on a threadpool. // - Once the native call is disposed, the Cancel() calls are ignored anyway // - We don't care about the overhead as OnFailedToStartCallLocked() only happens // when something goes very bad when initializing a call and that should // never happen when gRPC is used correctly. ThreadPool.QueueUserWorkItem((state) => OnAfterReleaseResourcesUnlocked()); } private INativeCall CreateNativeCall(CompletionQueueSafeHandle cq) { if (injectedNativeCall != null) { return injectedNativeCall; // allows injecting a mock INativeCall in tests. } var parentCall = details.Options.PropagationToken.AsImplOrNull()?.ParentCall ?? CallSafeHandle.NullInstance; var credentials = details.Options.Credentials; using (var nativeCredentials = credentials != null ? credentials.ToNativeCredentials() : null) { var result = details.Channel.Handle.CreateCall( parentCall, ContextPropagationTokenImpl.DefaultMask, cq, details.Method, details.Host, Timespec.FromDateTime(details.Options.Deadline.Value), nativeCredentials); return result; } } // Make sure that once cancellationToken for this call is cancelled, Cancel() will be called. private void RegisterCancellationCallback() { cancellationTokenRegistration = RegisterCancellationCallbackForToken(details.Options.CancellationToken); } /// <summary> /// Gets WriteFlags set in callDetails.Options.WriteOptions /// </summary> private WriteFlags GetWriteFlagsForCall() { var writeOptions = details.Options.WriteOptions; return writeOptions != null ? writeOptions.Flags : default(WriteFlags); } /// <summary> /// Handles receive status completion for calls with streaming response. /// </summary> private void HandleReceivedResponseHeaders(bool success, Metadata responseHeaders) { // TODO(jtattermusch): handle success==false responseHeadersTcs.SetResult(responseHeaders); } /// <summary> /// Handler for unary response completion. /// </summary> private void HandleUnaryResponse(bool success, ClientSideStatus receivedStatus, IBufferReader receivedMessageReader, Metadata responseHeaders) { // NOTE: because this event is a result of batch containing GRPC_OP_RECV_STATUS_ON_CLIENT, // success will be always set to true. TaskCompletionSource<object> delayedStreamingWriteTcs = null; TResponse msg = default(TResponse); var deserializeException = TryDeserialize(receivedMessageReader, out msg); bool releasedResources; lock (myLock) { finished = true; if (deserializeException != null && receivedStatus.Status.StatusCode == StatusCode.OK) { receivedStatus = new ClientSideStatus(DeserializeResponseFailureStatus, receivedStatus.Trailers); } finishedStatus = receivedStatus; if (isStreamingWriteCompletionDelayed) { delayedStreamingWriteTcs = streamingWriteTcs; streamingWriteTcs = null; } releasedResources = ReleaseResourcesIfPossible(); } if (releasedResources) { OnAfterReleaseResourcesUnlocked(); } responseHeadersTcs.SetResult(responseHeaders); if (delayedStreamingWriteTcs != null) { delayedStreamingWriteTcs.SetException(GetRpcExceptionClientOnly()); } var status = receivedStatus.Status; if (status.StatusCode != StatusCode.OK) { unaryResponseTcs.SetException(new RpcException(status, receivedStatus.Trailers)); return; } unaryResponseTcs.SetResult(msg); } /// <summary> /// Handles receive status completion for calls with streaming response. /// </summary> private void HandleFinished(bool success, ClientSideStatus receivedStatus) { // NOTE: because this event is a result of batch containing GRPC_OP_RECV_STATUS_ON_CLIENT, // success will be always set to true. TaskCompletionSource<object> delayedStreamingWriteTcs = null; bool releasedResources; lock (myLock) { finished = true; finishedStatus = receivedStatus; if (isStreamingWriteCompletionDelayed) { delayedStreamingWriteTcs = streamingWriteTcs; streamingWriteTcs = null; } releasedResources = ReleaseResourcesIfPossible(); } if (releasedResources) { OnAfterReleaseResourcesUnlocked(); } if (delayedStreamingWriteTcs != null) { delayedStreamingWriteTcs.SetException(GetRpcExceptionClientOnly()); } var status = receivedStatus.Status; if (status.StatusCode != StatusCode.OK) { streamingResponseCallFinishedTcs.SetException(new RpcException(status, receivedStatus.Trailers)); return; } streamingResponseCallFinishedTcs.SetResult(null); } IUnaryResponseClientCallback UnaryResponseClientCallback => this; void IUnaryResponseClientCallback.OnUnaryResponseClient(bool success, ClientSideStatus receivedStatus, IBufferReader receivedMessageReader, Metadata responseHeaders) { HandleUnaryResponse(success, receivedStatus, receivedMessageReader, responseHeaders); } IReceivedStatusOnClientCallback ReceivedStatusOnClientCallback => this; void IReceivedStatusOnClientCallback.OnReceivedStatusOnClient(bool success, ClientSideStatus receivedStatus) { HandleFinished(success, receivedStatus); } IReceivedResponseHeadersCallback ReceivedResponseHeadersCallback => this; void IReceivedResponseHeadersCallback.OnReceivedResponseHeaders(bool success, Metadata responseHeaders) { HandleReceivedResponseHeaders(success, responseHeaders); } } }
/* * Copyright (c) 2012 Calvin Rien * * Based on the JSON parser by Patrick van Bergen * http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html * * Simplified it so that it doesn't throw exceptions * and can be used in Unity iPhone with maximum code stripping. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; namespace MiniJSON { // Example usage: // // using UnityEngine; // using System.Collections; // using System.Collections.Generic; // using MiniJSON; // // public class MiniJSONTest : MonoBehaviour { // void Start () { // var jsonString = "{ \"array\": [1.44,2,3], " + // "\"object\": {\"key1\":\"value1\", \"key2\":256}, " + // "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " + // "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " + // "\"int\": 65536, " + // "\"float\": 3.1415926, " + // "\"bool\": true, " + // "\"null\": null }"; // // var dict = Json.Deserialize(jsonString) as Dictionary<string,object>; // // Debug.Log("deserialized: " + dict.GetType()); // Debug.Log("dict['array'][0]: " + ((List<object>) dict["array"])[0]); // Debug.Log("dict['string']: " + (string) dict["string"]); // Debug.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles // Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs // Debug.Log("dict['unicode']: " + (string) dict["unicode"]); // // var str = Json.Serialize(dict); // // Debug.Log("serialized: " + str); // } // } /// <summary> /// This class encodes and decodes JSON strings. /// Spec. details, see http://www.json.org/ /// /// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary. /// All numbers are parsed to doubles. /// </summary> public static class Json { /// <summary> /// Parses the string json into a value /// </summary> /// <param name="json">A JSON string.</param> /// <returns>An List&lt;object&gt;, a Dictionary&lt;string, object&gt;, a double, an integer,a string, null, true, or false</returns> public static object Deserialize(string json) { // save the string for debug information if (json == null) { return null; } return Parser.Parse(json); } sealed class Parser : IDisposable { const string WHITE_SPACE = " \t\n\r"; const string WORD_BREAK = " \t\n\r{}[],:\""; enum TOKEN { NONE, CURLY_OPEN, CURLY_CLOSE, SQUARED_OPEN, SQUARED_CLOSE, COLON, COMMA, STRING, NUMBER, TRUE, FALSE, NULL }; StringReader json; Parser(string jsonString) { json = new StringReader(jsonString); } public static object Parse(string jsonString) { using (var instance = new Parser(jsonString)) { return instance.ParseValue(); } } public void Dispose() { json.Dispose(); json = null; } Dictionary<string, object> ParseObject() { Dictionary<string, object> table = new Dictionary<string, object>(); // ditch opening brace json.Read(); // { while (true) { switch (NextToken) { case TOKEN.NONE: return null; case TOKEN.COMMA: continue; case TOKEN.CURLY_CLOSE: return table; default: // name string name = ParseString(); if (name == null) { return null; } // : if (NextToken != TOKEN.COLON) { return null; } // ditch the colon json.Read(); // value table[name] = ParseValue(); break; } } } List<object> ParseArray() { List<object> array = new List<object>(); // ditch opening bracket json.Read(); // [ var parsing = true; while (parsing) { TOKEN nextToken = NextToken; switch (nextToken) { case TOKEN.NONE: return null; case TOKEN.COMMA: continue; case TOKEN.SQUARED_CLOSE: parsing = false; break; default: object value = ParseByToken(nextToken); array.Add(value); break; } } return array; } object ParseValue() { TOKEN nextToken = NextToken; return ParseByToken(nextToken); } object ParseByToken(TOKEN token) { switch (token) { case TOKEN.STRING: return ParseString(); case TOKEN.NUMBER: return ParseNumber(); case TOKEN.CURLY_OPEN: return ParseObject(); case TOKEN.SQUARED_OPEN: return ParseArray(); case TOKEN.TRUE: return true; case TOKEN.FALSE: return false; case TOKEN.NULL: return null; default: return null; } } string ParseString() { StringBuilder s = new StringBuilder(); char c; // ditch opening quote json.Read(); bool parsing = true; while (parsing) { if (json.Peek() == -1) { parsing = false; break; } c = NextChar; switch (c) { case '"': parsing = false; break; case '\\': if (json.Peek() == -1) { parsing = false; break; } c = NextChar; switch (c) { case '"': case '\\': case '/': s.Append(c); break; case 'b': s.Append('\b'); break; case 'f': s.Append('\f'); break; case 'n': s.Append('\n'); break; case 'r': s.Append('\r'); break; case 't': s.Append('\t'); break; case 'u': var hex = new StringBuilder(); for (int i=0; i< 4; i++) { hex.Append(NextChar); } s.Append((char) Convert.ToInt32(hex.ToString(), 16)); break; } break; default: s.Append(c); break; } } return s.ToString(); } object ParseNumber() { string number = NextWord; if (number.IndexOf('.') == -1) { long parsedInt; Int64.TryParse(number, out parsedInt); return parsedInt; } double parsedDouble; Double.TryParse(number, out parsedDouble); return parsedDouble; } void EatWhitespace() { while (WHITE_SPACE.IndexOf(PeekChar) != -1) { json.Read(); if (json.Peek() == -1) { break; } } } char PeekChar { get { return Convert.ToChar(json.Peek()); } } char NextChar { get { return Convert.ToChar(json.Read()); } } string NextWord { get { StringBuilder word = new StringBuilder(); while (WORD_BREAK.IndexOf(PeekChar) == -1) { word.Append(NextChar); if (json.Peek() == -1) { break; } } return word.ToString(); } } TOKEN NextToken { get { EatWhitespace(); if (json.Peek() == -1) { return TOKEN.NONE; } char c = PeekChar; switch (c) { case '{': return TOKEN.CURLY_OPEN; case '}': json.Read(); return TOKEN.CURLY_CLOSE; case '[': return TOKEN.SQUARED_OPEN; case ']': json.Read(); return TOKEN.SQUARED_CLOSE; case ',': json.Read(); return TOKEN.COMMA; case '"': return TOKEN.STRING; case ':': return TOKEN.COLON; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': return TOKEN.NUMBER; } string word = NextWord; switch (word) { case "false": return TOKEN.FALSE; case "true": return TOKEN.TRUE; case "null": return TOKEN.NULL; } return TOKEN.NONE; } } } /// <summary> /// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string /// </summary> /// <param name="json">A Dictionary&lt;string, object&gt; / List&lt;object&gt;</param> /// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns> public static string Serialize(object obj) { return Serializer.Serialize(obj); } sealed class Serializer { StringBuilder builder; Serializer() { builder = new StringBuilder(); } public static string Serialize(object obj) { var instance = new Serializer(); instance.SerializeValue(obj); return instance.builder.ToString(); } void SerializeValue(object value) { IList asList; IDictionary asDict; string asStr; if (value == null) { builder.Append("null"); } else if ((asStr = value as string) != null) { SerializeString(asStr); } else if (value is bool) { builder.Append(value.ToString().ToLower()); } else if ((asList = value as IList) != null) { SerializeArray(asList); } else if ((asDict = value as IDictionary) != null) { SerializeObject(asDict); } else if (value is char) { SerializeString(value.ToString()); } else { SerializeOther(value); } } void SerializeObject(IDictionary obj) { bool first = true; builder.Append('{'); foreach (object e in obj.Keys) { if (!first) { builder.Append(','); } SerializeString(e.ToString()); builder.Append(':'); SerializeValue(obj[e]); first = false; } builder.Append('}'); } void SerializeArray(IList anArray) { builder.Append('['); bool first = true; foreach (object obj in anArray) { if (!first) { builder.Append(','); } SerializeValue(obj); first = false; } builder.Append(']'); } void SerializeString(string str) { builder.Append('\"'); char[] charArray = str.ToCharArray(); foreach (var c in charArray) { switch (c) { case '"': builder.Append("\\\""); break; case '\\': builder.Append("\\\\"); break; case '\b': builder.Append("\\b"); break; case '\f': builder.Append("\\f"); break; case '\n': builder.Append("\\n"); break; case '\r': builder.Append("\\r"); break; case '\t': builder.Append("\\t"); break; default: int codepoint = Convert.ToInt32(c); if ((codepoint >= 32) && (codepoint <= 126)) { builder.Append(c); } else { builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0')); } break; } } builder.Append('\"'); } void SerializeOther(object value) { if (value is float || value is int || value is uint || value is long || value is double || value is sbyte || value is byte || value is short || value is ushort || value is ulong || value is decimal) { builder.Append(value.ToString()); } else { SerializeString(value.ToString()); } } } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.Runtime.Serialization { using System; using System.Xml; using System.Xml.Schema; using System.Collections; using System.Collections.Generic; using System.Reflection; using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>; using System.Text; internal class DataContractSet { // Same string used in MessageContractImporter of System.ServiceModel.dll const String FailedReferenceTypeExceptionKey = "System.Runtime.Serialization.FailedReferenceType"; Dictionary<XmlQualifiedName, DataContract> contracts; Dictionary<DataContract, object> processedContracts; IDataContractSurrogate dataContractSurrogate; Hashtable surrogateDataTable; DataContractDictionary knownTypesForObject; ICollection<Type> referencedTypes; ICollection<Type> referencedCollectionTypes; Dictionary<XmlQualifiedName, object> referencedTypesDictionary; Dictionary<XmlQualifiedName, object> referencedCollectionTypesDictionary; internal DataContractSet(IDataContractSurrogate dataContractSurrogate) : this(dataContractSurrogate, null, null) { } internal DataContractSet(IDataContractSurrogate dataContractSurrogate, ICollection<Type> referencedTypes, ICollection<Type> referencedCollectionTypes) { this.dataContractSurrogate = dataContractSurrogate; this.referencedTypes = referencedTypes; this.referencedCollectionTypes = referencedCollectionTypes; } internal DataContractSet(DataContractSet dataContractSet) { if (dataContractSet == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("dataContractSet")); this.dataContractSurrogate = dataContractSet.dataContractSurrogate; this.referencedTypes = dataContractSet.referencedTypes; this.referencedCollectionTypes = dataContractSet.referencedCollectionTypes; foreach (KeyValuePair<XmlQualifiedName, DataContract> pair in dataContractSet) { Add(pair.Key, pair.Value); } if (dataContractSet.processedContracts != null) { foreach (KeyValuePair<DataContract, object> pair in dataContractSet.processedContracts) { ProcessedContracts.Add(pair.Key, pair.Value); } } } Dictionary<XmlQualifiedName, DataContract> Contracts { get { if (contracts == null) { contracts = new Dictionary<XmlQualifiedName, DataContract>(); } return contracts; } } Dictionary<DataContract, object> ProcessedContracts { get { if (processedContracts == null) { processedContracts = new Dictionary<DataContract, object>(); } return processedContracts; } } Hashtable SurrogateDataTable { get { if (surrogateDataTable == null) surrogateDataTable = new Hashtable(); return surrogateDataTable; } } internal DataContractDictionary KnownTypesForObject { get { return knownTypesForObject; } set { knownTypesForObject = value; } } internal void Add(Type type) { DataContract dataContract = GetDataContract(type); EnsureTypeNotGeneric(dataContract.UnderlyingType); Add(dataContract); } internal static void EnsureTypeNotGeneric(Type type) { if (type.ContainsGenericParameters) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.GenericTypeNotExportable, type))); } void Add(DataContract dataContract) { Add(dataContract.StableName, dataContract); } public void Add(XmlQualifiedName name, DataContract dataContract) { if (dataContract.IsBuiltInDataContract) return; InternalAdd(name, dataContract); } internal void InternalAdd(XmlQualifiedName name, DataContract dataContract) { DataContract dataContractInSet = null; if (Contracts.TryGetValue(name, out dataContractInSet)) { if (!dataContractInSet.Equals(dataContract)) { if (dataContract.UnderlyingType == null || dataContractInSet.UnderlyingType == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.DupContractInDataContractSet, dataContract.StableName.Name, dataContract.StableName.Namespace))); else { bool typeNamesEqual = (DataContract.GetClrTypeFullName(dataContract.UnderlyingType) == DataContract.GetClrTypeFullName(dataContractInSet.UnderlyingType)); throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.DupTypeContractInDataContractSet, (typeNamesEqual ? dataContract.UnderlyingType.AssemblyQualifiedName : DataContract.GetClrTypeFullName(dataContract.UnderlyingType)), (typeNamesEqual ? dataContractInSet.UnderlyingType.AssemblyQualifiedName : DataContract.GetClrTypeFullName(dataContractInSet.UnderlyingType)), dataContract.StableName.Name, dataContract.StableName.Namespace))); } } } else { Contracts.Add(name, dataContract); if (dataContract is ClassDataContract) { AddClassDataContract((ClassDataContract)dataContract); } else if (dataContract is CollectionDataContract) { AddCollectionDataContract((CollectionDataContract)dataContract); } else if (dataContract is XmlDataContract) { AddXmlDataContract((XmlDataContract)dataContract); } } } void AddClassDataContract(ClassDataContract classDataContract) { if (classDataContract.BaseContract != null) { Add(classDataContract.BaseContract.StableName, classDataContract.BaseContract); } if (!classDataContract.IsISerializable) { if (classDataContract.Members != null) { for (int i = 0; i < classDataContract.Members.Count; i++) { DataMember dataMember = classDataContract.Members[i]; DataContract memberDataContract = GetMemberTypeDataContract(dataMember); if (dataContractSurrogate != null && dataMember.MemberInfo != null) { object customData = DataContractSurrogateCaller.GetCustomDataToExport( dataContractSurrogate, dataMember.MemberInfo, memberDataContract.UnderlyingType); if (customData != null) SurrogateDataTable.Add(dataMember, customData); } Add(memberDataContract.StableName, memberDataContract); } } } AddKnownDataContracts(classDataContract.KnownDataContracts); } void AddCollectionDataContract(CollectionDataContract collectionDataContract) { if (collectionDataContract.IsDictionary) { ClassDataContract keyValueContract = collectionDataContract.ItemContract as ClassDataContract; AddClassDataContract(keyValueContract); } else { DataContract itemContract = GetItemTypeDataContract(collectionDataContract); if (itemContract != null) Add(itemContract.StableName, itemContract); } AddKnownDataContracts(collectionDataContract.KnownDataContracts); } void AddXmlDataContract(XmlDataContract xmlDataContract) { AddKnownDataContracts(xmlDataContract.KnownDataContracts); } void AddKnownDataContracts(DataContractDictionary knownDataContracts) { if (knownDataContracts != null) { foreach (DataContract knownDataContract in knownDataContracts.Values) { Add(knownDataContract); } } } internal XmlQualifiedName GetStableName(Type clrType) { if (dataContractSurrogate != null) { Type dcType = DataContractSurrogateCaller.GetDataContractType(dataContractSurrogate, clrType); //if (clrType.IsValueType != dcType.IsValueType) // throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.ValueTypeMismatchInSurrogatedType, dcType, clrType))); return DataContract.GetStableName(dcType); } return DataContract.GetStableName(clrType); } internal DataContract GetDataContract(Type clrType) { if (dataContractSurrogate == null) return DataContract.GetDataContract(clrType); DataContract dataContract = DataContract.GetBuiltInDataContract(clrType); if (dataContract != null) return dataContract; Type dcType = DataContractSurrogateCaller.GetDataContractType(dataContractSurrogate, clrType); //if (clrType.IsValueType != dcType.IsValueType) // throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.ValueTypeMismatchInSurrogatedType, dcType, clrType))); dataContract = DataContract.GetDataContract(dcType); if (!SurrogateDataTable.Contains(dataContract)) { object customData = DataContractSurrogateCaller.GetCustomDataToExport( dataContractSurrogate, clrType, dcType); if (customData != null) SurrogateDataTable.Add(dataContract, customData); } return dataContract; } internal DataContract GetMemberTypeDataContract(DataMember dataMember) { if (dataMember.MemberInfo != null) { Type dataMemberType = dataMember.MemberType; if (dataMember.IsGetOnlyCollection) { if (dataContractSurrogate != null) { Type dcType = DataContractSurrogateCaller.GetDataContractType(dataContractSurrogate, dataMemberType); if (dcType != dataMemberType) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.SurrogatesWithGetOnlyCollectionsNotSupported, DataContract.GetClrTypeFullName(dataMemberType), DataContract.GetClrTypeFullName(dataMember.MemberInfo.DeclaringType), dataMember.MemberInfo.Name))); } } return DataContract.GetGetOnlyCollectionDataContract(DataContract.GetId(dataMemberType.TypeHandle), dataMemberType.TypeHandle, dataMemberType, SerializationMode.SharedContract); } else { return GetDataContract(dataMemberType); } } return dataMember.MemberTypeContract; } internal DataContract GetItemTypeDataContract(CollectionDataContract collectionContract) { if (collectionContract.ItemType != null) return GetDataContract(collectionContract.ItemType); return collectionContract.ItemContract; } internal object GetSurrogateData(object key) { return SurrogateDataTable[key]; } internal void SetSurrogateData(object key, object surrogateData) { SurrogateDataTable[key] = surrogateData; } public DataContract this[XmlQualifiedName key] { get { DataContract dataContract = DataContract.GetBuiltInDataContract(key.Name, key.Namespace); if (dataContract == null) { Contracts.TryGetValue(key, out dataContract); } return dataContract; } } public IDataContractSurrogate DataContractSurrogate { get { return dataContractSurrogate; } } public bool Remove(XmlQualifiedName key) { if (DataContract.GetBuiltInDataContract(key.Name, key.Namespace) != null) return false; return Contracts.Remove(key); } public IEnumerator<KeyValuePair<XmlQualifiedName, DataContract>> GetEnumerator() { return Contracts.GetEnumerator(); } internal bool IsContractProcessed(DataContract dataContract) { return ProcessedContracts.ContainsKey(dataContract); } internal void SetContractProcessed(DataContract dataContract) { ProcessedContracts.Add(dataContract, dataContract); } #if !NO_CODEDOM internal ContractCodeDomInfo GetContractCodeDomInfo(DataContract dataContract) { object info; if (ProcessedContracts.TryGetValue(dataContract, out info)) return (ContractCodeDomInfo)info; return null; } internal void SetContractCodeDomInfo(DataContract dataContract, ContractCodeDomInfo info) { ProcessedContracts.Add(dataContract, info); } #endif Dictionary<XmlQualifiedName, object> GetReferencedTypes() { if (referencedTypesDictionary == null) { referencedTypesDictionary = new Dictionary<XmlQualifiedName, object>(); //Always include Nullable as referenced type //Do not allow surrogating Nullable<T> referencedTypesDictionary.Add(DataContract.GetStableName(Globals.TypeOfNullable), Globals.TypeOfNullable); if (this.referencedTypes != null) { foreach (Type type in this.referencedTypes) { if (type == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ReferencedTypesCannotContainNull))); try { AddReferencedType(referencedTypesDictionary, type); } catch (InvalidDataContractException ex) { ex.Data.Add(FailedReferenceTypeExceptionKey, type); throw; } catch (InvalidOperationException ex) { ex.Data.Add(FailedReferenceTypeExceptionKey, type); throw; } } } } return referencedTypesDictionary; } Dictionary<XmlQualifiedName, object> GetReferencedCollectionTypes() { if (referencedCollectionTypesDictionary == null) { referencedCollectionTypesDictionary = new Dictionary<XmlQualifiedName, object>(); if (this.referencedCollectionTypes != null) { foreach (Type type in this.referencedCollectionTypes) { if (type == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ReferencedCollectionTypesCannotContainNull))); AddReferencedType(referencedCollectionTypesDictionary, type); } } XmlQualifiedName genericDictionaryName = DataContract.GetStableName(Globals.TypeOfDictionaryGeneric); if (!referencedCollectionTypesDictionary.ContainsKey(genericDictionaryName) && GetReferencedTypes().ContainsKey(genericDictionaryName)) AddReferencedType(referencedCollectionTypesDictionary, Globals.TypeOfDictionaryGeneric); } return referencedCollectionTypesDictionary; } void AddReferencedType(Dictionary<XmlQualifiedName, object> referencedTypes, Type type) { if (IsTypeReferenceable(type)) { XmlQualifiedName stableName = this.GetStableName(type); object value; if (referencedTypes.TryGetValue(stableName, out value)) { Type referencedType = value as Type; if (referencedType != null) { if (referencedType != type) { referencedTypes.Remove(stableName); List<Type> types = new List<Type>(); types.Add(referencedType); types.Add(type); referencedTypes.Add(stableName, types); } } else { List<Type> types = (List<Type>)value; if (!types.Contains(type)) types.Add(type); } } else referencedTypes.Add(stableName, type); } } internal bool TryGetReferencedType(XmlQualifiedName stableName, DataContract dataContract, out Type type) { return TryGetReferencedType(stableName, dataContract, false/*useReferencedCollectionTypes*/, out type); } internal bool TryGetReferencedCollectionType(XmlQualifiedName stableName, DataContract dataContract, out Type type) { return TryGetReferencedType(stableName, dataContract, true/*useReferencedCollectionTypes*/, out type); } bool TryGetReferencedType(XmlQualifiedName stableName, DataContract dataContract, bool useReferencedCollectionTypes, out Type type) { object value; Dictionary<XmlQualifiedName, object> referencedTypes = useReferencedCollectionTypes ? GetReferencedCollectionTypes() : GetReferencedTypes(); if (referencedTypes.TryGetValue(stableName, out value)) { type = value as Type; if (type != null) return true; else { // Throw ambiguous type match exception List<Type> types = (List<Type>)value; StringBuilder errorMessage = new StringBuilder(); bool containsGenericType = false; for (int i = 0; i < types.Count; i++) { Type conflictingType = types[i]; if (!containsGenericType) containsGenericType = conflictingType.IsGenericTypeDefinition; errorMessage.AppendFormat("{0}\"{1}\" ", Environment.NewLine, conflictingType.AssemblyQualifiedName); if (dataContract != null) { DataContract other = this.GetDataContract(conflictingType); errorMessage.Append(SR.GetString(((other != null && other.Equals(dataContract)) ? SR.ReferencedTypeMatchingMessage : SR.ReferencedTypeNotMatchingMessage))); } } if (containsGenericType) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString( (useReferencedCollectionTypes ? SR.AmbiguousReferencedCollectionTypes1 : SR.AmbiguousReferencedTypes1), errorMessage.ToString()))); } else { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString( (useReferencedCollectionTypes ? SR.AmbiguousReferencedCollectionTypes3 : SR.AmbiguousReferencedTypes3), XmlConvert.DecodeName(stableName.Name), stableName.Namespace, errorMessage.ToString()))); } } } type = null; return false; } static bool IsTypeReferenceable(Type type) { Type itemType; return (type.IsSerializable || type.IsDefined(Globals.TypeOfDataContractAttribute, false) || (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type) && !type.IsGenericTypeDefinition) || CollectionDataContract.IsCollection(type, out itemType) || ClassDataContract.IsNonAttributedTypeValidForSerialization(type)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO.PortsTests; using System.Text; using System.Threading; using System.Threading.Tasks; using Legacy.Support; using Xunit; using Microsoft.DotNet.XUnitExtensions; namespace System.IO.Ports.Tests { public class Write_char_int_int_generic : PortsTest { //Set bounds fore random timeout values. //If the min is to low write will not timeout accurately and the testcase will fail private const int minRandomTimeout = 250; //If the max is to large then the testcase will take forever to run private const int maxRandomTimeout = 2000; //If the percentage difference between the expected timeout and the actual timeout //found through Stopwatch is greater then 10% then the timeout value was not correctly //to the write method and the testcase fails. private static double s_maxPercentageDifference = .15; //The char size used when veryifying exceptions that write will throw private const int CHAR_SIZE_EXCEPTION = 4; //The char size used when veryifying timeout private const int CHAR_SIZE_TIMEOUT = 4; //The char size used when veryifying BytesToWrite private const int CHAR_SIZE_BYTES_TO_WRITE = 4; //The char size used when veryifying Handshake private const int CHAR_SIZE_HANDSHAKE = 8; private const int NUM_TRYS = 5; #region Test Cases [Fact] public void WriteWithoutOpen() { using (SerialPort com = new SerialPort()) { Debug.WriteLine("Verifying write method throws exception without a call to Open()"); VerifyWriteException(com, typeof(InvalidOperationException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void WriteAfterFailedOpen() { using (SerialPort com = new SerialPort("BAD_PORT_NAME")) { Debug.WriteLine("Verifying write method throws exception with a failed call to Open()"); //Since the PortName is set to a bad port name Open will thrown an exception //however we don't care what it is since we are verifying a write method Assert.ThrowsAny<Exception>(() => com.Open()); VerifyWriteException(com, typeof(InvalidOperationException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void WriteAfterClose() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Verifying write method throws exception after a call to Cloes()"); com.Open(); com.Close(); VerifyWriteException(com, typeof(InvalidOperationException)); } } [KnownFailure] [ConditionalFact(nameof(HasNullModem))] public void Timeout() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(-55); byte[] XOffBuffer = new byte[1]; XOffBuffer[0] = 19; com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); com1.Handshake = Handshake.XOnXOff; Debug.WriteLine("Verifying WriteTimeout={0}", com1.WriteTimeout); com1.Open(); com2.Open(); com2.Write(XOffBuffer, 0, 1); Thread.Sleep(250); com2.Close(); VerifyTimeout(com1); } } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))] public void SuccessiveReadTimeout() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(-55); com.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); com.Handshake = Handshake.RequestToSendXOnXOff; // com.Encoding = new System.Text.UTF7Encoding(); com.Encoding = Encoding.Unicode; Debug.WriteLine("Verifying WriteTimeout={0} with successive call to write method", com.WriteTimeout); com.Open(); try { com.Write(new char[CHAR_SIZE_TIMEOUT], 0, CHAR_SIZE_TIMEOUT); } catch (TimeoutException) { } VerifyTimeout(com); } } [ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))] public void SuccessiveReadTimeoutWithWriteSucceeding() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(-55); AsyncEnableRts asyncEnableRts = new AsyncEnableRts(); var t = new Task(asyncEnableRts.EnableRTS); com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); com1.Handshake = Handshake.RequestToSend; com1.Encoding = new UTF8Encoding(); Debug.WriteLine("Verifying WriteTimeout={0} with successive call to write method with the write succeeding sometime before its timeout", com1.WriteTimeout); com1.Open(); //Call EnableRTS asynchronously this will enable RTS in the middle of the following write call allowing it to succeed //before the timeout is reached t.Start(); TCSupport.WaitForTaskToStart(t); try { com1.Write(new char[CHAR_SIZE_TIMEOUT], 0, CHAR_SIZE_TIMEOUT); } catch (TimeoutException) { } asyncEnableRts.Stop(); TCSupport.WaitForTaskCompletion(t); VerifyTimeout(com1); } } [ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))] public void BytesToWrite() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { AsyncWriteRndCharArray asyncWriteRndCharArray = new AsyncWriteRndCharArray(com, CHAR_SIZE_BYTES_TO_WRITE); var t = new Task(asyncWriteRndCharArray.WriteRndCharArray); Debug.WriteLine("Verifying BytesToWrite with one call to Write"); com.Handshake = Handshake.RequestToSend; com.Open(); com.WriteTimeout = 500; //Write a random char[] asynchronously so we can verify some things while the write call is blocking t.Start(); TCSupport.WaitForTaskToStart(t); TCSupport.WaitForExactWriteBufferLoad(com, CHAR_SIZE_BYTES_TO_WRITE); TCSupport.WaitForTaskCompletion(t); } } [ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))] public void BytesToWriteSuccessive() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { AsyncWriteRndCharArray asyncWriteRndCharArray = new AsyncWriteRndCharArray(com, CHAR_SIZE_BYTES_TO_WRITE); var t1 = new Task(asyncWriteRndCharArray.WriteRndCharArray); var t2 = new Task(asyncWriteRndCharArray.WriteRndCharArray); Debug.WriteLine("Verifying BytesToWrite with successive calls to Write"); com.Handshake = Handshake.RequestToSend; com.Open(); com.WriteTimeout = 4000; //Write a random char[] asynchronously so we can verify some things while the write call is blocking t1.Start(); TCSupport.WaitForTaskToStart(t1); TCSupport.WaitForExactWriteBufferLoad(com, CHAR_SIZE_BYTES_TO_WRITE); //Write a random char[] asynchronously so we can verify some things while the write call is blocking t2.Start(); TCSupport.WaitForTaskToStart(t2); TCSupport.WaitForExactWriteBufferLoad(com, CHAR_SIZE_BYTES_TO_WRITE * 2); //Wait for both write methods to timeout TCSupport.WaitForTaskCompletion(t1); var aggregatedException = Assert.Throws<AggregateException>(() => TCSupport.WaitForTaskCompletion(t2)); Assert.IsType<IOException>(aggregatedException.InnerException); } } [ConditionalFact(nameof(HasNullModem))] public void Handshake_None() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { AsyncWriteRndCharArray asyncWriteRndCharArray = new AsyncWriteRndCharArray(com, CHAR_SIZE_HANDSHAKE); var t = new Task(asyncWriteRndCharArray.WriteRndCharArray); //Write a random char[] asynchronously so we can verify some things while the write call is blocking Debug.WriteLine("Verifying Handshake=None"); com.Open(); t.Start(); TCSupport.WaitForTaskCompletion(t); Assert.Equal(0, com.BytesToWrite); } } [ConditionalFact(nameof(HasNullModem))] public void Handshake_RequestToSend() { Verify_Handshake(Handshake.RequestToSend); } [KnownFailure] [ConditionalFact(nameof(HasNullModem))] public void Handshake_XOnXOff() { Verify_Handshake(Handshake.XOnXOff); } [KnownFailure] [ConditionalFact(nameof(HasNullModem))] public void Handshake_RequestToSendXOnXOff() { Verify_Handshake(Handshake.RequestToSendXOnXOff); } public class AsyncEnableRts { private bool _stop; public void EnableRTS() { lock (this) { using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(-55); int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); //Sleep some random period with of a maximum duration of half the largest possible timeout value for a write method on COM1 Thread.Sleep(sleepPeriod); com2.Open(); com2.RtsEnable = true; while (!_stop) Monitor.Wait(this); com2.RtsEnable = false; } } } public void Stop() { lock (this) { _stop = true; Monitor.Pulse(this); } } } public class AsyncWriteRndCharArray { private readonly SerialPort _com; private readonly int _charLength; public AsyncWriteRndCharArray(SerialPort com, int charLength) { _com = com; _charLength = charLength; } public void WriteRndCharArray() { char[] buffer = TCSupport.GetRandomChars(_charLength, TCSupport.CharacterOptions.Surrogates); try { _com.Write(buffer, 0, buffer.Length); } catch (TimeoutException) { } } } #endregion #region Verification for Test Cases public static void VerifyWriteException(SerialPort com, Type expectedException) { Assert.Throws(expectedException, () => com.Write(new char[CHAR_SIZE_EXCEPTION], 0, CHAR_SIZE_EXCEPTION)); } private void VerifyTimeout(SerialPort com) { Stopwatch timer = new Stopwatch(); int expectedTime = com.WriteTimeout; int actualTime = 0; double percentageDifference; try { com.Write(new char[CHAR_SIZE_TIMEOUT], 0, CHAR_SIZE_TIMEOUT); //Warm up write method } catch (TimeoutException) { } Thread.CurrentThread.Priority = ThreadPriority.Highest; for (int i = 0; i < NUM_TRYS; i++) { timer.Start(); try { com.Write(new char[CHAR_SIZE_TIMEOUT], 0, CHAR_SIZE_TIMEOUT); } catch (TimeoutException) { } timer.Stop(); actualTime += (int)timer.ElapsedMilliseconds; timer.Reset(); } Thread.CurrentThread.Priority = ThreadPriority.Normal; actualTime /= NUM_TRYS; percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime); //Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference if (s_maxPercentageDifference < percentageDifference) { Fail("ERROR!!!: The write method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); } } private void Verify_Handshake(Handshake handshake) { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { bool rts = Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake; bool xonxoff = Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake; byte[] XOffBuffer = new byte[1]; byte[] XOnBuffer = new byte[1]; XOffBuffer[0] = 19; XOnBuffer[0] = 17; Debug.WriteLine("Verifying Handshake={0}", handshake); com1.Handshake = handshake; com1.Open(); com2.Open(); //Setup to ensure write will block with type of handshake method being used if (rts) { com2.RtsEnable = false; } if (xonxoff) { com2.Write(XOffBuffer, 0, 1); Thread.Sleep(250); } char[] writeArr = new char[] { 'A', 'B', 'C' }; Task writeTask = Task.Run(() => com1.Write(writeArr, 0, writeArr.Length)); CancellationTokenSource cts = new CancellationTokenSource(); Task<int> readTask = com2.BaseStream.ReadAsync(new byte[3], 0, 3, cts.Token); // Give it some time to make sure transmission doesn't happen Thread.Sleep(200); Assert.False(readTask.IsCompleted); cts.CancelAfter(500); if (rts) { Assert.False(com1.CtsHolding); com2.RtsEnable = true; } if (xonxoff) { com2.Write(XOnBuffer, 0, 1); } writeTask.Wait(); Assert.True(readTask.Result > 0); //Verify that CtsHolding is true if the RequestToSend or RequestToSendXOnXOff handshake method is used if (rts) { Assert.True(com1.CtsHolding); } } } #endregion } }
using System; using System.Text; using System.Security.Cryptography; using System.IO; using System.Collections.Generic; namespace DarkMultiPlayerCommon { public class Common { //Timeouts in milliseconds public const long HEART_BEAT_INTERVAL = 5000; public const long INITIAL_CONNECTION_TIMEOUT = 5000; public const long CONNECTION_TIMEOUT = 20000; //Any message bigger than 5MB will be invalid public const int MAX_MESSAGE_SIZE = 5242880; //Split messages into 8kb chunks to higher priority messages have more injection points into the TCP stream. public const int SPLIT_MESSAGE_LENGTH = 8192; //Bump this every time there is a network change (Basically, if MessageWriter or MessageReader is touched). public const int PROTOCOL_VERSION = 38; //Program version. This is written in the build scripts. public const string PROGRAM_VERSION = "Custom"; //Mod control version - The last version to add parts public const string MODCONTROL_VERSION = "1.0.3"; //Compression threshold public const int COMPRESSION_THRESHOLD = 4096; public static string CalculateSHA256Hash(string fileName) { return CalculateSHA256Hash(File.ReadAllBytes(fileName)); } public static string CalculateSHA256Hash(byte[] fileData) { StringBuilder sb = new StringBuilder(); using (SHA256Managed sha = new SHA256Managed()) { byte[] fileHashData = sha.ComputeHash(fileData); //Byte[] to string conversion adapted from MSDN... for (int i = 0; i < fileHashData.Length; i++) { sb.Append(fileHashData[i].ToString("x2")); } } return sb.ToString(); } public static byte[] PrependNetworkFrame(int messageType, byte[] messageData) { byte[] returnBytes; //Get type bytes byte[] typeBytes = BitConverter.GetBytes(messageType); if (BitConverter.IsLittleEndian) { Array.Reverse(typeBytes); } if (messageData == null || messageData.Length == 0) { returnBytes = new byte[8]; typeBytes.CopyTo(returnBytes, 0); } else { //Get length bytes if we have a payload byte[] lengthBytes = BitConverter.GetBytes(messageData.Length); if (BitConverter.IsLittleEndian) { Array.Reverse(lengthBytes); } returnBytes = new byte[8 + messageData.Length]; typeBytes.CopyTo(returnBytes, 0); lengthBytes.CopyTo(returnBytes, 4); messageData.CopyTo(returnBytes, 8); } return returnBytes; } public static string ConvertConfigStringToGUIDString(string configNodeString) { if (configNodeString == null || configNodeString.Length != 32) { return null; } string[] returnString = new string[5]; returnString[0] = configNodeString.Substring(0, 8); returnString[1] = configNodeString.Substring(8, 4); returnString[2] = configNodeString.Substring(12, 4); returnString[3] = configNodeString.Substring(16, 4); returnString[4] = configNodeString.Substring(20); return String.Join("-", returnString); } public static List<string> GetStockParts() { List<string> stockPartList = new List<string>(); stockPartList.Add("StandardCtrlSrf"); stockPartList.Add("CanardController"); stockPartList.Add("noseCone"); stockPartList.Add("AdvancedCanard"); stockPartList.Add("airplaneTail"); stockPartList.Add("deltaWing"); stockPartList.Add("noseConeAdapter"); stockPartList.Add("rocketNoseCone"); stockPartList.Add("smallCtrlSrf"); stockPartList.Add("standardNoseCone"); stockPartList.Add("sweptWing"); stockPartList.Add("tailfin"); stockPartList.Add("wingConnector"); stockPartList.Add("winglet"); stockPartList.Add("R8winglet"); stockPartList.Add("winglet3"); stockPartList.Add("Mark1Cockpit"); stockPartList.Add("Mark2Cockpit"); stockPartList.Add("Mark1-2Pod"); stockPartList.Add("advSasModule"); stockPartList.Add("asasmodule1-2"); stockPartList.Add("avionicsNoseCone"); stockPartList.Add("crewCabin"); stockPartList.Add("cupola"); stockPartList.Add("landerCabinSmall"); stockPartList.Add("mark3Cockpit"); stockPartList.Add("mk1pod"); stockPartList.Add("mk2LanderCabin"); stockPartList.Add("probeCoreCube"); stockPartList.Add("probeCoreHex"); stockPartList.Add("probeCoreOcto"); stockPartList.Add("probeCoreOcto2"); stockPartList.Add("probeCoreSphere"); stockPartList.Add("probeStackLarge"); stockPartList.Add("probeStackSmall"); stockPartList.Add("sasModule"); stockPartList.Add("seatExternalCmd"); stockPartList.Add("rtg"); stockPartList.Add("batteryBank"); stockPartList.Add("batteryBankLarge"); stockPartList.Add("batteryBankMini"); stockPartList.Add("batteryPack"); stockPartList.Add("ksp.r.largeBatteryPack"); stockPartList.Add("largeSolarPanel"); stockPartList.Add("solarPanels1"); stockPartList.Add("solarPanels2"); stockPartList.Add("solarPanels3"); stockPartList.Add("solarPanels4"); stockPartList.Add("solarPanels5"); stockPartList.Add("JetEngine"); stockPartList.Add("engineLargeSkipper"); stockPartList.Add("ionEngine"); stockPartList.Add("liquidEngine"); stockPartList.Add("liquidEngine1-2"); stockPartList.Add("liquidEngine2"); stockPartList.Add("liquidEngine2-2"); stockPartList.Add("liquidEngine3"); stockPartList.Add("liquidEngineMini"); stockPartList.Add("microEngine"); stockPartList.Add("nuclearEngine"); stockPartList.Add("radialEngineMini"); stockPartList.Add("radialLiquidEngine1-2"); stockPartList.Add("sepMotor1"); stockPartList.Add("smallRadialEngine"); stockPartList.Add("solidBooster"); stockPartList.Add("solidBooster1-1"); stockPartList.Add("toroidalAerospike"); stockPartList.Add("turboFanEngine"); stockPartList.Add("MK1Fuselage"); stockPartList.Add("Mk1FuselageStructural"); stockPartList.Add("RCSFuelTank"); stockPartList.Add("RCSTank1-2"); stockPartList.Add("rcsTankMini"); stockPartList.Add("rcsTankRadialLong"); stockPartList.Add("fuelTank"); stockPartList.Add("fuelTank1-2"); stockPartList.Add("fuelTank2-2"); stockPartList.Add("fuelTank3-2"); stockPartList.Add("fuelTank4-2"); stockPartList.Add("fuelTankSmall"); stockPartList.Add("fuelTankSmallFlat"); stockPartList.Add("fuelTank.long"); stockPartList.Add("miniFuelTank"); stockPartList.Add("mk2Fuselage"); stockPartList.Add("mk2SpacePlaneAdapter"); stockPartList.Add("mk3Fuselage"); stockPartList.Add("mk3spacePlaneAdapter"); stockPartList.Add("radialRCSTank"); stockPartList.Add("toroidalFuelTank"); stockPartList.Add("xenonTank"); stockPartList.Add("xenonTankRadial"); stockPartList.Add("adapterLargeSmallBi"); stockPartList.Add("adapterLargeSmallQuad"); stockPartList.Add("adapterLargeSmallTri"); stockPartList.Add("adapterSmallMiniShort"); stockPartList.Add("adapterSmallMiniTall"); stockPartList.Add("nacelleBody"); stockPartList.Add("radialEngineBody"); stockPartList.Add("smallHardpoint"); stockPartList.Add("stationHub"); stockPartList.Add("structuralIBeam1"); stockPartList.Add("structuralIBeam2"); stockPartList.Add("structuralIBeam3"); stockPartList.Add("structuralMiniNode"); stockPartList.Add("structuralPanel1"); stockPartList.Add("structuralPanel2"); stockPartList.Add("structuralPylon"); stockPartList.Add("structuralWing"); stockPartList.Add("strutConnector"); stockPartList.Add("strutCube"); stockPartList.Add("strutOcto"); stockPartList.Add("trussAdapter"); stockPartList.Add("trussPiece1x"); stockPartList.Add("trussPiece3x"); stockPartList.Add("CircularIntake"); stockPartList.Add("landingLeg1"); stockPartList.Add("landingLeg1-2"); stockPartList.Add("RCSBlock"); stockPartList.Add("stackDecoupler"); stockPartList.Add("airScoop"); stockPartList.Add("commDish"); stockPartList.Add("decoupler1-2"); stockPartList.Add("dockingPort1"); stockPartList.Add("dockingPort2"); stockPartList.Add("dockingPort3"); stockPartList.Add("dockingPortLarge"); stockPartList.Add("dockingPortLateral"); stockPartList.Add("fuelLine"); stockPartList.Add("ladder1"); stockPartList.Add("largeAdapter"); stockPartList.Add("largeAdapter2"); stockPartList.Add("launchClamp1"); stockPartList.Add("linearRcs"); stockPartList.Add("longAntenna"); stockPartList.Add("miniLandingLeg"); stockPartList.Add("parachuteDrogue"); stockPartList.Add("parachuteLarge"); stockPartList.Add("parachuteRadial"); stockPartList.Add("parachuteSingle"); stockPartList.Add("radialDecoupler"); stockPartList.Add("radialDecoupler1-2"); stockPartList.Add("radialDecoupler2"); stockPartList.Add("ramAirIntake"); stockPartList.Add("roverBody"); stockPartList.Add("sensorAccelerometer"); stockPartList.Add("sensorBarometer"); stockPartList.Add("sensorGravimeter"); stockPartList.Add("sensorThermometer"); stockPartList.Add("spotLight1"); stockPartList.Add("spotLight2"); stockPartList.Add("stackBiCoupler"); stockPartList.Add("stackDecouplerMini"); stockPartList.Add("stackPoint1"); stockPartList.Add("stackQuadCoupler"); stockPartList.Add("stackSeparator"); stockPartList.Add("stackSeparatorBig"); stockPartList.Add("stackSeparatorMini"); stockPartList.Add("stackTriCoupler"); stockPartList.Add("telescopicLadder"); stockPartList.Add("telescopicLadderBay"); stockPartList.Add("SmallGearBay"); stockPartList.Add("roverWheel1"); stockPartList.Add("roverWheel2"); stockPartList.Add("roverWheel3"); stockPartList.Add("wheelMed"); stockPartList.Add("flag"); stockPartList.Add("kerbalEVA"); stockPartList.Add("mediumDishAntenna"); stockPartList.Add("GooExperiment"); stockPartList.Add("science.module"); stockPartList.Add("RAPIER"); stockPartList.Add("Large.Crewed.Lab"); //0.23.5 parts stockPartList.Add("GrapplingDevice"); stockPartList.Add("LaunchEscapeSystem"); stockPartList.Add("MassiveBooster"); stockPartList.Add("PotatoRoid"); stockPartList.Add("Size2LFB"); stockPartList.Add("Size3AdvancedEngine"); stockPartList.Add("size3Decoupler"); stockPartList.Add("Size3EngineCluster"); stockPartList.Add("Size3LargeTank"); stockPartList.Add("Size3MediumTank"); stockPartList.Add("Size3SmallTank"); stockPartList.Add("Size3to2Adapter"); //0.24 parts stockPartList.Add("omsEngine"); stockPartList.Add("vernierEngine"); //0.25 parts stockPartList.Add("delta.small"); stockPartList.Add("elevon2"); stockPartList.Add("elevon3"); stockPartList.Add("elevon5"); stockPartList.Add("IntakeRadialLong"); stockPartList.Add("MK1IntakeFuselage"); stockPartList.Add("mk2.1m.AdapterLong"); stockPartList.Add("mk2.1m.Bicoupler"); stockPartList.Add("mk2CargoBayL"); stockPartList.Add("mk2CargoBayS"); stockPartList.Add("mk2Cockpit.Inline"); stockPartList.Add("mk2Cockpit.Standard"); stockPartList.Add("mk2CrewCabin"); stockPartList.Add("mk2DockingPort"); stockPartList.Add("mk2DroneCore"); stockPartList.Add("mk2FuselageLongLFO"); stockPartList.Add("mk2FuselageShortLFO"); stockPartList.Add("mk2FuselageShortLiquid"); stockPartList.Add("mk2FuselageShortMono"); stockPartList.Add("shockConeIntake"); stockPartList.Add("structuralWing2"); stockPartList.Add("structuralWing3"); stockPartList.Add("structuralWing4"); stockPartList.Add("sweptWing1"); stockPartList.Add("sweptWing2"); stockPartList.Add("wingConnector2"); stockPartList.Add("wingConnector3"); stockPartList.Add("wingConnector4"); stockPartList.Add("wingConnector5"); stockPartList.Add("wingStrake"); //0.90 parts stockPartList.Add("adapterMk3-Mk2"); stockPartList.Add("adapterMk3-Size2"); stockPartList.Add("adapterMk3-Size2Slant"); stockPartList.Add("adapterSize2-Mk2"); stockPartList.Add("adapterSize2-Size1"); stockPartList.Add("adapterSize2-Size1Slant"); stockPartList.Add("adapterSize3-Mk3"); stockPartList.Add("mk3CargoBayL"); stockPartList.Add("mk3CargoBayM"); stockPartList.Add("mk3CargoBayS"); stockPartList.Add("mk3Cockpit.Shuttle"); stockPartList.Add("mk3CrewCabin"); stockPartList.Add("mk3FuselageLF.100"); stockPartList.Add("mk3FuselageLF.25"); stockPartList.Add("mk3FuselageLF.50"); stockPartList.Add("mk3FuselageLFO.100"); stockPartList.Add("mk3FuselageLFO.25"); stockPartList.Add("mk3FuselageLFO.50"); stockPartList.Add("mk3FuselageMONO"); //1.0 parts stockPartList.Add("kerbalEVAfemale"); stockPartList.Add("airbrake1"); stockPartList.Add("airlinerCtrlSrf"); stockPartList.Add("airlinerMainWing"); stockPartList.Add("airlinerTailFin"); stockPartList.Add("pointyNoseConeA"); stockPartList.Add("pointyNoseConeB"); stockPartList.Add("airplaneTailB"); stockPartList.Add("fairingSize1"); stockPartList.Add("fairingSize2"); stockPartList.Add("fairingSize3"); stockPartList.Add("HeatShield1"); stockPartList.Add("HeatShield2"); stockPartList.Add("HeatShield3"); stockPartList.Add("wingShuttleDelta"); stockPartList.Add("elevonMk3"); stockPartList.Add("wingShuttleElevon1"); stockPartList.Add("wingShuttleElevon2"); stockPartList.Add("wingShuttleRudder"); stockPartList.Add("wingShuttleStrake"); stockPartList.Add("delta.small"); stockPartList.Add("mk2Cockpit.Inline"); stockPartList.Add("mk2Cockpit.Standard"); stockPartList.Add("mk3Cockpit.Shuttle"); stockPartList.Add("ksp.r.largeBatteryPack"); stockPartList.Add("solidBooster.sm"); stockPartList.Add("fuelTank.long"); stockPartList.Add("mk2.1m.Bicoupler"); stockPartList.Add("mk2.1m.AdapterLong"); stockPartList.Add("mk3FuselageLFO.100"); stockPartList.Add("mk3FuselageLFO.25"); stockPartList.Add("mk3FuselageLFO.50"); stockPartList.Add("mk3FuselageLF.100"); stockPartList.Add("mk3FuselageLF.25"); stockPartList.Add("mk3FuselageLF.50"); stockPartList.Add("xenonTankLarge"); stockPartList.Add("mk3Cockpit.Shuttle"); stockPartList.Add("FuelCell"); stockPartList.Add("FuelCellArray"); stockPartList.Add("ISRU"); stockPartList.Add("LargeTank"); stockPartList.Add("OrbitalScanner"); stockPartList.Add("RadialDrill"); stockPartList.Add("SmallTank"); stockPartList.Add("SurfaceScanner"); stockPartList.Add("SurveyScanner"); stockPartList.Add("sensorAtmosphere"); stockPartList.Add("Large.Crewed.Lab"); stockPartList.Add("science.module"); stockPartList.Add("radialDrogue"); stockPartList.Add("ServiceBay.125"); stockPartList.Add("ServiceBay.250"); stockPartList.Add("GearFixed"); stockPartList.Add("GearFree"); stockPartList.Add("GearLarge"); stockPartList.Add("GearMedium"); //1.0.1 parts stockPartList.Add("basicFin"); //1.0.3 parts stockPartList.Add("foldingRadLarge"); stockPartList.Add("foldingRadMed"); stockPartList.Add("foldingRadSmall"); stockPartList.Add("radPanelLg"); stockPartList.Add("radPanelSm"); return stockPartList; //MAKE SURE TO CHANGE Common.MODCONTROL_VERSION } public static string GenerateModFileStringData(string[] requiredFiles, string[] optionalFiles, bool isWhiteList, string[] whitelistBlacklistFiles, string[] partsList) { //This is the same format as KMPModControl.txt. It's a fairly sane format, and it makes sense to remain compatible. StringBuilder sb = new StringBuilder(); //Header stuff sb.AppendLine("#MODCONTROLVERSION=" + Common.MODCONTROL_VERSION); sb.AppendLine("#You can comment by starting a line with a #, these are ignored by the server."); sb.AppendLine("#Commenting will NOT work unless the line STARTS with a '#'."); sb.AppendLine("#You can also indent the file with tabs or spaces."); sb.AppendLine("#Sections supported are required-files, optional-files, partslist, resource-blacklist and resource-whitelist."); sb.AppendLine("#The client will be required to have the files found in required-files, and they must match the SHA hash if specified (this is where part mod files and play-altering files should go, like KWRocketry or Ferram Aerospace Research#The client may have the files found in optional-files, but IF they do then they must match the SHA hash (this is where mods that do not affect other players should go, like EditorExtensions or part catalogue managers"); sb.AppendLine("#You cannot use both resource-blacklist AND resource-whitelist in the same file."); sb.AppendLine("#resource-blacklist bans ONLY the files you specify"); sb.AppendLine("#resource-whitelist bans ALL resources except those specified in the resource-whitelist section OR in the SHA sections. A file listed in resource-whitelist will NOT be checked for SHA hash. This is useful if you want a mod that modifies files in its own directory as you play."); sb.AppendLine("#Each section has its own type of formatting. Examples have been given."); sb.AppendLine("#Sections are defined as follows:"); sb.AppendLine(""); //Required section sb.AppendLine("!required-files"); sb.AppendLine("#To generate the SHA256 of a file you can use a utility such as this one: http://hash.online-convert.com/sha256-generator (use the 'hex' string), or use sha256sum on linux."); sb.AppendLine("#File paths are read from inside GameData."); sb.AppendLine("#If there is no SHA256 hash listed here (i.e. blank after the equals sign or no equals sign), SHA matching will not be enforced."); sb.AppendLine("#You may not specify multiple SHAs for the same file. Do not put spaces around equals sign. Follow the example carefully."); sb.AppendLine("#Syntax:"); sb.AppendLine("#[File Path]=[SHA] or [File Path]"); sb.AppendLine("#Example: MechJeb2/Plugins/MechJeb2.dll=B84BB63AE740F0A25DA047E5EDA35B26F6FD5DF019696AC9D6AF8FC3E031F0B9"); sb.AppendLine("#Example: MechJeb2/Plugins/MechJeb2.dll"); foreach (string requiredFile in requiredFiles) { sb.AppendLine(requiredFile); } sb.AppendLine(""); sb.AppendLine(""); sb.AppendLine("!optional-files"); sb.AppendLine("#Formatting for this section is the same as the 'required-files' section"); foreach (string optionalFile in optionalFiles) { sb.AppendLine(optionalFile); } sb.AppendLine(""); sb.AppendLine(""); //Whitelist or blacklist section if (isWhiteList) { sb.AppendLine("!resource-whitelist"); sb.AppendLine("#!resource-blacklist"); } else { sb.AppendLine("!resource-blacklist"); sb.AppendLine("#!resource-whitelist"); } sb.AppendLine("#Only select one of these modes."); sb.AppendLine("#Resource blacklist: clients will be allowed to use any dll's, So long as they are not listed in this section"); sb.AppendLine("#Resource whitelist: clients will only be allowed to use dll's listed here or in the 'required-files' and 'optional-files' sections."); sb.AppendLine("#Syntax:"); sb.AppendLine("#[File Path]"); sb.AppendLine("#Example: MechJeb2/Plugins/MechJeb2.dll"); foreach (string whitelistBlacklistFile in whitelistBlacklistFiles) { sb.AppendLine(whitelistBlacklistFile); } sb.AppendLine(""); sb.AppendLine(""); //Parts section sb.AppendLine("!partslist"); sb.AppendLine("#This is a list of parts to allow users to put on their ships."); sb.AppendLine("#If a part the client has doesn't appear on this list, they can still join the server but not use the part."); sb.AppendLine("#The default stock parts have been added already for you."); sb.AppendLine("#To add a mod part, add the name from the part's .cfg file. The name is the name from the PART{} section, where underscores are replaced with periods."); sb.AppendLine("#[partname]"); sb.AppendLine("#Example: mumech.MJ2.Pod (NOTE: In the part.cfg this MechJeb2 pod is named mumech_MJ2_Pod. The _ have been replaced with .)"); sb.AppendLine("#You can use this application to generate partlists from a KSP installation if you want to add mod parts: http://forum.kerbalspaceprogram.com/threads/57284 "); foreach (string partName in partsList) { sb.AppendLine(partName); } sb.AppendLine(""); return sb.ToString(); } } public enum CraftType { VAB, SPH, SUBASSEMBLY } public enum ClientMessageType { HEARTBEAT, HANDSHAKE_RESPONSE, CHAT_MESSAGE, PLAYER_STATUS, PLAYER_COLOR, SCENARIO_DATA, KERBALS_REQUEST, KERBAL_PROTO, VESSELS_REQUEST, VESSEL_PROTO, VESSEL_UPDATE, VESSEL_REMOVE, CRAFT_LIBRARY, SCREENSHOT_LIBRARY, FLAG_SYNC, SYNC_TIME_REQUEST, PING_REQUEST, MOTD_REQUEST, WARP_CONTROL, LOCK_SYSTEM, MOD_DATA, SPLIT_MESSAGE, CONNECTION_END } public enum ServerMessageType { HEARTBEAT, HANDSHAKE_CHALLANGE, HANDSHAKE_REPLY, SERVER_SETTINGS, CHAT_MESSAGE, PLAYER_STATUS, PLAYER_COLOR, PLAYER_JOIN, PLAYER_DISCONNECT, SCENARIO_DATA, KERBAL_REPLY, KERBAL_COMPLETE, VESSEL_LIST, VESSEL_PROTO, VESSEL_UPDATE, VESSEL_COMPLETE, VESSEL_REMOVE, CRAFT_LIBRARY, SCREENSHOT_LIBRARY, FLAG_SYNC, SET_SUBSPACE, SYNC_TIME_REPLY, PING_REPLY, MOTD_REPLY, WARP_CONTROL, ADMIN_SYSTEM, LOCK_SYSTEM, MOD_DATA, SPLIT_MESSAGE, CONNECTION_END } public enum ConnectionStatus { DISCONNECTED, CONNECTING, CONNECTED } public enum ClientState { DISCONNECTED, CONNECTING, CONNECTED, HANDSHAKING, AUTHENTICATED, TIME_SYNCING, TIME_SYNCED, SYNCING_KERBALS, KERBALS_SYNCED, SYNCING_VESSELS, VESSELS_SYNCED, TIME_LOCKING, TIME_LOCKED, STARTING, RUNNING, DISCONNECTING } public enum WarpMode { MCW_FORCE, MCW_VOTE, MCW_LOWEST, SUBSPACE_SIMPLE, SUBSPACE, NONE } public enum GameMode { SANDBOX, SCIENCE, CAREER } public enum ModControlMode { DISABLED, ENABLED_STOP_INVALID_PART_SYNC, ENABLED_STOP_INVALID_PART_LAUNCH } public enum WarpMessageType { //MCW_VOTE REQUEST_VOTE, REPLY_VOTE, //ALL CHANGE_WARP, //MCW_VOTE/FORCE REQUEST_CONTROLLER, RELEASE_CONTROLLER, //MCW_VOTE/FORCE/LOWEST IGNORE_WARP, SET_CONTROLLER, //ALL NEW_SUBSPACE, CHANGE_SUBSPACE, RELOCK_SUBSPACE, REPORT_RATE } public enum CraftMessageType { LIST, REQUEST_FILE, RESPOND_FILE, UPLOAD_FILE, ADD_FILE, DELETE_FILE, } public enum ScreenshotMessageType { NOTIFY, SEND_START_NOTIFY, WATCH, SCREENSHOT, } public enum ChatMessageType { LIST, JOIN, LEAVE, CHANNEL_MESSAGE, PRIVATE_MESSAGE, CONSOLE_MESSAGE } public enum AdminMessageType { LIST, ADD, REMOVE, } public enum LockMessageType { LIST, ACQUIRE, RELEASE, } public enum FlagMessageType { LIST, FLAG_DATA, UPLOAD_FILE, DELETE_FILE, } public enum PlayerColorMessageType { LIST, SET, } public class ClientMessage { public bool handled; public ClientMessageType type; public byte[] data; } public class ServerMessage { public ServerMessageType type; public byte[] data; } public class PlayerStatus { public string playerName; public string vesselText; public string statusText; } public class Subspace { public long serverClock; public double planetTime; public float subspaceSpeed; } public class PlayerWarpRate { public bool isPhysWarp = false; public int rateIndex = 0; public long serverClock = 0; public double planetTime = 0; } public enum HandshakeReply : int { HANDSHOOK_SUCCESSFULLY = 0, PROTOCOL_MISMATCH = 1, ALREADY_CONNECTED = 2, RESERVED_NAME = 3, INVALID_KEY = 4, PLAYER_BANNED = 5, SERVER_FULL = 6, NOT_WHITELISTED = 7, INVALID_PLAYERNAME = 98, MALFORMED_HANDSHAKE = 99 } public enum GameDifficulty : int { EASY, NORMAL, MODERATE, HARD, CUSTOM } }
/* Copyright (C) 2013-2015 MetaMorph Software, Inc Permission is hereby granted, free of charge, to any person obtaining a copy of this data, including any software or models in source or binary form, as well as any drawings, specifications, and documentation (collectively "the Data"), to deal in the Data without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Data, and to permit persons to whom the Data 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 Data. THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA. ======================= This version of the META tools is a fork of an original version produced by Vanderbilt University's Institute for Software Integrated Systems (ISIS). Their license statement: Copyright (C) 2011-2014 Vanderbilt University Developed with the sponsorship of the Defense Advanced Research Projects Agency (DARPA) and delivered to the U.S. Government with Unlimited Rights as defined in DFARS 252.227-7013. Permission is hereby granted, free of charge, to any person obtaining a copy of this data, including any software or models in source or binary form, as well as any drawings, specifications, and documentation (collectively "the Data"), to deal in the Data without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Data, and to permit persons to whom the Data 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 Data. THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA. */ using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Text; using GME.CSharp; using GME; using GME.MGA; using GME.MGA.Core; using System.Linq; using System.Drawing; using System.Windows.Forms; using CyPhy = ISIS.GME.Dsml.CyPhyML.Interfaces; using CyPhyClasses = ISIS.GME.Dsml.CyPhyML.Classes; using CyPhyGUIs; //using Complexity; namespace CyPhyComplexity { /// <summary> /// This class implements the necessary COM interfaces for a GME interpreter component. /// </summary> [Guid(ComponentConfig.guid), ProgId(ComponentConfig.progID), ClassInterface(ClassInterfaceType.AutoDual)] [ComVisible(true)] public class CyPhyComplexityInterpreter : IMgaComponentEx, IGMEVersionInfo, ICyPhyInterpreter { /// <summary> /// Contains information about the GUI event that initiated the invocation. /// </summary> public enum ComponentStartMode { GME_MAIN_START = 0, // Not used by GME GME_BROWSER_START = 1, // Right click in the GME Tree Browser window GME_CONTEXT_START = 2, // Using the context menu by right clicking a model element in the GME modeling window GME_EMBEDDED_START = 3, // Not used by GME GME_MENU_START = 16, // Clicking on the toolbar icon, or using the main menu GME_BGCONTEXT_START = 18, // Using the context menu by right clicking the background of the GME modeling window GME_ICON_START = 32, // Not used by GME GME_SILENT_MODE = 128 // Not used by GME, available to testers not using GME } /// <summary> /// This function is called for each interpreter invocation before Main. /// Don't perform MGA operations here unless you open a tansaction. /// </summary> /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param> public void Initialize(MgaProject project) { MgaGateway = new MgaGateway(project); project.CreateTerritoryWithoutSink(out MgaGateway.territory); } /// <summary> /// The main entry point of the interpreter. A transaction is already open, /// GMEConsole is available. A general try-catch block catches all the exceptions /// coming from this function, you don't need to add it. For more information, see InvokeEx. /// </summary> /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param> /// <param name="currentobj">The model open in the active tab in GME. Its value is null if no model is open (no GME modeling windows open). </param> /// <param name="selectedobjs"> /// A collection for the selected model elements. It is never null. /// If the interpreter is invoked by the context menu of the GME Tree Browser, then the selected items in the tree browser. Folders /// are never passed (they are not FCOs). /// If the interpreter is invoked by clicking on the toolbar icon or the context menu of the modeling window, then the selected items /// in the active GME modeling window. If nothing is selected, the collection is empty (contains zero elements). /// </param> /// <param name="startMode">Contains information about the GUI event that initiated the invocation.</param> [ComVisible(false)] public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode) { if (currentobj.Meta.Name == "TestBench") { CyPhy.TestBench tb = ISIS.GME.Common.Utils.CreateObject<CyPhyClasses.TestBench>(currentobj as MgaObject); //var sut = tb.Children.TopLevelSystemUnderTestCollection.FirstOrDefault(); //String s_sutName = sut.Name; CyPhy.ComponentAssembly sut = null; foreach (CyPhy.ComponentAssembly ca in tb.Children.ComponentAssemblyCollection) { if ((ca.Impl as MgaFCO).get_RegistryValue("ElaboratedModel") != "") sut = ca; } if (sut != null) { var dm = CyPhy2DesignInterchange.CyPhy2DesignInterchange.Convert(sut); //dm = MakeFakeModel(); //String json = dm.Serialize(); String json = XSD2CSharp.AvmXmlSerializer.Serialize(dm); int json_len = json.Length; dm.SaveToFile(Path.Combine(OutputDirectory, dm.Name + ".adm")); Complexity.Design cd = METADesignInterchange2ComplexityLib.METADesign2Complexity.Design2Complexity(dm); Dictionary<string,string> dCSV_output = cd.SerializeToCSVFormat(); foreach (KeyValuePair<string, string> kvp in dCSV_output) { String s_filePath = Path.Combine(OutputDirectory, kvp.Key); using (System.IO.StreamWriter sw = new System.IO.StreamWriter(s_filePath)) { sw.Write(kvp.Value); } } string mainPythonFilename = Path.Combine(OutputDirectory, "ComplexityMain.py"); string mainCmdFilename = Path.Combine(OutputDirectory, "RunComplexityEvaluator.cmd"); using (StreamWriter writer = new StreamWriter(mainPythonFilename)) { writer.WriteLine(CyPhyComplexity.Properties.Resources.ComplexityMain); } using (StreamWriter writer = new StreamWriter(mainCmdFilename)) { writer.WriteLine("call \"{0}\"", META_PATH_PYTHON_ACTIVATE); writer.WriteLine("python {0} Components.csv Connections.csv 1", mainPythonFilename); //writer.WriteLine(CyPhyComplexity.Properties.Resources.RunComplexityEvaluator); } if (dCSV_output.Count == 2) { result.RunCommand = "RunComplexityEvaluator.cmd"; } GMEConsole.Info.WriteLine( "Result files are here: <a href=\"file:///{0}\" target=\"_blank\">{0}</a>.", Path.GetFullPath(OutputDirectory)); } } } public string META_PATH { get; set; } public string META_PATH_PYTHON_ACTIVATE { get { return Path.Combine(META_PATH, "bin", "Python27", "Scripts", "activate.bat"); } } #region IMgaComponentEx Members MgaGateway MgaGateway { get; set; } GMEConsole GMEConsole { get; set; } public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param) { if (!enabled) { return; } if (currentobj == null) { GMEConsole = GMEConsole.CreateFromProject(project); GMEConsole.Warning.WriteLine("Please run in the context of a TestBench"); return; } // Make sure running within the context of a testbench bool inTBContext = false; MgaGateway.PerformInTransaction(delegate { if (currentobj.Meta.Name == "TestBench") { inTBContext = true; } }); if (!inTBContext) { GMEConsole = GMEConsole.CreateFromProject(project); GMEConsole.Warning.WriteLine("Please run in the context of a TestBench"); return; } // Need to get an output path from the user. using (META.FolderBrowserDialog fbd = new META.FolderBrowserDialog()) { fbd.Description = "Choose a path for the generated files."; //fbd.ShowNewFolderButton = true; DialogResult dr = fbd.ShowDialog(); if (dr == DialogResult.OK) { OutputDirectory = fbd.SelectedPath; } else { GMEConsole = GMEConsole.CreateFromProject(project); GMEConsole.Out.WriteLine("CyPhyComplexity: Operation cancelled"); return; } } try { CallElaboratorAndMain(project, currentobj, selectedobjs, param); } finally { if (MgaGateway.territory != null) { MgaGateway.territory.Destroy(); } MgaGateway = null; project = null; currentobj = null; selectedobjs = null; GMEConsole = null; GC.Collect(); GC.WaitForPendingFinalizers(); } } private void CallElaboratorAndMain(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param) { string keyName = @"HKEY_LOCAL_MACHINE\Software\META"; string value = @"META_PATH"; META_PATH = (string)Microsoft.Win32.Registry.GetValue( keyName, value, "ERROR: " + keyName + value + " does not exist!"); GMEConsole = GMEConsole.CreateFromProject(project); #region Elaborate the TestBench // call elaborator and expand the references Type t = Type.GetTypeFromProgID("MGA.Interpreter.CyPhyElaborate"); IMgaComponentEx elaborator = Activator.CreateInstance(t) as IMgaComponentEx; elaborator.Initialize(project); elaborator.ComponentParameter["automated_expand"] = "true"; elaborator.ComponentParameter["console_messages"] = "off"; elaborator.InvokeEx(project, currentobj, selectedobjs, (int)ComponentStartMode.GME_SILENT_MODE); #endregion MgaGateway.PerformInTransaction(delegate { Main(project, currentobj, selectedobjs, Convert(param)); }); } private ComponentStartMode Convert(int param) { switch (param) { case (int)ComponentStartMode.GME_BGCONTEXT_START: return ComponentStartMode.GME_BGCONTEXT_START; case (int)ComponentStartMode.GME_BROWSER_START: return ComponentStartMode.GME_BROWSER_START; case (int)ComponentStartMode.GME_CONTEXT_START: return ComponentStartMode.GME_CONTEXT_START; case (int)ComponentStartMode.GME_EMBEDDED_START: return ComponentStartMode.GME_EMBEDDED_START; case (int)ComponentStartMode.GME_ICON_START: return ComponentStartMode.GME_ICON_START; case (int)ComponentStartMode.GME_MAIN_START: return ComponentStartMode.GME_MAIN_START; case (int)ComponentStartMode.GME_MENU_START: return ComponentStartMode.GME_MENU_START; case (int)ComponentStartMode.GME_SILENT_MODE: return ComponentStartMode.GME_SILENT_MODE; } return ComponentStartMode.GME_SILENT_MODE; } #region Component Information public string ComponentName { get { return GetType().Name; } } public string ComponentProgID { get { return ComponentConfig.progID; } } public componenttype_enum ComponentType { get { return ComponentConfig.componentType; } } public string Paradigm { get { return ComponentConfig.paradigmName; } } #endregion #region Enabling bool enabled = true; public void Enable(bool newval) { enabled = newval; } #endregion #region Interactive Mode protected bool interactiveMode = true; public bool InteractiveMode { get { return interactiveMode; } set { interactiveMode = value; } } #endregion #region Custom Parameters SortedDictionary<string, object> componentParameters = new SortedDictionary<string,object>(); public object get_ComponentParameter(string Name) { if (Name == "type") return "csharp"; if (Name == "path") return GetType().Assembly.Location; if (Name == "fullname") return GetType().FullName; object value; if (componentParameters != null && componentParameters.TryGetValue(Name, out value)) { return value; } return null; } public void set_ComponentParameter(string Name, object pVal) { if (componentParameters == null) { componentParameters = new SortedDictionary<string, object>(); } componentParameters[Name] = pVal; } #endregion #region Unused Methods // Old interface, it is never called for MgaComponentEx interfaces public void Invoke(MgaProject Project, MgaFCOs selectedobjs, int param) { throw new NotImplementedException(); } // Not used by GME public void ObjectsInvokeEx(MgaProject Project, MgaObject currentobj, MgaObjects selectedobjs, int param) { throw new NotImplementedException(); } #endregion #endregion #region IMgaVersionInfo Members public GMEInterfaceVersion_enum version { get { return GMEInterfaceVersion_enum.GMEInterfaceVersion_Current; } } #endregion #region Registration Helpers [ComRegisterFunctionAttribute] public static void GMERegister(Type t) { Registrar.RegisterComponentsInGMERegistry(); } [ComUnregisterFunctionAttribute] public static void GMEUnRegister(Type t) { Registrar.UnregisterComponentsInGMERegistry(); } #endregion public string InterpreterConfigurationProgId { get { return null; } } public IInterpreterPreConfiguration PreConfig(IPreConfigParameters parameters) { return null; } public IInterpreterConfiguration DoGUIConfiguration(IInterpreterPreConfiguration preConfig, IInterpreterConfiguration previousConfig) { return new CyPhyGUIs.NullInterpreterConfiguration(); } private string OutputDirectory; private InterpreterResult result = new InterpreterResult(); public IInterpreterResult Main(IInterpreterMainParameters parameters) { OutputDirectory = parameters.OutputDirectory; CallElaboratorAndMain(parameters.Project, parameters.CurrentFCO, parameters.SelectedFCOs, parameters.StartModeParam); result.Success = true; return result; } } }
#region Apache License 2.0 // Copyright 2008-2009 Christian Rodemeyer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Linq; using System.Collections.Generic; using System.Reflection; using System.Threading; using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.Store; using SvnQuery.Lucene; using SvnQuery.Svn; using SvnQuery; namespace SvnIndex { /// <summary> /// Main class for creating and updating the repository index. /// </summary> public class Indexer { const int MaxNumberOfTermsPerDocument = 500000; const int MaxDocumentSize = 1024 * 1024; readonly IndexerArgs _args; readonly Directory _indexDirectory; readonly ISvnApi _svn; readonly PendingJobs _pendingAnalyzeJobs = new PendingJobs(); readonly PendingJobs _pendingFetchJobs = new PendingJobs(); readonly Dictionary<string, IndexJobData> _headJobs = new Dictionary<string, IndexJobData>(); readonly HighestRevision _highestRevision = new HighestRevision(); readonly ManualResetEvent _stopIndexThread = new ManualResetEvent(false); readonly Semaphore _indexQueueLimit; readonly Queue<IndexJobData> _indexQueue = new Queue<IndexJobData>(); readonly EventWaitHandle _indexQueueHasData = new ManualResetEvent(false); readonly EventWaitHandle _indexQueueIsEmpty = new ManualResetEvent(true); IndexWriter _indexWriter; FilteredTextWriter _indexWriterMessageFilter; // reused objects for faster indexing readonly Term _idTerm = new Term(FieldName.Id, ""); readonly Field _idField = new Field(FieldName.Id, "", Field.Store.YES, Field.Index.UN_TOKENIZED); readonly Field _revFirstField = new Field(FieldName.RevisionFirst, "", Field.Store.YES, Field.Index.UN_TOKENIZED); readonly Field _revLastField = new Field(FieldName.RevisionLast, "", Field.Store.YES, Field.Index.UN_TOKENIZED); readonly Field _sizeField = new Field(FieldName.Size, "", Field.Store.YES, Field.Index.UN_TOKENIZED); readonly Field _timestampField = new Field(FieldName.Timestamp, "", Field.Store.YES, Field.Index.NO); readonly Field _authorField = new Field(FieldName.Author, "", Field.Store.YES, Field.Index.UN_TOKENIZED); readonly Field _typeField = new Field(FieldName.MimeType, "", Field.Store.NO, Field.Index.UN_TOKENIZED); readonly Field _messageField; readonly Field _pathField; readonly Field _contentField; readonly Field _externalsField; readonly SimpleTokenStream _pathTokenStream = new PathTokenStream(""); readonly SimpleTokenStream _contentTokenStream = new SimpleTokenStream(""); readonly SimpleTokenStream _externalsTokenStream = new PathTokenStream(""); readonly SimpleTokenStream _messageTokenStream = new SimpleTokenStream(""); public enum Command { Create, Update, Check } ; class AnalyzeJobData { public PathChange Change; public bool Recursive; } public class IndexJobData { public string Path; public int RevisionFirst; public int RevisionLast; public PathInfo Info; public string Content; public IDictionary<string, string> Properties; } public Indexer(IndexerArgs args) { WriteLogo(); WriteArgs(); _args = args; _indexDirectory = FSDirectory.GetDirectory(args.IndexPath); _indexQueueLimit = new Semaphore(args.MaxThreads * 4, args.MaxThreads * 4); ThreadPool.SetMaxThreads(args.MaxThreads, 1000); ThreadPool.SetMinThreads(args.MaxThreads / 2, Environment.ProcessorCount); _contentField = new Field(FieldName.Content, _contentTokenStream); _pathField = new Field(FieldName.Path, _pathTokenStream); _externalsField = new Field(FieldName.Externals, _externalsTokenStream); _messageField = new Field(FieldName.Message, _messageTokenStream); _svn = new SharpSvnApi(args.RepositoryLocalUri, args.Credentials.User, args.Credentials.Password); } /// <summary> /// This constructor is intended for tests in RAMDirectory only /// </summary> public Indexer(IndexerArgs args, Directory dir) : this(args) { _indexDirectory = dir; } static void WriteLogo() { Console.WriteLine(); AssemblyName name = Assembly.GetExecutingAssembly().GetName(); Console.WriteLine(name.Name + " " + name.Version); } static void WriteArgs() { Console.WriteLine(); } public void Run() { Console.WriteLine("Begin indexing ..."); DateTime start = DateTime.UtcNow; int startRevision = 1; int stopRevision = Math.Min(_args.MaxRevision, _svn.GetYoungestRevision()); bool optimize; Thread indexThread = new Thread(ProcessIndexQueue); indexThread.Name = "IndexThread"; indexThread.IsBackground = true; indexThread.Start(); // setup message filter for index writer _indexWriterMessageFilter = new FilteredTextWriter(Console.Out, // only allow messages starting with "maxFieldLength" // example message: "maxFieldLength 500000 reached for field content, ignoring following tokens" line => line.ToString().StartsWith("maxFieldLength")); _indexWriterMessageFilter.DefaultLineLength = 256; using (_indexWriterMessageFilter) { if (Command.Create == _args.Command) { _indexWriter = CreateIndexWriter(true); IndexProperty.SetSingleRevision(_indexWriter, _args.SingleRevision); QueueAnalyzeJob(new PathChange {Path = "/", Revision = 1, Change = Change.Add}); // add root directory manually optimize = true; } else // Command.Update { IndexReader reader = IndexReader.Open(_indexDirectory); // important: create reader before creating indexWriter! _highestRevision.Reader = reader; startRevision = IndexProperty.GetRevision(reader) + 1; _args.SingleRevision = IndexProperty.GetSingleRevision(reader); if (_args.SingleRevision) Console.WriteLine("SingleRevision index"); _indexWriter = CreateIndexWriter(false); optimize = stopRevision % _args.Optimize == 0 || stopRevision - startRevision > _args.Optimize; } IndexProperty.SetRepositoryLocalUri(_indexWriter, _args.RepositoryLocalUri); IndexProperty.SetRepositoryExternalUri(_indexWriter, _args.RepositoryExternalUri); IndexProperty.SetRepositoryName(_indexWriter, _args.RepositoryName); IndexProperty.SetRepositoryCredentials(_indexWriter, _args.Credentials); while (startRevision <= stopRevision) { IndexRevisionRange(startRevision, Math.Min(startRevision + _args.CommitInterval - 1, stopRevision)); startRevision += _args.CommitInterval; if (startRevision <= stopRevision) { if (_highestRevision.Reader != null) _highestRevision.Reader.Close(); CommitIndex(); _highestRevision.Reader = IndexReader.Open(_indexDirectory); _indexWriter = CreateIndexWriter(false); } } _stopIndexThread.Set(); if (_highestRevision.Reader != null) _highestRevision.Reader.Close(); _highestRevision.Reader = null; if (optimize) { Console.WriteLine("Optimizing index ..."); _indexWriter.Optimize(); } CommitIndex(); } _indexWriterMessageFilter = null; TimeSpan time = DateTime.UtcNow - start; Console.WriteLine("Finished in {0:00}:{1:00}:{2:00}", time.Hours, time.Minutes, time.Seconds); } IndexWriter CreateIndexWriter(bool createNewIndex) { var indexWriter = new IndexWriter(_indexDirectory, false, null, createNewIndex); indexWriter.SetInfoStream(_indexWriterMessageFilter); indexWriter.SetMaxFieldLength(MaxNumberOfTermsPerDocument); return indexWriter; } void CommitIndex() { Console.WriteLine("Commit index"); _indexWriter.Close(); } void IndexRevisionRange(int startRevision, int stopRevision) { foreach (var data in _svn.GetRevisionData(startRevision, stopRevision)) { IndexJobData jobData = new IndexJobData(); if (!_args.SingleRevision) { jobData.Path = "$Revision " + data.Revision; jobData.RevisionFirst = data.Revision; jobData.RevisionLast = data.Revision; jobData.Info = new PathInfo(); jobData.Info.Author = data.Author; jobData.Info.Timestamp = data.Timestamp; QueueIndexJob(jobData); } data.Changes.ForEach(QueueAnalyzeJobRecursive); _pendingAnalyzeJobs.Wait(); } foreach (var job in _headJobs.Values) // no lock necessary because no analyzeJobs are running { QueueFetchJob(job); } _headJobs.Clear(); _pendingFetchJobs.Wait(); _indexQueueIsEmpty.WaitOne(); IndexProperty.SetRevision(_indexWriter, stopRevision); Console.WriteLine("Index revision is now " + stopRevision); } void QueueAnalyzeJobRecursive(PathChange change) { if (IgnorePath(change.Path)) return; QueueAnalyzeJob(new AnalyzeJobData {Change = change, Recursive = true}); } void QueueAnalyzeJob(PathChange change) { if (IgnorePath(change.Path)) return; QueueAnalyzeJob(new AnalyzeJobData {Change = change, Recursive = false}); } bool IgnorePath(string path) { return _args.Filter.IsMatch(path); } void QueueAnalyzeJob(AnalyzeJobData jobData) { _pendingAnalyzeJobs.Increment(); ThreadPool.QueueUserWorkItem(AnalyzeJob, jobData); } // The ThreadPool entry point for an AnalyzeJob. // ThreadPool Exceptions are catched by the AppDomain Unhandled Exception Handler void AnalyzeJob(object data) { AnalyzeJob((AnalyzeJobData) data); _pendingAnalyzeJobs.Decrement(); } void AnalyzeJob(AnalyzeJobData jobData) { string path = jobData.Change.Path; int revision = jobData.Change.Revision; if (_args.Verbosity > 3) Console.WriteLine("Analyze " + jobData.Change.Change.ToString().PadRight(7) + path + " " + revision); switch (jobData.Change.Change) { case Change.Add: AddPath(path, revision, jobData.Recursive && jobData.Change.IsCopy); break; case Change.Replace: DeletePath(path, revision, jobData.Recursive); AddPath(path, revision, jobData.Recursive && jobData.Change.IsCopy); break; case Change.Modify: DeletePath(path, revision, false); AddPath(path, revision, false); break; case Change.Delete: DeletePath(path, revision, jobData.Recursive); break; } } void AddPath(string path, int revision, bool recursive) { if (!_highestRevision.Set(path, revision)) return; IndexJobData jobData = new IndexJobData(); jobData.Path = path; jobData.RevisionFirst = revision; jobData.RevisionLast = Revision.Head; jobData.Info = _svn.GetPathInfo(path, revision); if (jobData.Info == null) return; // workaround for issues with forbidden characters in local repository access lock (_headJobs) _headJobs[path] = jobData; if (recursive && jobData.Info.IsDirectory) { _svn.ForEachChild(path, revision, Change.Add, QueueAnalyzeJob); } } void DeletePath(string path, int revision, bool recursive) { IndexJobData jobData; lock (_headJobs) _headJobs.TryGetValue(path, out jobData); if (jobData != null) { lock (_headJobs) _headJobs.Remove(path); } else { int highest = _highestRevision.Get(path); if (highest == 0) return; // an atomic delete inside a svn copy operation jobData = new IndexJobData(); jobData.Path = path; jobData.RevisionFirst = highest; jobData.Info = _svn.GetPathInfo(path, highest); } jobData.RevisionLast = revision - 1; _highestRevision.Set(path, 0); if (jobData.Info == null) return; // workaround for issues with forbidden characters in local repository access if (recursive && jobData.Info.IsDirectory) { _svn.ForEachChild(path, revision, Change.Delete, QueueAnalyzeJob); } QueueFetchJob(jobData); } void QueueFetchJob(IndexJobData jobData) { _pendingFetchJobs.Increment(); ThreadPool.QueueUserWorkItem(FetchJob, jobData); } // The ThreadPool entry point for an AnalyzeJob. // ThreadPool Exceptions are catched by the AppDomain Unhandled Exception Handler void FetchJob(object data) { FetchJob((IndexJobData) data); _pendingFetchJobs.Decrement(); } /// <summary> /// Fetches some more information from the repository for an item /// </summary> /// <param name="jobData"></param> void FetchJob(IndexJobData jobData) { if (!_args.SingleRevision || jobData.RevisionLast == Revision.Head) // don't fetch if this data would be deleted anyway { if (_args.Verbosity > 1) Console.WriteLine("Fetch " + jobData.Path + " " + jobData.RevisionFirst + ":" + jobData.RevisionLast); jobData.Properties = _svn.GetPathProperties(jobData.Path, jobData.RevisionFirst); if (IsIndexable(jobData)) { jobData.Content = _svn.GetPathContent(jobData.Path, jobData.RevisionFirst, jobData.Info.Size); } } QueueIndexJob(jobData); } bool IsIndexable(IndexJobData jobData) { if (jobData.Info.IsDirectory) return false; if (jobData.Info.Size <= 0 || jobData.Info.Size > MaxDocumentSize) return false; if (_args.IgnoreBinaryFilter.IsMatch(jobData.Path)) return true; string mime; return !jobData.Properties.TryGetValue("svn:mime-type", out mime) || mime.StartsWith("text/"); } void QueueIndexJob(IndexJobData jobData) { _indexQueueLimit.WaitOne(); lock (_indexQueue) { _indexQueue.Enqueue(jobData); _indexQueueHasData.Set(); _indexQueueIsEmpty.Reset(); } } /// <summary> /// processes the index queue until there are no more pending reads and the queue is empty /// </summary> void ProcessIndexQueue() { WaitHandle[] wait = new WaitHandle[] {_indexQueueHasData, _stopIndexThread}; while (wait[WaitHandle.WaitAny(wait)] != _stopIndexThread) { for (;;) { IndexJobData data; lock (_indexQueue) { if (_indexQueue.Count == 0) { _indexQueueHasData.Reset(); _indexQueueIsEmpty.Set(); break; } data = _indexQueue.Dequeue(); } _indexQueueLimit.Release(); IndexDocument(data); } } } void IndexDocument(IndexJobData data) { if (_args.Verbosity == 0 && data.Path[0] == '$') Console.WriteLine("Revision " + data.RevisionFirst); else Console.WriteLine("Index {0} {1}:{2}", data.Path, data.RevisionFirst, data.RevisionLast); string idText = data.Path[0] == '$' ? data.Path : data.Path + "@" + data.RevisionFirst; Term id = _idTerm.CreateTerm(idText); _indexWriter.DeleteDocuments(id); if (_args.SingleRevision && data.RevisionLast != Revision.Head) return; Document doc = MakeDocument(); _idField.SetValue(idText); _pathTokenStream.SetText(data.Path); _revFirstField.SetValue(data.RevisionFirst.ToString(RevisionFilter.RevFormat)); _revLastField.SetValue(data.RevisionLast.ToString(RevisionFilter.RevFormat)); _authorField.SetValue(data.Info.Author.ToLowerInvariant()); SetTimestampField(data.Info.Timestamp); _messageTokenStream.SetText(_svn.GetLogMessage(data.RevisionFirst)); if (!data.Info.IsDirectory) { _sizeField.SetValue(PackedSizeConverter.ToSortableString(data.Info.Size)); doc.Add(_sizeField); } _contentTokenStream.SetText(data.Content); if (!_contentTokenStream.IsEmpty) doc.Add(_contentField); IndexProperties(doc, data.Properties); _indexWriter.AddDocument(doc); } void SetTimestampField(DateTime dt) { _timestampField.SetValue(dt.ToString("yyyy-MM-dd hh:mm")); } void IndexProperties(Document doc, IDictionary<string, string> properties) { if (properties == null) return; foreach (var prop in properties) { if (prop.Key == "svn:externals") { doc.Add(_externalsField); _externalsTokenStream.SetText(prop.Value); } else if (prop.Key == "svn:mime-type") { doc.Add(_typeField); _typeField.SetValue(prop.Value); } else if (prop.Key == "svn:mergeinfo") { continue; // don't index } else { doc.Add(new Field(prop.Key, new SimpleTokenStream(prop.Value))); } } } Document MakeDocument() { var doc = new Document(); doc.Add(_idField); doc.Add(_revFirstField); doc.Add(_revLastField); doc.Add(_timestampField); doc.Add(_authorField); doc.Add(_messageField); doc.Add(_pathField); return doc; } } }
using System; using System.Collections.Generic; using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Bson.Serialization.Conventions; using MongoDB.Driver; using Audit.Core; using System.Linq; using System.Threading.Tasks; namespace Audit.MongoDB.Providers { /// <summary> /// Mongo DB data access /// </summary> /// <remarks> /// Settings: /// - ConnectionString: Mongo connection string /// - Database: Database name /// - Collection: Collection name /// - IgnoreElementNames: indicate whether the element names should be validated and fixed or not /// </remarks> public class MongoDataProvider : AuditDataProvider { static MongoDataProvider() { ConfigureBsonMapping(); } /// <summary> /// Gets or sets the MongoDB connection string. /// </summary> public string ConnectionString { get; set; } = "mongodb://localhost:27017"; /// <summary> /// Gets or sets the MongoDB Database name. /// </summary> public string Database { get; set; } = "Audit"; /// <summary> /// Gets or sets the MongoDB collection name. /// </summary> public string Collection { get; set; } = "Event"; /// <summary> /// Gets or sets a value to indicate whether the element names should be validated/fixed or not. /// If <c>true</c> the element names are not validated, use this when you know the element names will not contain invalid characters. /// If <c>false</c> (default) the element names are validated and fixed to avoid containing invalid characters. /// </summary> public bool IgnoreElementNames { get; set; } = false; /// <summary> /// Gets or sets a value indicating whether the target object and extra fields should be serialized as Bson. /// Default is false to serialize using the default JSON serializer from Audit.Core.Configiration.JsonAdapter /// </summary> /// <value><c>true</c> if should serialize as Bson; or <c>false</c> to serialize as Json.</value> public bool SerializeAsBson { get; set; } = false; public MongoDataProvider() { } public MongoDataProvider(Action<ConfigurationApi.IMongoProviderConfigurator> config) { var mongoConfig = new ConfigurationApi.MongoProviderConfigurator(); if (config != null) { config.Invoke(mongoConfig); Collection = mongoConfig._collection; ConnectionString = mongoConfig._connectionString; Database = mongoConfig._database; SerializeAsBson = mongoConfig._serializeAsBson; } } private static void ConfigureBsonMapping() { var pack = new ConventionPack { new IgnoreIfNullConvention(true) }; ConventionRegistry.Register("Ignore null properties for AuditEvent", pack, type => type == typeof(AuditEvent)); BsonClassMap.RegisterClassMap<AuditTarget>(cm => { cm.AutoMap(); }); BsonClassMap.RegisterClassMap<AuditEvent>(cm => { cm.AutoMap(); cm.MapExtraElementsField(c => c.CustomFields); }); } public override object InsertEvent(AuditEvent auditEvent) { var db = GetDatabase(); var col = db.GetCollection<BsonDocument>(Collection); SerializeExtraFields(auditEvent); var doc = ParseBson(auditEvent); if (!IgnoreElementNames) { FixDocumentElementNames(doc); } col.InsertOne(doc); return (BsonObjectId)doc["_id"]; } public async override Task<object> InsertEventAsync(AuditEvent auditEvent) { var db = GetDatabase(); var col = db.GetCollection<BsonDocument>(Collection); SerializeExtraFields(auditEvent); var doc = ParseBson(auditEvent); if (!IgnoreElementNames) { FixDocumentElementNames(doc); } await col.InsertOneAsync(doc); return (BsonObjectId)doc["_id"]; } public override void ReplaceEvent(object eventId, AuditEvent auditEvent) { var db = GetDatabase(); var col = db.GetCollection<BsonDocument>(Collection); SerializeExtraFields(auditEvent); var doc = ParseBson(auditEvent); if (!IgnoreElementNames) { FixDocumentElementNames(doc); } var filter = Builders<BsonDocument>.Filter.Eq("_id", (BsonObjectId)eventId); col.ReplaceOne(filter, doc); } public async override Task ReplaceEventAsync(object eventId, AuditEvent auditEvent) { var db = GetDatabase(); var col = db.GetCollection<BsonDocument>(Collection); SerializeExtraFields(auditEvent); var doc = ParseBson(auditEvent); if (!IgnoreElementNames) { FixDocumentElementNames(doc); } var filter = Builders<BsonDocument>.Filter.Eq("_id", (BsonObjectId)eventId); await col.ReplaceOneAsync(filter, doc); } private void SerializeExtraFields(AuditEvent auditEvent) { foreach(var k in auditEvent.CustomFields.Keys.ToList()) { auditEvent.CustomFields[k] = Serialize(auditEvent.CustomFields[k]); } } private BsonDocument ParseBson(AuditEvent auditEvent) { if (SerializeAsBson) { return auditEvent.ToBsonDocument(); } else { return BsonDocument.Parse(Core.Configuration.JsonAdapter.Serialize(auditEvent)); } } /// <summary> /// Fixes the document Element Names (avoid using dots '.' and starting with '$'). /// </summary> /// <param name="document">The document to fix.</param> private void FixDocumentElementNames(BsonDocument document) { var toRename = new List<Tuple<string, BsonValue, string>>(); foreach (var elem in document) { if (elem.Name.Contains(".") || elem.Name.StartsWith("$")) { var value = elem.Value; var name = elem.Name.Replace('.', '_'); if (name.StartsWith("$")) { name = "_" + name.Substring(1); } toRename.Add(new Tuple<string, BsonValue, string>(elem.Name, value, name)); } if (elem.Value != null) { if (elem.Value.IsBsonDocument) { FixDocumentElementNames(elem.Value as BsonDocument); } else if (elem.Value.IsBsonArray) { foreach (var sub in (elem.Value as BsonArray)) { if (sub.IsBsonDocument) { FixDocumentElementNames(sub as BsonDocument); } } } } } foreach (var x in toRename) { document.Remove(x.Item1); document.Add(new BsonElement(x.Item3, x.Item2)); } } public override object Serialize<T>(T value) { if (value == null) { return null; } if (SerializeAsBson) { if (value is BsonDocument) { return value; } return value.ToBsonDocument(typeof(object)); } else { return (T)Configuration.JsonAdapter.Deserialize(Configuration.JsonAdapter.Serialize(value), value.GetType()); } } public void TestConnection() { var db = GetDatabase(); var test = db.RunCommand((Command<BsonDocument>)"{ping:1}"); if (test["ok"].ToInt64() != 1) { throw new Exception("Can't connect to Audit Mongo Database."); } } private IMongoDatabase GetDatabase() { var client = new MongoClient(ConnectionString); var db = client.GetDatabase(Database); return db; } public override T GetEvent<T>(object eventId) { var client = new MongoClient(ConnectionString); var db = client.GetDatabase(Database); var filter = Builders<BsonDocument>.Filter.Eq("_id", (BsonObjectId)eventId); var doc = db.GetCollection<BsonDocument>(Collection).Find(filter).FirstOrDefault(); return doc == null ? null : BsonSerializer.Deserialize<T>(doc); } public override async Task<T> GetEventAsync<T>(object eventId) { var client = new MongoClient(ConnectionString); var db = client.GetDatabase(Database); var filter = Builders<BsonDocument>.Filter.Eq("_id", (BsonObjectId)eventId); var doc = await (await db.GetCollection<BsonDocument>(Collection).FindAsync(filter)).FirstOrDefaultAsync(); return doc == null ? null : BsonSerializer.Deserialize<T>(doc); } #region Events Query /// <summary> /// Returns an IQueryable that enables querying against the audit events stored on Azure Document DB. /// </summary> public IQueryable<AuditEvent> QueryEvents() { var client = new MongoClient(ConnectionString); var db = client.GetDatabase(Database); return db.GetCollection<AuditEvent>(Collection).AsQueryable(); } /// <summary> /// Returns an IQueryable that enables querying against the audit events stored on Azure Document DB, for the audit event type given. /// </summary> /// <typeparam name="T">The AuditEvent type</typeparam> public IQueryable<T> QueryEvents<T>() where T : AuditEvent { var client = new MongoClient(ConnectionString); var db = client.GetDatabase(Database); return db.GetCollection<T>(Collection).AsQueryable(); } /// <summary> /// Returns a native mongo collection of audit events /// </summary> public IMongoCollection<AuditEvent> GetMongoCollection() { var client = new MongoClient(ConnectionString); var db = client.GetDatabase(Database); return db.GetCollection<AuditEvent>(Collection); } /// <summary> /// Returns a native mongo collection of audit events /// </summary> public IMongoCollection<T> GetMongoCollection<T>() where T : AuditEvent { var client = new MongoClient(ConnectionString); var db = client.GetDatabase(Database); return db.GetCollection<T>(Collection); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using TigerTodoAp.Areas.HelpPage.ModelDescriptions; using TigerTodoAp.Areas.HelpPage.Models; namespace TigerTodoAp.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Data; using System.Globalization; using System.IO; using System.Text; using System.Xml; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Models.EntityBase; using Umbraco.Web; using umbraco.BasePages; using umbraco.BusinessLogic; using umbraco.BusinessLogic.Actions; using umbraco.cms.businesslogic.propertytype; using umbraco.cms.businesslogic.task; using umbraco.cms.businesslogic.translation; //using umbraco.cms.businesslogic.utilities; using umbraco.cms.businesslogic.web; using ICSharpCode.SharpZipLib.BZip2; using ICSharpCode.SharpZipLib.Zip; using ICSharpCode.SharpZipLib.Zip.Compression; using ICSharpCode.SharpZipLib.Zip.Compression.Streams; using ICSharpCode.SharpZipLib.GZip; using Umbraco.Core.IO; using System.Collections.Generic; namespace umbraco.presentation.translation { public partial class _default : UmbracoEnsuredPage { public _default() { CurrentApp = DefaultApps.translation.ToString(); } protected void Page_Load(object sender, EventArgs e) { DataTable tasks = new DataTable(); tasks.Columns.Add("Id"); tasks.Columns.Add("Date"); tasks.Columns.Add("NodeId"); tasks.Columns.Add("NodeName"); tasks.Columns.Add("ReferingUser"); tasks.Columns.Add("Language"); taskList.Columns[0].HeaderText = ui.Text("nodeName"); taskList.Columns[1].HeaderText = ui.Text("translation", "taskAssignedBy"); taskList.Columns[2].HeaderText = ui.Text("date"); ((System.Web.UI.WebControls.HyperLinkField)taskList.Columns[3]).Text = ui.Text("translation", "details"); ((System.Web.UI.WebControls.HyperLinkField)taskList.Columns[4]).Text = ui.Text("translation", "downloadTaskAsXml"); Tasks ts = new Tasks(); if (Request["mode"] == "owned") { ts = Task.GetOwnedTasks(base.getUser(), false); pane_tasks.Text = ui.Text("translation", "ownedTasks"); Panel2.Text = ui.Text("translation", "ownedTasks"); } else { ts = Task.GetTasks(base.getUser(), false); pane_tasks.Text = ui.Text("translation", "assignedTasks"); Panel2.Text = ui.Text("translation", "assignedTasks"); } uploadFile.Text = ui.Text("upload"); pane_uploadFile.Text = ui.Text("translation", "uploadTranslationXml"); foreach (Task t in ts) { if (t.Type.Alias == "toTranslate") { DataRow task = tasks.NewRow(); task["Id"] = t.Id; task["Date"] = t.Date; task["NodeId"] = t.Node.Id; task["NodeName"] = t.Node.Text; task["ReferingUser"] = t.ParentUser.Name; tasks.Rows.Add(task); } } taskList.DataSource = tasks; taskList.DataBind(); feedback.Style.Add("margin-top", "10px"); } protected void uploadFile_Click(object sender, EventArgs e) { // Save temp file if (translationFile.PostedFile != null) { string tempFileName; if (translationFile.PostedFile.FileName.ToLower().Contains(".zip")) tempFileName = IOHelper.MapPath(SystemDirectories.Data + "/" + "translationFile_" + Guid.NewGuid().ToString() + ".zip"); else tempFileName = IOHelper.MapPath(SystemDirectories.Data + "/" + "translationFile_" + Guid.NewGuid().ToString() + ".xml"); translationFile.PostedFile.SaveAs(tempFileName); // xml or zip file if (new FileInfo(tempFileName).Extension.ToLower() == ".zip") { // Zip Directory string tempPath = IOHelper.MapPath(SystemDirectories.Data + "/" + "translationFiles_" + Guid.NewGuid().ToString()); // Add the path to the zipfile to viewstate ViewState.Add("zipFile", tempPath); // Unpack the zip file cms.businesslogic.utilities.Zip.UnPack(tempFileName, tempPath, true); // Test the number of xml files try { StringBuilder sb = new StringBuilder(); foreach (FileInfo translationFileXml in new DirectoryInfo(ViewState["zipFile"].ToString()).GetFiles("*.xml")) { try { foreach (Task translation in ImportTranslatationFile(translationFileXml.FullName)) { sb.Append("<li>" + translation.Node.Text + " <a target=\"_blank\" href=\"preview.aspx?id=" + translation.Id + "\">" + ui.Text("preview") + "</a></li>"); } } catch (Exception ee) { sb.Append("<li style=\"color: red;\">" + ee.ToString() + "</li>"); } } feedback.type = global::umbraco.uicontrols.Feedback.feedbacktype.success; feedback.Text = "<h3>" + ui.Text("translation", "MultipleTranslationDone") + "</h3><p>" + ui.Text("translation", "translationDoneHelp") + "</p><ul>" + sb.ToString() + "</ul>"; } catch (Exception ex) { feedback.type = global::umbraco.uicontrols.Feedback.feedbacktype.error; feedback.Text = "<h3>" + ui.Text("translation", "translationFailed") + "</h3><p>" + ex.ToString() + "</>"; } } else { StringBuilder sb = new StringBuilder(); List<Task> l = ImportTranslatationFile(tempFileName); if (l.Count == 1) { feedback.type = global::umbraco.uicontrols.Feedback.feedbacktype.success; feedback.Text = "<h3>" + ui.Text("translation", "translationDone") + "</h3><p>" + ui.Text("translation", "translationDoneHelp") + "</p><p><a target=\"_blank\" href=\"preview.aspx?id=" + l[0].Id + "\">" + ui.Text("preview") + "</a></p>"; } else { foreach (Task t in l) { sb.Append("<li>" + t.Node.Text + " <a target=\"_blank\" href=\"preview.aspx?id=" + t.Id + "\">" + ui.Text("preview") + "</a></li>"); } feedback.type = global::umbraco.uicontrols.Feedback.feedbacktype.success; feedback.Text = "<h3>" + ui.Text("translation", "MultipleTranslationDone") + "</h3><p>" + ui.Text("translation", "translationDoneHelp") + "</p><ul>" + sb.ToString() + "</ul>"; } } // clean up File.Delete(tempFileName); } } private List<Task> ImportTranslatationFile(string tempFileName) { try { List<Task> tl = new List<Task>(); // open file XmlDocument tf = new XmlDocument(); tf.XmlResolver = null; tf.Load(tempFileName); // Get task xml node XmlNodeList tasks = tf.SelectNodes("//task"); foreach (XmlNode taskXml in tasks) { string xpath = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "node" : "* [@isDoc]"; XmlNode taskNode = taskXml.SelectSingleNode(xpath); // validate file Task t = new Task(int.Parse(taskXml.Attributes.GetNamedItem("Id").Value)); if (t != null) { //user auth and content node validation if (t.Node.Id == int.Parse(taskNode.Attributes.GetNamedItem("id").Value) && (t.User.Id == UmbracoUser.Id || t.ParentUser.Id == UmbracoUser.Id)) { // update node contents var d = new Document(t.Node.Id); Document.Import(d.ParentId, UmbracoUser, (XmlElement)taskNode); //send notifications! TODO: This should be put somewhere centralized instead of hard coded directly here ApplicationContext.Services.NotificationService.SendNotification(d.ContentEntity, ActionTranslate.Instance, ApplicationContext); t.Closed = true; t.Save(); tl.Add(t); } } } return tl; } catch (Exception ee) { throw new Exception("Error importing translation file '" + tempFileName + "': " + ee.ToString()); } } } }
// 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.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsRequiredOptional { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; public static partial class ExplicitModelExtensions { /// <summary> /// Test explicitly required integer. Please put null and the client library /// should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static Error PostRequiredIntegerParameter(this IExplicitModel operations, int? bodyParameter) { return Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredIntegerParameterAsync(bodyParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required integer. Please put null and the client library /// should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> PostRequiredIntegerParameterAsync( this IExplicitModel operations, int? bodyParameter, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.PostRequiredIntegerParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Test explicitly optional integer. Please put null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static void PostOptionalIntegerParameter(this IExplicitModel operations, int? bodyParameter = default(int?)) { Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalIntegerParameterAsync(bodyParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional integer. Please put null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PostOptionalIntegerParameterAsync( this IExplicitModel operations, int? bodyParameter = default(int?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PostOptionalIntegerParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test explicitly required integer. Please put a valid int-wrapper with /// 'value' = null and the client library should throw before the request is /// sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> public static Error PostRequiredIntegerProperty(this IExplicitModel operations, int? value) { return Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredIntegerPropertyAsync(value), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required integer. Please put a valid int-wrapper with /// 'value' = null and the client library should throw before the request is /// sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> PostRequiredIntegerPropertyAsync( this IExplicitModel operations, int? value, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.PostRequiredIntegerPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Test explicitly optional integer. Please put a valid int-wrapper with /// 'value' = null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> public static void PostOptionalIntegerProperty(this IExplicitModel operations, int? value = default(int?)) { Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalIntegerPropertyAsync(value), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional integer. Please put a valid int-wrapper with /// 'value' = null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PostOptionalIntegerPropertyAsync( this IExplicitModel operations, int? value = default(int?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PostOptionalIntegerPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test explicitly required integer. Please put a header 'headerParameter' /// =&gt; null and the client library should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> public static Error PostRequiredIntegerHeader(this IExplicitModel operations, int? headerParameter) { return Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredIntegerHeaderAsync(headerParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required integer. Please put a header 'headerParameter' /// =&gt; null and the client library should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> PostRequiredIntegerHeaderAsync( this IExplicitModel operations, int? headerParameter, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.PostRequiredIntegerHeaderWithHttpMessagesAsync(headerParameter, null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Test explicitly optional integer. Please put a header 'headerParameter' /// =&gt; null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> public static void PostOptionalIntegerHeader(this IExplicitModel operations, int? headerParameter = default(int?)) { Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalIntegerHeaderAsync(headerParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional integer. Please put a header 'headerParameter' /// =&gt; null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PostOptionalIntegerHeaderAsync( this IExplicitModel operations, int? headerParameter = default(int?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PostOptionalIntegerHeaderWithHttpMessagesAsync(headerParameter, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test explicitly required string. Please put null and the client library /// should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static Error PostRequiredStringParameter(this IExplicitModel operations, string bodyParameter) { return Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredStringParameterAsync(bodyParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required string. Please put null and the client library /// should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> PostRequiredStringParameterAsync( this IExplicitModel operations, string bodyParameter, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.PostRequiredStringParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Test explicitly optional string. Please put null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static void PostOptionalStringParameter(this IExplicitModel operations, string bodyParameter = default(string)) { Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalStringParameterAsync(bodyParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional string. Please put null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PostOptionalStringParameterAsync( this IExplicitModel operations, string bodyParameter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PostOptionalStringParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test explicitly required string. Please put a valid string-wrapper with /// 'value' = null and the client library should throw before the request is /// sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> public static Error PostRequiredStringProperty(this IExplicitModel operations, string value) { return Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredStringPropertyAsync(value), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required string. Please put a valid string-wrapper with /// 'value' = null and the client library should throw before the request is /// sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> PostRequiredStringPropertyAsync( this IExplicitModel operations, string value, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.PostRequiredStringPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Test explicitly optional integer. Please put a valid string-wrapper with /// 'value' = null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> public static void PostOptionalStringProperty(this IExplicitModel operations, string value = default(string)) { Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalStringPropertyAsync(value), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional integer. Please put a valid string-wrapper with /// 'value' = null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PostOptionalStringPropertyAsync( this IExplicitModel operations, string value = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PostOptionalStringPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test explicitly required string. Please put a header 'headerParameter' /// =&gt; null and the client library should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> public static Error PostRequiredStringHeader(this IExplicitModel operations, string headerParameter) { return Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredStringHeaderAsync(headerParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required string. Please put a header 'headerParameter' /// =&gt; null and the client library should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> PostRequiredStringHeaderAsync( this IExplicitModel operations, string headerParameter, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.PostRequiredStringHeaderWithHttpMessagesAsync(headerParameter, null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Test explicitly optional string. Please put a header 'headerParameter' /// =&gt; null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static void PostOptionalStringHeader(this IExplicitModel operations, string bodyParameter = default(string)) { Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalStringHeaderAsync(bodyParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional string. Please put a header 'headerParameter' /// =&gt; null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PostOptionalStringHeaderAsync( this IExplicitModel operations, string bodyParameter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PostOptionalStringHeaderWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test explicitly required complex object. Please put null and the client /// library should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static Error PostRequiredClassParameter(this IExplicitModel operations, Product bodyParameter) { return Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredClassParameterAsync(bodyParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required complex object. Please put null and the client /// library should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> PostRequiredClassParameterAsync( this IExplicitModel operations, Product bodyParameter, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.PostRequiredClassParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Test explicitly optional complex object. Please put null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static void PostOptionalClassParameter(this IExplicitModel operations, Product bodyParameter = default(Product)) { Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalClassParameterAsync(bodyParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional complex object. Please put null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PostOptionalClassParameterAsync( this IExplicitModel operations, Product bodyParameter = default(Product), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PostOptionalClassParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test explicitly required complex object. Please put a valid class-wrapper /// with 'value' = null and the client library should throw before the /// request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> public static Error PostRequiredClassProperty(this IExplicitModel operations, Product value) { return Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredClassPropertyAsync(value), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required complex object. Please put a valid class-wrapper /// with 'value' = null and the client library should throw before the /// request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> PostRequiredClassPropertyAsync( this IExplicitModel operations, Product value, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.PostRequiredClassPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Test explicitly optional complex object. Please put a valid class-wrapper /// with 'value' = null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> public static void PostOptionalClassProperty(this IExplicitModel operations, Product value = default(Product)) { Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalClassPropertyAsync(value), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional complex object. Please put a valid class-wrapper /// with 'value' = null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PostOptionalClassPropertyAsync( this IExplicitModel operations, Product value = default(Product), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PostOptionalClassPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test explicitly required array. Please put null and the client library /// should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static Error PostRequiredArrayParameter(this IExplicitModel operations, IList<string> bodyParameter) { return Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredArrayParameterAsync(bodyParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required array. Please put null and the client library /// should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> PostRequiredArrayParameterAsync( this IExplicitModel operations, IList<string> bodyParameter, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.PostRequiredArrayParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Test explicitly optional array. Please put null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static void PostOptionalArrayParameter(this IExplicitModel operations, IList<string> bodyParameter = default(IList<string>)) { Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalArrayParameterAsync(bodyParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional array. Please put null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PostOptionalArrayParameterAsync( this IExplicitModel operations, IList<string> bodyParameter = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PostOptionalArrayParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test explicitly required array. Please put a valid array-wrapper with /// 'value' = null and the client library should throw before the request is /// sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> public static Error PostRequiredArrayProperty(this IExplicitModel operations, IList<string> value) { return Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredArrayPropertyAsync(value), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required array. Please put a valid array-wrapper with /// 'value' = null and the client library should throw before the request is /// sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> PostRequiredArrayPropertyAsync( this IExplicitModel operations, IList<string> value, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.PostRequiredArrayPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Test explicitly optional array. Please put a valid array-wrapper with /// 'value' = null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> public static void PostOptionalArrayProperty(this IExplicitModel operations, IList<string> value = default(IList<string>)) { Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalArrayPropertyAsync(value), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional array. Please put a valid array-wrapper with /// 'value' = null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PostOptionalArrayPropertyAsync( this IExplicitModel operations, IList<string> value = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PostOptionalArrayPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test explicitly required array. Please put a header 'headerParameter' /// =&gt; null and the client library should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> public static Error PostRequiredArrayHeader(this IExplicitModel operations, IList<string> headerParameter) { return Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredArrayHeaderAsync(headerParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required array. Please put a header 'headerParameter' /// =&gt; null and the client library should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> PostRequiredArrayHeaderAsync( this IExplicitModel operations, IList<string> headerParameter, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.PostRequiredArrayHeaderWithHttpMessagesAsync(headerParameter, null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Test explicitly optional integer. Please put a header 'headerParameter' /// =&gt; null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> public static void PostOptionalArrayHeader(this IExplicitModel operations, IList<string> headerParameter = default(IList<string>)) { Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalArrayHeaderAsync(headerParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional integer. Please put a header 'headerParameter' /// =&gt; null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PostOptionalArrayHeaderAsync( this IExplicitModel operations, IList<string> headerParameter = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PostOptionalArrayHeaderWithHttpMessagesAsync(headerParameter, null, cancellationToken).ConfigureAwait(false); } } }
using System.IO; using System.Linq; using System.Threading.Tasks; using Telegram.Bot.Tests.Integ.Framework; using Telegram.Bot.Tests.Integ.Framework.Fixtures; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using Xunit; namespace Telegram.Bot.Tests.Integ.Sending_Messages { [Collection(Constants.TestCollections.AlbumMessage)] [TestCaseOrderer(Constants.TestCaseOrderer, Constants.AssemblyName)] public class AlbumMessageTests : IClassFixture<EntitiesFixture<Message>> { private ITelegramBotClient BotClient => _fixture.BotClient; private readonly EntitiesFixture<Message> _classFixture; private readonly TestsFixture _fixture; public AlbumMessageTests(TestsFixture testsFixture, EntitiesFixture<Message> classFixture) { _fixture = testsFixture; _classFixture = classFixture; } [OrderedFact(DisplayName = FactTitles.ShouldUploadPhotosInAlbum)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.SendMediaGroup)] public async Task Should_Upload_2_Photos_Album() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldUploadPhotosInAlbum); Message[] messages; using (Stream stream1 = System.IO.File.OpenRead(Constants.FileNames.Photos.Logo), stream2 = System.IO.File.OpenRead(Constants.FileNames.Photos.Bot) ) { IAlbumInputMedia[] inputMedia = { new InputMediaPhoto(new InputMedia(stream1, "logo.png")) { Caption = "Logo" }, new InputMediaPhoto(new InputMedia(stream2, "bot.gif")) { Caption = "Bot" }, }; messages = await BotClient.SendMediaGroupAsync( /* inputMedia: */ inputMedia, /* chatId: */ _fixture.SupergroupChat.Id, /* disableNotification: */ true ); } Assert.Equal(2, messages.Length); Assert.All(messages, msg => Assert.Equal(MessageType.Photo, msg.Type)); // All media messages have the same mediaGroupId Assert.NotEmpty(messages.Select(m => m.MediaGroupId)); Assert.True(messages.Select(msg => msg.MediaGroupId).Distinct().Count() == 1); Assert.Equal("Logo", messages[0].Caption); Assert.Equal("Bot", messages[1].Caption); _classFixture.Entities = messages.ToList(); } [OrderedFact(DisplayName = FactTitles.ShouldSendFileIdPhotosInAlbum)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.SendMediaGroup)] public async Task Should_Send_3_Photos_Album_Using_FileId() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldSendFileIdPhotosInAlbum); // Take file_id of photos uploaded in previous test case string[] fileIds = _classFixture.Entities .Select(msg => msg.Photo.First().FileId) .ToArray(); Message[] messages = await BotClient.SendMediaGroupAsync( chatId: _fixture.SupergroupChat.Id, inputMedia: new[] { new InputMediaPhoto(fileIds[0]), new InputMediaPhoto(fileIds[1]), new InputMediaPhoto(fileIds[0]), } ); Assert.Equal(3, messages.Length); Assert.All(messages, msg => Assert.Equal(MessageType.Photo, msg.Type)); } [OrderedFact(DisplayName = FactTitles.ShouldSendUrlPhotosInAlbum)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.SendMediaGroup)] public async Task Should_Send_Photo_Album_Using_Url() { // ToDo add exception: Bad Request: failed to get HTTP URL content await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldSendUrlPhotosInAlbum); int replyToMessageId = _classFixture.Entities.First().MessageId; Message[] messages = await BotClient.SendMediaGroupAsync( /* inputMedia: */ new[] { new InputMediaPhoto("https://cdn.pixabay.com/photo/2017/06/20/19/22/fuchs-2424369_640.jpg"), new InputMediaPhoto("https://cdn.pixabay.com/photo/2017/04/11/21/34/giraffe-2222908_640.jpg"), }, /* chatId: */ _fixture.SupergroupChat.Id, replyToMessageId: replyToMessageId ); Assert.Equal(2, messages.Length); Assert.All(messages, msg => Assert.Equal(MessageType.Photo, msg.Type)); Assert.All(messages, msg => Assert.Equal(replyToMessageId, msg.ReplyToMessage.MessageId)); } [OrderedFact(DisplayName = FactTitles.ShouldUploadVideosInAlbum)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.SendMediaGroup)] public async Task Should_Upload_2_Videos_Album() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldUploadVideosInAlbum); Message[] messages; using (Stream stream0 = System.IO.File.OpenRead(Constants.FileNames.Videos.GoldenRatio), stream1 = System.IO.File.OpenRead(Constants.FileNames.Videos.MoonLanding), stream2 = System.IO.File.OpenRead(Constants.FileNames.Photos.Bot) ) { IAlbumInputMedia[] inputMedia = { new InputMediaVideo(new InputMedia(stream0, "GoldenRatio.mp4")) { Caption = "Golden Ratio", Height = 240, Width = 240, Duration = 28, }, new InputMediaVideo(new InputMedia(stream1, "MoonLanding.mp4")) { Caption = "Moon Landing" }, new InputMediaPhoto(new InputMedia(stream2, "bot.gif")) { Caption = "Bot" }, }; messages = await BotClient.SendMediaGroupAsync( chatId: _fixture.SupergroupChat.Id, inputMedia: inputMedia ); } Assert.Equal(3, messages.Length); Assert.Equal(MessageType.Video, messages[0].Type); Assert.Equal("Golden Ratio", messages[0].Caption); Assert.Equal(240, messages[0].Video.Width); Assert.Equal(240, messages[0].Video.Height); Assert.InRange(messages[0].Video.Duration, 28 - 2, 28 + 2); Assert.Equal(MessageType.Video, messages[1].Type); Assert.Equal("Moon Landing", messages[1].Caption); Assert.Equal(MessageType.Photo, messages[2].Type); Assert.Equal("Bot", messages[2].Caption); } [OrderedFact(DisplayName = FactTitles.ShouldUpload2PhotosAlbumWithMarkdownEncodedCaptions)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.SendMediaGroup)] public async Task Should_Upload_2_Photos_Album_With_Markdown_Encoded_Captions() { await _fixture.SendTestCaseNotificationAsync(FactTitles .ShouldUpload2PhotosAlbumWithMarkdownEncodedCaptions); Message[] messages; using (Stream stream1 = System.IO.File.OpenRead(Constants.FileNames.Photos.Logo), stream2 = System.IO.File.OpenRead(Constants.FileNames.Photos.Bot) ) { IAlbumInputMedia[] inputMedia = { new InputMediaPhoto(new InputMedia(stream1, "logo.png")) { Caption = "*Logo*", ParseMode = ParseMode.Markdown }, new InputMediaPhoto(new InputMedia(stream2, "bot.gif")) { Caption = "_Bot_", ParseMode = ParseMode.Markdown }, }; messages = await BotClient.SendMediaGroupAsync( chatId: _fixture.SupergroupChat.Id, inputMedia: inputMedia ); } Assert.Equal("Logo", messages[0].CaptionEntityValues.Single()); Assert.Equal(MessageEntityType.Bold, messages[0].CaptionEntities.Single().Type); Assert.Equal("Bot", messages[1].CaptionEntityValues.Single()); Assert.Equal(MessageEntityType.Italic, messages[1].CaptionEntities.Single().Type); } [OrderedFact(DisplayName = FactTitles.ShouldSendVideoWithThumb)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.SendMediaGroup)] public async Task Should_Video_With_Thumbnail_In_Album() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldSendVideoWithThumb); Message[] messages; using (Stream stream1 = System.IO.File.OpenRead(Constants.FileNames.Videos.GoldenRatio), stream2 = System.IO.File.OpenRead(Constants.FileNames.Thumbnail.Video) ) { IAlbumInputMedia[] inputMedia = { new InputMediaVideo(new InputMedia(stream1, "GoldenRatio.mp4")) { Thumb = new InputMedia(stream2, "thumbnail.jpg"), SupportsStreaming = true, }, new InputMediaPhoto("https://cdn.pixabay.com/photo/2017/04/11/21/34/giraffe-2222908_640.jpg"), }; messages = await BotClient.SendMediaGroupAsync( /* media: */ inputMedia, /* chatId: */ _fixture.SupergroupChat.Id ); } Assert.Equal(MessageType.Video, messages[0].Type); Assert.NotNull(messages[0].Video.Thumb); } private static class FactTitles { public const string ShouldUploadPhotosInAlbum = "Should upload 2 photos with captions and send them in an album"; public const string ShouldSendFileIdPhotosInAlbum = "Should send an album with 3 photos using their file_id"; public const string ShouldSendUrlPhotosInAlbum = "Should send an album using HTTP urls in reply to 1st album message"; public const string ShouldUploadVideosInAlbum = "Should upload 2 videos and a photo with captions and send them in an album"; public const string ShouldUpload2PhotosAlbumWithMarkdownEncodedCaptions = "Should upload 2 photos with markdown encoded captions and send them in an album"; public const string ShouldSendVideoWithThumb = "Should send a video with thumbnail in an album"; } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // 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 Microsoft.PowerShell.PackageManagement.Cmdlets { using System; using System.Globalization; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Management.Automation; using System.Management.Automation.Language; using System.Security; using System.Threading; using Microsoft.PackageManagement.Implementation; using Microsoft.PackageManagement.Internal.Api; using Microsoft.PackageManagement.Internal.Implementation; using Microsoft.PackageManagement.Internal.Packaging; using Microsoft.PackageManagement.Internal.Utility.Async; using Microsoft.PackageManagement.Internal.Utility.Collections; using Microsoft.PackageManagement.Internal.Utility.Extensions; using Microsoft.PackageManagement.Packaging; using Utility; using CollectionExtensions = Microsoft.PackageManagement.Internal.Utility.Extensions.CollectionExtensions; using Constants = PackageManagement.Constants; using DictionaryExtensions = Microsoft.PackageManagement.Internal.Utility.Extensions.DictionaryExtensions; using Directory = System.IO.Directory; using FilesystemExtensions = Microsoft.PackageManagement.Internal.Utility.Extensions.FilesystemExtensions; public abstract class CmdletWithSearchAndSource : CmdletWithSearch { internal readonly OrderedDictionary<string, List<SoftwareIdentity>> _resultsPerName = new OrderedDictionary<string, List<SoftwareIdentity>>(); protected List<PackageProvider> _providersNotFindingAnything = new List<PackageProvider>(); #if CORECLR internal static readonly string[] ProviderFilters = new[] { "Packagemanagement", "Provider", "PSEdition_Core" }; #else internal static readonly string[] ProviderFilters = new[] { "Packagemanagement", "Provider" }; #endif protected const string Bootstrap = "Bootstrap"; protected const string PowerShellGet = "PowerShellGet"; internal static readonly string[] RequiredProviders = new[] { Bootstrap, PowerShellGet }; private readonly HashSet<string> _sourcesTrusted = new HashSet<string>(); private readonly HashSet<string> _sourcesDeniedTrust = new HashSet<string>(); private bool _yesToAll = false; private bool _noToAll = false; protected CmdletWithSearchAndSource(OptionCategory[] categories) : base(categories) { } private string[] _sources; [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "It's a performance thing.")] [Parameter(ValueFromPipelineByPropertyName = true)] public virtual string[] Source { get { return _sources; } set { _sources = value; if (_sources != null && _sources.Length != 0) { ProviderInfo providerInfo; _sources = _sources.SelectMany(source => { if (source.Equals(".")) { source = ".\\"; } //Need to resolve the path created via psdrive. //e.g., New-PSDrive -Name x -PSProvider FileSystem -Root \\foobar\myfolder. Here we are resolving x:\ try { if (FilesystemExtensions.LooksLikeAFilename(source)) { var resolvedPaths = GetResolvedProviderPathFromPSPath(source, out providerInfo); // Ensure the path is a single path from the file system provider if ((providerInfo != null) && (resolvedPaths.Count == 1) && String.Equals(providerInfo.Name, "FileSystem", StringComparison.OrdinalIgnoreCase)) { return resolvedPaths[0].SingleItemAsEnumerable(); } } } catch (Exception) { //allow to continue handling the cases other than file system } return source.SingleItemAsEnumerable(); }).ToArray(); } } } [Parameter] public virtual PSCredential Credential {get; set;} [Parameter] [ValidateNotNull()] public Uri Proxy { get; set; } [Parameter] [ValidateNotNull()] public PSCredential ProxyCredential { get; set; } public override IEnumerable<string> Sources { get { if (CollectionExtensions.IsNullOrEmpty(Source)) { return Microsoft.PackageManagement.Internal.Constants.Empty; } return Source; } } /* protected override IEnumerable<PackageProvider> SelectedProviders { get { // filter on provider names - if they specify a provider name, narrow to only those provider names. var providers = SelectProviders(ProviderName).ReEnumerable(); // filter out providers that don't have the sources that have been specified (only if we have specified a source!) if (Source != null && Source.Length > 0) { // sources must actually match a name or location. Keeps providers from being a bit dishonest var potentialSources = providers.SelectMany(each => each.ResolvePackageSources(this.SuppressErrorsAndWarnings(IsProcessing)).Where(source => Source.ContainsAnyOfIgnoreCase(source.Name, source.Location))).ReEnumerable(); // prefer registered sources var registeredSources = potentialSources.Where(source => source.IsRegistered).ReEnumerable(); providers = registeredSources.Any() ? registeredSources.Select(source => source.Provider).Distinct().ReEnumerable() : potentialSources.Select(source => source.Provider).Distinct().ReEnumerable(); } // filter on: dynamic options - if they specify any dynamic options, limit the provider set to providers with those options. return FilterProvidersUsingDynamicParameters(providers).ToArray(); } } */ /// <summary> /// Returns web proxy that provider can use /// Construct the webproxy using InternalWebProxy /// </summary> public override System.Net.IWebProxy WebProxy { get { if (Proxy != null) { return new PackageManagement.Utility.InternalWebProxy(Proxy, ProxyCredential == null ? null : ProxyCredential.GetNetworkCredential()); } return null; } } public override string CredentialUsername { get { return Credential != null ? Credential.UserName : null; } } public override SecureString CredentialPassword { get { return Credential != null ? Credential.Password : null; } } public override bool ProcessRecordAsync() { // record the names in the collection. if (!CollectionExtensions.IsNullOrEmpty(Name)) { foreach (var name in Name) { DictionaryExtensions.GetOrAdd(_resultsPerName, name, () => null); } } // it's searching for packages. // we need to do the actual search for the packages now, // and hold the results until EndProcessingAsync() // where we can determine if we we have no ambiguity left. SearchForPackages(); return true; } private MutableEnumerable<string> FindFiles(string path) { if (FilesystemExtensions.LooksLikeAFilename(path)) { ProviderInfo providerInfo; var paths = GetResolvedProviderPathFromPSPath(path, out providerInfo).ReEnumerable(); return paths.SelectMany( each => FilesystemExtensions.FileExists(each) ? CollectionExtensions.SingleItemAsEnumerable(each) : FilesystemExtensions.DirectoryExists(each) ? Directory.GetFiles(each) : Microsoft.PackageManagement.Internal.Constants.Empty) .ReEnumerable(); } return Microsoft.PackageManagement.Internal.Constants.Empty.ReEnumerable(); } protected bool SpecifiedMinimumOrMaximum { get { return !string.IsNullOrWhiteSpace(MaximumVersion) || !string.IsNullOrWhiteSpace(MinimumVersion); } } private List<Uri> _uris = new List<Uri>(); private Dictionary<string, Tuple<List<string>, byte[]>> _files = new Dictionary<string, Tuple<List<string>, byte[]>>(StringComparer.OrdinalIgnoreCase); private IEnumerable<string> _names; private bool IsUri(string name) { Uri packageUri; if (Uri.TryCreate(name, UriKind.Absolute, out packageUri)) { // if it's an uri, then we search via uri or file! if (!packageUri.IsFile) { _uris.Add(packageUri); return true; } } return false; } private bool IsFile(string name) { var files = FindFiles(name); if (files.Any()) { foreach (var f in files) { if (_files.ContainsKey(f)) { // if we've got this file already by another parameter, just update it to // keep track that we've somehow got it twice. _files[f].Item1.Add(name); } else { // otherwise, lets' grab the first chunk of this file so we can check what providers // can handle it (later) DictionaryExtensions.Add(_files, f, new List<string> { name }, FilesystemExtensions.ReadBytes(f, 1024)); } } return true; } return false; } protected virtual IHostApi GetProviderSpecificOption(PackageProvider pv) { return this.ProviderSpecific(pv); } protected virtual bool EnsurePackageIsProvider(SoftwareIdentity package) { return true; } protected override string BootstrapNuGet { get { //find, install, save- inherits from this class. They all need bootstrap NuGet if does not exists. return "true"; } } /// <summary> /// Validate if the package is a provider package. /// </summary> /// <param name="package"></param> /// <returns></returns> protected bool ValidatePackageProvider(SoftwareIdentity package) { //no need to filter on the packages from the bootstrap site as only providers will be published out there. if (package.ProviderName.EqualsIgnoreCase("Bootstrap")) { return true; } //get the tags info from the package's swid var tags = package.Metadata["tags"].ToArray(); //Check if the provider has provider tags var found = false; foreach (var filter in ProviderFilters) { found = false; if (tags.Any(tag => tag.ContainsIgnoreCase(filter))) { found = true; } else { break; } } return found; } private void ProcessRequests(PackageProvider[] providers) { if (providers == null || providers.Length == 0) { return; } var requests = providers.SelectMany(pv => { Verbose(Resources.Messages.SelectedProviders, pv.ProviderName); // for a given provider, if we get an error, we want just that provider to stop. var host = GetProviderSpecificOption(pv); var a = _uris.Select(uri => new { query = new List<string> { uri.AbsolutePath }, provider = pv, packages = pv.FindPackageByUri(uri, host).CancelWhen(CancellationEvent.Token) }); var b = _files.Keys.Where(file => pv.IsSupportedFile(_files[file].Item2)).Select(file => new { query = _files[file].Item1, provider = pv, packages = pv.FindPackageByFile(file, host) }); var c = _names.Select(name => new { query = new List<string> { name }, provider = pv, packages = pv.FindPackage(name, RequiredVersion, MinimumVersion, MaximumVersion, (Sources != null && Sources.Count() > 1) ? host.SuppressErrorsAndWarnings(IsProcessing) : host) }); return a.Concat(b).Concat(c); }).ToArray(); Debug("Calling SearchForPackages After Select {0}", requests.Length); if (AllVersions || !SpecifiedMinimumOrMaximum) { // the user asked for every version or they didn't specify any version ranges // either way, that means that we can just return everything that we're finding. while (WaitForActivity(requests.Select(each => each.packages))) { // keep processing while any of the the queries is still going. foreach (var result in requests.Where(each => each.packages.HasData)) { // look only at requests that have data waiting. foreach (var package in result.packages.GetConsumingEnumerable()) { // process the results for that set. // check if the package is a provider package. If so we need to filter on the packages for the providers. if (EnsurePackageIsProvider(package)) { ProcessPackage(result.provider, result.query, package); } } } requests = requests.FilterWithFinalizer(each => each.packages.IsConsumed, each => each.packages.Dispose()).ToArray(); } } else { // now this is where it gets a bit funny. // the user specified a min or max // and so we have to only return the highest one in the set for a given package. while (WaitForActivity(requests.Select(each => each.packages))) { // keep processing while any of the the queries is still going. foreach (var perProvider in requests.GroupBy(each => each.provider)) { foreach (var perQuery in perProvider.GroupBy(each => each.query)) { if (perQuery.All(each => each.packages.IsCompleted && !each.packages.IsConsumed)) { foreach (var pkg in from p in perQuery.SelectMany(each => each.packages.GetConsumingEnumerable()) group p by new { p.Name, p.Source } // for a given name into grouping // get the latest version only select grouping.OrderByDescending(pp => pp, SoftwareIdentityVersionComparer.Instance).First()) { if (EnsurePackageIsProvider(pkg)) { ProcessPackage(perProvider.Key, perQuery.Key, pkg); } } } } } // filter out whatever we're done with. requests = requests.FilterWithFinalizer(each => each.packages.IsConsumed, each => each.packages.Dispose()).ToArray(); } } // dispose of any requests that didn't get cleaned up earlier. foreach (var i in requests) { i.packages.Dispose(); } } protected virtual void SearchForPackages() { try { var providers = SelectedProviders.ToArray(); // filter the items into three types of searches _names = CollectionExtensions.IsNullOrEmpty(Name) ? CollectionExtensions.SingleItemAsEnumerable(string.Empty) : Name.Where(each => !IsUri(each) && !IsFile(each)).ToArray(); foreach (var n in _names) { Debug("Calling SearchForPackages. Name='{0}'", n); } ProcessRequests(providers.Where(pv => string.Equals(pv.ProviderName, "bootstrap", StringComparison.OrdinalIgnoreCase)).ToArray()); ProcessRequests(providers.Where(pv => !string.Equals(pv.ProviderName, "bootstrap", StringComparison.OrdinalIgnoreCase)).ToArray()); } catch (Exception ex) { Debug(ex.ToString()); } } protected virtual void ProcessPackage(PackageProvider provider, IEnumerable<string> searchKey, SoftwareIdentity package) { foreach (var key in searchKey) { _resultsPerName.GetOrSetIfDefault(key, () => new List<SoftwareIdentity>()).Add(package); } } protected bool CheckUnmatchedPackages() { var unmatched = _resultsPerName.Keys.Where(each => _resultsPerName[each] == null).ReEnumerable(); var result = true; if (unmatched.Any()) { // whine about things not matched. foreach (var name in unmatched) { Debug(string.Format(CultureInfo.CurrentCulture, "unmatched package name='{0}'", name)); if (name == string.Empty) { // no name result = false; Error(Constants.Errors.NoPackagesFoundForProvider, _providersNotFindingAnything.Select(each => each.ProviderName).JoinWithComma()); } else { if (WildcardPattern.ContainsWildcardCharacters(name)) { Verbose(Constants.Messages.NoMatchesForWildcard, name); result = false; // even tho' it's not an 'error' it is still enough to know not to actually install. } else { result = false; NonTerminatingError(Constants.Errors.NoMatchFoundForCriteria, name); } } } } return result; } protected IEnumerable<SoftwareIdentity> CheckMatchedDuplicates() { // if there are overmatched packages we need to know why: // are they found across multiple providers? // are they found across multiple sources? // are they all from the same source? foreach (var list in _resultsPerName.Values.Where(each => each != null && each.Any())) { if (list.Count == 1) { //no overmatched yield return list.FirstOrDefault(); } else { //process the overmatched case SoftwareIdentity selectedPackage = null; var providers = list.Select(each => each.ProviderName).Distinct().ToArray(); var sources = list.Select(each => each.Source).Distinct().ToArray(); //case: a user specifies -Source and multiple packages are found. In this case to determine which one should be installed, // We treat the user's package source array is in a priority order, i.e. the first package source has the highest priority. // Of course, these packages should not be from a single source with the same provider. // Example: install-package -Source @('src1', 'src2') // install-package -Source @('src1', 'src2') -Provider @('p1', 'p2') if (Sources.Any() && (providers.Length != 1 || sources.Length != 1)) { // let's use the first source as our priority.As long as we find a package, we exit the 'for' loop right away foreach (var source in Sources) { //select all packages matched source var pkgs = list.Where(package => source.EqualsIgnoreCase(package.Source) || (UserSpecifiedSourcesList.Keys.ContainsIgnoreCase(package.Source) && source.EqualsIgnoreCase(UserSpecifiedSourcesList[package.Source]))).ToArray(); if (pkgs.Length == 0) { continue; } if (pkgs.Length == 1) { //only one provider found the package selectedPackage = pkgs[0]; break; } if (ProviderName == null) { //user does not specify '-providerName' but we found multiple packages with a source, can not determine which one //will error out break; } if (pkgs.Length > 1) { //case: multiple providers matched the same source. //need to process provider's priority order var pkg = ProviderName.Select(p => pkgs.FirstOrDefault(each => each.ProviderName.EqualsIgnoreCase(p))).FirstOrDefault(); if (pkg != null) { selectedPackage = pkg; break; } } }//inner foreach //case: a user specifies -Provider array but no -Source and multiple packages are found. In this case to determine which one should be installed, // We treat the user's package provider array is in a priority order, i.e. the first provider in the array has the highest priority. // Of course, these packages should not be from a single source with the same provider. // Example: install-package -Provider @('p1', 'p2') } else if (ProviderName != null && ProviderName.Any() && (providers.Length != 1 || sources.Length != 1)) { foreach (var providerName in ProviderName) { //select all packages matched with the provider name var packages = list.Where(each => providerName.EqualsIgnoreCase(each.ProviderName)).ToArray(); if (packages.Length == 0) { continue; } if (packages.Length == 1) { //only one provider found the package, that's good selectedPackage = packages[0]; break; } else { //user does not specify '-source' but we found multiple packages with one provider, we can not determine which one //will error out break; } } } if (selectedPackage != null) { yield return selectedPackage; } else { //error out for the overmatched case var suggestion = ""; if (providers.Length == 1) { // it's matching this package multiple times in the same provider. if (sources.Length == 1) { // matching it from a single source. // be more exact on matching name? or version? suggestion = Resources.Messages.SuggestRequiredVersion; } else { // it's matching the same package from multiple sources // tell them to use -source suggestion = Resources.Messages.SuggestSingleSource; } } else { // found across multiple providers // must specify -provider suggestion = Resources.Messages.SuggestSingleProviderName; } string searchKey = null; foreach (var pkg in list) { Warning(Constants.Messages.MatchesMultiplePackages, pkg.SearchKey, pkg.ProviderName, pkg.Name, pkg.Version, GetPackageSourceNameOrLocation(pkg)); searchKey = pkg.SearchKey; } Error(Constants.Errors.DisambiguateForInstall, searchKey, GetMessageString(suggestion, suggestion)); } } } } // Performs a reverse lookup from Package Source Location -> Source Name for a Provider private string GetPackageSourceNameOrLocation(SoftwareIdentity package) { // Default to Source Location Url string packageSourceName = package.Source; // Get the package provider object var packageProvider = SelectProviders(package.ProviderName).ReEnumerable(); if (!packageProvider.Any()) { return packageSourceName; } // For any issues with reverse lookup (SourceLocation -> SourceName), return Source Location Url try { var packageSource = packageProvider.Select(each => each.ResolvePackageSources(this.SuppressErrorsAndWarnings(IsProcessing)).Where(source => source.IsRegistered && (source.Location.EqualsIgnoreCase(package.Source)))).ReEnumerable(); if (packageSource.Any()) { var pkgSource = packageSource.FirstOrDefault(); if (pkgSource != null) { var source = pkgSource.FirstOrDefault(); if (source != null) { packageSourceName = source.Name; } } } } catch (Exception e) { e.Dump(); } return packageSourceName; } protected bool InstallPackages(params SoftwareIdentity[] packagesToInstall) { if(packagesToInstall == null || packagesToInstall.Length == 0) { return false; } // first, check to see if we have all the required dynamic parameters // for each package/provider foreach (var package in packagesToInstall) { var pkg = package; foreach (var parameter in DynamicParameterDictionary.Values.OfType<CustomRuntimeDefinedParameter>() .Where(param => param.IsSet == false && param.Options.Any(option => option.ProviderName == pkg.ProviderName && option.Category == OptionCategory.Install && option.IsRequired))) { // this is not good. there is a required parameter for the package // and the user didn't specify it. We should return the error to the user // and they can try again. Error(Constants.Errors.PackageInstallRequiresOption, package.Name, package.ProviderName, parameter.Name); Cancel(); } } if (IsCanceled) { return false; } var progressId = 0; var triedInstallCount = 0; if (packagesToInstall.Length > 1) { progressId = StartProgress(0, Constants.Messages.InstallingPackagesCount, packagesToInstall.Length); } var n = 0; foreach (var pkg in packagesToInstall) { if (packagesToInstall.Length > 1) { Progress(progressId, (n*100/packagesToInstall.Length) + 1, Constants.Messages.InstallingPackageMultiple, pkg.Name, ++n, packagesToInstall.Length); } var provider = SelectProviders(pkg.ProviderName).FirstOrDefault(); if (provider == null) { Error(Constants.Errors.UnknownProvider, pkg.ProviderName); return false; } // quickly check to see if this package is already installed. var installedPkgs = provider.GetInstalledPackages(pkg.Name, pkg.Version, null, null, this.ProviderSpecific(provider)).CancelWhen(CancellationEvent.Token).ToArray(); if (IsCanceled) { // if we're stopping, just get out asap. return false; } // todo: this is a terribly simplistic way to do this, we'd better rethink this soon if (!Force) { if (installedPkgs.Any(each => each.Name.EqualsIgnoreCase(pkg.Name) && each.Version.EqualsIgnoreCase(pkg.Version))) { // it looks like it's already installed. // skip it. Verbose(Constants.Messages.SkippedInstalledPackage, pkg.Name, pkg.Version); if (packagesToInstall.Length > 1) { Progress(progressId, (n*100/packagesToInstall.Length) + 1, Constants.Messages.SkippedInstalledPackageMultiple, pkg.Name, n, packagesToInstall.Length); } continue; } } try { if (ShouldProcessPackageInstall(pkg.Name, pkg.Version, pkg.Source)) { foreach (var installedPkg in provider.InstallPackage(pkg, this).CancelWhen(CancellationEvent.Token)) { if (IsCanceled) { // if we're stopping, just get out asap. return false; } WriteObject(AddPropertyToSoftwareIdentity(installedPkg)); LogEvent(EventTask.Install, EventId.Install, Resources.Messages.PackageInstalled, installedPkg.Name, installedPkg.Version, installedPkg.ProviderName, installedPkg.Source ?? string.Empty, installedPkg.Status ?? string.Empty, installedPkg.InstallationPath ?? string.Empty); TraceMessage(Constants.InstallPackageTrace, installedPkg); triedInstallCount++; } } } catch (Exception e) { e.Dump(); Error(Constants.Errors.InstallationFailure, pkg.Name); return false; } if (packagesToInstall.Length > 1) { Progress(progressId, (n*100/packagesToInstall.Length) + 1, Constants.Messages.InstalledPackageMultiple, pkg.Name, n, packagesToInstall.Length); } } return (triedInstallCount == packagesToInstall.Length); } protected bool ShouldProcessPackageInstall(string packageName, string version, string source) { try { //-force is already handled before reaching this stage return ShouldProcess(FormatMessageString(Constants.Messages.TargetPackage, packageName, version, source), FormatMessageString(Constants.Messages.ActionInstallPackage)).Result; } catch { } return false; } public override bool ShouldContinueWithUntrustedPackageSource(string package, string packageSource) { try { if (_sourcesTrusted.Contains(packageSource) || Force || WhatIf || _yesToAll) { return true; } if (_sourcesDeniedTrust.Contains(packageSource) || _noToAll) { return false; } var shouldContinueResult = ShouldContinue(FormatMessageString(Constants.Messages.QueryInstallUntrustedPackage, package, packageSource), FormatMessageString(Constants.Messages.CaptionSourceNotTrusted), true).Result; _yesToAll = shouldContinueResult.yesToAll; _noToAll = shouldContinueResult.noToAll; if (shouldContinueResult.result) { _sourcesTrusted.Add(packageSource); return true; } else { _sourcesDeniedTrust.Add(packageSource); } } catch { } return false; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.OverrideEqualsAndOperatorEqualsOnValueTypesAnalyzer, Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines.CSharpOverrideEqualsAndOperatorEqualsOnValueTypesFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.OverrideEqualsAndOperatorEqualsOnValueTypesAnalyzer, Microsoft.CodeQuality.VisualBasic.Analyzers.ApiDesignGuidelines.BasicOverrideEqualsAndOperatorEqualsOnValueTypesFixer>; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests { public class OverrideEqualsAndOperatorEqualsOnValueTypesTests { [Fact] public async Task CSharpDiagnosticForBothEqualsAndOperatorEqualsOnStruct() { await VerifyCS.VerifyAnalyzerAsync(@" public struct A { public int X; }", GetCSharpOverrideEqualsDiagnostic(2, 15, "A"), GetCSharpOperatorEqualsDiagnostic(2, 15, "A")); } [WorkItem(895, "https://github.com/dotnet/roslyn-analyzers/issues/895")] [Fact] public async Task CSharpNoDiagnosticForInternalAndPrivateStruct() { await VerifyCS.VerifyAnalyzerAsync(@" internal struct A { public int X; } public class B { private struct C { public int X; } } "); } [WorkItem(899, "https://github.com/dotnet/roslyn-analyzers/issues/899")] [Fact] public async Task CSharpNoDiagnosticForEnum() { await VerifyCS.VerifyAnalyzerAsync(@" public enum E { F = 0 } "); } [WorkItem(899, "https://github.com/dotnet/roslyn-analyzers/issues/899")] [Fact] public async Task CSharpNoDiagnosticForStructsWithoutMembers() { await VerifyCS.VerifyAnalyzerAsync(@" public struct EmptyStruct { } "); } [WorkItem(899, "https://github.com/dotnet/roslyn-analyzers/issues/899")] [Fact] public async Task CSharpNoDiagnosticForEnumerators() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Collections; public struct MyEnumerator : System.Collections.IEnumerator { public object Current { get { throw new NotImplementedException(); } } public bool MoveNext() { throw new NotImplementedException(); } public void Reset() { throw new NotImplementedException(); } } public struct MyGenericEnumerator<T> : System.Collections.Generic.IEnumerator<T> { public T Current { get { throw new NotImplementedException(); } } object IEnumerator.Current { get { throw new NotImplementedException(); } } public void Dispose() { throw new NotImplementedException(); } public bool MoveNext() { throw new NotImplementedException(); } public void Reset() { throw new NotImplementedException(); } } "); } [Fact] public async Task CSharpNoDiagnosticForEqualsOrOperatorEqualsOnClass() { await VerifyCS.VerifyAnalyzerAsync(@" public class A { public int X; }"); } [Fact] public async Task CSharpNoDiagnosticWhenStructImplementsEqualsAndOperatorEquals() { await VerifyCS.VerifyAnalyzerAsync(@" public struct A { public override bool Equals(object other) { return true; } public static bool operator==(A left, A right) { return true; } public static bool operator!=(A left, A right) { return true; } }"); } [Fact] public async Task CSharpDiagnosticWhenEqualsHasWrongSignature() { await VerifyCS.VerifyAnalyzerAsync(@" public struct A { public bool Equals(A other) { return true; } public static bool operator==(A left, A right) { return true; } public static bool operator!=(A left, A right) { return true; } }", GetCSharpOverrideEqualsDiagnostic(2, 15, "A")); } [Fact] public async Task CSharpDiagnosticWhenEqualsIsNotAnOverride() { await VerifyCS.VerifyAnalyzerAsync(@" public struct A { public new bool Equals(object other) { return true; } public static bool operator==(A left, A right) { return true; } public static bool operator!=(A left, A right) { return true; } }", GetCSharpOverrideEqualsDiagnostic(2, 15, "A")); } [Fact] public async Task BasicDiagnosticsForEqualsOnStructure() { await VerifyVB.VerifyAnalyzerAsync(@" Public Structure A Public X As Integer End Structure ", GetBasicOverrideEqualsDiagnostic(2, 18, "A"), GetBasicOperatorEqualsDiagnostic(2, 18, "A")); } [WorkItem(895, "https://github.com/dotnet/roslyn-analyzers/issues/895")] [Fact] public async Task BasicNoDiagnosticsForInternalAndPrivateStructure() { await VerifyVB.VerifyAnalyzerAsync(@" Friend Structure A Public X As Integer End Structure Public Class B Private Structure C Public X As Integer End Structure End Class "); } [WorkItem(899, "https://github.com/dotnet/roslyn-analyzers/issues/899")] [Fact] public async Task BasicNoDiagnosticForEnum() { await VerifyVB.VerifyAnalyzerAsync(@" Public Enum E F = 0 End Enum "); } [WorkItem(899, "https://github.com/dotnet/roslyn-analyzers/issues/899")] [Fact] public async Task BasicNoDiagnosticForStructsWithoutMembers() { await VerifyVB.VerifyAnalyzerAsync(@" Public Structure EmptyStruct End Structure "); } [WorkItem(899, "https://github.com/dotnet/roslyn-analyzers/issues/899")] [Fact] public async Task BasicNoDiagnosticForEnumerators() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System Imports System.Collections Imports System.Collections.Generic Public Structure MyEnumerator Implements IEnumerator Public ReadOnly Property Current As Object Implements IEnumerator.Current Get Throw New NotImplementedException() End Get End Property Public Function MoveNext() As Boolean Implements IEnumerator.MoveNext Throw New NotImplementedException() End Function Public Sub Reset() Implements IEnumerator.Reset Throw New NotImplementedException() End Sub End Structure Public Structure MyGenericEnumerator(Of T) Implements IEnumerator(Of T) Public ReadOnly Property Current As T Implements IEnumerator(Of T).Current Get Throw New NotImplementedException() End Get End Property Private ReadOnly Property IEnumerator_Current() As Object Implements IEnumerator.Current Get Throw New NotImplementedException() End Get End Property Public Sub Dispose() Implements IEnumerator(Of T).Dispose Throw New NotImplementedException() End Sub Public Function MoveNext() As Boolean Implements IEnumerator(Of T).MoveNext Throw New NotImplementedException() End Function Public Sub Reset() Implements IEnumerator(Of T).Reset Throw New NotImplementedException() End Sub End Structure "); } [Fact] public async Task BasicNoDiagnosticForEqualsOnClass() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class A End Class "); } [Fact] public async Task BasicNoDiagnosticWhenStructureImplementsEqualsAndOperatorEquals() { await VerifyVB.VerifyAnalyzerAsync(@" Public Structure A Public Overrides Overloads Function Equals(obj As Object) As Boolean Return True End Function Public Shared Operator =(left As A, right As A) Return True End Operator Public Shared Operator <>(left As A, right As A) Return False End Operator End Structure "); } [Fact] public async Task BasicDiagnosticWhenEqualsHasWrongSignature() { await VerifyVB.VerifyAnalyzerAsync(@" Public Structure A Public Overrides Overloads Function {|BC30284:Equals|}(obj As A) As Boolean Return True End Function Public Shared Operator =(left As A, right As A) Return True End Operator Public Shared Operator <>(left As A, right As A) Return False End Operator End Structure ", GetBasicOverrideEqualsDiagnostic(2, 18, "A")); } [Fact] public async Task BasicDiagnosticWhenEqualsIsNotAnOverride() { await VerifyVB.VerifyAnalyzerAsync(@" Public Structure A Public Shadows Function Equals(obj As Object) As Boolean Return True End Function Public Shared Operator =(left As A, right As A) Return True End Operator Public Shared Operator <>(left As A, right As A) Return False End Operator End Structure ", GetBasicOverrideEqualsDiagnostic(2, 18, "A")); } [Fact, WorkItem(2324, "https://github.com/dotnet/roslyn-analyzers/issues/2324")] public async Task CSharp_RefStruct_NoDiagnostic() { await new VerifyCS.Test { TestCode = @" public ref struct A { public int X; }", LanguageVersion = LanguageVersion.CSharp8 }.RunAsync(); } private static DiagnosticResult GetCSharpOverrideEqualsDiagnostic(int line, int column, string typeName) => VerifyCS.Diagnostic(OverrideEqualsAndOperatorEqualsOnValueTypesAnalyzer.EqualsRule) .WithLocation(line, column) .WithArguments(typeName); private static DiagnosticResult GetCSharpOperatorEqualsDiagnostic(int line, int column, string typeName) => VerifyCS.Diagnostic(OverrideEqualsAndOperatorEqualsOnValueTypesAnalyzer.OpEqualityRule) .WithLocation(line, column) .WithArguments(typeName); private static DiagnosticResult GetBasicOverrideEqualsDiagnostic(int line, int column, string typeName) => VerifyVB.Diagnostic(OverrideEqualsAndOperatorEqualsOnValueTypesAnalyzer.EqualsRule) .WithLocation(line, column) .WithArguments(typeName); private static DiagnosticResult GetBasicOperatorEqualsDiagnostic(int line, int column, string typeName) => VerifyVB.Diagnostic(OverrideEqualsAndOperatorEqualsOnValueTypesAnalyzer.OpEqualityRule) .WithLocation(line, column) .WithArguments(typeName); } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Converters; namespace Twilio.Rest.Verify.V2 { /// <summary> /// Create a new Verification Service. /// </summary> public class CreateServiceOptions : IOptions<ServiceResource> { /// <summary> /// A string to describe the verification service /// </summary> public string FriendlyName { get; } /// <summary> /// The length of the verification code to generate /// </summary> public int? CodeLength { get; set; } /// <summary> /// Whether to perform a lookup with each verification /// </summary> public bool? LookupEnabled { get; set; } /// <summary> /// Whether to skip sending SMS verifications to landlines /// </summary> public bool? SkipSmsToLandlines { get; set; } /// <summary> /// Whether to ask the user to press a number before delivering the verify code in a phone call /// </summary> public bool? DtmfInputRequired { get; set; } /// <summary> /// The name of an alternative text-to-speech service to use in phone calls /// </summary> public string TtsName { get; set; } /// <summary> /// Whether to pass PSD2 transaction parameters when starting a verification /// </summary> public bool? Psd2Enabled { get; set; } /// <summary> /// Whether to add a security warning at the end of an SMS. /// </summary> public bool? DoNotShareWarningEnabled { get; set; } /// <summary> /// Whether to allow sending verifications with a custom code. /// </summary> public bool? CustomCodeEnabled { get; set; } /// <summary> /// Optional. Include the date in the Challenge's reponse. Default: true /// </summary> public bool? PushIncludeDate { get; set; } /// <summary> /// Optional. Set APN Credential for this service. /// </summary> public string PushApnCredentialSid { get; set; } /// <summary> /// Optional. Set FCM Credential for this service. /// </summary> public string PushFcmCredentialSid { get; set; } /// <summary> /// Optional. Set TOTP Issuer for this service. /// </summary> public string TotpIssuer { get; set; } /// <summary> /// Optional. How often, in seconds, are TOTP codes generated /// </summary> public int? TotpTimeStep { get; set; } /// <summary> /// Optional. Number of digits for generated TOTP codes /// </summary> public int? TotpCodeLength { get; set; } /// <summary> /// Optional. The number of past and future time-steps valid at a given time /// </summary> public int? TotpSkew { get; set; } /// <summary> /// The verification template SMS messages. /// </summary> public string DefaultTemplateSid { get; set; } /// <summary> /// Construct a new CreateServiceOptions /// </summary> /// <param name="friendlyName"> A string to describe the verification service </param> public CreateServiceOptions(string friendlyName) { FriendlyName = friendlyName; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (FriendlyName != null) { p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName)); } if (CodeLength != null) { p.Add(new KeyValuePair<string, string>("CodeLength", CodeLength.ToString())); } if (LookupEnabled != null) { p.Add(new KeyValuePair<string, string>("LookupEnabled", LookupEnabled.Value.ToString().ToLower())); } if (SkipSmsToLandlines != null) { p.Add(new KeyValuePair<string, string>("SkipSmsToLandlines", SkipSmsToLandlines.Value.ToString().ToLower())); } if (DtmfInputRequired != null) { p.Add(new KeyValuePair<string, string>("DtmfInputRequired", DtmfInputRequired.Value.ToString().ToLower())); } if (TtsName != null) { p.Add(new KeyValuePair<string, string>("TtsName", TtsName)); } if (Psd2Enabled != null) { p.Add(new KeyValuePair<string, string>("Psd2Enabled", Psd2Enabled.Value.ToString().ToLower())); } if (DoNotShareWarningEnabled != null) { p.Add(new KeyValuePair<string, string>("DoNotShareWarningEnabled", DoNotShareWarningEnabled.Value.ToString().ToLower())); } if (CustomCodeEnabled != null) { p.Add(new KeyValuePair<string, string>("CustomCodeEnabled", CustomCodeEnabled.Value.ToString().ToLower())); } if (PushIncludeDate != null) { p.Add(new KeyValuePair<string, string>("Push.IncludeDate", PushIncludeDate.Value.ToString().ToLower())); } if (PushApnCredentialSid != null) { p.Add(new KeyValuePair<string, string>("Push.ApnCredentialSid", PushApnCredentialSid.ToString())); } if (PushFcmCredentialSid != null) { p.Add(new KeyValuePair<string, string>("Push.FcmCredentialSid", PushFcmCredentialSid.ToString())); } if (TotpIssuer != null) { p.Add(new KeyValuePair<string, string>("Totp.Issuer", TotpIssuer)); } if (TotpTimeStep != null) { p.Add(new KeyValuePair<string, string>("Totp.TimeStep", TotpTimeStep.ToString())); } if (TotpCodeLength != null) { p.Add(new KeyValuePair<string, string>("Totp.CodeLength", TotpCodeLength.ToString())); } if (TotpSkew != null) { p.Add(new KeyValuePair<string, string>("Totp.Skew", TotpSkew.ToString())); } if (DefaultTemplateSid != null) { p.Add(new KeyValuePair<string, string>("DefaultTemplateSid", DefaultTemplateSid.ToString())); } return p; } } /// <summary> /// Fetch specific Verification Service Instance. /// </summary> public class FetchServiceOptions : IOptions<ServiceResource> { /// <summary> /// The unique string that identifies the resource /// </summary> public string PathSid { get; } /// <summary> /// Construct a new FetchServiceOptions /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> public FetchServiceOptions(string pathSid) { PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// Delete a specific Verification Service Instance. /// </summary> public class DeleteServiceOptions : IOptions<ServiceResource> { /// <summary> /// The unique string that identifies the resource /// </summary> public string PathSid { get; } /// <summary> /// Construct a new DeleteServiceOptions /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> public DeleteServiceOptions(string pathSid) { PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// Retrieve a list of all Verification Services for an account. /// </summary> public class ReadServiceOptions : ReadOptions<ServiceResource> { /// <summary> /// Generate the necessary parameters /// </summary> public override List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (PageSize != null) { p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString())); } return p; } } /// <summary> /// Update a specific Verification Service. /// </summary> public class UpdateServiceOptions : IOptions<ServiceResource> { /// <summary> /// The unique string that identifies the resource /// </summary> public string PathSid { get; } /// <summary> /// A string to describe the verification service /// </summary> public string FriendlyName { get; set; } /// <summary> /// The length of the verification code to generate /// </summary> public int? CodeLength { get; set; } /// <summary> /// Whether to perform a lookup with each verification /// </summary> public bool? LookupEnabled { get; set; } /// <summary> /// Whether to skip sending SMS verifications to landlines /// </summary> public bool? SkipSmsToLandlines { get; set; } /// <summary> /// Whether to ask the user to press a number before delivering the verify code in a phone call /// </summary> public bool? DtmfInputRequired { get; set; } /// <summary> /// The name of an alternative text-to-speech service to use in phone calls /// </summary> public string TtsName { get; set; } /// <summary> /// Whether to pass PSD2 transaction parameters when starting a verification /// </summary> public bool? Psd2Enabled { get; set; } /// <summary> /// Whether to add a privacy warning at the end of an SMS. /// </summary> public bool? DoNotShareWarningEnabled { get; set; } /// <summary> /// Whether to allow sending verifications with a custom code. /// </summary> public bool? CustomCodeEnabled { get; set; } /// <summary> /// Optional. Include the date in the Challenge's reponse. Default: true /// </summary> public bool? PushIncludeDate { get; set; } /// <summary> /// Optional. Set APN Credential for this service. /// </summary> public string PushApnCredentialSid { get; set; } /// <summary> /// Optional. Set FCM Credential for this service. /// </summary> public string PushFcmCredentialSid { get; set; } /// <summary> /// Optional. Set TOTP Issuer for this service. /// </summary> public string TotpIssuer { get; set; } /// <summary> /// Optional. How often, in seconds, are TOTP codes generated /// </summary> public int? TotpTimeStep { get; set; } /// <summary> /// Optional. Number of digits for generated TOTP codes /// </summary> public int? TotpCodeLength { get; set; } /// <summary> /// Optional. The number of past and future time-steps valid at a given time /// </summary> public int? TotpSkew { get; set; } /// <summary> /// The verification template SMS messages. /// </summary> public string DefaultTemplateSid { get; set; } /// <summary> /// Construct a new UpdateServiceOptions /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> public UpdateServiceOptions(string pathSid) { PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (FriendlyName != null) { p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName)); } if (CodeLength != null) { p.Add(new KeyValuePair<string, string>("CodeLength", CodeLength.ToString())); } if (LookupEnabled != null) { p.Add(new KeyValuePair<string, string>("LookupEnabled", LookupEnabled.Value.ToString().ToLower())); } if (SkipSmsToLandlines != null) { p.Add(new KeyValuePair<string, string>("SkipSmsToLandlines", SkipSmsToLandlines.Value.ToString().ToLower())); } if (DtmfInputRequired != null) { p.Add(new KeyValuePair<string, string>("DtmfInputRequired", DtmfInputRequired.Value.ToString().ToLower())); } if (TtsName != null) { p.Add(new KeyValuePair<string, string>("TtsName", TtsName)); } if (Psd2Enabled != null) { p.Add(new KeyValuePair<string, string>("Psd2Enabled", Psd2Enabled.Value.ToString().ToLower())); } if (DoNotShareWarningEnabled != null) { p.Add(new KeyValuePair<string, string>("DoNotShareWarningEnabled", DoNotShareWarningEnabled.Value.ToString().ToLower())); } if (CustomCodeEnabled != null) { p.Add(new KeyValuePair<string, string>("CustomCodeEnabled", CustomCodeEnabled.Value.ToString().ToLower())); } if (PushIncludeDate != null) { p.Add(new KeyValuePair<string, string>("Push.IncludeDate", PushIncludeDate.Value.ToString().ToLower())); } if (PushApnCredentialSid != null) { p.Add(new KeyValuePair<string, string>("Push.ApnCredentialSid", PushApnCredentialSid.ToString())); } if (PushFcmCredentialSid != null) { p.Add(new KeyValuePair<string, string>("Push.FcmCredentialSid", PushFcmCredentialSid.ToString())); } if (TotpIssuer != null) { p.Add(new KeyValuePair<string, string>("Totp.Issuer", TotpIssuer)); } if (TotpTimeStep != null) { p.Add(new KeyValuePair<string, string>("Totp.TimeStep", TotpTimeStep.ToString())); } if (TotpCodeLength != null) { p.Add(new KeyValuePair<string, string>("Totp.CodeLength", TotpCodeLength.ToString())); } if (TotpSkew != null) { p.Add(new KeyValuePair<string, string>("Totp.Skew", TotpSkew.ToString())); } if (DefaultTemplateSid != null) { p.Add(new KeyValuePair<string, string>("DefaultTemplateSid", DefaultTemplateSid.ToString())); } return p; } } }
// 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.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.RecoveryServices.Backup { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.RecoveryServices; using Microsoft.Rest; using Microsoft.Rest.Azure; 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> /// ProtectionContainerOperationResultsOperations operations. /// </summary> internal partial class ProtectionContainerOperationResultsOperations : IServiceOperations<RecoveryServicesBackupClient>, IProtectionContainerOperationResultsOperations { /// <summary> /// Initializes a new instance of the ProtectionContainerOperationResultsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ProtectionContainerOperationResultsOperations(RecoveryServicesBackupClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the RecoveryServicesBackupClient /// </summary> public RecoveryServicesBackupClient Client { get; private set; } /// <summary> /// Fetches the result of any operation on the container. /// </summary> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='fabricName'> /// Fabric name associated with the container. /// </param> /// <param name='containerName'> /// Container name whose information should be fetched. /// </param> /// <param name='operationId'> /// Operation ID which represents the operation whose result needs to be /// fetched. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// 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<ProtectionContainerResource>> GetWithHttpMessagesAsync(string vaultName, string resourceGroupName, string fabricName, string containerName, string operationId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (vaultName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vaultName"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "fabricName"); } if (containerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "containerName"); } if (operationId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "operationId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("containerName", containerName); tracingParameters.Add("operationId", operationId); 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.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/protectionContainers/{containerName}/operationResults/{operationId}").ToString(); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); _url = _url.Replace("{containerName}", System.Uri.EscapeDataString(containerName)); _url = _url.Replace("{operationId}", System.Uri.EscapeDataString(operationId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ProtectionContainerResource>(); _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<ProtectionContainerResource>(_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; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Security; namespace System.Numerics { internal static partial class BigIntegerCalculator { public static uint[] Divide(uint[] left, uint right, out uint remainder) { Debug.Assert(left != null); Debug.Assert(left.Length >= 1); // Executes the division for one big and one 32-bit integer. // Thus, we've similar code than below, but there is no loop for // processing the 32-bit integer, since it's a single element. uint[] quotient = new uint[left.Length]; ulong carry = 0UL; for (int i = left.Length - 1; i >= 0; i--) { ulong value = (carry << 32) | left[i]; ulong digit = value / right; quotient[i] = (uint)digit; carry = value - digit * right; } remainder = (uint)carry; return quotient; } public static uint[] Divide(uint[] left, uint right) { Debug.Assert(left != null); Debug.Assert(left.Length >= 1); // Same as above, but only computing the quotient. uint[] quotient = new uint[left.Length]; ulong carry = 0UL; for (int i = left.Length - 1; i >= 0; i--) { ulong value = (carry << 32) | left[i]; ulong digit = value / right; quotient[i] = (uint)digit; carry = value - digit * right; } return quotient; } public static uint Remainder(uint[] left, uint right) { Debug.Assert(left != null); Debug.Assert(left.Length >= 1); // Same as above, but only computing the remainder. ulong carry = 0UL; for (int i = left.Length - 1; i >= 0; i--) { ulong value = (carry << 32) | left[i]; carry = value % right; } return (uint)carry; } [SecuritySafeCritical] public static unsafe uint[] Divide(uint[] left, uint[] right, out uint[] remainder) { Debug.Assert(left != null); Debug.Assert(right != null); Debug.Assert(left.Length >= 1); Debug.Assert(right.Length >= 1); Debug.Assert(left.Length >= right.Length); // Switching to unsafe pointers helps sparing // some nasty index calculations... // NOTE: left will get overwritten, we need a local copy uint[] localLeft = CreateCopy(left); uint[] bits = new uint[left.Length - right.Length + 1]; fixed (uint* l = &localLeft[0], r = &right[0], b = &bits[0]) { Divide(l, localLeft.Length, r, right.Length, b, bits.Length); } remainder = localLeft; return bits; } [SecuritySafeCritical] public static unsafe uint[] Divide(uint[] left, uint[] right) { Debug.Assert(left != null); Debug.Assert(right != null); Debug.Assert(left.Length >= 1); Debug.Assert(right.Length >= 1); Debug.Assert(left.Length >= right.Length); // Same as above, but only returning the quotient. // NOTE: left will get overwritten, we need a local copy uint[] localLeft = CreateCopy(left); uint[] bits = new uint[left.Length - right.Length + 1]; fixed (uint* l = &localLeft[0], r = &right[0], b = &bits[0]) { Divide(l, localLeft.Length, r, right.Length, b, bits.Length); } return bits; } [SecuritySafeCritical] public static unsafe uint[] Remainder(uint[] left, uint[] right) { Debug.Assert(left != null); Debug.Assert(right != null); Debug.Assert(left.Length >= 1); Debug.Assert(right.Length >= 1); Debug.Assert(left.Length >= right.Length); // Same as above, but only returning the remainder. // NOTE: left will get overwritten, we need a local copy uint[] localLeft = CreateCopy(left); fixed (uint* l = &localLeft[0], r = &right[0]) { Divide(l, localLeft.Length, r, right.Length, null, 0); } return localLeft; } [SecuritySafeCritical] private static unsafe void Divide(uint* left, int leftLength, uint* right, int rightLength, uint* bits, int bitsLength) { Debug.Assert(leftLength >= 1); Debug.Assert(rightLength >= 1); Debug.Assert(leftLength >= rightLength); Debug.Assert(bitsLength == leftLength - rightLength + 1 || bitsLength == 0); // Executes the "grammar-school" algorithm for computing q = a / b. // Before calculating q_i, we get more bits into the highest bit // block of the divisor. Thus, guessing digits of the quotient // will be more precise. Additionally we'll get r = a % b. uint divHi = right[rightLength - 1]; uint divLo = rightLength > 1 ? right[rightLength - 2] : 0; // We measure the leading zeros of the divisor int shift = LeadingZeros(divHi); int backShift = 32 - shift; // And, we make sure the most significant bit is set if (shift > 0) { uint divNx = rightLength > 2 ? right[rightLength - 3] : 0; divHi = (divHi << shift) | (divLo >> backShift); divLo = (divLo << shift) | (divNx >> backShift); } // Then, we divide all of the bits as we would do it using // pen and paper: guessing the next digit, subtracting, ... for (int i = leftLength; i >= rightLength; i--) { int n = i - rightLength; uint t = i < leftLength ? left[i] : 0; ulong valHi = ((ulong)t << 32) | left[i - 1]; uint valLo = i > 1 ? left[i - 2] : 0; // We shifted the divisor, we shift the dividend too if (shift > 0) { uint valNx = i > 2 ? left[i - 3] : 0; valHi = (valHi << shift) | (valLo >> backShift); valLo = (valLo << shift) | (valNx >> backShift); } // First guess for the current digit of the quotient, // which naturally must have only 32 bits... ulong digit = valHi / divHi; if (digit > 0xFFFFFFFF) digit = 0xFFFFFFFF; // Our first guess may be a little bit to big while (DivideGuessTooBig(digit, valHi, valLo, divHi, divLo)) --digit; if (digit > 0) { // Now it's time to subtract our current quotient uint carry = SubtractDivisor(left + n, leftLength - n, right, rightLength, digit); if (carry != t) { Debug.Assert(carry == t + 1); // Our guess was still exactly one too high carry = AddDivisor(left + n, leftLength - n, right, rightLength); --digit; Debug.Assert(carry == 1); } } // We have the digit! if (bitsLength != 0) bits[n] = (uint)digit; if (i < leftLength) left[i] = 0; } } [SecuritySafeCritical] private static unsafe uint AddDivisor(uint* left, int leftLength, uint* right, int rightLength) { Debug.Assert(leftLength >= 0); Debug.Assert(rightLength >= 0); Debug.Assert(leftLength >= rightLength); // Repairs the dividend, if the last subtract was too much ulong carry = 0UL; for (int i = 0; i < rightLength; i++) { ulong digit = (left[i] + carry) + right[i]; left[i] = unchecked((uint)digit); carry = digit >> 32; } return (uint)carry; } [SecuritySafeCritical] private static unsafe uint SubtractDivisor(uint* left, int leftLength, uint* right, int rightLength, ulong q) { Debug.Assert(leftLength >= 0); Debug.Assert(rightLength >= 0); Debug.Assert(leftLength >= rightLength); Debug.Assert(q <= 0xFFFFFFFF); // Combines a subtract and a multiply operation, which is naturally // more efficient than multiplying and then subtracting... ulong carry = 0UL; for (int i = 0; i < rightLength; i++) { carry += right[i] * q; uint digit = unchecked((uint)carry); carry = carry >> 32; if (left[i] < digit) ++carry; left[i] = unchecked(left[i] - digit); } return (uint)carry; } private static bool DivideGuessTooBig(ulong q, ulong valHi, uint valLo, uint divHi, uint divLo) { Debug.Assert(q <= 0xFFFFFFFF); // We multiply the two most significant limbs of the divisor // with the current guess for the quotient. If those are bigger // than the three most significant limbs of the current dividend // we return true, which means the current guess is still too big. ulong chkHi = divHi * q; ulong chkLo = divLo * q; chkHi = chkHi + (chkLo >> 32); chkLo = chkLo & 0xFFFFFFFF; if (chkHi < valHi) return false; if (chkHi > valHi) return true; if (chkLo < valLo) return false; if (chkLo > valLo) return true; return false; } private static uint[] CreateCopy(uint[] value) { Debug.Assert(value != null); Debug.Assert(value.Length != 0); uint[] bits = new uint[value.Length]; Array.Copy(value, 0, bits, 0, bits.Length); return bits; } private static int LeadingZeros(uint value) { if (value == 0) return 32; int count = 0; if ((value & 0xFFFF0000) == 0) { count += 16; value = value << 16; } if ((value & 0xFF000000) == 0) { count += 8; value = value << 8; } if ((value & 0xF0000000) == 0) { count += 4; value = value << 4; } if ((value & 0xC0000000) == 0) { count += 2; value = value << 2; } if ((value & 0x80000000) == 0) { count += 1; } return count; } } }
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using java.lang; using java.util; using stab.query; using stab.reflection; using cnatural.helpers; using cnatural.syntaxtree; namespace cnatural.compiler { class StatementValidator : StatementHandler<Void, Void> { private CompilerContext context; StatementValidator(CompilerContext context) : super(true) { this.context = context; } ExpressionValidator ExpressionValidator { get; set; } protected override Void handleBlock(BlockStatementNode block, Void source) { try { context.MemberResolver.enterScope(); foreach (var s in block.Statements) { handleStatement(s, null); } } finally { context.MemberResolver.leaveScope(); } return null; } protected override Void handleBreak(BreakStatementNode breakStatement, Void source) { return null; } protected override Void handleContinue(ContinueStatementNode continueStatement, Void source) { return null; } protected override Void handleDo(DoStatementNode doStatement, Void source) { try { context.MemberResolver.enterScope(); handleStatement(doStatement.Statement, source); } finally { context.MemberResolver.leaveScope(); } var condition = doStatement.Condition; this.ExpressionValidator.handleExpression(condition, null, true); ValidationHelper.setBoxing(context, context.TypeSystem.BooleanType, condition); var info = condition.getUserData(typeof(ExpressionInfo)); if (info == null || ValidationHelper.getType(context, condition) != context.TypeSystem.BooleanType) { throw context.error(CompileErrorId.NoImplicitConversion, condition, BytecodeHelper.getDisplayName(info == null ? null : info.Type), BytecodeHelper.getDisplayName(context.TypeSystem.BooleanType)); } return null; } protected override Void handleEmpty(EmptyStatementNode empty, Void source) { return null; } protected override Void handleExpression(ExpressionStatementNode expression, Void source) { this.ExpressionValidator.handleExpression(expression.Expression, null, false); return null; } protected override Void handleFor(ForStatementNode forStatement, Void source) { try { context.MemberResolver.enterScope(); foreach (var s in forStatement.Initializer) { handleStatement(s, null); } var condition = forStatement.Condition; if (condition != null) { this.ExpressionValidator.handleExpression(condition, null, true); ValidationHelper.setBoxing(context, context.TypeSystem.BooleanType, condition); var info = condition.getUserData(typeof(ExpressionInfo)); if (info == null || ValidationHelper.getType(context, condition) != context.TypeSystem.BooleanType) { throw context.error(CompileErrorId.NoImplicitConversion, condition, BytecodeHelper.getDisplayName(info == null ? null : info.Type), BytecodeHelper.getDisplayName(context.TypeSystem.BooleanType)); } } try { context.MemberResolver.enterScope(); handleStatement(forStatement.Statement, source); } finally { context.MemberResolver.leaveScope(); } foreach (var s in forStatement.Iterator) { handleStatement(s, source); } } finally { context.MemberResolver.leaveScope(); } return null; } protected override Void handleForeach(ForeachStatementNode foreachStatement, Void src) { try { context.MemberResolver.enterScope(); var source = foreachStatement.Source; this.ExpressionValidator.handleExpression(source, null, true); var sinfo = source.getUserData(typeof(ExpressionInfo)); if (sinfo == null) { throw context.error(CompileErrorId.NoImplicitConversion, source, "<null>", BytecodeHelper.getDisplayName(context.TypeSystem.getType("java/lang/Iterable"))); } var sourceType = ValidationHelper.getType(context, source); TypeInfo elementType; if (sourceType.IsArray) { elementType = sourceType.ElementType; } else { var iterableType = BytecodeHelper.getImplementedIterable(sourceType); if (iterableType == null) { throw context.error(CompileErrorId.NoImplicitConversion, source, BytecodeHelper.getDisplayName(sourceType), BytecodeHelper.getDisplayName(context.TypeSystem.getType("java/lang/Iterable"))); } foreachStatement.addOrReplaceUserData(iterableType); elementType = BytecodeHelper.getIterableOrIteratorElementType(iterableType); } var localName = context.getIdentifier(foreachStatement.NameOffset, foreachStatement.NameLength); if (context.MemberResolver.hasLocal(localName)) { context.addError(CompileErrorId.VariableRedefinition, foreachStatement, localName); } var local = context.MemberResolver.defineLocal(localName, ValidationHelper.getVariableType(context, elementType), context.CodeValidationContext.CurrentMethod); foreachStatement.addOrReplaceUserData(local); handleStatement(foreachStatement.Statement, null); } finally { context.MemberResolver.leaveScope(); } return null; } protected override Void handleGoto(GotoStatementNode gotoStatement, Void source) { return null; } protected override Void handleGotoCase(GotoCaseStatementNode gotoCase, Void source) { var expression = gotoCase.Expression; if (expression != null) { context.DisableIgnoredErrorTracking = true; if (this.ExpressionValidator.handleExpressionNoError(expression, null, true)) { context.DisableIgnoredErrorTracking = false; var einfo = expression.getUserData(typeof(ExpressionInfo)); if (einfo != null) { if (!einfo.IsConstant) { throw context.error(CompileErrorId.ConstantValueExpected, expression); } TypeInfo type = ValidationHelper.getType(context, expression); switch (type.NumericTypeKind) { case Long: case Float: case Double: throw context.error(CompileErrorId.IntegerStringOrEnumExpected, expression); default: ValidationHelper.setBoxing(context, context.TypeSystem.IntType, expression); break; case None: if (type != context.TypeSystem.StringType) { throw context.error(CompileErrorId.IntegerStringOrEnumExpected, expression); } break; } } } else { context.DisableIgnoredErrorTracking = false; } } return null; } protected override Void handleIf(IfStatementNode ifStatement, Void source) { var condition = ifStatement.Condition; this.ExpressionValidator.handleExpression(condition, context.TypeSystem.BooleanType, true); ValidationHelper.setBoxing(context, context.TypeSystem.BooleanType, condition); var cinfo = condition.getUserData(typeof(ExpressionInfo)); if (cinfo == null || ValidationHelper.getType(context, condition) != context.TypeSystem.BooleanType) { throw context.error(CompileErrorId.NoImplicitConversion, condition, BytecodeHelper.getDisplayName(cinfo == null ? null : cinfo.Type), BytecodeHelper.getDisplayName(context.TypeSystem.BooleanType)); } try { context.MemberResolver.enterScope(); handleStatement(ifStatement.IfTrue, null); } finally { context.MemberResolver.leaveScope(); } if (ifStatement.IfFalse != null) { try { context.MemberResolver.enterScope(); handleStatement(ifStatement.IfFalse, null); } finally { context.MemberResolver.leaveScope(); } } return null; } protected override Void handleLabeled(LabeledStatementNode labeled, Void source) { handleStatement(labeled.Statement, null); return null; } protected override Void handleLocalDeclaration(LocalDeclarationStatementNode localDeclaration, Void source) { if (localDeclaration.Type == null) { if (localDeclaration.Declarators.size() > 1) { context.addError(CompileErrorId.MultipleImplicitVariableDeclarators, localDeclaration); } var decl = localDeclaration.Declarators[0]; if (decl.Value == null) { throw context.error(CompileErrorId.MissingImplicitVariableInitializer, localDeclaration); } if (decl.Value.ExpressionKind == ExpressionKind.ArrayInitializer) { throw context.error(CompileErrorId.ImplicitVariableWithArrayInitializer, localDeclaration); } this.ExpressionValidator.handleExpression(decl.Value, null, true); var info = decl.Value.getUserData(typeof(ExpressionInfo)); if (info == null) { throw context.error(CompileErrorId.NullImplicitVariableInitializer, localDeclaration); } localDeclaration.addOrReplaceUserData(new ExpressionInfo(ValidationHelper.getType(context, decl.Value))); var name = context.getIdentifier(decl.NameOffset, decl.NameLength); if (context.MemberResolver.hasLocal(name)) { context.addError(CompileErrorId.VariableRedefinition, decl, name); } var local = context.MemberResolver.defineLocal(name, ValidationHelper.getVariableType(context, info.Type), context.CodeValidationContext.CurrentMethod); decl.addOrReplaceUserData(local); } else { var type = CompilerHelper.resolveTypeReference(context, context.CurrentType.PackageName, localDeclaration.Type); localDeclaration.addOrReplaceUserData(new ExpressionInfo(type)); foreach (var decl in localDeclaration.Declarators) { var name = context.getIdentifier(decl.NameOffset, decl.NameLength); if (decl.Value != null) { var isArrayInit = decl.Value.ExpressionKind == ExpressionKind.ArrayInitializer; if (isArrayInit && !type.IsArray) { throw context.error(CompileErrorId.ArrayTypeExpected, decl); } this.ExpressionValidator.handleExpression(decl.Value, type, true); ValidationHelper.setBoxing(context, type, decl.Value); if (!ValidationHelper.isAssignable(context, type, decl.Value)) { var vinfo = decl.Value.getUserData(typeof(ExpressionInfo)); var vtype = (vinfo == null) ? null : vinfo.Type; context.addError(CompileErrorId.NoImplicitConversion, decl.Value, BytecodeHelper.getDisplayName(vtype), BytecodeHelper.getDisplayName(type)); } if (isArrayInit) { ValidationHelper.setArrayInitializerTypes((ArrayInitializerExpressionNode)decl.Value, type); } } if (context.MemberResolver.hasLocal(name)) { context.addError(CompileErrorId.VariableRedefinition, decl, name); } var local = context.MemberResolver.defineLocal(name, ValidationHelper.getVariableType(context, type), context.CodeValidationContext.CurrentMethod); decl.addOrReplaceUserData(local); } } return null; } protected override Void handleReturn(ReturnStatementNode returnStatement, Void source) { var returnType = context.CodeValidationContext.CurrentMethod.ReturnType; if (returnType == null) { if (returnStatement.Value != null) { this.ExpressionValidator.handleExpression(returnStatement.Value, null, true); var rinfo = returnStatement.Value.getUserData(typeof(ExpressionInfo)); if (rinfo == null) { context.CodeValidationContext.LambdaReturnTypes.add(null); } else { context.CodeValidationContext.LambdaReturnTypes.add(ValidationHelper.getType(context, returnStatement.Value)); } } } else if (returnType == context.TypeSystem.VoidType) { if (returnStatement.Value != null) { context.addError(CompileErrorId.ReturnVoid, returnStatement); } } else if (returnStatement.Value == null) { context.addError(CompileErrorId.ReturnNotVoid, returnStatement); } else { this.ExpressionValidator.handleExpression(returnStatement.Value, returnType, true); ValidationHelper.setBoxing(context, returnType, returnStatement.Value); if (!ValidationHelper.isAssignable(context, returnType, returnStatement.Value)) { var vinfo = returnStatement.Value.getUserData(typeof(ExpressionInfo)); context.addError(CompileErrorId.NoImplicitConversion, returnStatement.Value, BytecodeHelper.getDisplayName((vinfo == null) ? null : vinfo.Type), BytecodeHelper.getDisplayName(returnType)); } } return null; } protected override Void handleSwitch(SwitchStatementNode switchStatement, Void source) { this.ExpressionValidator.handleExpression(switchStatement.Selector, null, true); var sinfo = switchStatement.Selector.getUserData(typeof(ExpressionInfo)); if (sinfo == null) { throw context.error(CompileErrorId.IntegerStringOrEnumExpected, switchStatement.Selector); } var type = ValidationHelper.getType(context, switchStatement.getSelector()); if (!type.IsNumeric && !type.IsEnum && type != context.TypeSystem.StringType) { throw context.error(CompileErrorId.IntegerStringOrEnumExpected, switchStatement.Selector); } var isString = false; switch (type.NumericTypeKind) { case Long: case Float: case Double: throw context.error(CompileErrorId.IntegerStringOrEnumExpected, switchStatement.Selector); default: ValidationHelper.setBoxing(context, context.TypeSystem.IntType, switchStatement.getSelector()); break; case None: isString = !type.IsEnum; break; } var hasDefault = false; HashMap<String, Integer> enumOrdinals = null; HashSet<String> cases = null; if (type.IsEnum) { enumOrdinals = new HashMap<String, Integer>(); cases = new HashSet<String>(); int i = 0; foreach (var f in type.Fields) { if (f.IsEnum) { enumOrdinals[f.Name] = Integer.valueOf(i++); } } } try { context.MemberResolver.enterScope(); foreach (var section in switchStatement.Sections) { if (section.CaseExpression == null) { if (hasDefault) { throw context.error(CompileErrorId.DuplicateCase, section); } hasDefault = true; } else { if (type.IsEnum) { if (section.CaseExpression.ExpressionKind != ExpressionKind.SimpleName) { throw context.error(CompileErrorId.EnumCaseNotIdentifier, section); } var name = (SimpleNameExpressionNode)section.CaseExpression; var text = context.getIdentifier(name.NameOffset, name.NameLength); if (!cases.add(text)) { throw context.error(CompileErrorId.DuplicateCase, section); } if (!enumOrdinals.containsKey(text)) { throw context.error(CompileErrorId.UnknownEnumMember, section, text, BytecodeHelper.getDisplayName(type)); } name.addOrReplaceUserData(enumOrdinals.get(text)); } else { this.ExpressionValidator.handleExpression(section.CaseExpression, type, true); ValidationHelper.getType(context, section.CaseExpression); var cinfo = section.CaseExpression.getUserData(typeof(ExpressionInfo)); if (cinfo == null) { if (!isString) { throw context.error(CompileErrorId.UnexpectedNull, switchStatement); } } else { if (!cinfo.IsConstant) { throw context.error(CompileErrorId.ConstantValueExpected, section); } if (!type.isAssignableFrom(ValidationHelper.getType(context, section.CaseExpression))) { context.addError(CompileErrorId.NoImplicitConversion, section.CaseExpression, BytecodeHelper.getDisplayName(cinfo.Type), BytecodeHelper.getDisplayName(type)); } } } } foreach (var s in section.Statements) { handleStatement(s, null); } } } finally { context.MemberResolver.leaveScope(); } return null; } protected override Void handleSynchronized(SynchronizedStatementNode synchronizedStatement, Void source) { var lock = synchronizedStatement.Lock; this.ExpressionValidator.handleExpression(lock, null, true); var linfo = lock.getUserData(typeof(ExpressionInfo)); if (linfo == null) { throw context.error(CompileErrorId.UnexpectedNull, lock); } if (ValidationHelper.getType(context, lock).IsPrimitive) { throw context.error(CompileErrorId.ReferenceTypeValueExpected, lock); } handleStatement(synchronizedStatement.Statement, null); return null; } protected override Void handleThrow(ThrowStatementNode throwStatement, Void source) { var exception = throwStatement.Exception; if (exception != null) { this.ExpressionValidator.handleExpression(exception, null, true); var einfo = exception.getUserData(typeof(ExpressionInfo)); if (einfo != null) { if (!context.TypeSystem.getType("java/lang/Throwable").isAssignableFrom(ValidationHelper.getType(context, exception))) { throw context.error(CompileErrorId.NoImplicitConversion, exception, BytecodeHelper.getDisplayName(einfo.Type), "java.lang.Throwable"); } } } return null; } protected override Void handleTry(TryStatementNode tryStatement, Void source) { handleStatement(tryStatement.Block, source); foreach (var node in tryStatement.CatchClauses) { try { context.MemberResolver.enterScope(); if (node.ExceptionType != null) { var etype = CompilerHelper.resolveTypeReference(context, context.CurrentType.PackageName, node.ExceptionType); node.addOrReplaceUserData(etype); if (etype.IsGenericParameter) { throw context.error(CompileErrorId.GenericParameterInCatch, node.ExceptionType, BytecodeHelper.getDisplayName(etype)); } if (!context.TypeSystem.getType("java/lang/Throwable").isAssignableFrom(etype)) { throw context.error(CompileErrorId.NoImplicitConversion, node.ExceptionType, BytecodeHelper.getDisplayName(etype), "java.lang.Throwable"); } if (node.NameLength > 0) { var local = context.MemberResolver.defineLocal(context.getIdentifier(node.NameOffset, node.NameLength), etype, context.CodeValidationContext.CurrentMethod); node.addOrReplaceUserData(local); } } foreach (var s in node.Block.Statements) { handleStatement(s, source); } } finally { context.MemberResolver.leaveScope(); } } if (tryStatement.Finally != null) { handleStatement(tryStatement.Finally, source); } return null; } protected override Void handleUsing(UsingStatementNode usingStatement, Void source) { try { context.MemberResolver.enterScope(); var resource = usingStatement.ResourceAcquisition; handleStatement(resource, null); if (resource.StatementKind == StatementKind.Expression) { var expr = ((ExpressionStatementNode)resource).Expression; var einfo = expr.getUserData(typeof(ExpressionInfo)); if (einfo == null || BytecodeHelper.getDisposeMethod(context.AnnotatedTypeSystem, ValidationHelper.getType(context, expr)) == null) { context.addError(CompileErrorId.NoDisposeMethod, expr, BytecodeHelper.getDisplayName(einfo == null ? null : einfo.Type)); } } else { foreach (var decl in ((LocalDeclarationStatementNode)resource).Declarators) { if (decl.Value == null) { context.addError(CompileErrorId.UsingVariableUninitialized, decl); } else { var vinfo = decl.Value.getUserData(typeof(ExpressionInfo)); if (vinfo == null || BytecodeHelper.getDisposeMethod(context.AnnotatedTypeSystem, ValidationHelper.getType(context, decl.Value)) == null) { context.addError(CompileErrorId.NoDisposeMethod, decl.Value, BytecodeHelper.getDisplayName(vinfo == null ? null : vinfo.Type)); } } } } handleStatement(usingStatement.Statement, null); } finally { context.MemberResolver.leaveScope(); } return null; } protected override Void handleWhile(WhileStatementNode whileStatement, Void source) { var condition = whileStatement.Condition; this.ExpressionValidator.handleExpression(condition, context.TypeSystem.BooleanType, true); ValidationHelper.setBoxing(context, context.TypeSystem.BooleanType, condition); var info = condition.getUserData(typeof(ExpressionInfo)); if (info == null || ValidationHelper.getType(context, condition) != context.TypeSystem.BooleanType) { throw context.error(CompileErrorId.NoImplicitConversion, condition, BytecodeHelper.getDisplayName(info == null ? null : ValidationHelper.getType(context, condition)), BytecodeHelper.getDisplayName(context.TypeSystem.BooleanType)); } try { context.MemberResolver.enterScope(); handleStatement(whileStatement.Statement, source); } finally { context.MemberResolver.leaveScope(); } return null; } protected override Void handleYield(YieldStatementNode yieldStatement, Void source) { var returnType = context.CodeValidationContext.CurrentMethod.ReturnType; var value = yieldStatement.Value; if (returnType == null) { if (value != null) { this.ExpressionValidator.handleExpression(value, returnType, true); } } else { var elementType = BytecodeHelper.getIterableOrIteratorElementType(returnType); if (elementType == null) { throw context.error(CompileErrorId.YieldOutsideIterator, yieldStatement); } if (value != null) { this.ExpressionValidator.handleExpression(value, elementType, true); ValidationHelper.setBoxing(context, elementType, value); if (!ValidationHelper.isAssignable(context, elementType, value)) { throw context.error(CompileErrorId.NoImplicitConversion, value, BytecodeHelper.getDisplayName(ValidationHelper.getType(context, value)), BytecodeHelper.getDisplayName(elementType)); } } } if (context.Iterables[context.CodeValidationContext.CurrentMethod] == null) { var prefix = "_" + context.CodeValidationContext.CurrentMethod.Name + "_Iterable"; int n = context.CurrentType.NestedTypes.count(p => p.Name.startsWith(prefix)); var typeBuilder = ((TypeBuilder)context.CurrentType).defineNestedType(prefix + n); typeBuilder.setSourceFile(PathHelper.getFileName(yieldStatement.Filename)); typeBuilder.setSynthetic(true); typeBuilder.setSuper(true); context.Iterables[context.CodeValidationContext.CurrentMethod] = typeBuilder; context.TypeBuilders.add(typeBuilder); typeBuilder.setBaseType(context.TypeSystem.ObjectType); } return null; } } }
// Copyright 2019, Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; using FirebaseAdmin.Tests; using Google.Apis.Http; using Google.Apis.Util; using Xunit; namespace FirebaseAdmin.Util.Tests { public class RetryHttpClientInitializerTest { [Fact] public async Task RetryDisabledByDefault() { var handler = new MockMessageHandler() { StatusCode = HttpStatusCode.ServiceUnavailable, Response = "{}", }; var factory = new MockHttpClientFactory(handler); var httpClient = factory.CreateHttpClient(new CreateHttpClientArgs()); var response = await httpClient.SendAsync(CreateRequest()); Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode); Assert.Equal(1, handler.Calls); } [Fact] public async Task RetryOnHttp503() { var handler = new MockMessageHandler() { StatusCode = HttpStatusCode.ServiceUnavailable, Response = "{}", }; var waiter = new MockWaiter(); var httpClient = CreateHttpClient(handler, RetryOptions.Default, waiter); var response = await httpClient.SendAsync(CreateRequest()); Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode); Assert.Equal(5, handler.Calls); var expected = new List<TimeSpan>() { TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(4), TimeSpan.FromSeconds(8), }; Assert.Equal(expected, waiter.WaitTimes); } [Fact] public async Task RetryOnUnsuccessfulResponseDisabled() { var handler = new MockMessageHandler() { StatusCode = HttpStatusCode.ServiceUnavailable, Response = "{}", }; var waiter = new MockWaiter(); var options = RetryOptions.Default; options.HandleUnsuccessfulResponseFunc = null; var httpClient = CreateHttpClient(handler, options, waiter); var response = await httpClient.SendAsync(CreateRequest()); Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode); Assert.Equal(1, handler.Calls); } [Fact] public async Task NoRetryOnHttp500ByDefault() { var handler = new MockMessageHandler() { StatusCode = HttpStatusCode.InternalServerError, Response = "{}", }; var waiter = new MockWaiter(); var httpClient = CreateHttpClient(handler, RetryOptions.Default, waiter); var response = await httpClient.SendAsync(CreateRequest()); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); Assert.Equal(1, handler.Calls); } [Fact] public async Task RetryOnHttp500WhenRequested() { var handler = new MockMessageHandler() { StatusCode = HttpStatusCode.InternalServerError, Response = "{}", }; var waiter = new MockWaiter(); var options = RetryOptions.Default; options.HandleUnsuccessfulResponseFunc = (resp) => resp.StatusCode == HttpStatusCode.InternalServerError; var httpClient = CreateHttpClient(handler, options, waiter); var response = await httpClient.SendAsync(CreateRequest()); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); Assert.Equal(5, handler.Calls); var expected = new List<TimeSpan>() { TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(4), TimeSpan.FromSeconds(8), }; Assert.Equal(expected, waiter.WaitTimes); } [Fact] public async Task RetryAfterSeconds() { var handler = new MockMessageHandler() { StatusCode = HttpStatusCode.ServiceUnavailable, ApplyHeaders = (headers, contentHeaders) => { headers.RetryAfter = RetryConditionHeaderValue.Parse("3"); }, Response = "{}", }; var waiter = new MockWaiter(); var httpClient = CreateHttpClient(handler, RetryOptions.Default, waiter); var response = await httpClient.SendAsync(CreateRequest()); Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode); Assert.Equal(5, handler.Calls); var expected = new List<TimeSpan>() { TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(3), }; Assert.Equal(expected, waiter.WaitTimes); } [Fact] public async Task RetryAfterTimestamp() { var clock = new MockClock(); var timestamp = clock.UtcNow.AddSeconds(4).ToString("r"); var handler = new MockMessageHandler() { StatusCode = HttpStatusCode.ServiceUnavailable, ApplyHeaders = (headers, contentHeaders) => { headers.RetryAfter = RetryConditionHeaderValue.Parse(timestamp); }, Response = "{}", }; var waiter = new MockWaiter(); var httpClient = CreateHttpClient(handler, RetryOptions.Default, waiter, clock); var response = await httpClient.SendAsync(CreateRequest()); Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode); Assert.Equal(5, handler.Calls); Assert.Equal(4, waiter.WaitTimes.Count); foreach (var timespan in waiter.WaitTimes) { // Due to the date format used in HTTP headers, the milliseconds precision gets // lost. Therefore the actual delay is going to be a value between 3 and 4 seconds. Assert.True(timespan.TotalSeconds > 3.0 && timespan.TotalSeconds <= 4.0); } } [Fact] public async Task RetryAfterTooLarge() { var handler = new MockMessageHandler() { StatusCode = HttpStatusCode.ServiceUnavailable, ApplyHeaders = (headers, contentHeaders) => { headers.RetryAfter = RetryConditionHeaderValue.Parse("300"); }, Response = "{}", }; var waiter = new MockWaiter(); var httpClient = CreateHttpClient(handler, RetryOptions.Default, waiter); var response = await httpClient.SendAsync(CreateRequest()); Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode); Assert.Equal(1, handler.Calls); } [Fact] public async Task RetryOnException() { var handler = new MockMessageHandler() { Exception = new Exception("transport error"), }; var waiter = new MockWaiter(); var httpClient = CreateHttpClient(handler, RetryOptions.Default, waiter); var ex = await Assert.ThrowsAsync<Exception>( async () => await httpClient.SendAsync(CreateRequest())); Assert.Equal("transport error", ex.Message); Assert.Equal(5, handler.Calls); var expected = new List<TimeSpan>() { TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(4), TimeSpan.FromSeconds(8), }; Assert.Equal(expected, waiter.WaitTimes); } [Fact] public async Task RetryOnExceptionDisabled() { var handler = new MockMessageHandler() { Exception = new Exception("transport error"), }; var waiter = new MockWaiter(); var options = RetryOptions.Default; options.HandleExceptionFunc = null; var httpClient = CreateHttpClient(handler, options, waiter); var ex = await Assert.ThrowsAsync<Exception>( async () => await httpClient.SendAsync(CreateRequest())); Assert.Equal("transport error", ex.Message); Assert.Equal(1, handler.Calls); } [Fact] public async Task BackOffFactor() { var handler = new MockMessageHandler() { Exception = new Exception("transport error"), }; var waiter = new MockWaiter(); var options = RetryOptions.Default; options.BackOffFactor = 1.5; var httpClient = CreateHttpClient(handler, options, waiter); var ex = await Assert.ThrowsAsync<Exception>( async () => await httpClient.SendAsync(CreateRequest())); Assert.Equal("transport error", ex.Message); Assert.Equal(5, handler.Calls); var expected = new List<TimeSpan>() { TimeSpan.FromSeconds(1.5), TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(6), TimeSpan.FromSeconds(12), }; Assert.Equal(expected, waiter.WaitTimes); } [Fact] public async Task BackOffFactorZero() { var handler = new MockMessageHandler() { Exception = new Exception("transport error"), }; var waiter = new MockWaiter(); var options = RetryOptions.Default; options.BackOffFactor = 0; var httpClient = CreateHttpClient(handler, options, waiter); var ex = await Assert.ThrowsAsync<Exception>( async () => await httpClient.SendAsync(CreateRequest())); Assert.Equal("transport error", ex.Message); Assert.Equal(5, handler.Calls); var expected = new List<TimeSpan>() { TimeSpan.Zero, TimeSpan.Zero, TimeSpan.Zero, TimeSpan.Zero, }; Assert.Equal(expected, waiter.WaitTimes); } [Fact] public void BackOffFactorNegative() { var options = RetryOptions.Default; options.BackOffFactor = -1; Assert.Throws<ArgumentException>(() => new RetryHttpClientInitializer(options)); } private static ConfigurableHttpClient CreateHttpClient( MockMessageHandler handler, RetryOptions options, IWaiter waiter, IClock clock = null) { var args = new CreateHttpClientArgs(); args.Initializers.Add(new RetryHttpClientInitializer(options, clock, waiter)); var factory = new MockHttpClientFactory(handler); return factory.CreateHttpClient(args); } private static HttpRequestMessage CreateRequest() { return new HttpRequestMessage() { Method = HttpMethod.Get, RequestUri = new Uri("https://firebase.google.com"), }; } internal sealed class MockWaiter : IWaiter { private readonly List<TimeSpan> waitTimes = new List<TimeSpan>(); internal IReadOnlyList<TimeSpan> WaitTimes { get => this.waitTimes; } public Task Wait(TimeSpan ts, CancellationToken cancellationToken) { this.waitTimes.Add(ts); return Task.CompletedTask; } } } }
//BSD, 2014-present, WinterDev //---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // C# Port port by: Lars Brubaker // larsbrubaker@gmail.com // Copyright (C) 2007 // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // // The author gratefully acknowleges the support of David Turner, // Robert Wilhelm, and Werner Lemberg - the authors of the FreeType // libray - in producing this work. See http://www.freetype.org for details. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- // // Adaptation for 32-bit screen coordinates has been sponsored by // Liberty Technology Systems, Inc., visit http://lib-sys.com // // Liberty Technology Systems, Inc. is the provider of // PostScript and PDF technology for software developers. // //---------------------------------------------------------------------------- using System; using poly_subpix = PixelFarm.CpuBlit.Rasterization.PolySubPix; namespace PixelFarm.CpuBlit.Rasterization { partial class ScanlineRasterizer { //-----------------------------------------------------------------cell_aa // A pixel cell. There're no constructors defined and it was done *** // intentionally in order to avoid extra overhead when allocating an **** // array of cells. *** struct CellAA { public readonly int x; public readonly int y; public readonly int cover; public readonly int area; #if DEBUG #if !COSMOS public int dbugLeft; public int dbugRight; #endif #endif private CellAA(int x, int y, int cover, int area) { this.x = x; this.y = y; this.cover = cover; this.area = area; #if DEBUG #if !COSMOS dbugLeft = 0; dbugRight = 0; #endif #endif } public static CellAA Create(int x, int y, int cover, int area) { return new CellAA(x, y, cover, area); //CellAA cell = new CellAA(); //cell.x = x; //cell.y = y; //cell.cover = cover; //cell.area = area; //return cell; } #if DEBUG public static CellAA dbugCreate(int x, int y, int cover, int area, int left, int right) { CellAA cell = new CellAA(x, y, cover, area); //cell.x = x; //cell.y = y; //cell.cover = cover; //cell.area = area; #if !COSMOS cell.dbugLeft = left; cell.dbugRight = right; #endif return cell; } #endif #if DEBUG #if !COSMOS public override string ToString() { return "x:" + x + ",y:" + y + ",cover:" + cover + ",area:" + area + ",left:" + dbugLeft + ",right:" + dbugRight; } #endif #endif } struct CellAABlob { readonly CellAARasterizer _cellAARas; public CellAABlob(CellAARasterizer aaRas) { _cellAARas = aaRas; #if DEBUG _dbugLockSortCell = false; #endif } public int MinX => _cellAARas.MinX; public int MinY => _cellAARas.MinY; // public int MaxX => _cellAARas.MaxX; public int MaxY => _cellAARas.MaxY; public void Reset() => _cellAARas.Reset(); public bool Sorted => _cellAARas.Sorted; /// <summary> /// sort cell, and return total cell count /// </summary> /// <returns></returns> public int SortCells() { #if DEBUG if (_dbugLockSortCell) { throw new NotSupportedException(); } #endif _cellAARas.SortCells(); return _cellAARas.TotalCells; } #if DEBUG bool _dbugLockSortCell; public void dbugLockSortCell(bool value) { _dbugLockSortCell = value; } #endif public CellAA[] UnsafeGetAllSortedCells() => _cellAARas.UnsafeGetAllSortedCells(); public void GetCellRange(int y, out int offset, out int num) { _cellAARas.GetCellRange(y, out offset, out num); } } //-----------------------------------------------------rasterizer_cells_aa // An internal class that implements the main rasterization algorithm. // Used in the rasterizer. Should not be used directly. sealed class CellAARasterizer { int _num_used_cells; ArrayList<CellAA> _cells; readonly ArrayList<CellAA> _sorted_cells; readonly ArrayList<SortedY> _sorted_y; //------------------ int _cCell_x; int _cCell_y; int _cCell_cover; int _cCell_area; //------------------ #if DEBUG int _cCell_left; int _cCell_right; #endif //------------------ int _min_x; int _min_y; int _max_x; int _max_y; bool _sorted; const int BLOCK_SHIFT = 12; const int BLOCK_SIZE = 1 << BLOCK_SHIFT; const int BLOCK_MASK = BLOCK_SIZE - 1; const int BLOCK_POOL = 256; const int BLOCK_LIMIT = BLOCK_SIZE * 1024; struct SortedY { internal int start; internal int num; } public CellAARasterizer() { _sorted_cells = new ArrayList<CellAA>(); _sorted_y = new ArrayList<SortedY>(); _min_x = (0x7FFFFFFF); _min_y = (0x7FFFFFFF); _max_x = (-0x7FFFFFFF); _max_y = (-0x7FFFFFFF); _sorted = false; ResetCurrentCell(); _cells = new ArrayList<CellAA>(BLOCK_SIZE); } void ResetCurrentCell() { _cCell_x = 0x7FFFFFFF; _cCell_y = 0x7FFFFFFF; _cCell_cover = 0; _cCell_area = 0; #if DEBUG _cCell_left = -1; _cCell_right = -1; #endif } public void Reset() { _num_used_cells = 0; ResetCurrentCell(); _sorted = false; _min_x = 0x7FFFFFFF; _min_y = 0x7FFFFFFF; _max_x = -0x7FFFFFFF; _max_y = -0x7FFFFFFF; } const int DX_LIMIT = (16384 << PolySubPix.SHIFT); const int POLY_SUBPIXEL_SHIFT = PolySubPix.SHIFT; const int POLY_SUBPIXEL_MASK = PolySubPix.MASK; const int POLY_SUBPIXEL_SCALE = PolySubPix.SCALE; public void DrawLine(int x1, int y1, int x2, int y2) { int dx = x2 - x1; if (dx >= DX_LIMIT || dx <= -DX_LIMIT) { int cx = (x1 + x2) >> 1; int cy = (y1 + y2) >> 1; DrawLine(x1, y1, cx, cy); DrawLine(cx, cy, x2, y2); } int dy = y2 - y1; int ex1 = x1 >> POLY_SUBPIXEL_SHIFT; int ex2 = x2 >> POLY_SUBPIXEL_SHIFT; int ey1 = y1 >> POLY_SUBPIXEL_SHIFT; int ey2 = y2 >> POLY_SUBPIXEL_SHIFT; int fy1 = y1 & POLY_SUBPIXEL_MASK; int fy2 = y2 & POLY_SUBPIXEL_MASK; int x_from, x_to; int p, rem, mod, lift, delta, first, incr; if (ex1 < _min_x) _min_x = ex1; if (ex1 > _max_x) _max_x = ex1; if (ey1 < _min_y) _min_y = ey1; if (ey1 > _max_y) _max_y = ey1; if (ex2 < _min_x) _min_x = ex2; if (ex2 > _max_x) _max_x = ex2; if (ey2 < _min_y) _min_y = ey2; if (ey2 > _max_y) _max_y = ey2; //*** AddNewCell(ex1, ey1); //*** //everything is on a single horizontal line if (ey1 == ey2) { RenderHLine(ey1, x1, fy1, x2, fy2); return; } //Vertical line - we have to calculate start and end cells, //and then - the common values of the area and coverage for //all cells of the line. We know exactly there's only one //cell, so, we don't have to call render_hline(). incr = 1; if (dx == 0) { int ex = x1 >> POLY_SUBPIXEL_SHIFT; int two_fx = (x1 - (ex << POLY_SUBPIXEL_SHIFT)) << 1; int area; first = POLY_SUBPIXEL_SCALE; if (dy < 0) { first = 0; incr = -1; } x_from = x1; delta = first - fy1; _cCell_cover += delta; _cCell_area += two_fx * delta; ey1 += incr; //*** AddNewCell(ex, ey1); //*** delta = first + first - POLY_SUBPIXEL_SCALE; area = two_fx * delta; while (ey1 != ey2) { _cCell_cover = delta; _cCell_area = area; ey1 += incr; //*** AddNewCell(ex, ey1); //*** } delta = fy2 - POLY_SUBPIXEL_SCALE + first; _cCell_cover += delta; _cCell_area += two_fx * delta; return; } //ok, we have to render several hlines p = (POLY_SUBPIXEL_SCALE - fy1) * dx; first = POLY_SUBPIXEL_SCALE; if (dy < 0) { p = fy1 * dx; first = 0; incr = -1; dy = -dy; } delta = p / dy; mod = p % dy; if (mod < 0) { delta--; mod += dy; } x_from = x1 + delta; RenderHLine(ey1, x1, fy1, x_from, first); ey1 += incr; //*** AddNewCell(x_from >> POLY_SUBPIXEL_SHIFT, ey1); //*** if (ey1 != ey2) { p = POLY_SUBPIXEL_SCALE * dx; lift = p / dy; rem = p % dy; if (rem < 0) { lift--; rem += dy; } mod -= dy; while (ey1 != ey2) { delta = lift; mod += rem; if (mod >= 0) { mod -= dy; delta++; } x_to = x_from + delta; //*** RenderHLine(ey1, x_from, POLY_SUBPIXEL_SCALE - first, x_to, first); //*** x_from = x_to; ey1 += incr; //*** AddNewCell(x_from >> POLY_SUBPIXEL_SHIFT, ey1); //*** } } RenderHLine(ey1, x_from, POLY_SUBPIXEL_SCALE - first, x2, fy2); } public int MinX => _min_x; public int MinY => _min_y; // public int MaxX => _max_x; public int MaxY => _max_y; public void SortCells() { if (_sorted) return; //Perform sort only the first time. WriteCurrentCell(); //---------------------------------- //reset current cell _cCell_x = 0x7FFFFFFF; _cCell_y = 0x7FFFFFFF; _cCell_cover = 0; _cCell_area = 0; //---------------------------------- if (_num_used_cells == 0) return; // Allocate the array of cell pointers _sorted_cells.Allocate(_num_used_cells); // Allocate and zero the Y array _sorted_y.Allocate((int)(_max_y - _min_y + 1)); _sorted_y.Zero(); CellAA[] cells = _cells.UnsafeInternalArray; SortedY[] sortedYData = _sorted_y.UnsafeInternalArray; CellAA[] sortedCellsData = _sorted_cells.UnsafeInternalArray; // Create the Y-histogram (count the numbers of cells for each Y) unsafe { fixed (SortedY* sortedY_arr = &sortedYData[0]) { for (int i = 0; i < _num_used_cells; ++i) { //int index = cells[i].y - _min_y;//dbug //sortedYData[index].start++; //sortedYData[cells[i].y - _min_y].start++; //SortedY* sortedY_elem = sortedY_arr + (cells[i].y - _min_y); //sortedY_elem->start++; (sortedY_arr + (cells[i].y - _min_y))->start++; } // Convert the Y-histogram into the array of starting indexes int start = 0; int sortedYSize = _sorted_y.Count; for (int i = 0; i < sortedYSize; i++) { SortedY* sortedY_elem = sortedY_arr + i; int v = sortedY_elem->start; sortedY_elem->start = start; start += v; } // Fill the cell pointer array sorted by Y for (int i = 0; i < _num_used_cells; ++i) { //int sortedIndex = cells[i].y - _min_y; //int curr_y_start = sortedYData[sortedIndex].start; //int curr_y_num = sortedYData[sortedIndex].num; //sortedCellsData[curr_y_start + curr_y_num] = cells[i]; //sortedYData[sortedIndex].num++; SortedY* sortedY_elem = sortedY_arr + (cells[i].y - _min_y); sortedCellsData[sortedY_elem->start + sortedY_elem->num] = cells[i]; sortedY_elem->num++; } // Finally arrange the X-arrays for (int i = 0; i < sortedYSize; i++) { SortedY* sortedY_elem = sortedY_arr + i; if (sortedY_elem->num != 0) { QuickSort.Sort(sortedCellsData, sortedY_elem->start, sortedY_elem->start + sortedY_elem->num - 1); } } } } _sorted = true; } public int TotalCells => _num_used_cells; public CellAA[] UnsafeGetAllSortedCells() => _sorted_cells.UnsafeInternalArray; public void GetCellRange(int y, out int offset, out int num) { SortedY d = _sorted_y[y - _min_y]; offset = d.start; num = d.num; } // public bool Sorted => _sorted; // void AddNewCell(int x, int y) { WriteCurrentCell(); _cCell_x = x; _cCell_y = y; //reset area and coverage after add new cell _cCell_cover = 0; _cCell_area = 0; } void WriteCurrentCell() { if ((_cCell_area | _cCell_cover) != 0) { //check cell limit if (_num_used_cells >= BLOCK_LIMIT) { return; } //------------------------------------------ //alloc if required if ((_num_used_cells + 1) >= _cells.AllocatedSize) { _cells = new ArrayList<CellAA>(_cells, BLOCK_SIZE); } #if DEBUG //m_cells.SetData(m_num_used_cells, CellAA.dbugCreate( // cCell_x, cCell_y, // cCell_cover, cCell_area, // cCell_left, // cCell_right)); _cells.SetData(_num_used_cells, CellAA.Create( _cCell_x, _cCell_y, _cCell_cover, _cCell_area)); #else _cells.SetData(_num_used_cells, CellAA.Create( _cCell_x, _cCell_y, _cCell_cover, _cCell_area)); #endif _num_used_cells++; } } void RenderHLine(int ey, int x1, int y1, int x2, int y2) { //trivial case. Happens often if (y1 == y2) { //*** AddNewCell(x2 >> poly_subpix.SHIFT, ey); //*** return; } int ex1 = x1 >> poly_subpix.SHIFT; int ex2 = x2 >> poly_subpix.SHIFT; int fx1 = x1 & (int)poly_subpix.MASK; int fx2 = x2 & (int)poly_subpix.MASK; int delta; //everything is located in a single cell. That is easy! if (ex1 == ex2) { delta = y2 - y1; _cCell_cover += delta; _cCell_area += (fx1 + fx2) * delta; return; } //---------------------------- int p, first, dx; int incr, lift, mod, rem; //---------------------------- //ok, we'll have to render a run of adjacent cells on the same hline... p = ((int)poly_subpix.SCALE - fx1) * (y2 - y1); first = (int)poly_subpix.SCALE; incr = 1; dx = x2 - x1; if (dx < 0) { p = fx1 * (y2 - y1); first = 0; incr = -1; dx = -dx; } delta = p / dx; mod = p % dx; if (mod < 0) { delta--; mod += dx; } _cCell_cover += delta; _cCell_area += (fx1 + first) * delta; ex1 += incr; //*** AddNewCell(ex1, ey); //*** y1 += delta; if (ex1 != ex2) { p = (int)poly_subpix.SCALE * (y2 - y1 + delta); lift = p / dx; rem = p % dx; if (rem < 0) { lift--; rem += dx; } mod -= dx; while (ex1 != ex2) { delta = lift; mod += rem; if (mod >= 0) { mod -= dx; delta++; } _cCell_cover += delta; _cCell_area += (int)poly_subpix.SCALE * delta; y1 += delta; ex1 += incr; //*** AddNewCell(ex1, ey); //*** } } delta = y2 - y1; _cCell_cover += delta; _cCell_area += (fx2 + (int)poly_subpix.SCALE - first) * delta; } //------------ static class QuickSort { public static void Sort(CellAA[] dataToSort) { Sort(dataToSort, 0, dataToSort.Length - 1); } public static void Sort(CellAA[] dataToSort, int beg, int end) { if (end == beg) { return; } else { int pivot = GetPivotPoint(dataToSort, beg, end); if (pivot > beg) { Sort(dataToSort, beg, pivot - 1); } if (pivot < end) { Sort(dataToSort, pivot + 1, end); } } } static int GetPivotPoint(CellAA[] dataToSort, int begPoint, int endPoint) { int pivot = begPoint; int m = begPoint + 1; int n = endPoint; int x_at_PivotPoint = dataToSort[pivot].x; while ((m < endPoint) && x_at_PivotPoint >= dataToSort[m].x) { m++; } while ((n > begPoint) && (x_at_PivotPoint <= dataToSort[n].x)) { n--; } while (m < n) { //swap data between m and n CellAA temp = dataToSort[m]; dataToSort[m] = dataToSort[n]; dataToSort[n] = temp; while ((m < endPoint) && (x_at_PivotPoint >= dataToSort[m].x)) { m++; } while ((n > begPoint) && (x_at_PivotPoint <= dataToSort[n].x)) { n--; } } if (pivot != n) { CellAA temp2 = dataToSort[n]; dataToSort[n] = dataToSort[pivot]; dataToSort[pivot] = temp2; } return n; } } } } }
using NUnit.Framework; namespace System.Data.SQLite.Tests { [TestFixture] public class SQLiteConnectionStringBuilderTests { [Test] public void Defaults() { var csb = new SQLiteConnectionStringBuilder(); Assert.AreEqual(0, csb.CacheSize); Assert.AreEqual("", csb.DataSource); Assert.AreEqual(0, csb.DefaultTimeout); Assert.IsFalse(csb.FailIfMissing); Assert.IsFalse(csb.ForeignKeys); Assert.AreEqual(SQLiteJournalModeEnum.Default, csb.JournalMode); Assert.AreEqual(0, csb.PageSize); Assert.IsNull(csb.Password); Assert.IsFalse(csb.ReadOnly); Assert.AreEqual(SynchronizationModes.Normal, csb.SyncMode); Assert.AreEqual(SQLiteTemporaryStore.Default, csb.TempStore); } [Test] public void ParseConnectionString() { var csb = new SQLiteConnectionStringBuilder { ConnectionString = "Data Source=\"C:\\temp\\test.db\";Synchronous=full;Read Only=true;FailIfMissing=True;Foreign Keys=true;Cache Size=6000;Page Size=2048;default timeout=30;password=S3kr3t;_TempStore=memory" }; Assert.AreEqual(6000, csb.CacheSize); Assert.AreEqual(@"C:\temp\test.db", csb.DataSource); Assert.AreEqual(30, csb.DefaultTimeout); Assert.IsTrue(csb.FailIfMissing); Assert.IsTrue(csb.ForeignKeys); Assert.AreEqual(SQLiteJournalModeEnum.Default, csb.JournalMode); Assert.AreEqual(2048, csb.PageSize); Assert.AreEqual("S3kr3t", csb.Password); Assert.IsTrue(csb.ReadOnly); Assert.AreEqual(SynchronizationModes.Full, csb.SyncMode); Assert.AreEqual(SQLiteTemporaryStore.Memory, csb.TempStore); } [TestCase("1000", 1000)] [TestCase("4000", 4000)] [TestCase(null, 0)] [TestCase("", 0)] public void CacheSize(string text, int expected) { SQLiteConnectionStringBuilder csb = new SQLiteConnectionStringBuilder { ConnectionString = "Cache Size=" + text }; Assert.AreEqual(expected, csb.CacheSize); } [TestCase("FALSE")] public void CacheSizeThrows(string text) { SQLiteConnectionStringBuilder csb = new SQLiteConnectionStringBuilder { ConnectionString = "Cache Size=" + text }; int unused; Assert.Catch<FormatException>(() => unused = csb.CacheSize); } [TestCase("Data Source", "C:\\temp\\test.db")] [TestCase("DATA SOURCE", "database.sqlite")] [TestCase("data source", "semi;colon.db")] public void DataSource(string keyName, string dataSource) { SQLiteConnectionStringBuilder csb = new SQLiteConnectionStringBuilder { ConnectionString = keyName + "=\"" + dataSource + "\";Read Only=false" }; Assert.AreEqual(dataSource, csb.DataSource); } [TestCase("30", 30)] [TestCase("86400", 86400)] [TestCase(null, 0)] [TestCase("", 0)] public void DefaultTimeout(string text, int expected) { SQLiteConnectionStringBuilder csb = new SQLiteConnectionStringBuilder { ConnectionString = "Default Timeout=" + text }; Assert.AreEqual(expected, csb.DefaultTimeout); } [TestCase("FALSE")] public void DefaultTimeoutThrows(string text) { SQLiteConnectionStringBuilder csb = new SQLiteConnectionStringBuilder { ConnectionString = "Default Timeout=" + text }; int unused; Assert.Catch<FormatException>(() => unused = csb.DefaultTimeout); } [TestCase("True", true)] [TestCase("true", true)] [TestCase("FALSE", false)] public void FailIfMissing(string text, bool expected) { SQLiteConnectionStringBuilder csb = new SQLiteConnectionStringBuilder { ConnectionString = "FailIfMissing=" + text }; Assert.AreEqual(expected, csb.FailIfMissing); } [TestCase("null")] public void FailIfMissingThrows(string text) { SQLiteConnectionStringBuilder csb = new SQLiteConnectionStringBuilder { ConnectionString = "FailIfMissing=" + text }; bool unused; Assert.Catch<FormatException>(() => unused = csb.FailIfMissing); } [TestCase("True", true)] [TestCase("true", true)] [TestCase("FALSE", false)] public void ForeignKeys(string text, bool expected) { SQLiteConnectionStringBuilder csb = new SQLiteConnectionStringBuilder { ConnectionString = "Foreign Keys=" + text }; Assert.AreEqual(expected, csb.ForeignKeys); } [TestCase("null")] public void ForeignKeysThrows(string text) { SQLiteConnectionStringBuilder csb = new SQLiteConnectionStringBuilder { ConnectionString = "Foreign Keys=" + text }; bool unused; Assert.Catch<FormatException>(() => unused = csb.ForeignKeys); } [TestCase("truncate", SQLiteJournalModeEnum.Truncate)] [TestCase("TRUNCATE", SQLiteJournalModeEnum.Truncate)] [TestCase("", SQLiteJournalModeEnum.Default)] [TestCase("default", SQLiteJournalModeEnum.Default)] [TestCase(null, SQLiteJournalModeEnum.Default)] [TestCase("off", SQLiteJournalModeEnum.Off)] [TestCase("Persist", SQLiteJournalModeEnum.Persist)] [TestCase("memory", SQLiteJournalModeEnum.Memory)] [TestCase("WAL", SQLiteJournalModeEnum.Wal)] public void JournalMode(string text, SQLiteJournalModeEnum expected) { SQLiteConnectionStringBuilder csb = new SQLiteConnectionStringBuilder { ConnectionString = "Journal Mode=" + text }; Assert.AreEqual(expected, csb.JournalMode); } [TestCase("1048576", 1048576)] [TestCase("4294967296", 4294967296L)] [TestCase(null, 0)] [TestCase("", 0)] public void MmapSize(string text, long expected) { SQLiteConnectionStringBuilder csb = new SQLiteConnectionStringBuilder { ConnectionString = "_MmapSize=" + text }; Assert.AreEqual(expected, csb.MmapSize); } [TestCase("FALSE")] public void MmapSizeThrows(string text) { SQLiteConnectionStringBuilder csb = new SQLiteConnectionStringBuilder { ConnectionString = "_MmapSize=" + text }; long unused; Assert.Catch<FormatException>(() => unused = csb.MmapSize); } [TestCase("1024", 1024)] [TestCase("4096", 4096)] [TestCase(null, 0)] [TestCase("", 0)] public void PageSize(string text, int expected) { SQLiteConnectionStringBuilder csb = new SQLiteConnectionStringBuilder { ConnectionString = "Page Size=" + text }; Assert.AreEqual(expected, csb.PageSize); } [TestCase("FALSE")] public void PageSizeThrows(string text) { SQLiteConnectionStringBuilder csb = new SQLiteConnectionStringBuilder { ConnectionString = "Page Size=" + text }; int unused; Assert.Catch<FormatException>(() => unused = csb.PageSize); } [TestCase("True", true)] [TestCase("true", true)] [TestCase("FALSE", false)] public void ReadOnly(string text, bool expected) { SQLiteConnectionStringBuilder csb = new SQLiteConnectionStringBuilder { ConnectionString = "Read Only=" + text }; Assert.AreEqual(expected, csb.ReadOnly); } [TestCase("null")] public void ReadOnlyThrows(string text) { SQLiteConnectionStringBuilder csb = new SQLiteConnectionStringBuilder { ConnectionString = "Read Only=" + text }; bool unused; Assert.Catch<FormatException>(() => unused = csb.ReadOnly); } [TestCase("off", SynchronizationModes.Off)] [TestCase("OFF", SynchronizationModes.Off)] [TestCase("normal", SynchronizationModes.Normal)] [TestCase("full", SynchronizationModes.Full)] [TestCase("", SynchronizationModes.Normal)] [TestCase(null, SynchronizationModes.Normal)] public void Synchronous(string text, SynchronizationModes expected) { SQLiteConnectionStringBuilder csb = new SQLiteConnectionStringBuilder { ConnectionString = "Synchronous=" + text }; Assert.AreEqual(expected, csb.SyncMode); } [TestCase("memory", SQLiteTemporaryStore.Memory)] [TestCase("MEMORY", SQLiteTemporaryStore.Memory)] [TestCase("File", SQLiteTemporaryStore.File)] [TestCase("", SQLiteTemporaryStore.Default)] [TestCase(null, SQLiteTemporaryStore.Default)] public void TempStore(string text, SQLiteTemporaryStore expected) { SQLiteConnectionStringBuilder csb = new SQLiteConnectionStringBuilder { ConnectionString = "_TempStore=" + text }; Assert.AreEqual(expected, csb.TempStore); } } }
/* * Copyright 2010-2013 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. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; namespace Amazon.RDS.Model { /// <summary> /// <para> This data type is used as a response element in the DescribeReservedDBInstancesOfferings action. </para> /// </summary> public class ReservedDBInstancesOffering { private string reservedDBInstancesOfferingId; private string dBInstanceClass; private int? duration; private double? fixedPrice; private double? usagePrice; private string currencyCode; private string productDescription; private string offeringType; private bool? multiAZ; private List<RecurringCharge> recurringCharges = new List<RecurringCharge>(); /// <summary> /// The offering identifier. /// /// </summary> public string ReservedDBInstancesOfferingId { get { return this.reservedDBInstancesOfferingId; } set { this.reservedDBInstancesOfferingId = value; } } /// <summary> /// Sets the ReservedDBInstancesOfferingId property /// </summary> /// <param name="reservedDBInstancesOfferingId">The value to set for the ReservedDBInstancesOfferingId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ReservedDBInstancesOffering WithReservedDBInstancesOfferingId(string reservedDBInstancesOfferingId) { this.reservedDBInstancesOfferingId = reservedDBInstancesOfferingId; return this; } // Check to see if ReservedDBInstancesOfferingId property is set internal bool IsSetReservedDBInstancesOfferingId() { return this.reservedDBInstancesOfferingId != null; } /// <summary> /// The DB instance class for the reserved DB Instance. /// /// </summary> public string DBInstanceClass { get { return this.dBInstanceClass; } set { this.dBInstanceClass = value; } } /// <summary> /// Sets the DBInstanceClass property /// </summary> /// <param name="dBInstanceClass">The value to set for the DBInstanceClass property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ReservedDBInstancesOffering WithDBInstanceClass(string dBInstanceClass) { this.dBInstanceClass = dBInstanceClass; return this; } // Check to see if DBInstanceClass property is set internal bool IsSetDBInstanceClass() { return this.dBInstanceClass != null; } /// <summary> /// The duration of the offering in seconds. /// /// </summary> public int Duration { get { return this.duration ?? default(int); } set { this.duration = value; } } /// <summary> /// Sets the Duration property /// </summary> /// <param name="duration">The value to set for the Duration property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ReservedDBInstancesOffering WithDuration(int duration) { this.duration = duration; return this; } // Check to see if Duration property is set internal bool IsSetDuration() { return this.duration.HasValue; } /// <summary> /// The fixed price charged for this offering. /// /// </summary> public double FixedPrice { get { return this.fixedPrice ?? default(double); } set { this.fixedPrice = value; } } /// <summary> /// Sets the FixedPrice property /// </summary> /// <param name="fixedPrice">The value to set for the FixedPrice property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ReservedDBInstancesOffering WithFixedPrice(double fixedPrice) { this.fixedPrice = fixedPrice; return this; } // Check to see if FixedPrice property is set internal bool IsSetFixedPrice() { return this.fixedPrice.HasValue; } /// <summary> /// The hourly price charged for this offering. /// /// </summary> public double UsagePrice { get { return this.usagePrice ?? default(double); } set { this.usagePrice = value; } } /// <summary> /// Sets the UsagePrice property /// </summary> /// <param name="usagePrice">The value to set for the UsagePrice property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ReservedDBInstancesOffering WithUsagePrice(double usagePrice) { this.usagePrice = usagePrice; return this; } // Check to see if UsagePrice property is set internal bool IsSetUsagePrice() { return this.usagePrice.HasValue; } /// <summary> /// The currency code for the reserved DB Instance offering. /// /// </summary> public string CurrencyCode { get { return this.currencyCode; } set { this.currencyCode = value; } } /// <summary> /// Sets the CurrencyCode property /// </summary> /// <param name="currencyCode">The value to set for the CurrencyCode property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ReservedDBInstancesOffering WithCurrencyCode(string currencyCode) { this.currencyCode = currencyCode; return this; } // Check to see if CurrencyCode property is set internal bool IsSetCurrencyCode() { return this.currencyCode != null; } /// <summary> /// The database engine used by the offering. /// /// </summary> public string ProductDescription { get { return this.productDescription; } set { this.productDescription = value; } } /// <summary> /// Sets the ProductDescription property /// </summary> /// <param name="productDescription">The value to set for the ProductDescription property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ReservedDBInstancesOffering WithProductDescription(string productDescription) { this.productDescription = productDescription; return this; } // Check to see if ProductDescription property is set internal bool IsSetProductDescription() { return this.productDescription != null; } /// <summary> /// The offering type. /// /// </summary> public string OfferingType { get { return this.offeringType; } set { this.offeringType = value; } } /// <summary> /// Sets the OfferingType property /// </summary> /// <param name="offeringType">The value to set for the OfferingType property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ReservedDBInstancesOffering WithOfferingType(string offeringType) { this.offeringType = offeringType; return this; } // Check to see if OfferingType property is set internal bool IsSetOfferingType() { return this.offeringType != null; } /// <summary> /// Indicates if the offering applies to Multi-AZ deployments. /// /// </summary> public bool MultiAZ { get { return this.multiAZ ?? default(bool); } set { this.multiAZ = value; } } /// <summary> /// Sets the MultiAZ property /// </summary> /// <param name="multiAZ">The value to set for the MultiAZ property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ReservedDBInstancesOffering WithMultiAZ(bool multiAZ) { this.multiAZ = multiAZ; return this; } // Check to see if MultiAZ property is set internal bool IsSetMultiAZ() { return this.multiAZ.HasValue; } /// <summary> /// The recurring price charged to run this reserved DB Instance. /// /// </summary> public List<RecurringCharge> RecurringCharges { get { return this.recurringCharges; } set { this.recurringCharges = value; } } /// <summary> /// Adds elements to the RecurringCharges collection /// </summary> /// <param name="recurringCharges">The values to add to the RecurringCharges collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ReservedDBInstancesOffering WithRecurringCharges(params RecurringCharge[] recurringCharges) { foreach (RecurringCharge element in recurringCharges) { this.recurringCharges.Add(element); } return this; } /// <summary> /// Adds elements to the RecurringCharges collection /// </summary> /// <param name="recurringCharges">The values to add to the RecurringCharges collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ReservedDBInstancesOffering WithRecurringCharges(IEnumerable<RecurringCharge> recurringCharges) { foreach (RecurringCharge element in recurringCharges) { this.recurringCharges.Add(element); } return this; } // Check to see if RecurringCharges property is set internal bool IsSetRecurringCharges() { return this.recurringCharges.Count > 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.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.DotNet.RemoteExecutor; using Microsoft.DotNet.XUnitExtensions; using Xunit; namespace System.Tests { public class EnvironmentTests : FileCleanupTestBase { [Fact] public void CurrentDirectory_Null_Path_Throws_ArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("value", () => Environment.CurrentDirectory = null); } [Fact] public void CurrentDirectory_Empty_Path_Throws_ArgumentException() { AssertExtensions.Throws<ArgumentException>("value", null, () => Environment.CurrentDirectory = string.Empty); } [Fact] public void CurrentDirectory_SetToNonExistentDirectory_ThrowsDirectoryNotFoundException() { Assert.Throws<DirectoryNotFoundException>(() => Environment.CurrentDirectory = GetTestFilePath()); } [Fact] public void CurrentDirectory_SetToValidOtherDirectory() { RemoteExecutor.Invoke(() => { Environment.CurrentDirectory = TestDirectory; Assert.Equal(Directory.GetCurrentDirectory(), Environment.CurrentDirectory); if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { // On OSX, the temp directory /tmp/ is a symlink to /private/tmp, so setting the current // directory to a symlinked path will result in GetCurrentDirectory returning the absolute // path that followed the symlink. Assert.Equal(TestDirectory, Directory.GetCurrentDirectory()); } }).Dispose(); } [Fact] public void CurrentManagedThreadId_Idempotent() { Assert.Equal(Environment.CurrentManagedThreadId, Environment.CurrentManagedThreadId); } [Fact] public void CurrentManagedThreadId_DifferentForActiveThreads() { var ids = new HashSet<int>(); Barrier b = new Barrier(10); Task.WaitAll((from i in Enumerable.Range(0, b.ParticipantCount) select Task.Factory.StartNew(() => { b.SignalAndWait(); lock (ids) ids.Add(Environment.CurrentManagedThreadId); b.SignalAndWait(); }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)).ToArray()); Assert.Equal(b.ParticipantCount, ids.Count); } [Fact] public void HasShutdownStarted_FalseWhileExecuting() { Assert.False(Environment.HasShutdownStarted); } [Fact] public void Is64BitProcess_MatchesIntPtrSize() { Assert.Equal(IntPtr.Size == 8, Environment.Is64BitProcess); } [Fact] public void Is64BitOperatingSystem_TrueIf64BitProcess() { if (Environment.Is64BitProcess) { Assert.True(Environment.Is64BitOperatingSystem); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment public void Is64BitOperatingSystem_Unix_TrueIff64BitProcess() { Assert.Equal(Environment.Is64BitProcess, Environment.Is64BitOperatingSystem); } [Fact] public void OSVersion_Idempotent() { Assert.Same(Environment.OSVersion, Environment.OSVersion); } [Fact] public void OSVersion_MatchesPlatform() { PlatformID id = Environment.OSVersion.Platform; Assert.Equal( RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? PlatformID.Win32NT : PlatformID.Unix, id); } [Fact] public void OSVersion_ValidVersion() { Version version = Environment.OSVersion.Version; string versionString = Environment.OSVersion.VersionString; Assert.False(string.IsNullOrWhiteSpace(versionString), "Expected non-empty version string"); Assert.True(version.Major > 0); Assert.Contains(version.ToString(2), versionString); Assert.Contains(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "Windows" : "Unix", versionString); } // On Unix, we must parse the version from uname -r [Theory] [PlatformSpecific(TestPlatforms.AnyUnix)] [InlineData("2.6.19-1.2895.fc6", 2, 6, 19, 1)] [InlineData("xxx1yyy2zzz3aaa4bbb", 1, 2, 3, 4)] [InlineData("2147483647.2147483647.2147483647.2147483647", int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue)] [InlineData("0.0.0.0", 0, 0, 0, 0)] [InlineData("-1.-1.-1.-1", 1, 1, 1, 1)] [InlineData("nelknet 4.15.0-10000000000-generic", 4, 15, 0, int.MaxValue)] // integer overflow [InlineData("nelknet 4.15.0-24201807041620-generic", 4, 15, 0, int.MaxValue)] // integer overflow [InlineData("", 0, 0, 0, 0)] [InlineData("1abc", 1, 0, 0, 0)] public void OSVersion_ParseVersion(string input, int major, int minor, int build, int revision) { var getOSMethod = typeof(Environment).GetMethod("GetOperatingSystem", BindingFlags.Static | BindingFlags.NonPublic); var expected = new Version(major, minor, build, revision); var actual = ((OperatingSystem)getOSMethod.Invoke(null, new object[] { input })).Version; Assert.Equal(expected, actual); } [Fact] public void SystemPageSize_Valid() { int pageSize = Environment.SystemPageSize; Assert.Equal(pageSize, Environment.SystemPageSize); Assert.True(pageSize > 0, "Expected positive page size"); Assert.True((pageSize & (pageSize - 1)) == 0, "Expected power-of-2 page size"); } [Fact] public void UserInteractive_True() { Assert.True(Environment.UserInteractive); } [Fact] public void Version_Valid() { Assert.True(Environment.Version >= new Version(3, 0)); } [Fact] public void WorkingSet_Valid() { Assert.True(Environment.WorkingSet > 0, "Expected positive WorkingSet value"); } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // fail fast crashes the process [OuterLoop] [Fact] public void FailFast_ExpectFailureExitCode() { using (RemoteInvokeHandle handle = RemoteExecutor.Invoke(() => Environment.FailFast("message"))) { Process p = handle.Process; handle.Process = null; p.WaitForExit(); Assert.NotEqual(RemoteExecutor.SuccessExitCode, p.ExitCode); } using (RemoteInvokeHandle handle = RemoteExecutor.Invoke(() => Environment.FailFast("message", new Exception("uh oh")))) { Process p = handle.Process; handle.Process = null; p.WaitForExit(); Assert.NotEqual(RemoteExecutor.SuccessExitCode, p.ExitCode); } } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // fail fast crashes the process [Fact] public void FailFast_ExceptionStackTrace_ArgumentException() { var psi = new ProcessStartInfo(); psi.RedirectStandardError = true; psi.RedirectStandardOutput = true; using (RemoteInvokeHandle handle = RemoteExecutor.Invoke( () => Environment.FailFast("message", new ArgumentException("bad arg")), new RemoteInvokeOptions { StartInfo = psi })) { Process p = handle.Process; handle.Process = null; p.WaitForExit(); string consoleOutput = p.StandardError.ReadToEnd(); Assert.Contains("ArgumentException:", consoleOutput); Assert.Contains("bad arg", consoleOutput); } } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // fail fast crashes the process [Fact] public void FailFast_ExceptionStackTrace_StackOverflowException() { // Test using another type of exception var psi = new ProcessStartInfo(); psi.RedirectStandardError = true; psi.RedirectStandardOutput = true; using (RemoteInvokeHandle handle = RemoteExecutor.Invoke( () => Environment.FailFast("message", new StackOverflowException("SO exception")), new RemoteInvokeOptions { StartInfo = psi })) { Process p = handle.Process; handle.Process = null; p.WaitForExit(); string consoleOutput = p.StandardError.ReadToEnd(); Assert.Contains("StackOverflowException", consoleOutput); Assert.Contains("SO exception", consoleOutput); } } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // fail fast crashes the process [Fact] public void FailFast_ExceptionStackTrace_InnerException() { // Test if inner exception details are also logged var psi = new ProcessStartInfo(); psi.RedirectStandardError = true; psi.RedirectStandardOutput = true; using (RemoteInvokeHandle handle = RemoteExecutor.Invoke( () => Environment.FailFast("message", new ArgumentException("first exception", new NullReferenceException("inner exception"))), new RemoteInvokeOptions { StartInfo = psi })) { Process p = handle.Process; handle.Process = null; p.WaitForExit(); string consoleOutput = p.StandardError.ReadToEnd(); Assert.Contains("first exception", consoleOutput); Assert.Contains("inner exception", consoleOutput); Assert.Contains("ArgumentException", consoleOutput); Assert.Contains("NullReferenceException", consoleOutput); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment public void GetFolderPath_Unix_PersonalIsHomeAndUserProfile() { Assert.Equal(Environment.GetEnvironmentVariable("HOME"), Environment.GetFolderPath(Environment.SpecialFolder.Personal)); Assert.Equal(Environment.GetEnvironmentVariable("HOME"), Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)); Assert.Equal(Environment.GetEnvironmentVariable("HOME"), Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); } [Theory] [OuterLoop] [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment [InlineData(Environment.SpecialFolder.ApplicationData)] [InlineData(Environment.SpecialFolder.Desktop)] [InlineData(Environment.SpecialFolder.DesktopDirectory)] [InlineData(Environment.SpecialFolder.Fonts)] [InlineData(Environment.SpecialFolder.MyMusic)] [InlineData(Environment.SpecialFolder.MyPictures)] [InlineData(Environment.SpecialFolder.MyVideos)] [InlineData(Environment.SpecialFolder.Templates)] public void GetFolderPath_Unix_SpecialFolderDoesNotExist_CreatesSuccessfully(Environment.SpecialFolder folder) { string path = Environment.GetFolderPath(folder, Environment.SpecialFolderOption.DoNotVerify); if (Directory.Exists(path)) return; path = Environment.GetFolderPath(folder, Environment.SpecialFolderOption.Create); Assert.True(Directory.Exists(path)); Directory.Delete(path); } [Fact] public void GetSystemDirectory() { if (PlatformDetection.IsWindowsNanoServer) { // https://github.com/dotnet/corefx/issues/19110 // On Windows Nano, ShGetKnownFolderPath currently doesn't give // the correct result for SystemDirectory. // Assert that it's wrong, so that if it's fixed, we don't forget to // enable this test for Nano. Assert.NotEqual(Environment.GetFolderPath(Environment.SpecialFolder.System), Environment.SystemDirectory); return; } Assert.Equal(Environment.GetFolderPath(Environment.SpecialFolder.System), Environment.SystemDirectory); } [Theory] [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment [InlineData(Environment.SpecialFolder.UserProfile, Environment.SpecialFolderOption.None)] [InlineData(Environment.SpecialFolder.MyDocuments, Environment.SpecialFolderOption.None)] // MyDocuments == Personal [InlineData(Environment.SpecialFolder.CommonApplicationData, Environment.SpecialFolderOption.None)] [InlineData(Environment.SpecialFolder.CommonTemplates, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.ApplicationData, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.Desktop, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.DesktopDirectory, Environment.SpecialFolderOption.DoNotVerify)] // Not set on Unix (amongst others) //[InlineData(Environment.SpecialFolder.System, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.Templates, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.MyVideos, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.MyMusic, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.MyPictures, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.Fonts, Environment.SpecialFolderOption.DoNotVerify)] public void GetFolderPath_Unix_NonEmptyFolderPaths(Environment.SpecialFolder folder, Environment.SpecialFolderOption option) { Assert.NotEmpty(Environment.GetFolderPath(folder, option)); if (option == Environment.SpecialFolderOption.None) { Assert.NotEmpty(Environment.GetFolderPath(folder)); } } [Theory] [PlatformSpecific(TestPlatforms.OSX)] // Tests OS-specific environment [InlineData(Environment.SpecialFolder.Favorites, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.InternetCache, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.ProgramFiles, Environment.SpecialFolderOption.None)] [InlineData(Environment.SpecialFolder.System, Environment.SpecialFolderOption.None)] public void GetFolderPath_OSX_NonEmptyFolderPaths(Environment.SpecialFolder folder, Environment.SpecialFolderOption option) { Assert.NotEmpty(Environment.GetFolderPath(folder, option)); if (option == Environment.SpecialFolderOption.None) { Assert.NotEmpty(Environment.GetFolderPath(folder)); } } // Requires recent RS3 builds and needs to run inside AppContainer [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsWindows10Version1709OrGreater), nameof(PlatformDetection.IsInAppContainer))] [InlineData(Environment.SpecialFolder.LocalApplicationData)] [InlineData(Environment.SpecialFolder.Cookies)] [InlineData(Environment.SpecialFolder.History)] [InlineData(Environment.SpecialFolder.InternetCache)] [InlineData(Environment.SpecialFolder.System)] [InlineData(Environment.SpecialFolder.SystemX86)] [InlineData(Environment.SpecialFolder.Windows)] public void GetFolderPath_UWP_ExistAndAccessible(Environment.SpecialFolder folder) { string knownFolder = Environment.GetFolderPath(folder); Assert.NotEmpty(knownFolder); AssertDirectoryExists(knownFolder); } // Requires recent RS3 builds and needs to run inside AppContainer [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsWindows10Version1709OrGreater), nameof(PlatformDetection.IsInAppContainer))] [InlineData(Environment.SpecialFolder.ApplicationData)] [InlineData(Environment.SpecialFolder.MyMusic)] [InlineData(Environment.SpecialFolder.MyPictures)] [InlineData(Environment.SpecialFolder.MyVideos)] [InlineData(Environment.SpecialFolder.Recent)] [InlineData(Environment.SpecialFolder.Templates)] [InlineData(Environment.SpecialFolder.DesktopDirectory)] [InlineData(Environment.SpecialFolder.Personal)] [InlineData(Environment.SpecialFolder.UserProfile)] [InlineData(Environment.SpecialFolder.CommonDocuments)] [InlineData(Environment.SpecialFolder.CommonMusic)] [InlineData(Environment.SpecialFolder.CommonPictures)] [InlineData(Environment.SpecialFolder.CommonDesktopDirectory)] [InlineData(Environment.SpecialFolder.CommonVideos)] // These are in the package folder [InlineData(Environment.SpecialFolder.CommonApplicationData)] [InlineData(Environment.SpecialFolder.Desktop)] [InlineData(Environment.SpecialFolder.Favorites)] public void GetFolderPath_UWP_NotEmpty(Environment.SpecialFolder folder) { // The majority of the paths here cannot be accessed from an appcontainer string knownFolder = Environment.GetFolderPath(folder); Assert.NotEmpty(knownFolder); } private void AssertDirectoryExists(string path) { // Directory.Exists won't tell us if access was denied, etc. Invoking directly // to get diagnosable test results. FileAttributes attributes = GetFileAttributesW(path); if (attributes == (FileAttributes)(-1)) { int error = Marshal.GetLastWin32Error(); Assert.False(true, $"error {error} getting attributes for {path}"); } Assert.True((attributes & FileAttributes.Directory) == FileAttributes.Directory, $"not a directory: {path}"); } // The commented out folders aren't set on all systems. [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] // https://github.com/dotnet/corefx/issues/19110 [InlineData(Environment.SpecialFolder.ApplicationData)] [InlineData(Environment.SpecialFolder.CommonApplicationData)] [InlineData(Environment.SpecialFolder.LocalApplicationData)] [InlineData(Environment.SpecialFolder.Cookies)] [InlineData(Environment.SpecialFolder.Desktop)] [InlineData(Environment.SpecialFolder.Favorites)] [InlineData(Environment.SpecialFolder.History)] [InlineData(Environment.SpecialFolder.InternetCache)] [InlineData(Environment.SpecialFolder.Programs)] // [InlineData(Environment.SpecialFolder.MyComputer)] [InlineData(Environment.SpecialFolder.MyMusic)] [InlineData(Environment.SpecialFolder.MyPictures)] [InlineData(Environment.SpecialFolder.MyVideos)] [InlineData(Environment.SpecialFolder.Recent)] [InlineData(Environment.SpecialFolder.SendTo)] [InlineData(Environment.SpecialFolder.StartMenu)] [InlineData(Environment.SpecialFolder.Startup)] [InlineData(Environment.SpecialFolder.System)] //[InlineData(Environment.SpecialFolder.Templates)] [InlineData(Environment.SpecialFolder.DesktopDirectory)] [InlineData(Environment.SpecialFolder.Personal)] [InlineData(Environment.SpecialFolder.ProgramFiles)] [InlineData(Environment.SpecialFolder.CommonProgramFiles)] [InlineData(Environment.SpecialFolder.AdminTools)] //[InlineData(Environment.SpecialFolder.CDBurning)] // Not available on Server Core [InlineData(Environment.SpecialFolder.CommonAdminTools)] [InlineData(Environment.SpecialFolder.CommonDocuments)] [InlineData(Environment.SpecialFolder.CommonMusic)] // [InlineData(Environment.SpecialFolder.CommonOemLinks)] [InlineData(Environment.SpecialFolder.CommonPictures)] [InlineData(Environment.SpecialFolder.CommonStartMenu)] [InlineData(Environment.SpecialFolder.CommonPrograms)] [InlineData(Environment.SpecialFolder.CommonStartup)] [InlineData(Environment.SpecialFolder.CommonDesktopDirectory)] [InlineData(Environment.SpecialFolder.CommonTemplates)] [InlineData(Environment.SpecialFolder.CommonVideos)] [InlineData(Environment.SpecialFolder.Fonts)] //[InlineData(Environment.SpecialFolder.NetworkShortcuts)] // [InlineData(Environment.SpecialFolder.PrinterShortcuts)] [InlineData(Environment.SpecialFolder.UserProfile)] [InlineData(Environment.SpecialFolder.CommonProgramFilesX86)] [InlineData(Environment.SpecialFolder.ProgramFilesX86)] [InlineData(Environment.SpecialFolder.Resources)] // [InlineData(Environment.SpecialFolder.LocalizedResources)] [InlineData(Environment.SpecialFolder.SystemX86)] [InlineData(Environment.SpecialFolder.Windows)] [PlatformSpecific(TestPlatforms.Windows)] // Tests OS-specific environment public unsafe void GetFolderPath_Windows(Environment.SpecialFolder folder) { string knownFolder = Environment.GetFolderPath(folder); Assert.NotEmpty(knownFolder); // Call the older folder API to compare our results. char* buffer = stackalloc char[260]; SHGetFolderPathW(IntPtr.Zero, (int)folder, IntPtr.Zero, 0, buffer); string folderPath = new string(buffer); Assert.Equal(folderPath, knownFolder); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Uses P/Invokes public void GetLogicalDrives_Unix_AtLeastOneIsRoot() { string[] drives = Environment.GetLogicalDrives(); Assert.NotNull(drives); Assert.True(drives.Length > 0, "Expected at least one drive"); Assert.All(drives, d => Assert.NotNull(d)); Assert.Contains(drives, d => d == "/"); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes public void GetLogicalDrives_Windows_MatchesExpectedLetters() { string[] drives = Environment.GetLogicalDrives(); uint mask = (uint)GetLogicalDrives(); var bits = new BitArray(new[] { (int)mask }); Assert.Equal(bits.Cast<bool>().Count(b => b), drives.Length); for (int bit = 0, d = 0; bit < bits.Length; bit++) { if (bits[bit]) { Assert.Contains((char)('A' + bit), drives[d++]); } } } [DllImport("kernel32.dll", SetLastError = true)] internal static extern int GetLogicalDrives(); [DllImport("shell32.dll", SetLastError = false, BestFitMapping = false, ExactSpelling = true)] internal static extern unsafe int SHGetFolderPathW( IntPtr hwndOwner, int nFolder, IntPtr hToken, uint dwFlags, char* pszPath); [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)] internal static extern FileAttributes GetFileAttributesW(string lpFileName); public static IEnumerable<object[]> EnvironmentVariableTargets { get { yield return new object[] { EnvironmentVariableTarget.Process }; yield return new object[] { EnvironmentVariableTarget.User }; yield return new object[] { EnvironmentVariableTarget.Machine }; } } } }
// 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; #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing.Internal #else namespace System.Diagnostics.Tracing.Internal #endif { #if ES_BUILD_AGAINST_DOTNET_V35 using Microsoft.Internal; #endif using Microsoft.Reflection; using System.Reflection; internal static class Environment { public static readonly string NewLine = System.Environment.NewLine; public static int TickCount { get { return System.Environment.TickCount; } } public static string GetResourceString(string key, params object[] args) { string fmt = rm.GetString(key); if (fmt != null) return string.Format(fmt, args); string sargs = string.Empty; foreach(var arg in args) { if (sargs != string.Empty) sargs += ", "; sargs += arg.ToString(); } return key + " (" + sargs + ")"; } public static string GetRuntimeResourceString(string key, params object[] args) { return GetResourceString(key, args); } private static System.Resources.ResourceManager rm = new System.Resources.ResourceManager("Microsoft.Diagnostics.Tracing.Messages", typeof(Environment).Assembly()); } } #if ES_BUILD_AGAINST_DOTNET_V35 namespace Microsoft.Internal { using System.Text; internal static class Tuple { public static Tuple<T1> Create<T1>(T1 item1) { return new Tuple<T1>(item1); } public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return new Tuple<T1, T2>(item1, item2); } } [Serializable] internal class Tuple<T1> { private readonly T1 m_Item1; public T1 Item1 { get { return m_Item1; } } public Tuple(T1 item1) { m_Item1 = item1; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); sb.Append(m_Item1); sb.Append(")"); return sb.ToString(); } int Size { get { return 1; } } } [Serializable] public class Tuple<T1, T2> { private readonly T1 m_Item1; private readonly T2 m_Item2; public T1 Item1 { get { return m_Item1; } } public T2 Item2 { get { return m_Item2; } } public Tuple(T1 item1, T2 item2) { m_Item1 = item1; m_Item2 = item2; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(")"); return sb.ToString(); } int Size { get { return 2; } } } } #endif namespace Microsoft.Reflection { using System.Reflection; #if ES_BUILD_PCL [Flags] public enum BindingFlags { DeclaredOnly = 0x02, // Only look at the members declared on the Type Instance = 0x04, // Include Instance members in search Static = 0x08, // Include Static members in search Public = 0x10, // Include Public members in search NonPublic = 0x20, // Include Non-Public members in search } public enum TypeCode { Empty = 0, // Null reference Object = 1, // Instance that isn't a value DBNull = 2, // Database null value Boolean = 3, // Boolean Char = 4, // Unicode character SByte = 5, // Signed 8-bit integer Byte = 6, // Unsigned 8-bit integer Int16 = 7, // Signed 16-bit integer UInt16 = 8, // Unsigned 16-bit integer Int32 = 9, // Signed 32-bit integer UInt32 = 10, // Unsigned 32-bit integer Int64 = 11, // Signed 64-bit integer UInt64 = 12, // Unsigned 64-bit integer Single = 13, // IEEE 32-bit float Double = 14, // IEEE 64-bit double Decimal = 15, // Decimal DateTime = 16, // DateTime String = 18, // Unicode character string } #endif static class ReflectionExtensions { #if (!ES_BUILD_PCL && !ES_BUILD_PN) // // Type extension methods // public static bool IsEnum(this Type type) { return type.IsEnum; } public static bool IsAbstract(this Type type) { return type.IsAbstract; } public static bool IsSealed(this Type type) { return type.IsSealed; } public static bool IsValueType(this Type type) { return type.IsValueType; } public static bool IsGenericType(this Type type) { return type.IsGenericType; } public static Type BaseType(this Type type) { return type.BaseType; } public static Assembly Assembly(this Type type) { return type.Assembly; } public static TypeCode GetTypeCode(this Type type) { return Type.GetTypeCode(type); } public static bool ReflectionOnly(this Assembly assm) { return assm.ReflectionOnly; } #else // ES_BUILD_PCL // // Type extension methods // public static bool IsEnum(this Type type) { return type.GetTypeInfo().IsEnum; } public static bool IsAbstract(this Type type) { return type.GetTypeInfo().IsAbstract; } public static bool IsSealed(this Type type) { return type.GetTypeInfo().IsSealed; } public static bool IsValueType(this Type type) { return type.GetTypeInfo().IsValueType; } public static bool IsGenericType(this Type type) { return type.IsConstructedGenericType; } public static Type BaseType(this Type type) { return type.GetTypeInfo().BaseType; } public static Assembly Assembly(this Type type) { return type.GetTypeInfo().Assembly; } public static IEnumerable<PropertyInfo> GetProperties(this Type type) { #if ES_BUILD_PN return type.GetProperties(); #else return type.GetRuntimeProperties(); #endif } public static MethodInfo GetGetMethod(this PropertyInfo propInfo) { return propInfo.GetMethod; } public static Type[] GetGenericArguments(this Type type) { return type.GenericTypeArguments; } public static MethodInfo[] GetMethods(this Type type, BindingFlags flags) { // Minimal implementation to cover only the cases we need System.Diagnostics.Debug.Assert((flags & BindingFlags.DeclaredOnly) != 0); System.Diagnostics.Debug.Assert((flags & ~(BindingFlags.DeclaredOnly|BindingFlags.Instance|BindingFlags.Static|BindingFlags.Public|BindingFlags.NonPublic)) == 0); Func<MethodInfo, bool> visFilter; Func<MethodInfo, bool> instFilter; switch (flags & (BindingFlags.Public | BindingFlags.NonPublic)) { case 0: visFilter = mi => false; break; case BindingFlags.Public: visFilter = mi => mi.IsPublic; break; case BindingFlags.NonPublic: visFilter = mi => !mi.IsPublic; break; default: visFilter = mi => true; break; } switch (flags & (BindingFlags.Instance | BindingFlags.Static)) { case 0: instFilter = mi => false; break; case BindingFlags.Instance: instFilter = mi => !mi.IsStatic; break; case BindingFlags.Static: instFilter = mi => mi.IsStatic; break; default: instFilter = mi => true; break; } List<MethodInfo> methodInfos = new List<MethodInfo>(); foreach (var declaredMethod in type.GetTypeInfo().DeclaredMethods) { if (visFilter(declaredMethod) && instFilter(declaredMethod)) methodInfos.Add(declaredMethod); } return methodInfos.ToArray(); } public static FieldInfo[] GetFields(this Type type, BindingFlags flags) { // Minimal implementation to cover only the cases we need System.Diagnostics.Debug.Assert((flags & BindingFlags.DeclaredOnly) != 0); System.Diagnostics.Debug.Assert((flags & ~(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) == 0); Func<FieldInfo, bool> visFilter; Func<FieldInfo, bool> instFilter; switch (flags & (BindingFlags.Public | BindingFlags.NonPublic)) { case 0: visFilter = fi => false; break; case BindingFlags.Public: visFilter = fi => fi.IsPublic; break; case BindingFlags.NonPublic: visFilter = fi => !fi.IsPublic; break; default: visFilter = fi => true; break; } switch (flags & (BindingFlags.Instance | BindingFlags.Static)) { case 0: instFilter = fi => false; break; case BindingFlags.Instance: instFilter = fi => !fi.IsStatic; break; case BindingFlags.Static: instFilter = fi => fi.IsStatic; break; default: instFilter = fi => true; break; } List<FieldInfo> fieldInfos = new List<FieldInfo>(); foreach (var declaredField in type.GetTypeInfo().DeclaredFields) { if (visFilter(declaredField) && instFilter(declaredField)) fieldInfos.Add(declaredField); } return fieldInfos.ToArray(); } public static Type GetNestedType(this Type type, string nestedTypeName) { TypeInfo ti = null; foreach(var nt in type.GetTypeInfo().DeclaredNestedTypes) { if (nt.Name == nestedTypeName) { ti = nt; break; } } return ti == null ? null : ti.AsType(); } public static TypeCode GetTypeCode(this Type type) { if (type == typeof(bool)) return TypeCode.Boolean; else if (type == typeof(byte)) return TypeCode.Byte; else if (type == typeof(char)) return TypeCode.Char; else if (type == typeof(ushort)) return TypeCode.UInt16; else if (type == typeof(uint)) return TypeCode.UInt32; else if (type == typeof(ulong)) return TypeCode.UInt64; else if (type == typeof(sbyte)) return TypeCode.SByte; else if (type == typeof(short)) return TypeCode.Int16; else if (type == typeof(int)) return TypeCode.Int32; else if (type == typeof(long)) return TypeCode.Int64; else if (type == typeof(string)) return TypeCode.String; else if (type == typeof(float)) return TypeCode.Single; else if (type == typeof(double)) return TypeCode.Double; else if (type == typeof(DateTime)) return TypeCode.DateTime; else if (type == (typeof(decimal))) return TypeCode.Decimal; else return TypeCode.Object; } // // FieldInfo extension methods // public static object GetRawConstantValue(this FieldInfo fi) { return fi.GetValue(null); } // // Assembly extension methods // public static bool ReflectionOnly(this Assembly assm) { // In PCL we can't load in reflection-only context return false; } #endif } } // Defining some no-ops in PCL builds #if ES_BUILD_PCL namespace System.Security { class SuppressUnmanagedCodeSecurityAttribute : Attribute { } enum SecurityAction { Demand } } namespace System.Security.Permissions { class HostProtectionAttribute : Attribute { public bool MayLeakOnAbort { get; set; } } class PermissionSetAttribute : Attribute { public PermissionSetAttribute(System.Security.SecurityAction action) { } public bool Unrestricted { get; set; } } } #endif #if ES_BUILD_PN namespace System { internal static class AppDomain { public static int GetCurrentThreadId() { return Internal.Runtime.Augments.RuntimeThread.CurrentThread.ManagedThreadId; } } } #endif #if ES_BUILD_STANDALONE namespace Microsoft.Win32 { using System.Runtime.InteropServices; using System.Security; [SuppressUnmanagedCodeSecurityAttribute()] internal static class Win32Native { [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] internal static extern uint GetCurrentProcessId(); } } #endif
// using UnityEngine; using System; using System.Collections; using System.Text; namespace GameAnalyticsSDK.Utilities { /* Based on the JSON parser from * http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html * * I simplified it so that it doesn't throw exceptions * and can be used in Unity iPhone with maximum code stripping. */ /// <summary> /// This class encodes and decodes JSON strings. /// Spec. details, see http://www.json.org/ /// /// JSON uses Arrays and Objects. These correspond here to the datatypes ArrayList and Hashtable. /// All numbers are parsed to floats. /// </summary> public class GA_MiniJSON { public const int TOKEN_NONE = 0; public const int TOKEN_CURLY_OPEN = 1; public const int TOKEN_CURLY_CLOSE = 2; public const int TOKEN_SQUARED_OPEN = 3; public const int TOKEN_SQUARED_CLOSE = 4; public const int TOKEN_COLON = 5; public const int TOKEN_COMMA = 6; public const int TOKEN_STRING = 7; public const int TOKEN_NUMBER = 8; public const int TOKEN_TRUE = 9; public const int TOKEN_FALSE = 10; public const int TOKEN_NULL = 11; private const int BUILDER_CAPACITY = 2000; protected static GA_MiniJSON instance = new GA_MiniJSON(); /// <summary> /// On decoding, this value holds the position at which the parse failed (-1 = no error). /// </summary> protected int lastErrorIndex = -1; protected string lastDecode = ""; /// <summary> /// Parses the string json into a value /// </summary> /// <param name="json">A JSON string.</param> /// <returns>An ArrayList, a Hashtable, a float, a string, null, true, or false</returns> public static object JsonDecode(string json) { // save the string for debug information GA_MiniJSON.instance.lastDecode = json; if(json != null) { char[] charArray = json.ToCharArray(); int index = 0; bool success = true; object value = GA_MiniJSON.instance.ParseValue(charArray, ref index, ref success); if(success) { GA_MiniJSON.instance.lastErrorIndex = -1; } else { GA_MiniJSON.instance.lastErrorIndex = index; } return value; } else { return null; } } /// <summary> /// Converts a Hashtable / ArrayList object into a JSON string /// </summary> /// <param name="json">A Hashtable / ArrayList</param> /// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns> public static string JsonEncode(object json) { StringBuilder builder = new StringBuilder(BUILDER_CAPACITY); bool success = GA_MiniJSON.instance.SerializeValue(json, builder); return (success ? builder.ToString() : null); } /// <summary> /// On decoding, this function returns the position at which the parse failed (-1 = no error). /// </summary> /// <returns></returns> public static bool LastDecodeSuccessful() { return (GA_MiniJSON.instance.lastErrorIndex == -1); } /// <summary> /// On decoding, this function returns the position at which the parse failed (-1 = no error). /// </summary> /// <returns></returns> public static int GetLastErrorIndex() { return GA_MiniJSON.instance.lastErrorIndex; } /// <summary> /// If a decoding error occurred, this function returns a piece of the JSON string /// at which the error took place. To ease debugging. /// </summary> /// <returns></returns> public static string GetLastErrorSnippet() { if(GA_MiniJSON.instance.lastErrorIndex == -1) { return ""; } else { int startIndex = GA_MiniJSON.instance.lastErrorIndex - 5; int endIndex = GA_MiniJSON.instance.lastErrorIndex + 15; if(startIndex < 0) { startIndex = 0; } if(endIndex >= GA_MiniJSON.instance.lastDecode.Length) { endIndex = GA_MiniJSON.instance.lastDecode.Length - 1; } return GA_MiniJSON.instance.lastDecode.Substring(startIndex, endIndex - startIndex + 1); } } protected Hashtable ParseObject(char[] json, ref int index) { Hashtable table = new Hashtable(); int token; // { NextToken(json, ref index); bool done = false; while(!done) { token = LookAhead(json, index); if(token == GA_MiniJSON.TOKEN_NONE) { return null; } else if(token == GA_MiniJSON.TOKEN_COMMA) { NextToken(json, ref index); } else if(token == GA_MiniJSON.TOKEN_CURLY_CLOSE) { NextToken(json, ref index); return table; } else { // name string name = ParseString(json, ref index); if(name == null) { return null; } // : token = NextToken(json, ref index); if(token != GA_MiniJSON.TOKEN_COLON) { return null; } // value bool success = true; object value = ParseValue(json, ref index, ref success); if(!success) { return null; } table[name] = value; } } return table; } protected ArrayList ParseArray(char[] json, ref int index) { ArrayList array = new ArrayList(); // [ NextToken(json, ref index); bool done = false; while(!done) { int token = LookAhead(json, index); if(token == GA_MiniJSON.TOKEN_NONE) { return null; } else if(token == GA_MiniJSON.TOKEN_COMMA) { NextToken(json, ref index); } else if(token == GA_MiniJSON.TOKEN_SQUARED_CLOSE) { NextToken(json, ref index); break; } else { bool success = true; object value = ParseValue(json, ref index, ref success); if(!success) { return null; } array.Add(value); } } return array; } protected object ParseValue(char[] json, ref int index, ref bool success) { switch(LookAhead(json, index)) { case GA_MiniJSON.TOKEN_STRING: return ParseString(json, ref index); case GA_MiniJSON.TOKEN_NUMBER: return ParseNumber(json, ref index); case GA_MiniJSON.TOKEN_CURLY_OPEN: return ParseObject(json, ref index); case GA_MiniJSON.TOKEN_SQUARED_OPEN: return ParseArray(json, ref index); case GA_MiniJSON.TOKEN_TRUE: NextToken(json, ref index); return Boolean.Parse("TRUE"); case GA_MiniJSON.TOKEN_FALSE: NextToken(json, ref index); return Boolean.Parse("FALSE"); case GA_MiniJSON.TOKEN_NULL: NextToken(json, ref index); return null; case GA_MiniJSON.TOKEN_NONE: break; } success = false; return null; } protected string ParseString(char[] json, ref int index) { string s = ""; char c; EatWhitespace(json, ref index); // " c = json[index]; index++; bool complete = false; while(!complete) { if(index == json.Length) { break; } c = json[index]; index++; if(c == '"') { complete = true; break; } else if(c == '\\') { if(index == json.Length) { break; } c = json[index]; index++; if(c == '"') { s += '"'; } else if(c == '\\') { s += '\\'; } else if(c == '/') { s += '/'; } else if(c == 'b') { s += '\b'; } else if(c == 'f') { s += '\f'; } else if(c == 'n') { s += '\n'; } else if(c == 'r') { s += '\r'; } else if(c == 't') { s += '\t'; } else if(c == 'u') { int remainingLength = json.Length - index; if(remainingLength >= 4) { char[] unicodeCharArray = new char[4]; // Array.Copy(json, index, unicodeCharArray, 0, 4); for(int i = 0; i < 4; i++) { unicodeCharArray[i] = json[index + i]; } // Drop in the HTML markup for the unicode character s += "&#x" + new string(unicodeCharArray) + ";"; /* uint codePoint = UInt32.Parse(new string(unicodeCharArray), NumberStyles.HexNumber); // convert the integer codepoint to a unicode char and add to string s += Char.ConvertFromUtf32((int)codePoint); */ // skip 4 chars index += 4; } else { break; } } } else { s += c.ToString(); } } if(!complete) { return null; } return s; } protected float ParseNumber(char[] json, ref int index) { EatWhitespace(json, ref index); int lastIndex = GetLastIndexOfNumber(json, index); int charLength = (lastIndex - index) + 1; char[] numberCharArray = new char[charLength]; // Array.Copy(json, index, numberCharArray, 0, charLength); for(int i = 0; i < charLength; i++) { numberCharArray[i] = json[index + i]; } index = lastIndex + 1; return Single.Parse(new string(numberCharArray)); // , CultureInfo.InvariantCulture); } protected int GetLastIndexOfNumber(char[] json, int index) { int lastIndex; for(lastIndex = index; lastIndex < json.Length; lastIndex++) { if("0123456789+-.eE".IndexOf(json[lastIndex]) == -1) { break; } } return lastIndex - 1; } protected void EatWhitespace(char[] json, ref int index) { for(; index < json.Length; index++) { if(" \t\n\r".IndexOf(json[index]) == -1) { break; } } } protected int LookAhead(char[] json, int index) { int saveIndex = index; return NextToken(json, ref saveIndex); } protected int NextToken(char[] json, ref int index) { EatWhitespace(json, ref index); if(index == json.Length) { return GA_MiniJSON.TOKEN_NONE; } char c = json[index]; index++; switch(c) { case '{': return GA_MiniJSON.TOKEN_CURLY_OPEN; case '}': return GA_MiniJSON.TOKEN_CURLY_CLOSE; case '[': return GA_MiniJSON.TOKEN_SQUARED_OPEN; case ']': return GA_MiniJSON.TOKEN_SQUARED_CLOSE; case ',': return GA_MiniJSON.TOKEN_COMMA; case '"': return GA_MiniJSON.TOKEN_STRING; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': return GA_MiniJSON.TOKEN_NUMBER; case ':': return GA_MiniJSON.TOKEN_COLON; } index--; int remainingLength = json.Length - index; // false if(remainingLength >= 5) { if(json[index] == 'f' && json[index + 1] == 'a' && json[index + 2] == 'l' && json[index + 3] == 's' && json[index + 4] == 'e') { index += 5; return GA_MiniJSON.TOKEN_FALSE; } } // true if(remainingLength >= 4) { if(json[index] == 't' && json[index + 1] == 'r' && json[index + 2] == 'u' && json[index + 3] == 'e') { index += 4; return GA_MiniJSON.TOKEN_TRUE; } } // null if(remainingLength >= 4) { if(json[index] == 'n' && json[index + 1] == 'u' && json[index + 2] == 'l' && json[index + 3] == 'l') { index += 4; return GA_MiniJSON.TOKEN_NULL; } } return GA_MiniJSON.TOKEN_NONE; } protected bool SerializeObjectOrArray(object objectOrArray, StringBuilder builder) { if(objectOrArray is Hashtable) { return SerializeObject((Hashtable)objectOrArray, builder); } else if(objectOrArray is ArrayList) { return SerializeArray((ArrayList)objectOrArray, builder); } else { return false; } } protected bool SerializeObject(Hashtable anObject, StringBuilder builder) { builder.Append("{"); IDictionaryEnumerator e = anObject.GetEnumerator(); bool first = true; while(e.MoveNext()) { string key = e.Key.ToString(); object value = e.Value; if(!first) { builder.Append(", "); } SerializeString(key, builder); builder.Append(":"); if(!SerializeValue(value, builder)) { return false; } first = false; } builder.Append("}"); return true; } protected bool SerializeArray(ArrayList anArray, StringBuilder builder) { builder.Append("["); bool first = true; for(int i = 0; i < anArray.Count; i++) { object value = anArray[i]; if(!first) { builder.Append(", "); } if(!SerializeValue(value, builder)) { return false; } first = false; } builder.Append("]"); return true; } protected bool SerializeValue(object value, StringBuilder builder) { // Type t = value.GetType(); // Debug.Log("type: " + t.ToString() + " isArray: " + t.IsArray); if(value == null) { builder.Append("null"); } else if(value.GetType().IsArray) { SerializeArray(new ArrayList((ICollection)value), builder); } else if(value is string) { SerializeString((string)value, builder); } else if(value is Char) { SerializeString(value.ToString(), builder); } else if(value is Hashtable) { SerializeObject((Hashtable)value, builder); } else if(value is ArrayList) { SerializeArray((ArrayList)value, builder); } else if((value is Boolean) && ((Boolean)value == true)) { builder.Append("true"); } else if((value is Boolean) && ((Boolean)value == false)) { builder.Append("false"); } // else if (value.GetType().IsPrimitive) { else if(value is Single) { SerializeNumber((Single)value, builder); } else { return false; } return true; } protected void SerializeString(string aString, StringBuilder builder) { builder.Append("\""); char[] charArray = aString.ToCharArray(); for(int i = 0; i < charArray.Length; i++) { char c = charArray[i]; if(c == '"') { builder.Append("\\\""); } else if(c == '\\') { builder.Append("\\\\"); } else if(c == '\b') { builder.Append("\\b"); } else if(c == '\f') { builder.Append("\\f"); } else if(c == '\n') { builder.Append("\\n"); } else if(c == '\r') { builder.Append("\\r"); } else if(c == '\t') { builder.Append("\\t"); } else { int codepoint = (Int32)c; if((codepoint >= 32) && (codepoint <= 126)) { builder.Append(c); } // else // { // builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0')); // } } } builder.Append("\""); } protected void SerializeNumber(float number, StringBuilder builder) { builder.Append(number.ToString()); // , CultureInfo.InvariantCulture)); } /* /// <summary> /// Determines if a given object is numeric in any way /// (can be integer, float, etc). C# has no pretty way to do this. /// </summary> protected bool IsNumeric(object o) { try { Single.Parse(o.ToString()); } catch (Exception) { return false; } return true; } */ } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEditor.Collaboration; using UnityEngine.TestTools; using NUnit.Framework; namespace UnityEditor.Collaboration.Tests { [TestFixture] internal class HistoryTests { private TestHistoryWindow _window; private TestRevisionsService _service; private CollabHistoryPresenter _presenter; [SetUp] public void SetUp() { _window = new TestHistoryWindow(); _service = new TestRevisionsService(); _presenter = new CollabHistoryPresenter(_window, new CollabHistoryItemFactory(), _service); } [TearDown] public void TearDown() { } [Test] public void CollabHistoryPresenter_OnUpdatePage__PropagatesRevisionResult() { _service.result = new RevisionsResult() { Revisions = new List<Revision>() { new Revision(authorName: "authorName", comment: "comment", revisionID: "revisionID"), } }; _presenter.OnUpdatePage(0); var item = _window.items.First(); Assert.AreEqual("revisionID", item.id); Assert.AreEqual("authorName", item.authorName); Assert.AreEqual("comment", item.comment); } [Test] public void CollabHistoryPresenter_OnUpdatePage__RevisionNumberingIsInOrder() { _service.result = new RevisionsResult() { RevisionsInRepo = 4, Revisions = new List<Revision>() { new Revision(revisionID: "0"), new Revision(revisionID: "1"), new Revision(revisionID: "2"), new Revision(revisionID: "3"), } }; _presenter.OnUpdatePage(0); var items = _window.items.ToArray(); Assert.AreEqual(4, items[0].index); Assert.AreEqual(3, items[1].index); Assert.AreEqual(2, items[2].index); Assert.AreEqual(1, items[3].index); } [Test] public void CollabHistoryPresenter_OnUpdatePage__RevisionNumberingChangesForMorePages() { _service.result = new RevisionsResult() { RevisionsInRepo = 12, Revisions = new List<Revision>() { new Revision(revisionID: "0"), new Revision(revisionID: "1"), new Revision(revisionID: "2"), new Revision(revisionID: "3"), new Revision(revisionID: "4"), } }; _presenter.OnUpdatePage(1); var items = _window.items.ToArray(); Assert.AreEqual(12, items[0].index); Assert.AreEqual(11, items[1].index); Assert.AreEqual(10, items[2].index); Assert.AreEqual(9, items[3].index); Assert.AreEqual(8, items[4].index); } [Test] public void CollabHistoryPresenter_OnUpdatePage__ObtainedIsCalculated() { _service.result = new RevisionsResult() { Revisions = new List<Revision>() { new Revision(isObtained: false), new Revision(isObtained: true), } }; _presenter.OnUpdatePage(0); var items = _window.items.ToArray(); Assert.IsFalse(items[0].obtained); Assert.IsTrue(items[1].obtained); } [Test] public void CollabHistoryPresenter_OnUpdatePage__CurrentIsCalculated() { _service.result = new RevisionsResult() { Revisions = new List<Revision>() { new Revision(revisionID: "1"), new Revision(revisionID: "2"), new Revision(revisionID: "3"), } }; _service.tipRevision = "2"; _presenter.OnUpdatePage(0); var items = _window.items.ToArray(); Assert.AreEqual(false, items[0].current); Assert.AreEqual(true, items[1].current); Assert.AreEqual(false, items[2].current); } [Test] public void CollabHistoryPresenter_OnUpdatePage__InProgressIsCalculated() { _service.result = new RevisionsResult() { Revisions = new List<Revision>() { new Revision(revisionID: "1"), new Revision(revisionID: "2"), new Revision(revisionID: "3"), } }; _window.inProgressRevision = "2"; _presenter.OnUpdatePage(0); var items = _window.items.ToArray(); Assert.IsFalse(items[0].inProgress); Assert.IsTrue(items[1].inProgress); Assert.IsFalse(items[2].inProgress); } [Test] public void CollabHistoryPresenter_OnUpdatePage__EnabledIsCalculated() { _service.result = new RevisionsResult() { Revisions = new List<Revision>() { new Revision(revisionID: "0"), } }; _window.revisionActionsEnabled = true; _presenter.OnUpdatePage(0); var item = _window.items.First(); Assert.AreEqual(true, item.enabled); } [Test] public void CollabHistoryPresenter_OnUpdatePage__DisabledIsCalculated() { _service.result = new RevisionsResult() { Revisions = new List<Revision>() { new Revision(revisionID: "0"), } }; _window.revisionActionsEnabled = false; _presenter.OnUpdatePage(0); var item = _window.items.First(); Assert.AreEqual(false, item.enabled); } [Test] public void CollabHistoryPresenter_OnUpdatePage__BuildStateHasNoneWhenNotTip() { _service.result = new RevisionsResult() { Revisions = new List<Revision>() { new Revision(revisionID: "1"), } }; _service.tipRevision = "0"; _presenter.BuildServiceEnabled = false; _presenter.OnUpdatePage(0); var item = _window.items.First(); Assert.AreEqual(BuildState.None, item.buildState); } [Test] public void CollabHistoryPresenter_OnUpdatePage__BuildStateTipHasNoneWhenEnabled() { _service.result = new RevisionsResult() { Revisions = new List<Revision>() { new Revision(revisionID: "0"), } }; _service.tipRevision = "0"; _presenter.BuildServiceEnabled = true; _presenter.OnUpdatePage(0); var item = _window.items.First(); Assert.AreEqual(BuildState.None, item.buildState); } [Test] public void CollabHistoryPresenter_OnUpdatePage__BuildStateHasConfigureWhenTip() { _service.result = new RevisionsResult() { Revisions = new List<Revision>() { new Revision(revisionID: "0"), } }; _service.tipRevision = "0"; _presenter.BuildServiceEnabled = false; _presenter.OnUpdatePage(0); var item = _window.items.First(); Assert.AreEqual(BuildState.Configure, item.buildState); } [Test] public void CollabHistoryPresenter_OnUpdatePage__BuildStateHasConfigureWhenZeroBuildStatus() { _service.result = new RevisionsResult() { Revisions = new List<Revision>() { new Revision(revisionID: "0"), } }; _service.tipRevision = "0"; _presenter.BuildServiceEnabled = false; _presenter.OnUpdatePage(0); var item = _window.items.First(); Assert.AreEqual(BuildState.Configure, item.buildState); } [Test] public void CollabHistoryPresenter_OnUpdatePage__BuildStateHasNoneWhenZeroBuildStatuses() { _service.result = new RevisionsResult() { Revisions = new List<Revision>() { new Revision(revisionID: "0"), } }; _service.tipRevision = "0"; _presenter.BuildServiceEnabled = true; _presenter.OnUpdatePage(0); var item = _window.items.First(); Assert.AreEqual(BuildState.None, item.buildState); } [Test] public void CollabHistoryPresenter_OnUpdatePage__BuildStateHasSuccessWhenCompleteAndSucceeded() { _service.result = new RevisionsResult() { Revisions = new List<Revision>() { new Revision ( revisionID: "0", buildStatuses: new CloudBuildStatus[1] { new CloudBuildStatus(complete: true, success: true), } ), } }; _service.tipRevision = "0"; _presenter.BuildServiceEnabled = true; _presenter.OnUpdatePage(0); var item = _window.items.First(); Assert.AreEqual(BuildState.Success, item.buildState); } [Test] public void CollabHistoryPresenter_OnUpdatePage__BuildStateHasInProgress() { _service.result = new RevisionsResult() { Revisions = new List<Revision>() { new Revision ( revisionID: "0", buildStatuses: new CloudBuildStatus[1] { new CloudBuildStatus(complete: false), } ), } }; _service.tipRevision = "0"; _presenter.BuildServiceEnabled = true; _presenter.OnUpdatePage(0); var item = _window.items.First(); Assert.AreEqual(BuildState.InProgress, item.buildState); } [Test] public void CollabHistoryPresenter_OnUpdatePage__BuildStateHasFailure() { _service.result = new RevisionsResult() { Revisions = new List<Revision>() { new Revision ( revisionID: "0", buildStatuses: new CloudBuildStatus[1] { new CloudBuildStatus(complete: true, success: false), } ), } }; _service.tipRevision = "0"; _presenter.BuildServiceEnabled = true; _presenter.OnUpdatePage(0); var item = _window.items.First(); Assert.AreEqual(BuildState.Failed, item.buildState); } [Test] public void CollabHistoryPresenter_OnUpdatePage__BuildStateHasFailureWhenAnyBuildsFail() { _service.result = new RevisionsResult() { Revisions = new List<Revision>() { new Revision ( revisionID: "0", buildStatuses: new CloudBuildStatus[3] { new CloudBuildStatus(complete: true, success: false), new CloudBuildStatus(complete: true, success: false), new CloudBuildStatus(complete: true, success: true), } ), } }; _service.tipRevision = "0"; _presenter.BuildServiceEnabled = true; _presenter.OnUpdatePage(0); var item = _window.items.First(); Assert.AreEqual(BuildState.Failed, item.buildState); } [Test] public void CollabHistoryPresenter_OnUpdatePage__ChangesPropagateThrough() { _service.result = new RevisionsResult() { Revisions = new List<Revision>() { new Revision(revisionID: "0", entries: GenerateChangeActions(3)), } }; _presenter.OnUpdatePage(0); var item = _window.items.First(); var changes = item.changes.ToList(); Assert.AreEqual("Path0", changes[0].path); Assert.AreEqual("Path1", changes[1].path); Assert.AreEqual("Path2", changes[2].path); } [Test] public void CollabHistoryPresenter_OnUpdatePage__ChangesTotalIsCalculated() { _service.result = new RevisionsResult() { Revisions = new List<Revision>() { new Revision(revisionID: "0", entries: GenerateChangeActions(3)), } }; _presenter.OnUpdatePage(0); var item = _window.items.First(); Assert.AreEqual(3, item.changes.Count); } [Test] public void CollabHistoryPresenter_OnUpdatePage__ChangesTruncatedIsCalculated() { for (var i = 0; i < 20; i++) { _service.result = new RevisionsResult() { Revisions = new List<Revision>() { new Revision(revisionID: "0", entries: GenerateChangeActions(i)), } }; _presenter.OnUpdatePage(0); var item = _window.items.First(); Assert.AreEqual(i > 10, item.changesTruncated); } } [Test] public void CollabHistoryPresenter_OnUpdatePage__OnlyKeeps10ChangeActions() { _service.result = new RevisionsResult() { Revisions = new List<Revision>() { new Revision(authorName: "Test", author: "test", entries: GenerateChangeActions(12)), } }; _presenter.OnUpdatePage(1); var item = _window.items.First(); Assert.AreEqual(10, item.changes.Count); Assert.AreEqual(12, item.changesTotal); Assert.AreEqual(true, item.changesTruncated); } [Test] public void CollabHistoryPresenter_OnUpdatePage__DeduplicatesMetaFiles() { _service.result = new RevisionsResult() { Revisions = new List<Revision>() { new Revision ( authorName: "Test", author: "test", revisionID: "", entries: new ChangeAction[2] { new ChangeAction(path: "Path1", action: "Action1"), new ChangeAction(path: "Path1.meta", action: "Action1"), } ), } }; _presenter.OnUpdatePage(1); var item = _window.items.First(); Assert.AreEqual(1, item.changes.Count); Assert.AreEqual(1, item.changesTotal); Assert.AreEqual("Path1", item.changes.First().path); } [Test] public void CollabHistoryPresenter_OnUpdatePage__FolderMetaFilesAreCounted() { _service.result = new RevisionsResult() { Revisions = new List<Revision>() { new Revision ( authorName: "Test", author: "test", entries: new ChangeAction[1] { new ChangeAction(path: "Folder1.meta", action: "Action1"), } ), } }; _presenter.OnUpdatePage(1); var item = _window.items.First(); Assert.AreEqual(1, item.changes.Count); Assert.AreEqual(1, item.changesTotal); Assert.AreEqual("Folder1", item.changes.First().path); } private static ChangeAction[] GenerateChangeActions(int count) { var entries = new ChangeAction[count]; for (var i = 0; i < count; i++) entries[i] = new ChangeAction(path: "Path" + i, action: "Action" + i); return entries; } } internal class TestRevisionsService : IRevisionsService { public RevisionsResult result; public event RevisionsDelegate FetchRevisionsCallback; public string tipRevision { get; set; } public string currentUser { get; set; } public void GetRevisions(int offset, int count) { if(FetchRevisionsCallback != null) { FetchRevisionsCallback(result); } } } internal class TestHistoryWindow : ICollabHistoryWindow { public IEnumerable<RevisionData> items; public bool revisionActionsEnabled { get; set; } public int itemsPerPage { get; set; } public string errMessage { get; set; } public string inProgressRevision { get; set; } public PageChangeAction OnPageChangeAction { get; set; } public RevisionAction OnGoBackAction { get; set; } public RevisionAction OnUpdateAction { get; set; } public RevisionAction OnRestoreAction { get; set; } public ShowBuildAction OnShowBuildAction { get; set; } public Action OnShowServicesAction { get; set; } public void UpdateState(HistoryState state, bool force) { } public void UpdateRevisions(IEnumerable<RevisionData> items, string tip, int totalRevisions, int currPage) { this.items = items; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //////////////////////////////////////////////////////////////////////////// // // Class: TextInfo // // Purpose: This Class defines behaviors specific to a writing system. // A writing system is the collection of scripts and // orthographic rules required to represent a language as text. // // Date: March 31, 1999 // //////////////////////////////////////////////////////////////////////////// using System.Security; using System; using System.Text; using System.Threading; using System.Runtime; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace System.Globalization { public partial class TextInfo { ////--------------------------------------------------------------------// //// Internal Information // ////--------------------------------------------------------------------// //// //// Variables. //// private String m_listSeparator; private bool m_isReadOnly = false; //// //// In Whidbey we had several names: //// m_win32LangID is the name of the culture, but only used for (de)serialization. //// customCultureName is the name of the creating custom culture (if custom) In combination with m_win32LangID //// this is authoratative, ie when deserializing. //// m_cultureTableRecord was the data record of the creating culture. (could have different name if custom) //// m_textInfoID is the LCID of the textinfo itself (no longer used) //// m_name is the culture name (from cultureinfo.name) //// //// In Silverlight/Arrowhead this is slightly different: //// m_cultureName is the name of the creating culture. Note that we consider this authoratative, //// if the culture's textinfo changes when deserializing, then behavior may change. //// (ala Whidbey behavior). This is the only string Arrowhead needs to serialize. //// m_cultureData is the data that backs this class. //// m_textInfoName is the actual name of the textInfo (from cultureData.STEXTINFO) //// this can be the same as m_cultureName on Silverlight since the OS knows //// how to do the sorting. However in the desktop, when we call the sorting dll, it doesn't //// know how to resolve custom locle names to sort ids so we have to have alredy resolved this. //// private readonly String m_cultureName; // Name of the culture that created this text info private readonly CultureData m_cultureData; // Data record for the culture that made us, not for this textinfo private readonly String m_textInfoName; // Name of the text info we're using (ie: m_cultureData.STEXTINFO) private bool? m_IsAsciiCasingSameAsInvariant; // Invariant text info internal static TextInfo Invariant { get { if (s_Invariant == null) s_Invariant = new TextInfo(CultureData.Invariant); return s_Invariant; } } internal volatile static TextInfo s_Invariant; // // Internal ordinal comparison functions // internal static int GetHashCodeOrdinalIgnoreCase(String s) { // This is the same as an case insensitive hash for Invariant // (not necessarily true for sorting, but OK for casing & then we apply normal hash code rules) return (Invariant.GetCaseInsensitiveHashCode(s)); } // Currently we don't have native functions to do this, so we do it the hard way [SecuritySafeCritical] internal static int IndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count) { if (count > source.Length || count < 0 || startIndex < 0 || startIndex >= source.Length || startIndex + count > source.Length) { return -1; } return CompareInfo.IndexOfOrdinal(source, value, startIndex, count, ignoreCase: true); } // Currently we don't have native functions to do this, so we do it the hard way [SecuritySafeCritical] internal static int LastIndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count) { if (count > source.Length || count < 0 || startIndex < 0 || startIndex > source.Length - 1 || (startIndex - count + 1 < 0)) { return -1; } return CompareInfo.LastIndexOfOrdinal(source, value, startIndex, count, ignoreCase: true); } ////////////////////////////////////////////////////////////////////////// //// //// CultureName //// //// The name of the culture associated with the current TextInfo. //// ////////////////////////////////////////////////////////////////////////// public string CultureName { get { return m_textInfoName; } } //////////////////////////////////////////////////////////////////////// // // IsReadOnly // // Detect if the object is readonly. // //////////////////////////////////////////////////////////////////////// [System.Runtime.InteropServices.ComVisible(false)] public bool IsReadOnly { get { return (m_isReadOnly); } } ////////////////////////////////////////////////////////////////////////// //// //// Clone //// //// Is the implementation of IColnable. //// ////////////////////////////////////////////////////////////////////////// internal virtual Object Clone() { object o = MemberwiseClone(); ((TextInfo)o).SetReadOnlyState(false); return (o); } //////////////////////////////////////////////////////////////////////// // // ReadOnly // // Create a cloned readonly instance or return the input one if it is // readonly. // //////////////////////////////////////////////////////////////////////// [System.Runtime.InteropServices.ComVisible(false)] internal static TextInfo ReadOnly(TextInfo textInfo) { if (textInfo == null) { throw new ArgumentNullException("textInfo"); } Contract.EndContractBlock(); if (textInfo.IsReadOnly) { return (textInfo); } TextInfo clonedTextInfo = (TextInfo)(textInfo.MemberwiseClone()); clonedTextInfo.SetReadOnlyState(true); return (clonedTextInfo); } private void VerifyWritable() { if (m_isReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } } internal void SetReadOnlyState(bool readOnly) { m_isReadOnly = readOnly; } //////////////////////////////////////////////////////////////////////// // // ListSeparator // // Returns the string used to separate items in a list. // //////////////////////////////////////////////////////////////////////// public virtual String ListSeparator { get { if (m_listSeparator == null) { m_listSeparator = this.m_cultureData.SLIST; } return (m_listSeparator); } set { if (value == null) { throw new ArgumentNullException("value", SR.ArgumentNull_String); } VerifyWritable(); m_listSeparator = value; } } //////////////////////////////////////////////////////////////////////// // // ToLower // // Converts the character or string to lower case. Certain locales // have different casing semantics from the file systems in Win32. // //////////////////////////////////////////////////////////////////////// public unsafe virtual char ToLower(char c) { if (IsAscii(c) && IsAsciiCasingSameAsInvariant) { return ToLowerAsciiInvariant(c); } return (ChangeCase(c, toUpper: false)); } public unsafe virtual String ToLower(String str) { if (str == null) { throw new ArgumentNullException("str"); } return ChangeCase(str, toUpper: false); } private static Char ToLowerAsciiInvariant(Char c) { Contract.Assert(IsAscii(c)); return (Char)s_toLowerAsciiMapping[c & 0x7F]; } private static readonly byte[] s_toLowerAsciiMapping = new byte[128] { // s_toLowerAsciiMapping[c] == invariant lower case value of c 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F }; //////////////////////////////////////////////////////////////////////// // // ToUpper // // Converts the character or string to upper case. Certain locales // have different casing semantics from the file systems in Win32. // //////////////////////////////////////////////////////////////////////// public unsafe virtual char ToUpper(char c) { if (IsAscii(c) && IsAsciiCasingSameAsInvariant) { return ToUpperAsciiInvariant(c); } return (ChangeCase(c, toUpper: true)); } public unsafe virtual String ToUpper(String str) { if (str == null) { throw new ArgumentNullException("str"); } return ChangeCase(str, toUpper: true); } private static Char ToUpperAsciiInvariant(Char c) { Contract.Assert(IsAscii(c)); return (Char)s_toUpperAsciiMapping[c & 0x7F]; } private static readonly byte[] s_toUpperAsciiMapping = new byte[128] { // s_toUpperAsciiMapping[c] == invariant upper case value of c 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F }; static private bool IsAscii(Char c) { return c < 0x80; } private bool IsAsciiCasingSameAsInvariant { get { if (m_IsAsciiCasingSameAsInvariant == null) { m_IsAsciiCasingSameAsInvariant = CultureInfo.GetCultureInfo(m_textInfoName).CompareInfo.Compare("abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", CompareOptions.IgnoreCase) == 0; } return (bool)m_IsAsciiCasingSameAsInvariant; } } // IsRightToLeft // // Returns true if the dominant direction of text and UI such as the relative position of buttons and scroll bars // public bool IsRightToLeft { get { return this.m_cultureData.IsRightToLeft; } } //////////////////////////////////////////////////////////////////////// // // Equals // // Implements Object.Equals(). Returns a boolean indicating whether // or not object refers to the same CultureInfo as the current instance. // //////////////////////////////////////////////////////////////////////// public override bool Equals(Object obj) { TextInfo that = obj as TextInfo; if (that != null) { return this.CultureName.Equals(that.CultureName); } return (false); } //////////////////////////////////////////////////////////////////////// // // GetHashCode // // Implements Object.GetHashCode(). Returns the hash code for the // CultureInfo. The hash code is guaranteed to be the same for CultureInfo A // and B where A.Equals(B) is true. // //////////////////////////////////////////////////////////////////////// public override int GetHashCode() { return (this.CultureName.GetHashCode()); } //////////////////////////////////////////////////////////////////////// // // ToString // // Implements Object.ToString(). Returns a string describing the // TextInfo. // //////////////////////////////////////////////////////////////////////// public override String ToString() { return ("TextInfo - " + this.m_cultureData.CultureName); } // // Get case-insensitive hash code for the specified string. // internal unsafe int GetCaseInsensitiveHashCode(String str) { // Validate inputs if (str == null) { throw new ArgumentNullException("str"); } // This code assumes that ASCII casing is safe for whatever context is passed in. // this is true today, because we only ever call these methods on Invariant. It would be ideal to refactor // these methods so they were correct by construction and we could only ever use Invariant. uint hash = 5381; uint c; // Note: We assume that str contains only ASCII characters until // we hit a non-ASCII character to optimize the common case. for (int i = 0; i < str.Length; i++) { c = str[i]; if (c >= 0x80) { return GetCaseInsensitiveHashCodeSlow(str); } // If we have a lowercase character, ANDing off 0x20 // will make it an uppercase character. if ((c - 'a') <= ('z' - 'a')) { c = (uint)((int)c & ~0x20); } hash = ((hash << 5) + hash) ^ c; } return (int)hash; } private unsafe int GetCaseInsensitiveHashCodeSlow(String str) { Contract.Assert(str != null); string upper = ToUpper(str); uint hash = 5381; uint c; for (int i = 0; i < upper.Length; i++) { c = upper[i]; hash = ((hash << 5) + hash) ^ c; } return (int)hash; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using System.Xml.Linq; using CoreXml.Test.XLinq; using Microsoft.Test.ModuleCore; using XmlCoreTest.Common; namespace XLinqTests { public class XNodeSequenceRemove : XLinqTestCase { // Type is CoreXml.Test.XLinq.FunctionalTests+TreeManipulationTests+XNodeSequenceRemove // Test Case #region Fields private EventsHelper _eHelper; private bool _runWithEvents; #endregion #region Public Methods and Operators public override void AddChildren() { AddChild(new TestVariation(ElementsFromMixedContent) { Attribute = new VariationAttribute("All elements from mixed content") { Priority = 0 } }); AddChild(new TestVariation(AllFromDocument) { Attribute = new VariationAttribute("All content from the XDocument (doc level)") { Priority = 0 } }); AddChild(new TestVariation(AllNodes) { Attribute = new VariationAttribute("All nodes from the XDocument") { Priority = 0 } }); AddChild(new TestVariation(TwoDocuments) { Attribute = new VariationAttribute("Nodes from two documents") { Priority = 0 } }); AddChild(new TestVariation(DuplicateNodes) { Attribute = new VariationAttribute("Duplicate nodes in sequence") { Priority = 0 } }); AddChild(new TestVariation(IdAttrsNulls) { Attribute = new VariationAttribute("Nodes from multiple elements + nulls") { Priority = 1 } }); AddChild(new TestVariation(EmptySequence) { Attribute = new VariationAttribute("Empty sequence") { Priority = 1 } }); AddChild(new TestVariation(XNodeAncestors) { Attribute = new VariationAttribute("XNode.Ancestors") { Priority = 1 } }); AddChild(new TestVariation(XNodeAncestorsXName) { Attribute = new VariationAttribute("XNode.Ancestors(XName)") { Priority = 1 } }); AddChild(new TestVariation(XNodesBeforeSelf) { Attribute = new VariationAttribute("XNode.NodesBeforeSelf") { Priority = 1 } }); AddChild(new TestVariation(XNodesAfterSelf) { Attribute = new VariationAttribute("XNode.NodesAfterSelf") { Priority = 1 } }); AddChild(new TestVariation(XElementsBeforeSelf) { Attribute = new VariationAttribute("XNode.ElementsBeforeSelf") { Priority = 1 } }); AddChild(new TestVariation(XElementsAfterSelf) { Attribute = new VariationAttribute("XNode.ElementsAfterSelf") { Priority = 1 } }); AddChild(new TestVariation(XElementsBeforeSelfXName) { Attribute = new VariationAttribute("XNode.ElementsBeforeSelf(XName)") { Priority = 1 } }); AddChild(new TestVariation(XElementsAfterSelfXName) { Attribute = new VariationAttribute("XNode.ElementsAfterSelf(XName)") { Priority = 1 } }); AddChild(new TestVariation(Document_Nodes) { Attribute = new VariationAttribute("XDocument.Nodes") { Priority = 2 } }); AddChild(new TestVariation(Document_DescendantNodes) { Attribute = new VariationAttribute("XDocument.DescendantNodes") { Priority = 2 } }); AddChild(new TestVariation(Document_Descendants) { Attribute = new VariationAttribute("XDocument.Descendants") { Priority = 2 } }); AddChild(new TestVariation(Document_Elements) { Attribute = new VariationAttribute("XDocument.Elements") { Priority = 2 } }); AddChild(new TestVariation(Document_DescendantsXName) { Attribute = new VariationAttribute("XDocument.Descendants(XName)") { Priority = 2 } }); AddChild(new TestVariation(Document_ElementsXName) { Attribute = new VariationAttribute("XDocument.Elements(XName)") { Priority = 2 } }); AddChild(new TestVariation(Element_Nodes) { Attribute = new VariationAttribute("XElement.Nodes") { Priority = 2 } }); AddChild(new TestVariation(Element_DescendantNodes) { Attribute = new VariationAttribute("XElement.DescendantNodes") { Priority = 2 } }); AddChild(new TestVariation(Element_Descendants) { Attribute = new VariationAttribute("XElement.Descendants") { Priority = 2 } }); AddChild(new TestVariation(Element_Elements) { Attribute = new VariationAttribute("XElement.Elements") { Priority = 2 } }); AddChild(new TestVariation(Element_DescendantsXName) { Attribute = new VariationAttribute("XElement.Descendants(XName)") { Priority = 2 } }); AddChild(new TestVariation(Element_ElementsXName) { Attribute = new VariationAttribute("XElement.Elements(XName)") { Priority = 2 } }); AddChild(new TestVariation(Element_AncestorsAndSelf) { Attribute = new VariationAttribute("XElement.AncestorsAndSelf") { Priority = 2 } }); AddChild(new TestVariation(Element_DescendantNodesAndSelf) { Attribute = new VariationAttribute("XElement.DescendantNodesAndSelf") { Priority = 2 } }); AddChild(new TestVariation(Element_DescendantsAndSelf) { Attribute = new VariationAttribute("XElement.DescendantsAndSelf") { Priority = 2 } }); AddChild(new TestVariation(Element_DescendantsAndSelfXName) { Attribute = new VariationAttribute("XElement.DescendantsAndSelf(XName) II.") { Param = false, Priority = 2 } }); AddChild(new TestVariation(Element_DescendantsAndSelfXName) { Attribute = new VariationAttribute("XElement.DescendantsAndSelf(XName) I.") { Param = true, Priority = 2 } }); AddChild(new TestVariation(Element_AncestorsAndSelfXName) { Attribute = new VariationAttribute("XElement.AncestorsAndSelf(XName) I.") { Param = true, Priority = 2 } }); AddChild(new TestVariation(Element_AncestorsAndSelfXName) { Attribute = new VariationAttribute("XElement.AncestorsAndSelf(XName) II.") { Param = false, Priority = 2 } }); } //[Variation(Priority = 0, Desc = "All elements from mixed content")] //[Variation(Priority = 0, Desc = "All content from the XDocument (doc level)")] public void AllFromDocument() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Parse("\t<?PI?><A xmlns='a'/>\r\n <!--comment-->", LoadOptions.PreserveWhitespace); IEnumerable<XNode> toRemove = doc.Nodes(); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = toRemove.IsEmpty() ? 0 : toRemove.Count(); } VerifyDeleteNodes(toRemove); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } //[Variation(Priority = 0, Desc = "All nodes from the XDocument")] public void AllNodes() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Parse("\t<?PI?><A xmlns='a'/>\r\n <!--comment-->", LoadOptions.PreserveWhitespace); IEnumerable<XNode> toRemove = doc.DescendantNodes(); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = toRemove.IsEmpty() ? 0 : toRemove.Count(); } VerifyDeleteNodes(toRemove); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } //[Variation(Priority = 0, Desc = "Nodes from two documents")] //[Variation(Priority = 2, Desc = "XDocument.DescendantNodes")] public void Document_DescendantNodes() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Load(FilePathUtil.getStream(Path.Combine("TestData", "XLinq", "Books.xml")), LoadOptions.PreserveWhitespace); IEnumerable<XNode> toRemove = doc.DescendantNodes(); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = doc.Nodes().Count(); } VerifyDeleteNodes(toRemove); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } //[Variation(Priority = 2, Desc = "XDocument.Descendants")] public void Document_Descendants() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Load(FilePathUtil.getStream(Path.Combine(@"TestData", "XLinq", "Books.xml")), LoadOptions.PreserveWhitespace); IEnumerable<XNode> toRemove = doc.Descendants().OfType<XNode>(); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = doc.Elements().Count(); } VerifyDeleteNodes(toRemove); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } //[Variation(Priority = 2, Desc = "XDocument.Elements")] //[Variation(Priority = 2, Desc = "XDocument.Descendants(XName)")] public void Document_DescendantsXName() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Load(FilePathUtil.getStream(Path.Combine("TestData", "XLinq", "Books.xml")), LoadOptions.PreserveWhitespace); IEnumerable<XNode> toRemove = doc.Descendants(@"{http://www.books.com/}book").OfType<XNode>(); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = toRemove.IsEmpty() ? 0 : toRemove.Count(); } VerifyDeleteNodes(toRemove); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } public void Document_Elements() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Load(FilePathUtil.getStream(Path.Combine("TestData", "XLinq", "Books.xml")), LoadOptions.PreserveWhitespace); IEnumerable<XNode> toRemove = doc.Elements().OfType<XNode>(); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = toRemove.IsEmpty() ? 0 : toRemove.Count(); } VerifyDeleteNodes(toRemove); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } //[Variation(Priority = 2, Desc = "XDocument.Elements(XName)")] public void Document_ElementsXName() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Load(FilePathUtil.getStream(Path.Combine("TestData", "XLinq", "Books.xml")), LoadOptions.PreserveWhitespace); IEnumerable<XNode> toRemove = doc.Elements("bookstore").OfType<XNode>(); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = toRemove.IsEmpty() ? 0 : toRemove.Count(); } VerifyDeleteNodes(toRemove); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } public void Document_Nodes() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Load(FilePathUtil.getStream(Path.Combine("TestData", "XLinq", "Books.xml")), LoadOptions.PreserveWhitespace); IEnumerable<XNode> toRemove = doc.Nodes(); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = toRemove.IsEmpty() ? 0 : toRemove.Count(); } VerifyDeleteNodes(toRemove); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } public void DuplicateNodes() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Parse("<A xmlns='a'><!--comment-->text1<X/></A>", LoadOptions.PreserveWhitespace); IEnumerable<XNode> toRemove = doc.Root.Nodes().Take(2).Concat2(doc.Root.Elements()); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = toRemove.IsEmpty() ? 0 : toRemove.Count(); } VerifyDeleteNodes(toRemove); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } //[Variation(Priority = 2, Desc = "XElement.Nodes")] // XElement: // IEnumerable<XElement> AncestorsAndSelf() // IEnumerable<XNode> SelfAndDescendantNodes() // IEnumerable<XElement> DescendantsAndSelf() // IEnumerable<XElement> DescendantsAndSelf(XName name) // IEnumerable<XElement> AncestorsAndSelf(XName name) //[Variation(Priority = 2, Desc = "XElement.AncestorsAndSelf")] public void Element_AncestorsAndSelf() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Load(FilePathUtil.getStream(Path.Combine("TestData", "XLinq", "Books.xml")), LoadOptions.PreserveWhitespace); XElement e = doc.Descendants(@"{http://www.books.com/}book").Where(x => x.Element("title").Value == "XQL The Golden Years").First(); TestLog.Compare(e != null, "TEST_FAILED: wrong starting position"); IEnumerable<XNode> toRemove = e.AncestorsAndSelf().OfType<XNode>(); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = toRemove.IsEmpty() ? 0 : toRemove.Count(); } VerifyDeleteNodes(toRemove); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } public void Element_AncestorsAndSelfXName() { int count = 0; _runWithEvents = (bool)Params[0]; var useSelf = (bool)Variation.Param; XDocument doc = XDocument.Load(FilePathUtil.getStream(Path.Combine("TestData", "XLinq", "Books.xml")), LoadOptions.PreserveWhitespace); XElement e = doc.Descendants(@"{http://www.books.com/}book").Where(x => x.Element("title").Value == "XQL The Golden Years").First(); TestLog.Compare(e != null, "TEST_FAILED: wrong starting position"); IEnumerable<XNode> toRemove = e.AncestorsAndSelf(useSelf ? @"{http://www.books.com/}book" : @"bookstore").OfType<XNode>(); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = toRemove.IsEmpty() ? 0 : toRemove.Count(); } VerifyDeleteNodes(toRemove); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } public void Element_DescendantNodes() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Load(FilePathUtil.getStream(Path.Combine("TestData", "XLinq", "Books.xml")), LoadOptions.PreserveWhitespace); XElement e = doc.Descendants(@"{http://www.books.com/}book").Where(x => x.Element("title").Value == "XQL The Golden Years").First(); TestLog.Compare(e != null, "TEST_FAILING: wrong starting position"); IEnumerable<XNode> toRemove = e.DescendantNodes(); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = e.Nodes().Count(); } VerifyDeleteNodes(toRemove); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } //[Variation(Priority = 2, Desc = "XElement.DescendantNodesAndSelf")] public void Element_DescendantNodesAndSelf() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Load(FilePathUtil.getStream(Path.Combine("TestData", "XLinq", "Books.xml")), LoadOptions.PreserveWhitespace); XElement e = doc.Descendants(@"{http://www.books.com/}book").Where(x => x.Element("title").Value == "XQL The Golden Years").First(); TestLog.Compare(e != null, "TEST_FAILING: wrong starting position"); IEnumerable<XNode> toRemove = e.DescendantNodesAndSelf(); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = 1; } VerifyDeleteNodes(toRemove); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } public void Element_Descendants() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Load(FilePathUtil.getStream(Path.Combine("TestData", "XLinq", "Books.xml")), LoadOptions.PreserveWhitespace); XElement e = doc.Descendants(@"{http://www.books.com/}book").Where(x => x.Element("title").Value == "XQL The Golden Years").First(); TestLog.Compare(e != null, "TEST_FAILING: wrong starting position"); IEnumerable<XNode> toRemove = e.Descendants().OfType<XNode>(); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = e.Elements().Count(); } VerifyDeleteNodes(toRemove); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } //[Variation(Priority = 2, Desc = "XElement.DescendantsAndSelf")] public void Element_DescendantsAndSelf() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Load(FilePathUtil.getStream(Path.Combine("TestData", "XLinq", "Books.xml")), LoadOptions.PreserveWhitespace); XElement e = doc.Descendants(@"{http://www.books.com/}book").Where(x => x.Element("title").Value == "XQL The Golden Years").First(); TestLog.Compare(e != null, "TEST_FAILING: wrong starting position"); IEnumerable<XNode> toRemove = e.DescendantsAndSelf().OfType<XNode>(); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = 1; } VerifyDeleteNodes(toRemove); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } //[Variation(Priority = 2, Desc = "XElement.DescendantsAndSelf(XName) I.", Param = true)] //[Variation(Priority = 2, Desc = "XElement.DescendantsAndSelf(XName) II.", Param = false)] public void Element_DescendantsAndSelfXName() { int count = 0; _runWithEvents = (bool)Params[0]; var useSelf = (bool)Variation.Param; XDocument doc = XDocument.Load(FilePathUtil.getStream(Path.Combine("TestData", "XLinq", "Books.xml")), LoadOptions.PreserveWhitespace); XElement e = useSelf ? doc.Descendants(@"{http://www.books.com/}book").Where(x => x.Element("title").Value == "XQL The Golden Years").First() : doc.Root; TestLog.Compare(e != null, "TEST_FAILING: wrong starting position"); IEnumerable<XNode> toRemove = e.DescendantsAndSelf(@"{http://www.books.com/}book").OfType<XNode>(); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = toRemove.IsEmpty() ? 0 : toRemove.Count(); } VerifyDeleteNodes(toRemove); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } public void Element_DescendantsXName() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Load(FilePathUtil.getStream(Path.Combine("TestData", "XLinq", "Books.xml")), LoadOptions.PreserveWhitespace); IEnumerable<XNode> toRemove = doc.Root.Descendants(@"{http://www.books.com/}book").OfType<XNode>(); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = toRemove.IsEmpty() ? 0 : toRemove.Count(); } VerifyDeleteNodes(toRemove); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } public void Element_Elements() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Load(FilePathUtil.getStream(Path.Combine("TestData", "XLinq", "Books.xml")), LoadOptions.PreserveWhitespace); XElement e = doc.Descendants(@"{http://www.books.com/}book").Where(x => x.Element("title").Value == "XQL The Golden Years").First(); TestLog.Compare(e != null, "TEST_FAILING: wrong starting position"); IEnumerable<XNode> toRemove = e.Elements().OfType<XNode>(); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = toRemove.IsEmpty() ? 0 : toRemove.Count(); } VerifyDeleteNodes(toRemove); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } public void Element_ElementsXName() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Load(FilePathUtil.getStream(Path.Combine("TestData", "XLinq", "Books.xml")), LoadOptions.PreserveWhitespace); IEnumerable<XNode> toRemove = doc.Root.Elements(@"{http://www.books.com/}book").OfType<XNode>(); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = toRemove.IsEmpty() ? 0 : toRemove.Count(); } VerifyDeleteNodes(toRemove); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } public void Element_Nodes() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Load(FilePathUtil.getStream(Path.Combine("TestData", "XLinq", "Books.xml")), LoadOptions.PreserveWhitespace); XElement e = doc.Descendants(@"{http://www.books.com/}book").Where(x => x.Element("title").Value == "XQL The Golden Years").First(); TestLog.Compare(e != null, "TEST_FAILED: wrong starting position"); IEnumerable<XNode> toRemove = e.Nodes(); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = toRemove.IsEmpty() ? 0 : toRemove.Count(); } VerifyDeleteNodes(toRemove); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } public void ElementsFromMixedContent() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Parse(@"<A xmlns='a'><B/>text1<p:B xmlns:p='nsp'/>text2<!--comment--><C><innerElement/></C></A>", LoadOptions.PreserveWhitespace); IEnumerable<XElement> toRemove = doc.Root.Elements(); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = toRemove.IsEmpty() ? 0 : toRemove.Count(); } VerifyDeleteNodes(toRemove); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } public void EmptySequence() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D id='x' datrt='dat'/></A>"); IEnumerable<XNode> noNodes = doc.Descendants().Where(x => x.Name == "NonExisting").OfType<XNode>(); var ms1 = new MemoryStream(); doc.Save(new StreamWriter(ms1)); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = noNodes.IsEmpty() ? 0 : noNodes.Count(); } noNodes.Remove(); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } var ms2 = new MemoryStream(); doc.Save(new StreamWriter(ms2)); TestLog.Compare(ms1.ToArray().SequenceEqual(ms2.ToArray()), "Documents different"); } public void IdAttrsNulls() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D id='x' datrt='dat'/></A>"); IEnumerable<XNode> someNodes = doc.Root.Descendants().OfType<XNode>().InsertNulls(1); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = someNodes.IsEmpty() ? 0 : someNodes.Count() / 2; } VerifyDeleteNodes(someNodes); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } public void TwoDocuments() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc1 = XDocument.Parse("<A xmlns='a'><!--comment-->text1<X/></A>", LoadOptions.PreserveWhitespace); XDocument doc2 = XDocument.Parse("<A xmlns='b'>text1<X/>text2</A>", LoadOptions.PreserveWhitespace); IEnumerable<XNode> toRemove = doc1.Root.DescendantNodes().Where(x => x.NodeType == XmlNodeType.Comment).Concat2(doc2.Root.Elements()); if (_runWithEvents) { _eHelper = new EventsHelper(doc1); count = doc1.Root.DescendantNodes().Where(x => x.NodeType == XmlNodeType.Comment).Count(); } VerifyDeleteNodes(toRemove); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } public void XElementsAfterSelf() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Load(FilePathUtil.getStream(Path.Combine("TestData", "XLinq", "Books.xml")), LoadOptions.PreserveWhitespace); XElement e = doc.Descendants("magazine").Where(x => x.Element("title").Value == "PC Week").First(); TestLog.Compare(e != null, "TEST_FAILED: wrong starting position"); IEnumerable<XNode> toRemove = e.ElementsAfterSelf().OfType<XNode>(); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = toRemove.IsEmpty() ? 0 : toRemove.Count(); } VerifyDeleteNodes(toRemove); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } public void XElementsAfterSelfXName() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Load(FilePathUtil.getStream(Path.Combine("TestData", "XLinq", "Books.xml")), LoadOptions.PreserveWhitespace); XElement e = doc.Descendants("magazine").Where(x => x.Element("title").Value == "PC Week").First(); TestLog.Compare(e != null, "TEST_FAILED: wrong starting position"); IEnumerable<XNode> toRemove = e.ElementsAfterSelf(@"{http://www.books.com/}book").OfType<XNode>(); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = toRemove.IsEmpty() ? 0 : toRemove.Count(); } VerifyDeleteNodes(toRemove); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } public void XElementsBeforeSelf() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Load(FilePathUtil.getStream(Path.Combine("TestData", "XLinq", "Books.xml")), LoadOptions.PreserveWhitespace); XElement e = doc.Descendants("magazine").Where(x => x.Element("title").Value == "PC Week").First(); TestLog.Compare(e != null, "TEST_FAILED: wrong starting position"); IEnumerable<XNode> toRemove = e.ElementsBeforeSelf().OfType<XNode>(); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = toRemove.IsEmpty() ? 0 : toRemove.Count(); } VerifyDeleteNodes(toRemove); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } public void XElementsBeforeSelfXName() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Load(FilePathUtil.getStream(Path.Combine("TestData", "XLinq", "Books.xml")), LoadOptions.PreserveWhitespace); XElement e = doc.Descendants("magazine").Where(x => x.Element("title").Value == "PC Week").First(); TestLog.Compare(e != null, "TEST_FAILED: wrong starting position"); IEnumerable<XNode> toRemove = e.ElementsBeforeSelf(@"{http://www.books.com/}book").OfType<XNode>(); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = toRemove.IsEmpty() ? 0 : toRemove.Count(); } VerifyDeleteNodes(toRemove); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } public void XNodeAncestors() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Load(FilePathUtil.getStream(Path.Combine("TestData", "XLinq", "Books.xml")), LoadOptions.PreserveWhitespace); XElement e = doc.Descendants("last.name").Where(x => x.Value == "Marsh").First(); TestLog.Compare(e != null, "TEST_FAILED: wrong starting position"); IEnumerable<XNode> toRemove = e.Ancestors().OfType<XNode>(); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = toRemove.IsEmpty() ? 0 : toRemove.Count(); } VerifyDeleteNodes(e.Ancestors()); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } //[Variation(Priority = 1, Desc = "XNode.Ancestors(XName)")] public void XNodeAncestorsXName() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Load(FilePathUtil.getStream(Path.Combine("TestData", "XLinq", "Books.xml")), LoadOptions.PreserveWhitespace); XElement e = doc.Descendants("last.name").Where(x => x.Value == "Marsh").First(); TestLog.Compare(e != null, "TEST_FAILED: wrong starting position"); IEnumerable<XNode> toRemove = e.Ancestors("author").OfType<XNode>(); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = toRemove.IsEmpty() ? 0 : toRemove.Count(); } VerifyDeleteNodes(e.Ancestors("author")); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } public void XNodesAfterSelf() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Load(FilePathUtil.getStream(Path.Combine("TestData", "XLinq", "Books.xml")), LoadOptions.PreserveWhitespace); XElement e = doc.Descendants("magazine").Where(x => x.Element("title").Value == "PC Week").First(); TestLog.Compare(e != null, "TEST_FAILED: wrong starting position"); IEnumerable<XNode> toRemove = e.NodesAfterSelf(); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = toRemove.IsEmpty() ? 0 : toRemove.Count(); } VerifyDeleteNodes(toRemove); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } public void XNodesBeforeSelf() { int count = 0; _runWithEvents = (bool)Params[0]; XDocument doc = XDocument.Load(FilePathUtil.getStream(Path.Combine("TestData", "XLinq", "Books.xml")), LoadOptions.PreserveWhitespace); XElement e = doc.Descendants("magazine").Where(x => x.Element("title").Value == "PC Week").First(); TestLog.Compare(e != null, "TEST_FAILED: wrong starting position"); IEnumerable<XNode> toRemove = e.NodesBeforeSelf(); if (_runWithEvents) { _eHelper = new EventsHelper(doc); count = toRemove.IsEmpty() ? 0 : toRemove.Count(); } VerifyDeleteNodes(toRemove); if (_runWithEvents) { _eHelper.Verify(XObjectChange.Remove, count); } } #endregion //[Variation(Priority = 2, Desc = "XElement.AncestorsAndSelf(XName) I.", Param = true)] //[Variation(Priority = 2, Desc = "XElement.AncestorsAndSelf(XName) II.", Param = false)] #region Methods private void VerifyDeleteNodes<T>(IEnumerable<T> toRemove) where T : XNode { // copy of the data to delete IEnumerable<XNode> toRemoveCopy = toRemove.OfType<XNode>().ToList(); // Create array of parents IEnumerable<XContainer> parents = toRemove.Select(x => (x == null) ? (XContainer)null : (x.Parent != null ? (XContainer)x.Parent : (XContainer)x.Document)).ToList(); // calculate the expected results for the parents of the processed elements var expectedNodesForParent = new Dictionary<XContainer, List<ExpectedValue>>(); foreach (XContainer p in parents) { if (p != null) { expectedNodesForParent.TryAdd(p, p.Nodes().Except(toRemoveCopy.Where(x => x != null)).Select(a => new ExpectedValue(!(a is XText), a)).ProcessNodes().ToList()); } } toRemove.Remove(); IEnumerator<XNode> copyToRemove = toRemoveCopy.GetEnumerator(); IEnumerator<XContainer> parentsEnum = parents.GetEnumerator(); // verify on parents: deleted elements should not be found while (copyToRemove.MoveNext() && parentsEnum.MoveNext()) { XNode node = copyToRemove.Current; if (node != null) { XContainer parent = parentsEnum.Current; TestLog.Compare(node.Parent, null, "Parent of deleted"); TestLog.Compare(node.Document, null, "Document of deleted"); TestLog.Compare(node.NextNode, null, "NextNode of deleted"); TestLog.Compare(node.PreviousNode, null, "PreviousNode of deleted"); if (parent != null) { TestLog.Compare(parent.Nodes().Where(x => x == node).IsEmpty(), "Nodes axis"); if (node is XElement) { var e = node as XElement; e.Verify(); TestLog.Compare(parent.Element(e.Name) != node, "Element axis"); TestLog.Compare(parent.Elements(e.Name).Where(x => x == e).IsEmpty(), "Elements axis"); } // Compare the rest of the elements TestLog.Compare(expectedNodesForParent[parent].EqualAll(parent.Nodes(), XNode.EqualityComparer), "The rest of the nodes"); } } } } #endregion } }
using System; using System.Collections.Generic; namespace BraveHaxvius.Data { public class Request { public String Name { get; set; } public String Url { get; set; } public String EncodeKey { get; set; } public String RequestID { get; set; } public static readonly Request PurchaseSettlement = new Request { Name = "PurchaseSettlement", Url = "yt82BRwk", EncodeKey = "jmh7xID8", RequestID = "JsFd4b7j"}; public static readonly Request RbMatching = new Request { Name = "RbMatching", Url = "mn5cHaJ0", EncodeKey = "4GSMn0qb", RequestID = "DgG4Cy0F"}; public static readonly Request RmDungeonStart = new Request { Name = "RmDungeonStart", Url = "NC8Ie07P", EncodeKey = "A7V1zkyc", RequestID = "R5mWbQ3M"}; public static readonly Request RmEnd = new Request { Name = "RmEnd", Url = "I9p3n48A", EncodeKey = "FX5L3Sfv", RequestID = "fyp10Rrc"}; public static readonly Request FacebookRewardClaim = new Request { Name = "FacebookRewardClaim", Url = "47R9pLGq", EncodeKey = "Rja82ZUK", RequestID = "47R9pLGq"}; public static readonly Request FriendDelete = new Request { Name = "FriendDelete", Url = "8R4fQbYh", EncodeKey = "d0VP5ia6", RequestID = "a2d6omAy"}; public static readonly Request UpdateSwitchInfo = new Request { Name = "UpdateSwitchInfo", Url = "SqoB3a1T", EncodeKey = "4Z5UNaIW", RequestID = "mRPo5n2j"}; public static readonly Request VariableStoreCheck = new Request { Name = "VariableStoreCheck", Url = "Nhn93ukW", EncodeKey = "Hi0FJU3c", RequestID = "i0woEP4B"}; public static readonly Request CraftStart = new Request { Name = "CraftStart", Url = "w71MZ0Gg", EncodeKey = "K92H8wkY", RequestID = "Gr9zxXk5"}; public static readonly Request SearchGetItemInfo = new Request { Name = "SearchGetItemInfo", Url = "e4Gjkf0x", EncodeKey = "vK2V8mZM", RequestID = "0D9mpGUR"}; public static readonly Request SublimationSkill = new Request { Name = "SublimationSkill", Url = "xG3jBbw5", EncodeKey = "97Uvrdz3", RequestID = "s48Qzvhd"}; public static readonly Request TownIn = new Request { Name = "TownIn", Url = "isHfQm09", EncodeKey = "JI8zU5rC", RequestID = "8EYGrg76"}; public static readonly Request MissionBreak = new Request { Name = "MissionBreak", Url = "P4oIeVf0", EncodeKey = "Z2oPiE6p", RequestID = "17LFJD0b"}; public static readonly Request BeastMix = new Request { Name = "BeastMix", Url = "7vHqNPF0", EncodeKey = "WfNSmy98", RequestID = "C8X1KUpV"}; public static readonly Request LoginBonus = new Request { Name = "LoginBonus", Url = "iP9ogKy6", EncodeKey = "Vi6vd9zG", RequestID = "vw9RP3i4"}; public static readonly Request Initialize = new Request { Name = "Initialize", Url = "fSG1eXI9", EncodeKey = "rVG09Xnt", RequestID = "75fYdNxq"}; public static readonly Request DmgRankEnd = new Request { Name = "DmgRankEnd", Url = "zd5KJ3jn", EncodeKey = "7pGj8hSW", RequestID = "s98cw1WA"}; public static readonly Request GameSetting = new Request { Name = "GameSetting", Url = "OTX6Fmvu", EncodeKey = "4foXVwWd", RequestID = "OTX6Fmvu"}; public static readonly Request GetUserInfo = new Request { Name = "GetUserInfo", Url = "u7sHDCg4", EncodeKey = "rcsq2eG7", RequestID = "X07iYtp5"}; public static readonly Request NoticeUpdate = new Request { Name = "NoticeUpdate", Url = "TqtzK84R", EncodeKey = "9t68YyjT", RequestID = "CQ4jTm2F"}; public static readonly Request sgExpdAccelerate = new Request { Name = "sgExpdAccelerate", Url = "Ik142Ff6", EncodeKey = "d3D4l8b4", RequestID = "Ik142Ff6"}; public static readonly Request TownOut = new Request { Name = "TownOut", Url = "0EF3JPjL", EncodeKey = "Kc2PXd9D", RequestID = "sJcMPy04"}; public static readonly Request BeastBoardPieceOpen = new Request { Name = "BeastBoardPieceOpen", Url = "Y2Zvnad9", EncodeKey = "7uxYTm3k", RequestID = "0gk3Tfbz"}; public static readonly Request NoticeReadUpdate = new Request { Name = "NoticeReadUpdate", Url = "j6kSWR3q", EncodeKey = "iLdaq6j2", RequestID = "pC3a2JWU"}; public static readonly Request MissionWaveStart = new Request { Name = "MissionWaveStart", Url = "Mn15zmDZ", EncodeKey = "d2mqJ6pT", RequestID = "BSq28mwY"}; public static readonly Request MissionContinue = new Request { Name = "MissionContinue", Url = "ZzCXI6E7", EncodeKey = "34n2iv7z", RequestID = "LuCN4tU5"}; public static readonly Request RoutineGachaUpdate = new Request { Name = "RoutineGachaUpdate", Url = "qS0YW57G", EncodeKey = "Q6ZGJj0h", RequestID = "t60dQP49"}; public static readonly Request ExchangeShop = new Request { Name = "ExchangeShop", Url = "1bf0HF4w", EncodeKey = "qoRP87Fw", RequestID = "I7fmVX3R"}; public static readonly Request GiftUpdate = new Request { Name = "GiftUpdate", Url = "noN8I0UK", EncodeKey = "xLEtf78b", RequestID = "9KN5rcwj"}; public static readonly Request FriendSuggest = new Request { Name = "FriendSuggest", Url = "6TCn0BFh", EncodeKey = "j2P3uqRC", RequestID = "iAs67PhJ"}; public static readonly Request RoutineWorldUpdate = new Request { Name = "RoutineWorldUpdate", Url = "oR1psQ5B", EncodeKey = "XDIL4E7j", RequestID = "6H1R9WID"}; public static readonly Request UnitSell = new Request { Name = "UnitSell", Url = "0qmzs2gA", EncodeKey = "DJ43wmds", RequestID = "9itzg1jc"}; public static readonly Request StrongBoxOpen = new Request { Name = "StrongBoxOpen", Url = "48ktHf13", EncodeKey = "sgc30nRh", RequestID = "PIv7u8jU"}; public static readonly Request RbStart = new Request { Name = "RbStart", Url = "dR20sWwE", EncodeKey = "P1w8BKLI", RequestID = "eHY7X8Nn"}; public static readonly Request ClsmStart = new Request { Name = "ClsmStart", Url = "rncR9js8", EncodeKey = "wdSs23yW", RequestID = "4uCSA3ko"}; public static readonly Request GachaExe = new Request { Name = "GachaExe", Url = "oC30VTFp", EncodeKey = "oaEJ9y1Z", RequestID = "9fVIioy1"}; public static readonly Request sgExpdQuestStart = new Request { Name = "sgExpdQuestStart", Url = "I8uq68c3", EncodeKey = "60Os29Mg", RequestID = "I8uq68c3"}; public static readonly Request MissionReStart = new Request { Name = "MissionReStart", Url = "r5vfM1Y3", EncodeKey = "Vw6bP0rN", RequestID = "GfI4LaU3"}; public static readonly Request CraftExe = new Request { Name = "CraftExe", Url = "UyHLjV60", EncodeKey = "ZbHEB15J", RequestID = "PKDhIN34"}; public static readonly Request OptionUpdate = new Request { Name = "OptionUpdate", Url = "0Xh2ri5E", EncodeKey = "B9mAa7rp", RequestID = "otgXV79T"}; public static readonly Request RoutineRaidMenuUpdate = new Request { Name = "RoutineRaidMenuUpdate", Url = "Sv85kcPQ", EncodeKey = "z80swWd9", RequestID = "g0BjrU5D"}; public static readonly Request Friend = new Request { Name = "Friend", Url = "8drhF2mG", EncodeKey = "6WAkj0IH", RequestID = "j0A5vQd8"}; public static readonly Request MedalExchange = new Request { Name = "MedalExchange", Url = "0X8Fpjhb", EncodeKey = "dCja1E54", RequestID = "LiM9Had2"}; public static readonly Request RbBoardPieceOpen = new Request { Name = "RbBoardPieceOpen", Url = "iXKfI4v1", EncodeKey = "g68FW4k1", RequestID = "hqzU9Qc5"}; public static readonly Request RmRetire = new Request { Name = "RmRetire", Url = "fBn58ApV", EncodeKey = "T4Undsr6", RequestID = "e0R3iDm1"}; public static readonly Request FriendList = new Request { Name = "FriendList", Url = "p3hwqW5U", EncodeKey = "1iV2oN9r", RequestID = "u7Id4bMg"}; public static readonly Request MailList = new Request { Name = "MailList", Url = "u3E8hpad", EncodeKey = "7kgsrGQ1", RequestID = "KQHpi0D7"}; public static readonly Request FriendRefuse = new Request { Name = "FriendRefuse", Url = "Vw0a4I3i", EncodeKey = "RYdX9h2A", RequestID = "1nbWRV9w"}; public static readonly Request RmRestart = new Request { Name = "RmRestart", Url = "NC8Ie07P", EncodeKey = "R1VjnNx0", RequestID = "yh21MTaG"}; public static readonly Request MissionEnd = new Request { Name = "MissionEnd", Url = "0ydjM5sU", EncodeKey = "1tg0Lsqj", RequestID = "x5Unqg2d"}; public static readonly Request UpdateUserInfo = new Request { Name = "UpdateUserInfo", Url = "v3RD1CUB", EncodeKey = "6v5ykfpr", RequestID = "ey8mupb4"}; public static readonly Request RmStart = new Request { Name = "RmStart", Url = "8BJSL7g0", EncodeKey = "iu67waph", RequestID = "7FyJS3Zn"}; public static readonly Request FacebookRewardList = new Request { Name = "FacebookRewardList", Url = "8YZsGLED", EncodeKey = "85YBRzZg", RequestID = "8YZsGLED"}; public static readonly Request MissionUpdate = new Request { Name = "MissionUpdate", Url = "fRDUy3E2", EncodeKey = "Nq9uKGP7", RequestID = "j5JHKq6S"}; public static readonly Request sgExpdQuestRefresh = new Request { Name = "sgExpdQuestRefresh", Url = "vTgYyHM6", EncodeKey = "vceNlSf3gn", RequestID = "vTgYyHM6lC"}; public static readonly Request CreateUser = new Request { Name = "CreateUser", Url = "0FK8NJRX", EncodeKey = "73BUnZEr", RequestID = "P6pTz4WA"}; public static readonly Request ClsmEnd = new Request { Name = "ClsmEnd", Url = "7vHqNPF0", EncodeKey = "6aBHXGv4", RequestID = "3zgbapQ7"}; public static readonly Request sgMissionUnlock = new Request { Name = "sgMissionUnlock", Url = "LJhqu0x6", EncodeKey = "ZcBV06K4", RequestID = "LJhqu0x6"}; public static readonly Request DailyQuestUpdate = new Request { Name = "DailyQuestUpdate", Url = "QWDn5epF", EncodeKey = "9QtGVCWg", RequestID = "6QYd5Hym"}; public static readonly Request FacebookLogout = new Request { Name = "FacebookLogout", Url = "xHTo4BZp", EncodeKey = "wwHxtAy6", RequestID = "xHTo4BZp"}; public static readonly Request DailyQuestClaimReward = new Request { Name = "DailyQuestClaimReward", Url = "Br9PwJ6A", EncodeKey = "jwYGF3sY", RequestID = "Zy8fYJ5e"}; public static readonly Request RmEntry = new Request { Name = "RmEntry", Url = "fBn58ApV", EncodeKey = "p2tqP7Ng", RequestID = "wx5sg9ye"}; public static readonly Request TransferCodeCheck = new Request { Name = "TransferCodeCheck", Url = "C9LoeYJ8", EncodeKey = "c5aNjK9J", RequestID = "CY89mIdz"}; public static readonly Request CraftEnd = new Request { Name = "CraftEnd", Url = "9G7Vc8Ny", EncodeKey = "yD97t8kB", RequestID = "WIuvh09n"}; public static readonly Request RoutineEventUpdate = new Request { Name = "RoutineEventUpdate", Url = "WCK5tvr0", EncodeKey = "V0TGwId5", RequestID = "4kA1Ne05"}; public static readonly Request RmBreak = new Request { Name = "RmBreak", Url = "8BJSL7g0", EncodeKey = "W3YTRI8e", RequestID = "kWrXKC35"}; public static readonly Request MissionRetire = new Request { Name = "MissionRetire", Url = "gbZ64SQ2", EncodeKey = "oUh1grm8", RequestID = "v51PM7wj"}; public static readonly Request FriendAgree = new Request { Name = "FriendAgree", Url = "1DYp5Nqm", EncodeKey = "9FjK0zM3", RequestID = "kx13SLUY"}; public static readonly Request BundlePurchase = new Request { Name = "BundlePurchase", Url = "tPc64qmn", EncodeKey = "NE3Pp4K8", RequestID = "w6Z9a6tD"}; public static readonly Request ClsmEntry = new Request { Name = "ClsmEntry", Url = "UmLwv56W", EncodeKey = "8bmHF3Cz", RequestID = "5g0vWZFq"}; public static readonly Request GetBackgroundDownloadInfo = new Request { Name = "GetBackgroundDownloadInfo", Url = "action", EncodeKey = "Z1krd75o", RequestID = "lEHBdOEf"}; public static readonly Request TransferCodeIssue = new Request { Name = "TransferCodeIssue", Url = "hF0yCKc1", EncodeKey = "T0y6ij47", RequestID = "crzI2bA5"}; public static readonly Request RoutineHomeUpdate = new Request { Name = "RoutineHomeUpdate", Url = "1YWTzU9h", EncodeKey = "aw0syG7H", RequestID = "Daud71Hn"}; public static readonly Request ItemCarryEdit = new Request { Name = "ItemCarryEdit", Url = "8BE6tJbf", EncodeKey = "04opy1kf", RequestID = "UM7hA0Zd"}; public static readonly Request ClsmLottery = new Request { Name = "ClsmLottery", Url = "4uj3NhUQ", EncodeKey = "pU62SkhJ", RequestID = "Un16HuNI"}; public static readonly Request MissionStart = new Request { Name = "MissionStart", Url = "63VqtzbQ", EncodeKey = "i48eAVL6", RequestID = "29JRaDbd"}; public static readonly Request ItemBuy = new Request { Name = "ItemBuy", Url = "oQrAys71", EncodeKey = "InN5PUR0", RequestID = "sxK2HG6T"}; public static readonly Request sgExpdQuestInfo = new Request { Name = "sgExpdQuestInfo", Url = "hW0804Q9", EncodeKey = "4Bn7d973", RequestID = "hW0804Q9"}; public static readonly Request FacebookAddFriend = new Request { Name = "FacebookAddFriend", Url = "NAW9vJnm", EncodeKey = "532vAYUy", RequestID = "NAW9vJnm"}; public static readonly Request CraftAdd = new Request { Name = "CraftAdd", Url = "iQ7R4CFB", EncodeKey = "qz0SG1Ay", RequestID = "QkN1Sp64"}; public static readonly Request PurchaseCurrentState = new Request { Name = "PurchaseCurrentState", Url = "bAR4k7Qd", EncodeKey = "X9k5vFdu", RequestID = "9mM3eXgi"}; public static readonly Request UnitFavorite = new Request { Name = "UnitFavorite", Url = "sqeRg12M", EncodeKey = "w9mWkGX0", RequestID = "tBDi10Ay"}; public static readonly Request BundleStatus = new Request { Name = "BundleStatus", Url = "tPc64qmn", EncodeKey = "PrSPuc8c", RequestID = "uLXAMvCT"}; public static readonly Request FriendFavorite = new Request { Name = "FriendFavorite", Url = "8IYSJ5H1", EncodeKey = "3EBXbj1d", RequestID = "1oE3Fwn4"}; public static readonly Request RbRanking = new Request { Name = "RbRanking", Url = "3fd8y7W1", EncodeKey = "SR6PoLM3", RequestID = "kcW85SfU"}; public static readonly Request DailyDungeonSelect = new Request { Name = "DailyDungeonSelect", Url = "9LgmdR0v", EncodeKey = "ioC6zqG1", RequestID = "JyfxY2e0"}; public static readonly Request PurchaseList = new Request { Name = "PurchaseList", Url = "YqZ6Qc1z", EncodeKey = "X3Csghu0", RequestID = "BT28S96F"}; public static readonly Request DailyQuestClaimAllReward = new Request { Name = "DailyQuestClaimAllReward", Url = "Br9PwJ6A", EncodeKey = "KHx6JdrT", RequestID = "DCmya9WD"}; public static readonly Request RbReStart = new Request { Name = "RbReStart", Url = "DQ49vsGL", EncodeKey = "PRzAL3V2", RequestID = "6ZNY3zAm"}; public static readonly Request ArchiveUpdate = new Request { Name = "ArchiveUpdate", Url = "2bCcKx0D", EncodeKey = "IFLW9H4M", RequestID = "cVTxW0K3"}; public static readonly Request PurchaseSetting = new Request { Name = "PurchaseSetting", Url = "9hUtW0F8", EncodeKey = "ePFcMX53", RequestID = "QkwU4aD9"}; public static readonly Request RbEntry = new Request { Name = "RbEntry", Url = "30inL7I6", EncodeKey = "EA5amS29", RequestID = "f8kXGWy0"}; public static readonly Request DungeonLiberation = new Request { Name = "DungeonLiberation", Url = "0vc6irBY", EncodeKey = "0xDA4Cr9", RequestID = "nQMb2L4h"}; public static readonly Request UnitMix = new Request { Name = "UnitMix", Url = "6aLHwhJ8", EncodeKey = "4zCuj2hK", RequestID = "UiSC9y8R"}; public static readonly Request sgExpdMileStoneClaim = new Request { Name = "sgExpdMileStoneClaim", Url = "r4A791RF", EncodeKey = "t04N07LQ", RequestID = "r4A791RF"}; public static readonly Request sgExpdRecall = new Request { Name = "sgExpdRecall", Url = "0Fb87D0F", EncodeKey = "9J02K0lX", RequestID = "0Fb87D0F"}; public static readonly Request Transfer = new Request { Name = "Transfer", Url = "v6Jba7pX", EncodeKey = "C6eHo3wU", RequestID = "oE5fmZN9"}; public static readonly Request PurchaseGiveUp = new Request { Name = "PurchaseGiveUp", Url = "C2w0f3go", EncodeKey = "xoZ62QWy", RequestID = "BFf1nwh6"}; public static readonly Request GachaInfo = new Request { Name = "GachaInfo", Url = "3nhWq25K", EncodeKey = "VA8QR57X", RequestID = "UNP1GR5n"}; public static readonly Request PurchaseStart = new Request { Name = "PurchaseStart", Url = "tPc64qmn", EncodeKey = "9Kf4gYvm", RequestID = "qAUzP3R6"}; public static readonly Request RmDungeonEnd = new Request { Name = "RmDungeonEnd", Url = "CH9fWn8K", EncodeKey = "dEnsQ75t", RequestID = "WaPC2T6i"}; public static readonly Request sgHomeMarqueeInfo = new Request { Name = "sgHomeMarqueeInfo", Url = "PBSP9qn5", EncodeKey = "d3GDS9X8", RequestID = "PBSP9qn5"}; public static readonly Request TownUpdate = new Request { Name = "TownUpdate", Url = "0ZJzH2qY", EncodeKey = "37nH21zE", RequestID = "G1hQM8Dr"}; public static readonly Request GetTitleInfo = new Request { Name = "GetTitleInfo", Url = "BbIeq31M", EncodeKey = "Mw56RNZ2", RequestID = "ocP3A1FI"}; public static readonly Request RateAppReward = new Request { Name = "RateAppReward", Url = "L0OsxMaT", EncodeKey = "m1pPBwC3", RequestID = "L0OsxMaT"}; public static readonly Request PurchaseFailed = new Request { Name = "PurchaseFailed", Url = "2TCis0R6", EncodeKey = "sW0vf3ZM", RequestID = "jSe80Gx7"}; public static readonly Request CampaignAccept = new Request { Name = "CampaignAccept", Url = "n7Hitfg4", EncodeKey = "Xb0G1wcB", RequestID = "G6ye0D1t"}; public static readonly Request PurchaseCancel = new Request { Name = "PurchaseCancel", Url = "y71uBCER", EncodeKey = "Z1mojg9a", RequestID = "L7K0ezU2"}; public static readonly Request DmgRankRetire = new Request { Name = "DmgRankRetire", Url = "8wdmR9yG", EncodeKey = "5fkWyeE6", RequestID = "W3Z4VF1X"}; public static readonly Request ItemSell = new Request { Name = "ItemSell", Url = "hQRf8D6r", EncodeKey = "E8H3UerF", RequestID = "d9Si7TYm"}; public static readonly Request PurchaseHold = new Request { Name = "PurchaseHold", Url = "dCxtMZ27", EncodeKey = "5Mwfq90Z", RequestID = "79EVRjeM"}; public static readonly Request MailReceipt = new Request { Name = "MailReceipt", Url = "M2fHBe9d", EncodeKey = "P2YFr7N9", RequestID = "XK7efER9"}; public static readonly Request UnitClassUp = new Request { Name = "UnitClassUp", Url = "8z4Z0DUY", EncodeKey = "L2sTK0GM", RequestID = "zf49XKg8"}; public static readonly Request PartyDeckEdit = new Request { Name = "PartyDeckEdit", Url = "6xkK4eDG", EncodeKey = "34qFNPf7", RequestID = "TS5Dx9aZ"}; public static readonly Request FriendSearch = new Request { Name = "FriendSearch", Url = "6Y1jM3Wp", EncodeKey = "VCL5oj6u", RequestID = "3siZRSU4"}; public static readonly Request sgExpdEnd = new Request { Name = "sgExpdEnd", Url = "2pe3Xa8bpG", EncodeKey = "cjHumZ2Jkt", RequestID = "2pe3Xa8bpG"}; public static readonly Request ShopUse = new Request { Name = "ShopUse", Url = "w76ThDMm", EncodeKey = "ZT0Ua4wL", RequestID = "73SD2aMR"}; public static readonly Request UnitEquip = new Request { Name = "UnitEquip", Url = "nIk9z5pT", EncodeKey = "45VZgFYv", RequestID = "pB3st6Tg"}; public static readonly Request DmgRankStart = new Request { Name = "DmgRankStart", Url = "j37Vk5xe", EncodeKey = "1d5AP9p6", RequestID = "5P6ULvjg"}; public static readonly Request RbEnd = new Request { Name = "RbEnd", Url = "e8AHNiT7", EncodeKey = "MVA3Te2i", RequestID = "os4k7C0b"}; public static readonly Request TrophyReward = new Request { Name = "TrophyReward", Url = "05vJDxg9", EncodeKey = "2o7kErn1", RequestID = "wukWY4t2"}; public static readonly Request MissionWaveReStart = new Request { Name = "MissionWaveReStart", Url = "8m7KNezI", EncodeKey = "M3bYZoU5", RequestID = "e9RP8Cto"}; public static readonly Request CraftCancel = new Request { Name = "CraftCancel", Url = "7WdDLIE4", EncodeKey = "68zcUF3E", RequestID = "79xDN1Mw"}; public static readonly Request CampaignTieup = new Request { Name = "CampaignTieup", Url = "2u30vqfY", EncodeKey = "72d5UTNC", RequestID = "mI0Q2YhW"}; public static readonly Request SpChallengeRewardGet = new Request { Name = "SpChallengeRewardGet", Url = "9inGHyqC", EncodeKey = "mG25PIUn", RequestID = "2G7ZVs4A"}; public static readonly Request PlaybackMissionWaveStart = new Request { Name = "PlaybackMissionWaveStart", Url = "scyPYa81", EncodeKey = "NdkX15vE", RequestID = "1BpXP3Fs"}; public static readonly Request DungeonResourceLoadMstList = new Request { Name = "DungeonResourceLoadMstList", Url = "Sl8UgmP4", EncodeKey = "3PVu6ReZ", RequestID = "jnw49dUq"}; public static readonly Request MissionSwitchUpdate = new Request { Name = "MissionSwitchUpdate", Url = "1Xz8kJLr", EncodeKey = "bZezA63a", RequestID = "Tvq54dx6"}; public static readonly Request AllianceDeckEdit = new Request { Name = "AllianceDeckEdit", Url = "7gAGFC4I", EncodeKey = "2E3UinsJ", RequestID = "P76LYXow"}; public static readonly Request IsNeedValidate = new Request { Name = "IsNeedValidate", Url = "gk3Wtr8A", EncodeKey = "djhiU6x8", RequestID = "er5xMIj6"}; public static readonly Request SpChallengeEntry = new Request { Name = "SpChallengeEntry", Url = "8DermCsY", EncodeKey = "Uey5jW2G", RequestID = "MTf2j9aK"}; public static readonly Request ChallengeClear = new Request { Name = "ChallengeClear", Url = "dEvLKchl", EncodeKey = "UD5QCa2s", RequestID = "D9xphQ8X"}; public static readonly Request GetReinforcementInfo = new Request { Name = "GetReinforcementInfo", Url = "hXMoLwgE", EncodeKey = "87khNMou", RequestID = "AJhnI37s"}; public static readonly Request PlaybackMissionStart = new Request { Name = "PlaybackMissionStart", Url = "zm2ip59f", EncodeKey = "YC20v1Uj", RequestID = "1YnQM4iB"}; public static readonly Request AllianceEntry = new Request { Name = "AllianceEntry", Url = "EzfT0wX6", EncodeKey = "zS4tPgi7", RequestID = "HtR8XF4e"}; public static readonly List<Request> Requests = new List<Request> { PurchaseSettlement, RbMatching, RmDungeonStart, RmEnd, FacebookRewardClaim, FriendDelete, UpdateSwitchInfo, VariableStoreCheck, CraftStart, SearchGetItemInfo, SublimationSkill, TownIn, MissionBreak, BeastMix, LoginBonus, Initialize, DmgRankEnd, GameSetting, GetUserInfo, NoticeUpdate, sgExpdAccelerate, TownOut, BeastBoardPieceOpen, NoticeReadUpdate, MissionWaveStart, MissionContinue, RoutineGachaUpdate, ExchangeShop, GiftUpdate, FriendSuggest, RoutineWorldUpdate, UnitSell, StrongBoxOpen, RbStart, ClsmStart, GachaExe, sgExpdQuestStart, MissionReStart, CraftExe, OptionUpdate, RoutineRaidMenuUpdate, Friend, MedalExchange, RbBoardPieceOpen, RmRetire, FriendList, MailList, FriendRefuse, RmRestart, MissionEnd, UpdateUserInfo, RmStart, FacebookRewardList, MissionUpdate, sgExpdQuestRefresh, CreateUser, ClsmEnd, sgMissionUnlock, DailyQuestUpdate, FacebookLogout, DailyQuestClaimReward, RmEntry, TransferCodeCheck, CraftEnd, RoutineEventUpdate, RmBreak, MissionRetire, FriendAgree, BundlePurchase, ClsmEntry, GetBackgroundDownloadInfo, TransferCodeIssue, RoutineHomeUpdate, ItemCarryEdit, ClsmLottery, MissionStart, ItemBuy, sgExpdQuestInfo, FacebookAddFriend, CraftAdd, PurchaseCurrentState, UnitFavorite, BundleStatus, FriendFavorite, RbRanking, DailyDungeonSelect, PurchaseList, DailyQuestClaimAllReward, RbReStart, ArchiveUpdate, PurchaseSetting, RbEntry, DungeonLiberation, UnitMix, sgExpdMileStoneClaim, sgExpdRecall, Transfer, PurchaseGiveUp, GachaInfo, PurchaseStart, RmDungeonEnd, sgHomeMarqueeInfo, TownUpdate, GetTitleInfo, RateAppReward, PurchaseFailed, CampaignAccept, PurchaseCancel, DmgRankRetire, ItemSell, PurchaseHold, MailReceipt, UnitClassUp, PartyDeckEdit, FriendSearch, sgExpdEnd, ShopUse, UnitEquip, DmgRankStart, RbEnd, TrophyReward, MissionWaveReStart, CraftCancel, CampaignTieup, SpChallengeRewardGet, PlaybackMissionWaveStart, DungeonResourceLoadMstList, MissionSwitchUpdate, AllianceDeckEdit, IsNeedValidate, SpChallengeEntry, ChallengeClear, GetReinforcementInfo, PlaybackMissionStart, AllianceEntry, }; } }
using System.Text.RegularExpressions; using System.Diagnostics; using System; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.Collections; using System.Drawing; using Microsoft.VisualBasic; using System.Data.SqlClient; using System.Data; using System.Collections.Generic; using WeifenLuo.WinFormsUI; using Microsoft.Win32; using WeifenLuo; using System.ComponentModel; // ***************************************************************************** // // Copyright 2004, Weifen Luo // All rights reserved. The software and associated documentation // supplied hereunder are the proprietary information of Weifen Luo // and are supplied subject to licence terms. // // WinFormsUI Library Version 1.0 // ***************************************************************************** namespace SoftLogik.Win { namespace UI { namespace Docking { [ToolboxItem(false)]public class DockPaneCaptionFromBase : DockPaneCaptionBase { #region consts private const int _TextGapTop = 1; private const int _TextGapBottom = 2; private const int _TextGapLeft = 3; private const int _TextGapRight = 3; private const int _ButtonGapTop = 2; private const int _ButtonGapBottom = 2; private const int _ButtonGapBetween = 4; private const int _ButtonGapLeft = 1; private const int _ButtonGapRight = 2; private const int _ButtonMargin = 2; private const string _ResourceImageCloseEnabled = "DockPaneCaption.CloseEnabled.bmp"; private const string _ResourceImageCloseDisabled = "DockPaneCaption.CloseDisabled.bmp"; private const string _ResourceImageOptionsEnabled = "DockPaneCaption.OptionsEnabled.bmp"; private const string _ResourceImageOptionsDisabled = "DockPaneCaption.OptionsDisabled.bmp"; private const string _ResourceImageAutoHideYes = "DockPaneCaption.AutoHideYes.bmp"; private const string _ResourceImageAutoHideNo = "DockPaneCaption.AutoHideNo.bmp"; private const string _ResourceToolTipClose = "DockPaneCaption_ToolTipClose"; private const string _ResourceToolTipAutoHide = "DockPaneCaption_ToolTipAutoHide"; private const string _ResourceToolTipOptions = "DockPaneCaption_ToolTipOptions"; #endregion private PopupButton m_buttonClose; private PopupButton m_buttonAutoHide; private PopupButton m_buttonOptions; protected internal DockPaneCaptionFromBase(DockPane pane) : base(pane) { SuspendLayout(); Font = SystemInformation.MenuFont; m_buttonClose = new PopupButton(ImageCloseEnabled, ImageCloseDisabled); m_buttonClose.ActiveBackColorGradientBegin = Color.FromArgb(59, 128, 237); m_buttonClose.ActiveBackColorGradientEnd = Color.FromArgb(49, 106, 197); m_buttonClose.InactiveBackColorGradientBegin = Color.FromArgb(204, 199, 186); m_buttonClose.InactiveBackColorGradientEnd = Color.FromArgb(204, 199, 186); m_buttonAutoHide = new PopupButton(); m_buttonAutoHide.ActiveBackColorGradientBegin = Color.FromArgb(59, 128, 237); m_buttonAutoHide.ActiveBackColorGradientEnd = Color.FromArgb(49, 106, 197); m_buttonAutoHide.InactiveBackColorGradientBegin = Color.FromArgb(204, 199, 186); m_buttonAutoHide.InactiveBackColorGradientEnd = Color.FromArgb(204, 199, 186); m_buttonOptions = new PopupButton(ImageOptionsEnabled, ImageOptionsDisabled); m_buttonOptions.ActiveBackColorGradientBegin = Color.FromArgb(59, 128, 237); m_buttonOptions.ActiveBackColorGradientEnd = Color.FromArgb(49, 106, 197); m_buttonOptions.InactiveBackColorGradientBegin = Color.FromArgb(204, 199, 186); m_buttonOptions.InactiveBackColorGradientEnd = Color.FromArgb(204, 199, 186); m_buttonClose.ToolTipText = ToolTipClose; m_buttonClose.Anchor = AnchorStyles.Top || AnchorStyles.Right; m_buttonClose.Click += new System.EventHandler(Close_Click); m_buttonAutoHide.ToolTipText = ToolTipAutoHide; m_buttonAutoHide.Anchor = AnchorStyles.Top || AnchorStyles.Right; m_buttonAutoHide.Click += new System.EventHandler(AutoHide_Click); m_buttonOptions.ToolTipText = ToolTipOptions; m_buttonOptions.Anchor = AnchorStyles.Top || AnchorStyles.Right; m_buttonOptions.Click += new System.EventHandler(Options_Click); Controls.AddRange(new Control[] {m_buttonClose, m_buttonAutoHide, m_buttonOptions}); ResumeLayout(); } #region Customizable Properties protected virtual int TextGapTop { get { return _TextGapTop; } } protected virtual int TextGapBottom { get { return _TextGapBottom; } } protected virtual int TextGapLeft { get { return _TextGapLeft; } } protected virtual int TextGapRight { get { return _TextGapRight; } } protected virtual int ButtonGapTop { get { return _ButtonGapTop; } } protected virtual int ButtonGapBottom { get { return _ButtonGapBottom; } } protected virtual int ButtonGapLeft { get { return _ButtonGapLeft; } } protected virtual int ButtonGapRight { get { return _ButtonGapRight; } } protected virtual int ButtonGapBetween { get { return _ButtonGapBetween; } } private static Image _imageOptionsEnabled = null; protected virtual Image ImageOptionsEnabled { get { if (_imageOptionsEnabled == null) { _imageOptionsEnabled = ResourceHelper.LoadExtenderBitmap(_ResourceImageOptionsEnabled); } return _imageOptionsEnabled; } } private static Image _imageOptionsDisabled = null; protected virtual Image ImageOptionsDisabled { get { if (_imageOptionsDisabled == null) { _imageOptionsDisabled = ResourceHelper.LoadExtenderBitmap(_ResourceImageOptionsDisabled); } return _imageOptionsDisabled; } } private static Image _imageCloseEnabled = null; protected virtual Image ImageCloseEnabled { get { if (_imageCloseEnabled == null) { _imageCloseEnabled = ResourceHelper.LoadExtenderBitmap(_ResourceImageCloseEnabled); } return _imageCloseEnabled; } } private static Image _imageCloseDisabled = null; protected virtual Image ImageCloseDisabled { get { if (_imageCloseDisabled == null) { _imageCloseDisabled = ResourceHelper.LoadExtenderBitmap(_ResourceImageCloseDisabled); } return _imageCloseDisabled; } } private static Image _imageAutoHideYes = null; protected virtual Image ImageAutoHideYes { get { if (_imageAutoHideYes == null) { _imageAutoHideYes = ResourceHelper.LoadExtenderBitmap(_ResourceImageAutoHideYes); } return _imageAutoHideYes; } } private static Image _imageAutoHideNo = null; protected virtual Image ImageAutoHideNo { get { if (_imageAutoHideNo == null) { _imageAutoHideNo = ResourceHelper.LoadExtenderBitmap(_ResourceImageAutoHideNo); } return _imageAutoHideNo; } } private static string _toolTipClose = null; protected virtual string ToolTipClose { get { if (_toolTipClose == null) { _toolTipClose = ResourceHelper.GetString(_ResourceToolTipClose); } return _toolTipClose; } } private static string _toolTipAutoHide = null; protected virtual string ToolTipAutoHide { get { if (_toolTipAutoHide == null) { _toolTipAutoHide = ResourceHelper.GetString(_ResourceToolTipAutoHide); } return _toolTipAutoHide; } } private static string _toolTipOptions = null; protected virtual string ToolTipOptions { get { if (_toolTipOptions == null) { _toolTipOptions = ResourceHelper.GetString(_ResourceToolTipOptions); } return _toolTipOptions; } } protected virtual Color ActiveBackColor { get { return Color.FromArgb(59, 128, 237); } } protected virtual Color InactiveBackColor { get { return Color.FromArgb(204, 199, 186); } } protected virtual Color ActiveTextColor { get { return SystemColors.ActiveCaptionText; } } protected virtual Color InactiveTextColor { get { return SystemColors.ControlText; } } protected virtual Color InactiveBorderColor { get { return SystemColors.GrayText; } } protected virtual Color ActiveButtonBorderColor { get { return Color.FromArgb(60, 90, 170); } } protected virtual Color InactiveButtonBorderColor { get { return Color.FromArgb(140, 134, 123); } } private static StringFormat _textStringFormat = null; protected virtual StringFormat TextStringFormat { get { if (_textStringFormat == null) { _textStringFormat = new StringFormat(); _textStringFormat.Trimming = StringTrimming.EllipsisCharacter; _textStringFormat.LineAlignment = StringAlignment.Center; _textStringFormat.FormatFlags = StringFormatFlags.NoWrap; } return _textStringFormat; } } #endregion protected override int MeasureHeight() { int height = Font.Height + TextGapTop + TextGapBottom; if (height < (ImageCloseEnabled.Height + ButtonGapTop + ButtonGapBottom)) { height = ImageCloseEnabled.Height + ButtonGapTop + ButtonGapBottom; } return height; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); if (DockPane.IsActivated) { using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, Color.FromArgb(59, 128, 237), Color.FromArgb(49, 106, 197), LinearGradientMode.Vertical)) { e.Graphics.FillRectangle(brush, ClientRectangle); } } DrawCaption(e.Graphics); } private void DrawCaption(Graphics g) { if (DockPane.IsActivated) { BackColor = ActiveBackColor; } else { BackColor = InactiveBackColor; } Rectangle rectCaption = ClientRectangle; if (! DockPane.IsActivated) { using (Pen pen = new Pen(InactiveBorderColor)) { g.DrawLine(pen, rectCaption.X + 1, rectCaption.Y, rectCaption.X + rectCaption.Width - 2, rectCaption.Y); g.DrawLine(pen, rectCaption.X + 1, rectCaption.Y + rectCaption.Height - 1, rectCaption.X + rectCaption.Width - 2, rectCaption.Y + rectCaption.Height - 1); g.DrawLine(pen, rectCaption.X, rectCaption.Y + 1, rectCaption.X, rectCaption.Y + rectCaption.Height - 2); g.DrawLine(pen, rectCaption.X + rectCaption.Width - 1, rectCaption.Y + 1, rectCaption.X + rectCaption.Width - 1, rectCaption.Y + rectCaption.Height - 2); } } Rectangle rectCaptionText = rectCaption; rectCaptionText.X += TextGapLeft; rectCaptionText.Width = rectCaption.Width - ButtonGapRight - ButtonGapLeft - ButtonGapBetween - 3 * m_buttonClose.Width - TextGapLeft - TextGapRight; rectCaptionText.Y += TextGapTop; rectCaptionText.Height -= TextGapTop + TextGapBottom; Brush brush; if (DockPane.IsActivated) { brush = new SolidBrush(ActiveTextColor); } else { brush = new SolidBrush(InactiveTextColor); } using (brush) { g.DrawString(DockPane.CaptionText, Font, brush, rectCaptionText, TextStringFormat); } } protected override void OnLayout(LayoutEventArgs levent) { // set the size and location for close and auto-hide buttons Rectangle rectCaption = ClientRectangle; int buttonWidth = ImageCloseEnabled.Width; int buttonHeight = ImageCloseEnabled.Height; int height = rectCaption.Height - ButtonGapTop - ButtonGapBottom; if (buttonHeight < height) { buttonWidth = buttonWidth * (height / buttonHeight); buttonHeight = height; } m_buttonClose.SuspendLayout(); m_buttonAutoHide.SuspendLayout(); m_buttonOptions.SuspendLayout(); Size buttonSize = new Size(buttonWidth, buttonHeight); m_buttonAutoHide.Size = buttonSize; m_buttonClose.Size = buttonSize; m_buttonOptions.Size = buttonSize; int x = rectCaption.X + rectCaption.Width - 1 - ButtonGapRight - m_buttonClose.Width; int y = rectCaption.Y + ButtonGapTop; Point point = new Point(x, y); m_buttonClose.Location = point; point.Offset(- (m_buttonAutoHide.Width + ButtonGapBetween), 0); m_buttonAutoHide.Location = point; point.Offset(- (m_buttonOptions.Width + ButtonGapBetween), 0); m_buttonOptions.Location = point; m_buttonClose.ResumeLayout(); m_buttonAutoHide.ResumeLayout(); m_buttonOptions.ResumeLayout(); base.OnLayout(levent); } protected override void OnRefreshChanges() { SetButtons(); Invalidate(); } private ContextMenuStrip m_contextmenu; private void SetButtons() { if (DockPane.ActiveContent != null) { m_buttonClose.Enabled = DockPane.ActiveContent.DockHandler.CloseButton; m_contextmenu = DockPane.ActiveContent.DockHandler.TabPageContextMenuStrip; if (m_contextmenu != null) { m_buttonOptions.Visible = true; if (m_buttonOptions.ToolTipText == "") { m_buttonOptions.ToolTipText = m_contextmenu.Text; } } else { m_buttonOptions.Visible = false; } } else { m_buttonClose.Enabled = false; } m_buttonAutoHide.Visible = ! DockPane.IsFloat; if (DockPane.IsAutoHide) { m_buttonAutoHide.ImageEnabled = ImageAutoHideYes; } else { m_buttonAutoHide.ImageEnabled = ImageAutoHideNo; } m_buttonAutoHide.IsActivated = DockPane.IsActivated; m_buttonClose.IsActivated = DockPane.IsActivated; m_buttonOptions.IsActivated = DockPane.IsActivated; if (DockPane.IsActivated) { m_buttonAutoHide.ForeColor = ActiveTextColor; m_buttonAutoHide.BorderColor = ActiveButtonBorderColor; } else { m_buttonAutoHide.ForeColor = InactiveTextColor; m_buttonAutoHide.BorderColor = InactiveButtonBorderColor; } m_buttonClose.ForeColor = m_buttonAutoHide.ForeColor; m_buttonClose.BorderColor = m_buttonAutoHide.BorderColor; m_buttonOptions.ForeColor = m_buttonAutoHide.ForeColor; m_buttonOptions.BorderColor = m_buttonAutoHide.BorderColor; } private void Close_Click(object sender, EventArgs e) { DockPane.CloseActiveContent(); } private void AutoHide_Click(object sender, EventArgs e) { DockPane.DockState = DockHelper.ToggleAutoHideState(DockPane.DockState); if (! DockPane.IsAutoHide) { DockPane.Activate(); } } private void Options_Click(object sender, EventArgs e) { if (m_contextmenu != null) { int x = 0; int y = m_buttonOptions.Location.Y + m_buttonOptions.Height; m_contextmenu.Show(m_buttonOptions, new Point(x, y)); } } } } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using Microsoft.PythonTools.Analysis; using Microsoft.PythonTools.Editor; using Microsoft.VisualStudio.Language.StandardClassification; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; namespace Microsoft.PythonTools.Intellisense { /// <summary> /// Parses an expression in reverse to get the experssion we need to /// analyze for completion, quick info, or signature help. /// </summary> class ReverseExpressionParser : IEnumerable<ClassificationSpan> { private readonly ITextSnapshot _snapshot; private readonly ITextBuffer _buffer; private readonly ITrackingSpan _span; private ITextSnapshotLine _curLine; private readonly PythonClassifier _classifier; private static readonly HashSet<string> _assignOperators = new HashSet<string> { "=" , "+=" , "-=" , "/=" , "%=" , "^=" , "*=" , "//=" , "&=" , "|=" , ">>=" , "<<=" , "**=", "@=" }; public ReverseExpressionParser(ITextSnapshot snapshot, ITextBuffer buffer, ITrackingSpan span) { _snapshot = snapshot; _buffer = buffer; _span = span; var loc = span.GetSpan(snapshot); var line = _curLine = snapshot.GetLineFromPosition(loc.Start); var targetSpan = new Span(line.Start.Position, span.GetEndPoint(snapshot).Position - line.Start.Position); _classifier = _buffer.GetPythonClassifier(); if (_classifier == null) { throw new ArgumentException(Strings.ReverseExpressionParserFailedToGetClassifierFromBufferException); } } internal static IEnumerator<ClassificationSpan> ForwardClassificationSpanEnumerator(PythonClassifier classifier, SnapshotPoint startPoint) { var startLine = startPoint.GetContainingLine(); int curLine = startLine.LineNumber; if (startPoint > startLine.End) { // May occur if startPoint is between \r and \n startPoint = startLine.End; } var tokens = classifier.GetClassificationSpans(new SnapshotSpan(startPoint, startLine.End)); for (; ; ) { for (int i = 0; i < tokens.Count; ++i) { yield return tokens[i]; } // indicate the line break yield return null; ++curLine; if (curLine < startPoint.Snapshot.LineCount) { var nextLine = startPoint.Snapshot.GetLineFromLineNumber(curLine); tokens = classifier.GetClassificationSpans(nextLine.Extent); } else { break; } } } internal static IEnumerator<ClassificationSpan> ReverseClassificationSpanEnumerator(PythonClassifier classifier, SnapshotPoint startPoint) { var startLine = startPoint.GetContainingLine(); int curLine = startLine.LineNumber; var tokens = classifier.GetClassificationSpans(new SnapshotSpan(startLine.Start, startPoint)); for (; ; ) { for (int i = tokens.Count - 1; i >= 0; i--) { yield return tokens[i]; } // indicate the line break yield return null; curLine--; if (curLine >= 0) { var prevLine = startPoint.Snapshot.GetLineFromLineNumber(curLine); tokens = classifier.GetClassificationSpans(prevLine.Extent); } else { break; } } } /// <summary> /// Walks backwards to figure out if we're a parameter name which comes after a ( /// </summary> private bool IsParameterNameOpenParen(IEnumerator<ClassificationSpan> enumerator) { if (MoveNextSkipExplicitNewLines(enumerator)) { if (enumerator.Current.ClassificationType.IsOfType(PredefinedClassificationTypeNames.Identifier)) { if (MoveNextSkipExplicitNewLines(enumerator) && enumerator.Current.ClassificationType == Classifier.Provider.Keyword && enumerator.Current.Span.GetText() == "def") { return true; } } } return false; } /// <summary> /// Walks backwards to figure out if we're a parameter name which comes after a comma. /// </summary> private bool IsParameterNameComma(IEnumerator<ClassificationSpan> enumerator) { int groupingLevel = 1; while (MoveNextSkipExplicitNewLines(enumerator)) { if (enumerator.Current.ClassificationType == Classifier.Provider.Keyword) { if (enumerator.Current.Span.GetText() == "def" && groupingLevel == 0) { return true; } if (PythonKeywords.IsOnlyStatementKeyword(enumerator.Current.Span.GetText())) { return false; } } if (enumerator.Current.IsOpenGrouping()) { groupingLevel--; if (groupingLevel == 0) { return IsParameterNameOpenParen(enumerator); } } else if (enumerator.Current.IsCloseGrouping()) { groupingLevel++; } } return false; } private bool MoveNextSkipExplicitNewLines(IEnumerator<ClassificationSpan> enumerator) { while (enumerator.MoveNext()) { if (enumerator.Current == null) { while (enumerator.Current == null) { if (!enumerator.MoveNext()) { return false; } } if (!IsExplicitLineJoin(enumerator.Current)) { return true; } } else { return true; } } return false; } /// <summary> /// Gets the range of the expression to the left of our starting span. /// </summary> /// <param name="nesting">1 if we have an opening parenthesis for sig completion</param> /// <param name="paramIndex">The current parameter index.</param> /// <returns></returns> [Obsolete("Use GetExpressionAtPoint instead")] public SnapshotSpan? GetExpressionRange(int nesting, out int paramIndex, out SnapshotPoint? sigStart, out string lastKeywordArg, out bool isParameterName, bool forCompletion = true) { SnapshotSpan? start = null; paramIndex = 0; sigStart = null; bool nestingChanged = false, lastTokenWasCommaOrOperator = true, lastTokenWasKeywordArgAssignment = false; int otherNesting = 0; bool isSigHelp = nesting != 0; isParameterName = false; lastKeywordArg = null; ClassificationSpan lastToken = null; // Walks backwards over all the lines var enumerator = ReverseClassificationSpanEnumerator(Classifier, _span.GetSpan(_snapshot).End); if (enumerator.MoveNext()) { if (enumerator.Current != null && enumerator.Current.ClassificationType == this.Classifier.Provider.StringLiteral) { return enumerator.Current.Span; } lastToken = enumerator.Current; while (ShouldSkipAsLastToken(lastToken, forCompletion) && enumerator.MoveNext()) { // skip trailing new line if the user is hovering at the end of the line if (lastToken == null && (nesting + otherNesting == 0)) { // new line out of a grouping... return _span.GetSpan(_snapshot); } lastToken = enumerator.Current; } int currentParamAtLastColon = -1; // used to track the current param index at this last colon, before we hit a lambda. SnapshotSpan? startAtLastToken = null; // Walk backwards over the tokens in the current line do { var token = enumerator.Current; if (token == null) { // new line if (nesting != 0 || otherNesting != 0 || (enumerator.MoveNext() && IsExplicitLineJoin(enumerator.Current))) { // we're in a grouping, or the previous token is an explicit line join, we'll keep going. continue; } else { break; } } var text = token.Span.GetText(); if (text == "(") { if (nesting != 0) { nesting--; nestingChanged = true; if (nesting == 0) { if (sigStart == null) { sigStart = token.Span.Start; } } } else { if (start == null && !forCompletion) { // hovering directly over an open paren, don't provide a tooltip return null; } // figure out if we're a parameter definition isParameterName = IsParameterNameOpenParen(enumerator); break; } lastTokenWasCommaOrOperator = true; lastTokenWasKeywordArgAssignment = false; } else if (token.IsOpenGrouping()) { if (otherNesting != 0) { otherNesting--; } else { if (nesting == 0) { if (start == null) { return null; } break; } paramIndex = 0; } nestingChanged = true; lastTokenWasCommaOrOperator = true; lastTokenWasKeywordArgAssignment = false; } else if (text == ")") { nesting++; nestingChanged = true; lastTokenWasCommaOrOperator = true; lastTokenWasKeywordArgAssignment = false; } else if (token.IsCloseGrouping()) { otherNesting++; nestingChanged = true; lastTokenWasCommaOrOperator = true; lastTokenWasKeywordArgAssignment = false; } else if (token.ClassificationType == Classifier.Provider.Keyword || token.ClassificationType == Classifier.Provider.Operator) { lastTokenWasKeywordArgAssignment = false; if (token.ClassificationType == Classifier.Provider.Keyword && text == "lambda") { if (currentParamAtLastColon != -1) { paramIndex = currentParamAtLastColon; currentParamAtLastColon = -1; } else { // fabcd(lambda a, b, c[PARAMINFO] // We have to be the 1st param. paramIndex = 0; } } if (text == ":") { startAtLastToken = start; currentParamAtLastColon = paramIndex; } if (nesting == 0 && otherNesting == 0) { if (start == null) { // http://pytools.codeplex.com/workitem/560 // yield_value = 42 // def f(): // yield<ctrl-space> // yield <ctrl-space> // // If we're next to the keyword, just return the keyword. // If we're after the keyword, return the span of the text proceeding // the keyword so we can complete after it. // // Also repros with "return <ctrl-space>" or "print <ctrl-space>" both // of which we weren't reporting completions for before if (forCompletion) { if (token.Span.IntersectsWith(_span.GetSpan(_snapshot))) { return token.Span; } else { return _span.GetSpan(_snapshot); } } // hovering directly over a keyword, don't provide a tooltip return null; } else if ((nestingChanged || forCompletion) && token.ClassificationType == Classifier.Provider.Keyword && (text == "def" || text == "class")) { return null; } if (text == "*" || text == "**") { if (MoveNextSkipExplicitNewLines(enumerator)) { if (enumerator.Current.ClassificationType == Classifier.Provider.CommaClassification) { isParameterName = IsParameterNameComma(enumerator); } else if (enumerator.Current.IsOpenGrouping() && enumerator.Current.Span.GetText() == "(") { isParameterName = IsParameterNameOpenParen(enumerator); } } } break; } else if ((token.ClassificationType == Classifier.Provider.Keyword && PythonKeywords.IsOnlyStatementKeyword(text)) || (token.ClassificationType == Classifier.Provider.Operator && IsAssignmentOperator(text))) { if (nesting != 0 && text == "=") { // keyword argument allowed in signatures lastTokenWasKeywordArgAssignment = lastTokenWasCommaOrOperator = true; } else if (start == null || (nestingChanged && nesting != 0)) { return null; } else { break; } } else if (token.ClassificationType == Classifier.Provider.Keyword && (text == "if" || text == "else")) { // if and else can be used in an expression context or a statement context if (currentParamAtLastColon != -1) { start = startAtLastToken; if (start == null) { return null; } break; } } lastTokenWasCommaOrOperator = true; } else if (token.ClassificationType == Classifier.Provider.DotClassification) { lastTokenWasCommaOrOperator = true; lastTokenWasKeywordArgAssignment = false; } else if (token.ClassificationType == Classifier.Provider.CommaClassification) { lastTokenWasCommaOrOperator = true; lastTokenWasKeywordArgAssignment = false; if (nesting == 0 && otherNesting == 0) { if (start == null && !forCompletion) { return null; } isParameterName = IsParameterNameComma(enumerator); break; } else if (nesting == 1 && otherNesting == 0 && sigStart == null) { paramIndex++; } } else if (token.ClassificationType == Classifier.Provider.Comment) { return null; } else if (!lastTokenWasCommaOrOperator) { if (nesting == 0 && otherNesting == 0) { break; } } else { if (lastTokenWasKeywordArgAssignment && token.ClassificationType.IsOfType(PredefinedClassificationTypeNames.Identifier) && lastKeywordArg == null) { if (paramIndex == 0) { lastKeywordArg = text; } else { lastKeywordArg = ""; } } lastTokenWasCommaOrOperator = false; } start = token.Span; } while (enumerator.MoveNext()); } if (start.HasValue && lastToken != null && (lastToken.Span.End.Position - start.Value.Start.Position) >= 0) { var spanToReturn = new SnapshotSpan( Snapshot, new Span( start.Value.Start.Position, lastToken.Span.End.Position - start.Value.Start.Position ) ); // To handle a case where a space is returned for displaying the type signature. if (string.IsNullOrWhiteSpace(spanToReturn.GetText())) { return null; } return spanToReturn; } return _span.GetSpan(_snapshot); } private static bool IsAssignmentOperator(string text) { return _assignOperators.Contains(text); } internal static bool IsExplicitLineJoin(ClassificationSpan cur) { if (cur != null && cur.ClassificationType.IsOfType(PythonPredefinedClassificationTypeNames.Operator)) { var text = cur.Span.GetText(); return text == "\\\r\n" || text == "\\\r" || text == "\n"; } return false; } /// <summary> /// Returns true if we should skip this token when it's the last token that the user hovers over. Currently true /// for new lines and dot classifications. /// </summary> private bool ShouldSkipAsLastToken(ClassificationSpan lastToken, bool forCompletion) { return lastToken == null || ( (lastToken.ClassificationType.Classification == PredefinedClassificationTypeNames.WhiteSpace && (lastToken.Span.GetText() == "\r\n" || lastToken.Span.GetText() == "\n" || lastToken.Span.GetText() == "\r")) || (lastToken.ClassificationType == Classifier.Provider.DotClassification && !forCompletion)); } public PythonClassifier Classifier { get { return _classifier; } } public ITextSnapshot Snapshot { get { return _snapshot; } } public ITextBuffer Buffer { get { return _buffer; } } public ITrackingSpan Span { get { return _span; } } public IEnumerator<ClassificationSpan> GetEnumerator() { return ReverseClassificationSpanEnumerator(Classifier, _span.GetSpan(_snapshot).End); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ReverseClassificationSpanEnumerator(Classifier, _span.GetSpan(_snapshot).End); } internal static bool IsInGrouping(ITextSnapshot snapshot, IEnumerable<TrackingTokenInfo> tokensInReverse) { int nesting = 0; foreach (var token in tokensInReverse) { if (token.Category == Parsing.TokenCategory.Grouping) { var t = token.GetText(snapshot); if (t.IsCloseGrouping()) { nesting++; } else if (t.IsOpenGrouping()) { if (nesting-- == 0) { return true; } } } else if (token.Category == Parsing.TokenCategory.Delimiter) { if (nesting == 0 && token.GetText(snapshot) == ",") { return true; } } else if (token.Category == Parsing.TokenCategory.Keyword) { if (PythonKeywords.IsOnlyStatementKeyword(token.GetText(snapshot))) { return false; } } } return false; } internal bool IsInGrouping() { // We assume that groupings are correctly matched and keep a simple // nesting count. int nesting = 0; foreach (var token in this) { if (token == null) { continue; } if (token.IsCloseGrouping()) { nesting++; } else if (token.IsOpenGrouping()) { if (nesting-- == 0) { return true; } } else if (token.ClassificationType.IsOfType(PythonPredefinedClassificationTypeNames.Comma)) { if (nesting == 0) { // A preceding comma at our level is only valid in a // grouping. return true; } } else if (token.ClassificationType.IsOfType(PredefinedClassificationTypeNames.Keyword) && PythonKeywords.IsOnlyStatementKeyword(token.Span.GetText())) { return false; } } return false; } internal SnapshotSpan? GetStatementRange() { var tokenStack = new Stack<ClassificationSpan>(); bool eol = false, finishLine = false; // Collect all the tokens until we know we're not in any groupings foreach (var token in this) { if (eol) { eol = false; if (!IsExplicitLineJoin(token)) { tokenStack.Push(null); if (finishLine) { break; } } } if (token == null) { eol = true; continue; } tokenStack.Push(token); if (token.ClassificationType.IsOfType(PredefinedClassificationTypeNames.Keyword) && PythonKeywords.IsOnlyStatementKeyword(token.Span.GetText())) { finishLine = true; } } if (tokenStack.Count == 0) { return null; } // Now scan forward through the tokens setting our current statement // start point. SnapshotPoint start = new SnapshotPoint(_snapshot, 0); SnapshotPoint end = start; bool setStart = true; int nesting = 0; foreach (var token in tokenStack) { if (setStart && token != null) { start = token.Span.Start; setStart = false; } if (token == null) { if (nesting == 0) { setStart = true; } } else { end = token.Span.End; if (token.IsOpenGrouping()) { ++nesting; } else if (token.IsCloseGrouping()) { --nesting; } } } // Keep going to find the end of the statement using (var e = ForwardClassificationSpanEnumerator(Classifier, Span.GetStartPoint(Snapshot))) { eol = false; while (e.MoveNext()) { if (e.Current == null) { if (nesting == 0) { break; } eol = true; } else { eol = false; if (setStart) { // Final token was EOL, so our start is the first // token moving forwards start = e.Current.Span.Start; setStart = false; } end = e.Current.Span.End; } } if (setStart) { start = Span.GetStartPoint(Snapshot); } if (eol) { end = Span.GetEndPoint(Snapshot); } } if (end <= start) { // No statement here return null; } return new SnapshotSpan(start, end); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace System.IO { /// <summary>Provides an implementation of a file stream for Unix files.</summary> public partial class FileStream : Stream { /// <summary>File mode.</summary> private FileMode _mode; /// <summary>Advanced options requested when opening the file.</summary> private FileOptions _options; /// <summary>If the file was opened with FileMode.Append, the length of the file when opened; otherwise, -1.</summary> private long _appendStart = -1; /// <summary> /// Extra state used by the file stream when _useAsyncIO is true. This includes /// the semaphore used to serialize all operation, the buffer/offset/count provided by the /// caller for ReadAsync/WriteAsync operations, and the last successful task returned /// synchronously from ReadAsync which can be reused if the count matches the next request. /// Only initialized when <see cref="_useAsyncIO"/> is true. /// </summary> private AsyncState _asyncState; /// <summary>Lazily-initialized value for whether the file supports seeking.</summary> private bool? _canSeek; private SafeFileHandle OpenHandle(FileMode mode, FileShare share, FileOptions options) { // FileStream performs most of the general argument validation. We can assume here that the arguments // are all checked and consistent (e.g. non-null-or-empty path; valid enums in mode, access, share, and options; etc.) // Store the arguments _mode = mode; _options = options; if (_useAsyncIO) _asyncState = new AsyncState(); // Translate the arguments into arguments for an open call. Interop.Sys.OpenFlags openFlags = PreOpenConfigurationFromOptions(mode, _access, share, options); // If the file gets created a new, we'll select the permissions for it. Most Unix utilities by default use 666 (read and // write for all), so we do the same (even though this doesn't match Windows, where by default it's possible to write out // a file and then execute it). No matter what we choose, it'll be subject to the umask applied by the system, such that the // actual permissions will typically be less than what we select here. const Interop.Sys.Permissions OpenPermissions = Interop.Sys.Permissions.S_IRUSR | Interop.Sys.Permissions.S_IWUSR | Interop.Sys.Permissions.S_IRGRP | Interop.Sys.Permissions.S_IWGRP | Interop.Sys.Permissions.S_IROTH | Interop.Sys.Permissions.S_IWOTH; // Open the file and store the safe handle. return SafeFileHandle.Open(_path, openFlags, (int)OpenPermissions); } /// <summary>Initializes a stream for reading or writing a Unix file.</summary> /// <param name="mode">How the file should be opened.</param> /// <param name="share">What other access to the file should be allowed. This is currently ignored.</param> private void Init(FileMode mode, FileShare share) { _fileHandle.IsAsync = _useAsyncIO; // Lock the file if requested via FileShare. This is only advisory locking. FileShare.None implies an exclusive // lock on the file and all other modes use a shared lock. While this is not as granular as Windows, not mandatory, // and not atomic with file opening, it's better than nothing. Interop.Sys.LockOperations lockOperation = (share == FileShare.None) ? Interop.Sys.LockOperations.LOCK_EX : Interop.Sys.LockOperations.LOCK_SH; if (Interop.Sys.FLock(_fileHandle, lockOperation | Interop.Sys.LockOperations.LOCK_NB) < 0) { // The only error we care about is EWOULDBLOCK, which indicates that the file is currently locked by someone // else and we would block trying to access it. Other errors, such as ENOTSUP (locking isn't supported) or // EACCES (the file system doesn't allow us to lock), will only hamper FileStream's usage without providing value, // given again that this is only advisory / best-effort. Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EWOULDBLOCK) { throw Interop.GetExceptionForIoErrno(errorInfo, _path, isDirectory: false); } } // These provide hints around how the file will be accessed. Specifying both RandomAccess // and Sequential together doesn't make sense as they are two competing options on the same spectrum, // so if both are specified, we prefer RandomAccess (behavior on Windows is unspecified if both are provided). Interop.Sys.FileAdvice fadv = (_options & FileOptions.RandomAccess) != 0 ? Interop.Sys.FileAdvice.POSIX_FADV_RANDOM : (_options & FileOptions.SequentialScan) != 0 ? Interop.Sys.FileAdvice.POSIX_FADV_SEQUENTIAL : 0; if (fadv != 0) { CheckFileCall(Interop.Sys.PosixFAdvise(_fileHandle, 0, 0, fadv), ignoreNotSupported: true); // just a hint. } // Jump to the end of the file if opened as Append. if (_mode == FileMode.Append) { _appendStart = SeekCore(_fileHandle, 0, SeekOrigin.End); } } /// <summary>Initializes a stream from an already open file handle (file descriptor).</summary> private void InitFromHandle(SafeFileHandle handle, FileAccess access, bool useAsyncIO) { if (useAsyncIO) _asyncState = new AsyncState(); if (CanSeekCore(handle)) // use non-virtual CanSeekCore rather than CanSeek to avoid making virtual call during ctor SeekCore(handle, 0, SeekOrigin.Current); } /// <summary>Translates the FileMode, FileAccess, and FileOptions values into flags to be passed when opening the file.</summary> /// <param name="mode">The FileMode provided to the stream's constructor.</param> /// <param name="access">The FileAccess provided to the stream's constructor</param> /// <param name="share">The FileShare provided to the stream's constructor</param> /// <param name="options">The FileOptions provided to the stream's constructor</param> /// <returns>The flags value to be passed to the open system call.</returns> private static Interop.Sys.OpenFlags PreOpenConfigurationFromOptions(FileMode mode, FileAccess access, FileShare share, FileOptions options) { // Translate FileMode. Most of the values map cleanly to one or more options for open. Interop.Sys.OpenFlags flags = default(Interop.Sys.OpenFlags); switch (mode) { default: case FileMode.Open: // Open maps to the default behavior for open(...). No flags needed. break; case FileMode.Append: // Append is the same as OpenOrCreate, except that we'll also separately jump to the end later case FileMode.OpenOrCreate: flags |= Interop.Sys.OpenFlags.O_CREAT; break; case FileMode.Create: flags |= (Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_TRUNC); break; case FileMode.CreateNew: flags |= (Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_EXCL); break; case FileMode.Truncate: flags |= Interop.Sys.OpenFlags.O_TRUNC; break; } // Translate FileAccess. All possible values map cleanly to corresponding values for open. switch (access) { case FileAccess.Read: flags |= Interop.Sys.OpenFlags.O_RDONLY; break; case FileAccess.ReadWrite: flags |= Interop.Sys.OpenFlags.O_RDWR; break; case FileAccess.Write: flags |= Interop.Sys.OpenFlags.O_WRONLY; break; } // Handle Inheritable, other FileShare flags are handled by Init if ((share & FileShare.Inheritable) == 0) { flags |= Interop.Sys.OpenFlags.O_CLOEXEC; } // Translate some FileOptions; some just aren't supported, and others will be handled after calling open. // - Asynchronous: Handled in ctor, setting _useAsync and SafeFileHandle.IsAsync to true // - DeleteOnClose: Doesn't have a Unix equivalent, but we approximate it in Dispose // - Encrypted: No equivalent on Unix and is ignored // - RandomAccess: Implemented after open if posix_fadvise is available // - SequentialScan: Implemented after open if posix_fadvise is available // - WriteThrough: Handled here if ((options & FileOptions.WriteThrough) != 0) { flags |= Interop.Sys.OpenFlags.O_SYNC; } return flags; } /// <summary>Gets a value indicating whether the current stream supports seeking.</summary> public override bool CanSeek => CanSeekCore(_fileHandle); /// <summary>Gets a value indicating whether the current stream supports seeking.</summary> /// <remarks> /// Separated out of CanSeek to enable making non-virtual call to this logic. /// We also pass in the file handle to allow the constructor to use this before it stashes the handle. /// </remarks> private bool CanSeekCore(SafeFileHandle fileHandle) { if (fileHandle.IsClosed) { return false; } if (!_canSeek.HasValue) { // Lazily-initialize whether we're able to seek, tested by seeking to our current location. _canSeek = Interop.Sys.LSeek(fileHandle, 0, Interop.Sys.SeekWhence.SEEK_CUR) >= 0; } return _canSeek.Value; } private long GetLengthInternal() { // Get the length of the file as reported by the OS Interop.Sys.FileStatus status; CheckFileCall(Interop.Sys.FStat(_fileHandle, out status)); long length = status.Size; // But we may have buffered some data to be written that puts our length // beyond what the OS is aware of. Update accordingly. if (_writePos > 0 && _filePosition + _writePos > length) { length = _writePos + _filePosition; } return length; } /// <summary>Releases the unmanaged resources used by the stream.</summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { try { if (_fileHandle != null && !_fileHandle.IsClosed) { // Flush any remaining data in the file try { FlushWriteBuffer(); } catch (IOException) when (!disposing) { // On finalization, ignore failures from trying to flush the write buffer, // e.g. if this stream is wrapping a pipe and the pipe is now broken. } // If DeleteOnClose was requested when constructed, delete the file now. // (Unix doesn't directly support DeleteOnClose, so we mimic it here.) if (_path != null && (_options & FileOptions.DeleteOnClose) != 0) { // Since we still have the file open, this will end up deleting // it (assuming we're the only link to it) once it's closed, but the // name will be removed immediately. Interop.Sys.Unlink(_path); // ignore errors; it's valid that the path may no longer exist } } } finally { if (_fileHandle != null && !_fileHandle.IsClosed) { _fileHandle.Dispose(); } base.Dispose(disposing); } } /// <summary>Flushes the OS buffer. This does not flush the internal read/write buffer.</summary> private void FlushOSBuffer() { if (Interop.Sys.FSync(_fileHandle) < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); switch (errorInfo.Error) { case Interop.Error.EROFS: case Interop.Error.EINVAL: case Interop.Error.ENOTSUP: // Ignore failures due to the FileStream being bound to a special file that // doesn't support synchronization. In such cases there's nothing to flush. break; default: throw Interop.GetExceptionForIoErrno(errorInfo, _path, isDirectory: false); } } } /// <summary>Writes any data in the write buffer to the underlying stream and resets the buffer.</summary> private void FlushWriteBuffer() { AssertBufferInvariants(); if (_writePos > 0) { WriteNative(GetBuffer(), 0, _writePos); _writePos = 0; } } /// <summary>Asynchronously clears all buffers for this stream, causing any buffered data to be written to the underlying device.</summary> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous flush operation.</returns> private Task FlushAsyncInternal(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } // As with Win32FileStream, flush the buffers synchronously to avoid race conditions. try { FlushInternalBuffer(); } catch (Exception e) { return Task.FromException(e); } // We then separately flush to disk asynchronously. This is only // necessary if we support writing; otherwise, we're done. if (CanWrite) { return Task.Factory.StartNew( state => ((FileStream)state).FlushOSBuffer(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } else { return Task.CompletedTask; } } /// <summary>Sets the length of this stream to the given value.</summary> /// <param name="value">The new length of the stream.</param> private void SetLengthInternal(long value) { FlushInternalBuffer(); if (_appendStart != -1 && value < _appendStart) { throw new IOException(SR.IO_SetLengthAppendTruncate); } long origPos = _filePosition; VerifyOSHandlePosition(); if (_filePosition != value) { SeekCore(_fileHandle, value, SeekOrigin.Begin); } CheckFileCall(Interop.Sys.FTruncate(_fileHandle, value)); // Return file pointer to where it was before setting length if (origPos != value) { if (origPos < value) { SeekCore(_fileHandle, origPos, SeekOrigin.Begin); } else { SeekCore(_fileHandle, 0, SeekOrigin.End); } } } /// <summary>Reads a block of bytes from the stream and writes the data in a given buffer.</summary> /// <param name="array"> /// When this method returns, contains the specified byte array with the values between offset and /// (offset + count - 1) replaced by the bytes read from the current source. /// </param> /// <param name="offset">The byte offset in array at which the read bytes will be placed.</param> /// <param name="count">The maximum number of bytes to read. </param> /// <returns> /// The total number of bytes read into the buffer. This might be less than the number of bytes requested /// if that number of bytes are not currently available, or zero if the end of the stream is reached. /// </returns> public override int Read(byte[] array, int offset, int count) { ValidateReadWriteArgs(array, offset, count); if (_useAsyncIO) { _asyncState.Wait(); try { return ReadCore(array, offset, count); } finally { _asyncState.Release(); } } else { return ReadCore(array, offset, count); } } /// <summary>Reads a block of bytes from the stream and writes the data in a given buffer.</summary> /// <param name="array"> /// When this method returns, contains the specified byte array with the values between offset and /// (offset + count - 1) replaced by the bytes read from the current source. /// </param> /// <param name="offset">The byte offset in array at which the read bytes will be placed.</param> /// <param name="count">The maximum number of bytes to read. </param> /// <returns> /// The total number of bytes read into the buffer. This might be less than the number of bytes requested /// if that number of bytes are not currently available, or zero if the end of the stream is reached. /// </returns> private int ReadCore(byte[] array, int offset, int count) { PrepareForReading(); // Are there any bytes available in the read buffer? If yes, // we can just return from the buffer. If the buffer is empty // or has no more available data in it, we can either refill it // (and then read from the buffer into the user's buffer) or // we can just go directly into the user's buffer, if they asked // for more data than we'd otherwise buffer. int numBytesAvailable = _readLength - _readPos; bool readFromOS = false; if (numBytesAvailable == 0) { // If we're not able to seek, then we're not able to rewind the stream (i.e. flushing // a read buffer), in which case we don't want to use a read buffer. Similarly, if // the user has asked for more data than we can buffer, we also want to skip the buffer. if (!CanSeek || (count >= _bufferLength)) { // Read directly into the user's buffer _readPos = _readLength = 0; return ReadNative(array, offset, count); } else { // Read into our buffer. _readLength = numBytesAvailable = ReadNative(GetBuffer(), 0, _bufferLength); _readPos = 0; if (numBytesAvailable == 0) { return 0; } // Note that we did an OS read as part of this Read, so that later // we don't try to do one again if what's in the buffer doesn't // meet the user's request. readFromOS = true; } } // Now that we know there's data in the buffer, read from it into the user's buffer. Debug.Assert(numBytesAvailable > 0, "Data must be in the buffer to be here"); int bytesRead = Math.Min(numBytesAvailable, count); Buffer.BlockCopy(GetBuffer(), _readPos, array, offset, bytesRead); _readPos += bytesRead; // We may not have had enough data in the buffer to completely satisfy the user's request. // While Read doesn't require that we return as much data as the user requested (any amount // up to the requested count is fine), FileStream on Windows tries to do so by doing a // subsequent read from the file if we tried to satisfy the request with what was in the // buffer but the buffer contained less than the requested count. To be consistent with that // behavior, we do the same thing here on Unix. Note that we may still get less the requested // amount, as the OS may give us back fewer than we request, either due to reaching the end of // file, or due to its own whims. if (!readFromOS && bytesRead < count) { Debug.Assert(_readPos == _readLength, "bytesToRead should only be < count if numBytesAvailable < count"); _readPos = _readLength = 0; // no data left in the read buffer bytesRead += ReadNative(array, offset + bytesRead, count - bytesRead); } return bytesRead; } /// <summary>Unbuffered, reads a block of bytes from the stream and writes the data in a given buffer.</summary> /// <param name="array"> /// When this method returns, contains the specified byte array with the values between offset and /// (offset + count - 1) replaced by the bytes read from the current source. /// </param> /// <param name="offset">The byte offset in array at which the read bytes will be placed.</param> /// <param name="count">The maximum number of bytes to read. </param> /// <returns> /// The total number of bytes read into the buffer. This might be less than the number of bytes requested /// if that number of bytes are not currently available, or zero if the end of the stream is reached. /// </returns> private unsafe int ReadNative(byte[] array, int offset, int count) { FlushWriteBuffer(); // we're about to read; dump the write buffer VerifyOSHandlePosition(); int bytesRead; fixed (byte* bufPtr = array) { bytesRead = CheckFileCall(Interop.Sys.Read(_fileHandle, bufPtr + offset, count)); Debug.Assert(bytesRead <= count); } _filePosition += bytesRead; return bytesRead; } /// <summary> /// Asynchronously reads a sequence of bytes from the current stream and advances /// the position within the stream by the number of bytes read. /// </summary> /// <param name="buffer">The buffer to write the data into.</param> /// <param name="offset">The byte offset in buffer at which to begin writing data from the stream.</param> /// <param name="count">The maximum number of bytes to read.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous read operation.</returns> private Task<int> ReadAsyncInternal(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (_useAsyncIO) { if (!CanRead) // match Windows behavior; this gets thrown synchronously { throw Error.GetReadNotSupported(); } // Serialize operations using the semaphore. Task waitTask = _asyncState.WaitAsync(); // If we got ownership immediately, and if there's enough data in our buffer // to satisfy the full request of the caller, hand back the buffered data. // While it would be a legal implementation of the Read contract, we don't // hand back here less than the amount requested so as to match the behavior // in ReadCore that will make a native call to try to fulfill the remainder // of the request. if (waitTask.Status == TaskStatus.RanToCompletion) { int numBytesAvailable = _readLength - _readPos; if (numBytesAvailable >= count) { try { PrepareForReading(); Buffer.BlockCopy(GetBuffer(), _readPos, buffer, offset, count); _readPos += count; return _asyncState._lastSuccessfulReadTask != null && _asyncState._lastSuccessfulReadTask.Result == count ? _asyncState._lastSuccessfulReadTask : (_asyncState._lastSuccessfulReadTask = Task.FromResult(count)); } catch (Exception exc) { return Task.FromException<int>(exc); } finally { _asyncState.Release(); } } } // Otherwise, issue the whole request asynchronously. _asyncState.Update(buffer, offset, count); return waitTask.ContinueWith((t, s) => { // The options available on Unix for writing asynchronously to an arbitrary file // handle typically amount to just using another thread to do the synchronous write, // which is exactly what this implementation does. This does mean there are subtle // differences in certain FileStream behaviors between Windows and Unix when multiple // asynchronous operations are issued against the stream to execute concurrently; on // Unix the operations will be serialized due to the usage of a semaphore, but the // position /length information won't be updated until after the write has completed, // whereas on Windows it may happen before the write has completed. Debug.Assert(t.Status == TaskStatus.RanToCompletion); var thisRef = (FileStream)s; try { byte[] b = thisRef._asyncState._buffer; thisRef._asyncState._buffer = null; // remove reference to user's buffer return thisRef.ReadCore(b, thisRef._asyncState._offset, thisRef._asyncState._count); } finally { thisRef._asyncState.Release(); } }, this, CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default); } else { return base.ReadAsync(buffer, offset, count, cancellationToken); } } /// <summary> /// Reads a byte from the stream and advances the position within the stream /// by one byte, or returns -1 if at the end of the stream. /// </summary> /// <returns>The unsigned byte cast to an Int32, or -1 if at the end of the stream.</returns> public override int ReadByte() { if (_useAsyncIO) { _asyncState.Wait(); try { return ReadByteCore(); } finally { _asyncState.Release(); } } else { return ReadByteCore(); } } /// <summary>Writes a block of bytes to the file stream.</summary> /// <param name="array">The buffer containing data to write to the stream.</param> /// <param name="offset">The zero-based byte offset in array from which to begin copying bytes to the stream.</param> /// <param name="count">The maximum number of bytes to write.</param> public override void Write(byte[] array, int offset, int count) { ValidateReadWriteArgs(array, offset, count); if (_useAsyncIO) { _asyncState.Wait(); try { WriteCore(array, offset, count); } finally { _asyncState.Release(); } } else { WriteCore(array, offset, count); } } /// <summary>Writes a block of bytes to the file stream.</summary> /// <param name="array">The buffer containing data to write to the stream.</param> /// <param name="offset">The zero-based byte offset in array from which to begin copying bytes to the stream.</param> /// <param name="count">The maximum number of bytes to write.</param> private void WriteCore(byte[] array, int offset, int count) { PrepareForWriting(); // If no data is being written, nothing more to do. if (count == 0) { return; } // If there's already data in our write buffer, then we need to go through // our buffer to ensure data isn't corrupted. if (_writePos > 0) { // If there's space remaining in the buffer, then copy as much as // we can from the user's buffer into ours. int spaceRemaining = _bufferLength - _writePos; if (spaceRemaining > 0) { int bytesToCopy = Math.Min(spaceRemaining, count); Buffer.BlockCopy(array, offset, GetBuffer(), _writePos, bytesToCopy); _writePos += bytesToCopy; // If we've successfully copied all of the user's data, we're done. if (count == bytesToCopy) { return; } // Otherwise, keep track of how much more data needs to be handled. offset += bytesToCopy; count -= bytesToCopy; } // At this point, the buffer is full, so flush it out. FlushWriteBuffer(); } // Our buffer is now empty. If using the buffer would slow things down (because // the user's looking to write more data than we can store in the buffer), // skip the buffer. Otherwise, put the remaining data into the buffer. Debug.Assert(_writePos == 0); if (count >= _bufferLength) { WriteNative(array, offset, count); } else { Buffer.BlockCopy(array, offset, GetBuffer(), _writePos, count); _writePos = count; } } /// <summary>Unbuffered, writes a block of bytes to the file stream.</summary> /// <param name="array">The buffer containing data to write to the stream.</param> /// <param name="offset">The zero-based byte offset in array from which to begin copying bytes to the stream.</param> /// <param name="count">The maximum number of bytes to write.</param> private unsafe void WriteNative(byte[] array, int offset, int count) { VerifyOSHandlePosition(); fixed (byte* bufPtr = array) { while (count > 0) { int bytesWritten = CheckFileCall(Interop.Sys.Write(_fileHandle, bufPtr + offset, count)); Debug.Assert(bytesWritten <= count); _filePosition += bytesWritten; count -= bytesWritten; offset += bytesWritten; } } } /// <summary> /// Asynchronously writes a sequence of bytes to the current stream, advances /// the current position within this stream by the number of bytes written, and /// monitors cancellation requests. /// </summary> /// <param name="buffer">The buffer to write data from.</param> /// <param name="offset">The zero-based byte offset in buffer from which to begin copying bytes to the stream.</param> /// <param name="count">The maximum number of bytes to write.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous write operation.</returns> private Task WriteAsyncInternal(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (_useAsyncIO) { if (!CanWrite) // match Windows behavior; this gets thrown synchronously { throw Error.GetWriteNotSupported(); } // Serialize operations using the semaphore. Task waitTask = _asyncState.WaitAsync(); // If we got ownership immediately, and if there's enough space in our buffer // to buffer the entire write request, then do so and we're done. if (waitTask.Status == TaskStatus.RanToCompletion) { int spaceRemaining = _bufferLength - _writePos; if (spaceRemaining >= count) { try { PrepareForWriting(); Buffer.BlockCopy(buffer, offset, GetBuffer(), _writePos, count); _writePos += count; return Task.CompletedTask; } catch (Exception exc) { return Task.FromException(exc); } finally { _asyncState.Release(); } } } // Otherwise, issue the whole request asynchronously. _asyncState.Update(buffer, offset, count); return waitTask.ContinueWith((t, s) => { // The options available on Unix for writing asynchronously to an arbitrary file // handle typically amount to just using another thread to do the synchronous write, // which is exactly what this implementation does. This does mean there are subtle // differences in certain FileStream behaviors between Windows and Unix when multiple // asynchronous operations are issued against the stream to execute concurrently; on // Unix the operations will be serialized due to the usage of a semaphore, but the // position /length information won't be updated until after the write has completed, // whereas on Windows it may happen before the write has completed. Debug.Assert(t.Status == TaskStatus.RanToCompletion); var thisRef = (FileStream)s; try { byte[] b = thisRef._asyncState._buffer; thisRef._asyncState._buffer = null; // remove reference to user's buffer thisRef.WriteCore(b, thisRef._asyncState._offset, thisRef._asyncState._count); } finally { thisRef._asyncState.Release(); } }, this, CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default); } else { return base.WriteAsync(buffer, offset, count, cancellationToken); } } /// <summary> /// Writes a byte to the current position in the stream and advances the position /// within the stream by one byte. /// </summary> /// <param name="value">The byte to write to the stream.</param> public override void WriteByte(byte value) // avoids an array allocation in the base implementation { if (_useAsyncIO) { _asyncState.Wait(); try { WriteByteCore(value); } finally { _asyncState.Release(); } } else { WriteByteCore(value); } } /// <summary>Sets the current position of this stream to the given value.</summary> /// <param name="offset">The point relative to origin from which to begin seeking. </param> /// <param name="origin"> /// Specifies the beginning, the end, or the current position as a reference /// point for offset, using a value of type SeekOrigin. /// </param> /// <returns>The new position in the stream.</returns> public override long Seek(long offset, SeekOrigin origin) { if (origin < SeekOrigin.Begin || origin > SeekOrigin.End) { throw new ArgumentException(SR.Argument_InvalidSeekOrigin, nameof(origin)); } if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } if (!CanSeek) { throw Error.GetSeekNotSupported(); } VerifyOSHandlePosition(); // Flush our write/read buffer. FlushWrite will output any write buffer we have and reset _bufferWritePos. // We don't call FlushRead, as that will do an unnecessary seek to rewind the read buffer, and since we're // about to seek and update our position, we can simply update the offset as necessary and reset our read // position and length to 0. (In the future, for some simple cases we could potentially add an optimization // here to just move data around in the buffer for short jumps, to avoid re-reading the data from disk.) FlushWriteBuffer(); if (origin == SeekOrigin.Current) { offset -= (_readLength - _readPos); } _readPos = _readLength = 0; // Keep track of where we were, in case we're in append mode and need to verify long oldPos = 0; if (_appendStart >= 0) { oldPos = SeekCore(_fileHandle, 0, SeekOrigin.Current); } // Jump to the new location long pos = SeekCore(_fileHandle, offset, origin); // Prevent users from overwriting data in a file that was opened in append mode. if (_appendStart != -1 && pos < _appendStart) { SeekCore(_fileHandle, oldPos, SeekOrigin.Begin); throw new IOException(SR.IO_SeekAppendOverwrite); } // Return the new position return pos; } /// <summary>Sets the current position of this stream to the given value.</summary> /// <param name="offset">The point relative to origin from which to begin seeking. </param> /// <param name="origin"> /// Specifies the beginning, the end, or the current position as a reference /// point for offset, using a value of type SeekOrigin. /// </param> /// <returns>The new position in the stream.</returns> private long SeekCore(SafeFileHandle fileHandle, long offset, SeekOrigin origin) { Debug.Assert(!fileHandle.IsClosed && (GetType() != typeof(FileStream) || CanSeekCore(fileHandle))); // verify that we can seek, but only if CanSeek won't be a virtual call (which could happen in the ctor) Debug.Assert(origin >= SeekOrigin.Begin && origin <= SeekOrigin.End); long pos = CheckFileCall(Interop.Sys.LSeek(fileHandle, offset, (Interop.Sys.SeekWhence)(int)origin)); // SeekOrigin values are the same as Interop.libc.SeekWhence values _filePosition = pos; return pos; } private long CheckFileCall(long result, bool ignoreNotSupported = false) { if (result < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (!(ignoreNotSupported && errorInfo.Error == Interop.Error.ENOTSUP)) { throw Interop.GetExceptionForIoErrno(errorInfo, _path, isDirectory: false); } } return result; } private int CheckFileCall(int result, bool ignoreNotSupported = false) { CheckFileCall((long)result, ignoreNotSupported); return result; } /// <summary>State used when the stream is in async mode.</summary> private sealed class AsyncState : SemaphoreSlim { /// <summary>The caller's buffer currently being used by the active async operation.</summary> internal byte[] _buffer; /// <summary>The caller's offset currently being used by the active async operation.</summary> internal int _offset; /// <summary>The caller's count currently being used by the active async operation.</summary> internal int _count; /// <summary>The last task successfully, synchronously returned task from ReadAsync.</summary> internal Task<int> _lastSuccessfulReadTask; /// <summary>Initialize the AsyncState.</summary> internal AsyncState() : base(initialCount: 1, maxCount: 1) { } /// <summary>Sets the active buffer, offset, and count.</summary> internal void Update(byte[] buffer, int offset, int count) { _buffer = buffer; _offset = offset; _count = count; } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenSim.Server.Base; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; using OpenMetaverse; using log4net; namespace OpenSim.Region.CoreModules.World.Estate { public class EstateConnector { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected EstateModule m_EstateModule; private string token; uint port = 0; public EstateConnector(EstateModule module, string _token, uint _port) { m_EstateModule = module; token = _token; port = _port; } public void SendTeleportHomeOneUser(uint EstateID, UUID PreyID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["METHOD"] = "teleport_home_one_user"; sendData["TOKEN"] = token; sendData["EstateID"] = EstateID.ToString(); sendData["PreyID"] = PreyID.ToString(); SendToEstate(EstateID, sendData); } public void SendTeleportHomeAllUsers(uint EstateID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["METHOD"] = "teleport_home_all_users"; sendData["TOKEN"] = token; sendData["EstateID"] = EstateID.ToString(); SendToEstate(EstateID, sendData); } public bool SendUpdateCovenant(uint EstateID, UUID CovenantID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["METHOD"] = "update_covenant"; sendData["TOKEN"] = token; sendData["CovenantID"] = CovenantID.ToString(); sendData["EstateID"] = EstateID.ToString(); // Handle local regions locally // foreach (Scene s in m_EstateModule.Scenes) { if (s.RegionInfo.EstateSettings.EstateID == EstateID) s.RegionInfo.RegionSettings.Covenant = CovenantID; // s.ReloadEstateData(); } SendToEstate(EstateID, sendData); return true; } public bool SendUpdateEstate(uint EstateID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["METHOD"] = "update_estate"; sendData["TOKEN"] = token; sendData["EstateID"] = EstateID.ToString(); // Handle local regions locally // foreach (Scene s in m_EstateModule.Scenes) { if (s.RegionInfo.EstateSettings.EstateID == EstateID) s.ReloadEstateData(); } SendToEstate(EstateID, sendData); return true; } public void SendEstateMessage(uint EstateID, UUID FromID, string FromName, string Message) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["METHOD"] = "estate_message"; sendData["TOKEN"] = token; sendData["EstateID"] = EstateID.ToString(); sendData["FromID"] = FromID.ToString(); sendData["FromName"] = FromName; sendData["Message"] = Message; SendToEstate(EstateID, sendData); } private void SendToEstate(uint EstateID, Dictionary<string, object> sendData) { List<UUID> regions = m_EstateModule.Scenes[0].GetEstateRegions((int)EstateID); // Don't send to the same instance twice List<string> done = new List<string>(); // Handle local regions locally lock (m_EstateModule.Scenes) { foreach (Scene s in m_EstateModule.Scenes) { RegionInfo sreg = s.RegionInfo; if (regions.Contains(sreg.RegionID)) { string url = sreg.ExternalHostName + ":" + sreg.HttpPort; regions.Remove(sreg.RegionID); if(!done.Contains(url)) // we may have older regs with same url lost in dbs done.Add(url); } } } if(regions.Count == 0) return; Scene baseScene = m_EstateModule.Scenes[0]; UUID ScopeID = baseScene.RegionInfo.ScopeID; IGridService gridService = baseScene.GridService; if(gridService == null) return; // Send to remote regions foreach (UUID regionID in regions) { GridRegion region = gridService.GetRegionByUUID(ScopeID, regionID); if (region != null) { string url = region.ExternalHostName + ":" + region.HttpPort; if(done.Contains(url)) continue; Call(region, sendData); done.Add(url); } } } private bool Call(GridRegion region, Dictionary<string, object> sendData) { string reqString = ServerUtils.BuildQueryString(sendData); // m_log.DebugFormat("[XESTATE CONNECTOR]: queryString = {0}", reqString); try { string url = ""; if(port != 0) url = "http://" + region.ExternalHostName + ":" + port; else url = region.ServerURI; string reply = SynchronousRestFormsRequester.MakeRequest("POST", url + "/estate", reqString); if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData.ContainsKey("RESULT")) { if (replyData["RESULT"].ToString().ToLower() == "true") return true; else return false; } else m_log.DebugFormat("[XESTATE CONNECTOR]: reply data does not contain result field"); } else m_log.DebugFormat("[XESTATE CONNECTOR]: received empty reply"); } catch (Exception e) { m_log.DebugFormat("[XESTATE CONNECTOR]: Exception when contacting remote sim: {0}", e.Message); } return false; } } }
#region License // // The Open Toolkit Library License // // Copyright (c) 2006 - 2010 the Open Toolkit library. // // 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 // Created by Erik Ylvisaker on 3/17/08. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; #if !MINIMAL using System.Drawing; #endif using System.Text; namespace OpenTK.Platform.MacOS { using Carbon; using Graphics; class CarbonGLNative : INativeWindow { #region Fields CarbonWindowInfo window; CarbonInput mInputDriver; static MacOSKeyMap Keymap = new MacOSKeyMap(); IntPtr uppHandler; string title = "OpenTK Window"; Rectangle bounds, clientRectangle; Rectangle windowedBounds; bool mIsDisposed = false; bool mExists = true; DisplayDevice mDisplayDevice; WindowAttributes mWindowAttrib; WindowClass mWindowClass; WindowPositionMethod mPositionMethod = WindowPositionMethod.CenterOnMainScreen; int mTitlebarHeight; private WindowBorder windowBorder = WindowBorder.Resizable; private WindowState windowState = WindowState.Normal; static Dictionary<IntPtr, WeakReference> mWindows = new Dictionary<IntPtr, WeakReference>(new IntPtrEqualityComparer()); KeyPressEventArgs mKeyPressArgs = new KeyPressEventArgs((char)0); bool mMouseIn = false; bool mIsActive = false; Icon mIcon; // Used to accumulate mouse motion when the cursor is hidden. float mouse_rel_x; float mouse_rel_y; #endregion #region AGL Device Hack static internal Dictionary<IntPtr, WeakReference> WindowRefMap { get { return mWindows; } } internal DisplayDevice TargetDisplayDevice { get { return mDisplayDevice; } } #endregion #region Constructors static CarbonGLNative() { Application.Initialize(); } CarbonGLNative() : this(WindowClass.Document, WindowAttributes.StandardDocument | WindowAttributes.StandardHandler | WindowAttributes.InWindowMenu | WindowAttributes.LiveResize) { } CarbonGLNative(WindowClass @class, WindowAttributes attrib) { mWindowClass = @class; mWindowAttrib = attrib; } public CarbonGLNative(int x, int y, int width, int height, string title, GraphicsMode mode, GameWindowFlags options, DisplayDevice device) { CreateNativeWindow(WindowClass.Document, WindowAttributes.StandardDocument | WindowAttributes.StandardHandler | WindowAttributes.InWindowMenu | WindowAttributes.LiveResize, new Rect((short)x, (short)y, (short)width, (short)height)); mDisplayDevice = device; } #endregion #region IDisposable public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (mIsDisposed) return; Debug.Print("Disposing of CarbonGLNative window."); CursorVisible = true; API.DisposeWindow(window.WindowRef); mIsDisposed = true; mExists = false; CG.SetLocalEventsSuppressionInterval(0.25); if (disposing) { mWindows.Remove(window.WindowRef); window.Dispose(); window = null; } DisposeUPP(); Disposed(this, EventArgs.Empty); } ~CarbonGLNative() { Dispose(false); } #endregion #region Private Members void DisposeUPP() { if (uppHandler != IntPtr.Zero) { //API.RemoveEventHandler(uppHandler); //API.DisposeEventHandlerUPP(uppHandler); } uppHandler = IntPtr.Zero; } void CreateNativeWindow(WindowClass @class, WindowAttributes attrib, Rect r) { Debug.Print("Creating window..."); Debug.Indent(); IntPtr windowRef = API.CreateNewWindow(@class, attrib, r); API.SetWindowTitle(windowRef, title); window = new CarbonWindowInfo(windowRef, true, false); SetLocation(r.X, r.Y); SetSize(r.Width, r.Height); Debug.Unindent(); Debug.Print("Created window."); mWindows.Add(windowRef, new WeakReference(this)); LoadSize(); Rect titleSize = API.GetWindowBounds(window.WindowRef, WindowRegionCode.TitleBarRegion); mTitlebarHeight = titleSize.Height; Debug.Print("Titlebar size: {0}", titleSize); ConnectEvents(); System.Diagnostics.Debug.WriteLine("Attached window events."); } void ConnectEvents() { mInputDriver = new CarbonInput(); EventTypeSpec[] eventTypes = new EventTypeSpec[] { new EventTypeSpec(EventClass.Window, WindowEventKind.WindowClose), new EventTypeSpec(EventClass.Window, WindowEventKind.WindowClosed), new EventTypeSpec(EventClass.Window, WindowEventKind.WindowBoundsChanged), new EventTypeSpec(EventClass.Window, WindowEventKind.WindowActivate), new EventTypeSpec(EventClass.Window, WindowEventKind.WindowDeactivate), //new EventTypeSpec(EventClass.Mouse, MouseEventKind.MouseDown), //new EventTypeSpec(EventClass.Mouse, MouseEventKind.MouseUp), //new EventTypeSpec(EventClass.Mouse, MouseEventKind.MouseMoved), //new EventTypeSpec(EventClass.Mouse, MouseEventKind.MouseDragged), //new EventTypeSpec(EventClass.Mouse, MouseEventKind.MouseEntered), //new EventTypeSpec(EventClass.Mouse, MouseEventKind.MouseExited), //new EventTypeSpec(EventClass.Mouse, MouseEventKind.WheelMoved), //new EventTypeSpec(EventClass.Keyboard, KeyboardEventKind.RawKeyDown), //new EventTypeSpec(EventClass.Keyboard, KeyboardEventKind.RawKeyRepeat), //new EventTypeSpec(EventClass.Keyboard, KeyboardEventKind.RawKeyUp), //new EventTypeSpec(EventClass.Keyboard, KeyboardEventKind.RawKeyModifiersChanged), }; MacOSEventHandler handler = EventHandler; uppHandler = API.NewEventHandlerUPP(handler); API.InstallWindowEventHandler(window.WindowRef, uppHandler, eventTypes, window.WindowRef, IntPtr.Zero); Application.WindowEventHandler = this; } void Activate() { API.SelectWindow(window.WindowRef); } void Show() { IntPtr parent = IntPtr.Zero; API.ShowWindow(window.WindowRef); API.RepositionWindow(window.WindowRef, parent, WindowPositionMethod); API.SelectWindow(window.WindowRef); } void Hide() { API.HideWindow(window.WindowRef); } internal void SetFullscreen(AglContext context) { windowedBounds = bounds; int width, height; context.SetFullScreen(window, out width, out height); Debug.Print("Prev Size: {0}, {1}", Width, Height); clientRectangle.Size = new Size(width, height); Debug.Print("New Size: {0}, {1}", Width, Height); // TODO: if we go full screen we need to make this use the device specified. bounds = mDisplayDevice.Bounds; windowState = WindowState.Fullscreen; } internal void UnsetFullscreen(AglContext context) { context.UnsetFullScreen(window); Debug.Print("Telling Carbon to reset window state to " + windowState.ToString()); SetCarbonWindowState(); SetSize((short)windowedBounds.Width, (short)windowedBounds.Height); } bool IsDisposed { get { return mIsDisposed; } } WindowPositionMethod WindowPositionMethod { get { return mPositionMethod; } set { mPositionMethod = value; } } internal OSStatus DispatchEvent(IntPtr inCaller, IntPtr inEvent, EventInfo evt, IntPtr userData) { switch (evt.EventClass) { case EventClass.Window: return ProcessWindowEvent(inCaller, inEvent, evt, userData); case EventClass.Mouse: return ProcessMouseEvent(inCaller, inEvent, evt, userData); case EventClass.Keyboard: return ProcessKeyboardEvent(inCaller, inEvent, evt, userData); default: return OSStatus.EventNotHandled; } } protected static OSStatus EventHandler(IntPtr inCaller, IntPtr inEvent, IntPtr userData) { if (mWindows.ContainsKey(userData) == false) { // Bail out if the window passed in is not actually our window. // I think this happens if using winforms with a GameWindow sometimes. return OSStatus.EventNotHandled; } WeakReference reference = mWindows[userData]; if (reference.IsAlive == false) { // Bail out if the CarbonGLNative window has been garbage collected. mWindows.Remove(userData); return OSStatus.EventNotHandled; } CarbonGLNative window = (CarbonGLNative)reference.Target; if (window == null) { Debug.WriteLine("Window for event not found."); return OSStatus.EventNotHandled; } EventInfo evt = new EventInfo(inEvent); return window.DispatchEvent(inCaller, inEvent, evt, userData); } private OSStatus ProcessKeyboardEvent(IntPtr inCaller, IntPtr inEvent, EventInfo evt, IntPtr userData) { System.Diagnostics.Debug.Assert(evt.EventClass == EventClass.Keyboard); MacOSKeyCode code = (MacOSKeyCode)0; char charCode = '\0'; switch (evt.KeyboardEventKind) { case KeyboardEventKind.RawKeyDown: case KeyboardEventKind.RawKeyRepeat: case KeyboardEventKind.RawKeyUp: GetCharCodes(inEvent, out code, out charCode); mKeyPressArgs.KeyChar = charCode; break; } switch (evt.KeyboardEventKind) { case KeyboardEventKind.RawKeyRepeat: if (InputDriver.Keyboard[0].KeyRepeat) goto case KeyboardEventKind.RawKeyDown; break; case KeyboardEventKind.RawKeyDown: { OpenTK.Input.Key key; if (Keymap.TryGetValue(code, out key)) { InputDriver.Keyboard[0][key] = true; OnKeyPress(mKeyPressArgs); } return OSStatus.NoError; } case KeyboardEventKind.RawKeyUp: { OpenTK.Input.Key key; if (Keymap.TryGetValue(code, out key)) { InputDriver.Keyboard[0][key] = false; } return OSStatus.NoError; } case KeyboardEventKind.RawKeyModifiersChanged: ProcessModifierKey(inEvent); return OSStatus.NoError; } return OSStatus.EventNotHandled; } private OSStatus ProcessWindowEvent(IntPtr inCaller, IntPtr inEvent, EventInfo evt, IntPtr userData) { System.Diagnostics.Debug.Assert(evt.EventClass == EventClass.Window); switch (evt.WindowEventKind) { case WindowEventKind.WindowClose: CancelEventArgs cancel = new CancelEventArgs(); OnClosing(cancel); if (cancel.Cancel) return OSStatus.NoError; else return OSStatus.EventNotHandled; case WindowEventKind.WindowClosed: mExists = false; OnClosed(); return OSStatus.NoError; case WindowEventKind.WindowBoundsChanged: int thisWidth = Width; int thisHeight = Height; int thisX = X; int thisY = Y; LoadSize(); if (thisX != X || thisY != Y) Move(this, EventArgs.Empty); if (thisWidth != Width || thisHeight != Height) Resize(this, EventArgs.Empty); return OSStatus.EventNotHandled; case WindowEventKind.WindowActivate: OnActivate(); return OSStatus.EventNotHandled; case WindowEventKind.WindowDeactivate: OnDeactivate(); return OSStatus.EventNotHandled; default: Debug.Print("{0}", evt); return OSStatus.EventNotHandled; } } protected OSStatus ProcessMouseEvent(IntPtr inCaller, IntPtr inEvent, EventInfo evt, IntPtr userData) { System.Diagnostics.Debug.Assert(evt.EventClass == EventClass.Mouse); MouseButton button = MouseButton.Primary; HIPoint pt = new HIPoint(); HIPoint screenLoc = new HIPoint(); IntPtr thisEventWindow; API.GetEventWindowRef(inEvent, out thisEventWindow); OSStatus err = API.GetEventMouseLocation(inEvent, out screenLoc); if (this.windowState == WindowState.Fullscreen) { pt = screenLoc; } else if (CursorVisible) { err = API.GetEventWindowMouseLocation(inEvent, out pt); pt.Y -= mTitlebarHeight; } else { err = API.GetEventMouseDelta(inEvent, out pt); pt.X += mouse_rel_x; pt.Y += mouse_rel_y; pt = ConfineMouseToWindow(thisEventWindow, pt); ResetMouseToWindowCenter(); mouse_rel_x = pt.X; mouse_rel_y = pt.Y; } if (err != OSStatus.NoError && err != OSStatus.EventParameterNotFound) { // this error comes up from the application event handler. throw new MacOSException(err); } Point mousePosInClient = new Point((int)pt.X, (int)pt.Y); CheckEnterLeaveEvents(thisEventWindow, mousePosInClient); switch (evt.MouseEventKind) { case MouseEventKind.MouseDown: case MouseEventKind.MouseUp: button = API.GetEventMouseButton(inEvent); bool pressed = evt.MouseEventKind == MouseEventKind.MouseDown; switch (button) { case MouseButton.Primary: InputDriver.Mouse[0][OpenTK.Input.MouseButton.Left] = pressed; break; case MouseButton.Secondary: InputDriver.Mouse[0][OpenTK.Input.MouseButton.Right] = pressed; break; case MouseButton.Tertiary: InputDriver.Mouse[0][OpenTK.Input.MouseButton.Middle] = pressed; break; } return OSStatus.NoError; case MouseEventKind.WheelMoved: float delta = API.GetEventMouseWheelDelta(inEvent); InputDriver.Mouse[0].WheelPrecise += delta; return OSStatus.NoError; case MouseEventKind.MouseMoved: case MouseEventKind.MouseDragged: if (this.windowState == WindowState.Fullscreen) { if (mousePosInClient.X != InputDriver.Mouse[0].X || mousePosInClient.Y != InputDriver.Mouse[0].Y) { InputDriver.Mouse[0].Position = mousePosInClient; } } else { // ignore clicks in the title bar if (pt.Y < 0) return OSStatus.EventNotHandled; if (mousePosInClient.X != InputDriver.Mouse[0].X || mousePosInClient.Y != InputDriver.Mouse[0].Y) { InputDriver.Mouse[0].Position = mousePosInClient; } } return OSStatus.EventNotHandled; default: Debug.Print("{0}", evt); return OSStatus.EventNotHandled; } } void ResetMouseToWindowCenter() { OpenTK.Input.Mouse.SetPosition( (Bounds.Left + Bounds.Right) / 2, (Bounds.Top + Bounds.Bottom) / 2); } private void CheckEnterLeaveEvents(IntPtr eventWindowRef, Point pt) { if (window == null) return; bool thisIn = eventWindowRef == window.WindowRef; if (pt.Y < 0) thisIn = false; if (thisIn != mMouseIn) { mMouseIn = thisIn; if (mMouseIn) OnMouseEnter(); else OnMouseLeave(); } } // Point in client (window) coordinates private HIPoint ConfineMouseToWindow(IntPtr window, HIPoint client) { if (client.X < 0) client.X = 0; if (client.X >= Width) client.X = Width - 1; if (client.Y < 0) client.Y = 0; if (client.Y >= Height) client.Y = Height - 1; return client; } private static void GetCharCodes(IntPtr inEvent, out MacOSKeyCode code, out char charCode) { code = API.GetEventKeyboardKeyCode(inEvent); charCode = API.GetEventKeyboardChar(inEvent); } private void ProcessModifierKey(IntPtr inEvent) { MacOSKeyModifiers modifiers = API.GetEventKeyModifiers(inEvent); bool caps = (modifiers & MacOSKeyModifiers.CapsLock) != 0 ? true : false; bool control = (modifiers & MacOSKeyModifiers.Control) != 0 ? true : false; bool command = (modifiers & MacOSKeyModifiers.Command) != 0 ? true : false; bool option = (modifiers & MacOSKeyModifiers.Option) != 0 ? true : false; bool shift = (modifiers & MacOSKeyModifiers.Shift) != 0 ? true : false; Debug.Print("Modifiers Changed: {0}", modifiers); Input.KeyboardDevice keyboard = InputDriver.Keyboard[0]; if (keyboard[OpenTK.Input.Key.AltLeft] ^ option) keyboard[OpenTK.Input.Key.AltLeft] = option; if (keyboard[OpenTK.Input.Key.ShiftLeft] ^ shift) keyboard[OpenTK.Input.Key.ShiftLeft] = shift; if (keyboard[OpenTK.Input.Key.WinLeft] ^ command) keyboard[OpenTK.Input.Key.WinLeft] = command; if (keyboard[OpenTK.Input.Key.ControlLeft] ^ control) keyboard[OpenTK.Input.Key.ControlLeft] = control; if (keyboard[OpenTK.Input.Key.CapsLock] ^ caps) keyboard[OpenTK.Input.Key.CapsLock] = caps; } Rect GetRegion() { Rect retval = API.GetWindowBounds(window.WindowRef, WindowRegionCode.ContentRegion); return retval; } void SetLocation(short x, short y) { if (windowState == WindowState.Fullscreen) return; API.MoveWindow(window.WindowRef, x, y, false); } void SetSize(short width, short height) { if (WindowState == WindowState.Fullscreen) return; // The bounds of the window should be the size specified, but // API.SizeWindow sets the content region size. So // we reduce the size to get the correct bounds. width -= (short)(bounds.Width - clientRectangle.Width); height -= (short)(bounds.Height - clientRectangle.Height); API.SizeWindow(window.WindowRef, width, height, true); } void SetClientSize(short width, short height) { if (WindowState == WindowState.Fullscreen) return; API.SizeWindow(window.WindowRef, width, height, true); } private void LoadSize() { if (WindowState == WindowState.Fullscreen) return; Rect r = API.GetWindowBounds(window.WindowRef, WindowRegionCode.StructureRegion); bounds = new Rectangle(r.X, r.Y, r.Width, r.Height); r = API.GetWindowBounds(window.WindowRef, WindowRegionCode.GlobalPortRegion); clientRectangle = new Rectangle(0, 0, r.Width, r.Height); } #endregion #region INativeWindow Members public void ProcessEvents() { Application.ProcessEvents(); } public Point PointToClient(Point point) { Rect r = Carbon.API.GetWindowBounds(window.WindowRef, WindowRegionCode.ContentRegion); return new Point(point.X - r.X, point.Y - r.Y); } public Point PointToScreen(Point point) { Rect r = Carbon.API.GetWindowBounds(window.WindowRef, WindowRegionCode.ContentRegion); return new Point(point.X + r.X, point.Y + r.Y); } public bool Exists { get { return mExists; } } public IWindowInfo WindowInfo { get { return window; } } public bool IsIdle { get { return true; } } public OpenTK.Input.IInputDriver InputDriver { get { return mInputDriver; } } public Icon Icon { get { return mIcon; } set { if (value != Icon) { SetIcon(value); mIcon = value; IconChanged(this, EventArgs.Empty); } } } private void SetIcon(Icon icon) { // The code for this function was adapted from Mono's // XplatUICarbon implementation, written by Geoff Norton // http://anonsvn.mono-project.com/viewvc/trunk/mcs/class/Managed.Windows.Forms/System.Windows.Forms/XplatUICarbon.cs?view=markup&pathrev=136932 if (icon == null) { API.RestoreApplicationDockTileImage(); } else { Bitmap bitmap; int size; IntPtr[] data; int index; bitmap = new Bitmap(128, 128); #if MINIMAL using (OpenTK.Minimal.Graphics g = OpenTK.Minimal.Graphics.FromImage(bitmap)) #else using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap)) #endif { g.DrawImage(icon.ToBitmap(), 0, 0, 128, 128); } index = 0; size = bitmap.Width * bitmap.Height; data = new IntPtr[size]; for (int y = 0; y < bitmap.Height; y++) { for (int x = 0; x < bitmap.Width; x++) { int pixel = bitmap.GetPixel(x, y).ToArgb(); if (BitConverter.IsLittleEndian) { byte a = (byte)((pixel >> 24) & 0xFF); byte r = (byte)((pixel >> 16) & 0xFF); byte g = (byte)((pixel >> 8) & 0xFF); byte b = (byte)(pixel & 0xFF); data[index++] = (IntPtr)(a + (r << 8) + (g << 16) + (b << 24)); } else { data[index++] = (IntPtr)pixel; } } } IntPtr provider = API.CGDataProviderCreateWithData(IntPtr.Zero, data, size * 4, IntPtr.Zero); IntPtr image = API.CGImageCreate(128, 128, 8, 32, 4 * 128, API.CGColorSpaceCreateDeviceRGB(), 4, provider, IntPtr.Zero, 0, 0); API.SetApplicationDockTileImage(image); } } public string Title { get { return title; } set { if (value != Title) { API.SetWindowTitle(window.WindowRef, value); title = value; TitleChanged(this, EventArgs.Empty); } } } public bool Visible { get { return API.IsWindowVisible(window.WindowRef); } set { if (value != Visible) { if (value) Show(); else Hide(); VisibleChanged(this, EventArgs.Empty); } } } public bool Focused { get { return this.mIsActive; } } public Rectangle Bounds { get { return bounds; } set { Location = value.Location; Size = value.Size; } } public Point Location { get { return Bounds.Location; } set { SetLocation((short)value.X, (short)value.Y); } } public Size Size { get { return bounds.Size; } set { SetSize((short)value.Width, (short)value.Height); } } public int Width { get { return ClientRectangle.Width; } set { SetClientSize((short)value, (short)Height); } } public int Height { get { return ClientRectangle.Height; } set { SetClientSize((short)Width, (short)value); } } public int X { get { return ClientRectangle.X; } set { Location = new Point(value, Y); } } public int Y { get { return ClientRectangle.Y; } set { Location = new Point(X, value); } } public Rectangle ClientRectangle { get { return clientRectangle; } // just set the size, and ignore the location value. // this is the behavior of the Windows WinGLNative. set { ClientSize = value.Size; } } public Size ClientSize { get { return clientRectangle.Size; } set { API.SizeWindow(window.WindowRef, (short)value.Width, (short)value.Height, true); LoadSize(); Resize(this, EventArgs.Empty); } } public bool CursorVisible { get { return CG.CursorIsVisible(); } set { if (value) { CG.DisplayShowCursor(IntPtr.Zero); CG.AssociateMouseAndMouseCursorPosition(true); } else { CG.DisplayHideCursor(IntPtr.Zero); ResetMouseToWindowCenter(); CG.AssociateMouseAndMouseCursorPosition(false); } } } public void Close() { CancelEventArgs e = new CancelEventArgs(); OnClosing(e); if (e.Cancel) return; OnClosed(); Dispose(); } public WindowState WindowState { get { if (windowState == WindowState.Fullscreen) return WindowState.Fullscreen; if (Carbon.API.IsWindowCollapsed(window.WindowRef)) return WindowState.Minimized; if (Carbon.API.IsWindowInStandardState(window.WindowRef)) { return WindowState.Maximized; } return WindowState.Normal; } set { if (value == WindowState) return; Debug.Print("Switching window state from {0} to {1}", WindowState, value); WindowState oldState = WindowState; windowState = value; if (oldState == WindowState.Fullscreen) { window.GoWindowedHack = true; // when returning from full screen, wait until the context is updated // to actually do the work. return; } if (oldState == WindowState.Minimized) { API.CollapseWindow(window.WindowRef, false); } SetCarbonWindowState(); } } private void SetCarbonWindowState() { CarbonPoint idealSize; switch (windowState) { case WindowState.Fullscreen: window.GoFullScreenHack = true; break; case WindowState.Maximized: // hack because mac os has no concept of maximized. Instead windows are "zoomed" // meaning they are maximized up to their reported ideal size. So we report a // large ideal size. idealSize = new CarbonPoint(9000, 9000); API.ZoomWindowIdeal(window.WindowRef, WindowPartCode.inZoomOut, ref idealSize); break; case WindowState.Normal: if (WindowState == WindowState.Maximized) { idealSize = new CarbonPoint(); API.ZoomWindowIdeal(window.WindowRef, WindowPartCode.inZoomIn, ref idealSize); } break; case WindowState.Minimized: API.CollapseWindow(window.WindowRef, true); break; } WindowStateChanged(this, EventArgs.Empty); LoadSize(); Resize(this, EventArgs.Empty); } public WindowBorder WindowBorder { get { return windowBorder; } set { if (windowBorder == value) return; windowBorder = value; if (windowBorder == WindowBorder.Resizable) { API.ChangeWindowAttributes(window.WindowRef, WindowAttributes.Resizable | WindowAttributes.FullZoom, WindowAttributes.NoAttributes); } else if (windowBorder == WindowBorder.Fixed) { API.ChangeWindowAttributes(window.WindowRef, WindowAttributes.NoAttributes, WindowAttributes.Resizable | WindowAttributes.FullZoom); } WindowBorderChanged(this, EventArgs.Empty); } } #region --- Event wrappers --- private void OnKeyPress(KeyPressEventArgs keyPressArgs) { KeyPress(this, keyPressArgs); } private void OnWindowStateChanged() { WindowStateChanged(this, EventArgs.Empty); } protected virtual void OnClosing(CancelEventArgs e) { Closing(this, e); } protected virtual void OnClosed() { Closed(this, EventArgs.Empty); } private void OnMouseLeave() { MouseLeave(this, EventArgs.Empty); } private void OnMouseEnter() { MouseEnter(this, EventArgs.Empty); } private void OnActivate() { mIsActive = true; FocusedChanged(this, EventArgs.Empty); } private void OnDeactivate() { mIsActive = false; FocusedChanged(this, EventArgs.Empty); } #endregion public event EventHandler<EventArgs> Move = delegate { }; public event EventHandler<EventArgs> Resize = delegate { }; public event EventHandler<CancelEventArgs> Closing = delegate { }; public event EventHandler<EventArgs> Closed = delegate { }; public event EventHandler<EventArgs> Disposed = delegate { }; public event EventHandler<EventArgs> IconChanged = delegate { }; public event EventHandler<EventArgs> TitleChanged = delegate { }; public event EventHandler<EventArgs> VisibleChanged = delegate { }; public event EventHandler<EventArgs> FocusedChanged = delegate { }; public event EventHandler<EventArgs> WindowBorderChanged = delegate { }; public event EventHandler<EventArgs> WindowStateChanged = delegate { }; public event EventHandler<OpenTK.Input.KeyboardKeyEventArgs> KeyDown = delegate { }; public event EventHandler<KeyPressEventArgs> KeyPress = delegate { }; public event EventHandler<OpenTK.Input.KeyboardKeyEventArgs> KeyUp = delegate { }; public event EventHandler<EventArgs> MouseEnter = delegate { }; public event EventHandler<EventArgs> MouseLeave = delegate { }; #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using Xunit; namespace System.Text.RegularExpressions.Tests { public class RegexMatchTests : RemoteExecutorTestBase { public static IEnumerable<object[]> Match_Basic_TestData() { // Testing octal sequence matches: "\\060(\\061)?\\061" // Octal \061 is ASCII 49 ('1') yield return new object[] { @"\060(\061)?\061", "011", RegexOptions.None, 0, 3, true, "011" }; // Testing hexadecimal sequence matches: "(\\x30\\x31\\x32)" // Hex \x31 is ASCII 49 ('1') yield return new object[] { @"(\x30\x31\x32)", "012", RegexOptions.None, 0, 3, true, "012" }; // Testing control character escapes???: "2", "(\u0032)" yield return new object[] { "(\u0034)", "4", RegexOptions.None, 0, 1, true, "4", }; // Using *, +, ?, {}: Actual - "a+\\.?b*\\.?c{2}" yield return new object[] { @"a+\.?b*\.+c{2}", "ab.cc", RegexOptions.None, 0, 5, true, "ab.cc" }; // Using [a-z], \s, \w: Actual - "([a-zA-Z]+)\\s(\\w+)" yield return new object[] { @"([a-zA-Z]+)\s(\w+)", "David Bau", RegexOptions.None, 0, 9, true, "David Bau" }; // \\S, \\d, \\D, \\W: Actual - "(\\S+):\\W(\\d+)\\s(\\D+)" yield return new object[] { @"(\S+):\W(\d+)\s(\D+)", "Price: 5 dollars", RegexOptions.None, 0, 16, true, "Price: 5 dollars" }; // \\S, \\d, \\D, \\W: Actual - "[^0-9]+(\\d+)" yield return new object[] { @"[^0-9]+(\d+)", "Price: 30 dollars", RegexOptions.None, 0, 17, true, "Price: 30" }; // Zero-width negative lookahead assertion: Actual - "abc(?!XXX)\\w+" yield return new object[] { @"abc(?!XXX)\w+", "abcXXXdef", RegexOptions.None, 0, 9, false, string.Empty }; // Zero-width positive lookbehind assertion: Actual - "(\\w){6}(?<=XXX)def" yield return new object[] { @"(\w){6}(?<=XXX)def", "abcXXXdef", RegexOptions.None, 0, 9, true, "abcXXXdef" }; // Zero-width negative lookbehind assertion: Actual - "(\\w){6}(?<!XXX)def" yield return new object[] { @"(\w){6}(?<!XXX)def", "XXXabcdef", RegexOptions.None, 0, 9, true, "XXXabcdef" }; // Nonbacktracking subexpression: Actual - "[^0-9]+(?>[0-9]+)3" // The last 3 causes the match to fail, since the non backtracking subexpression does not give up the last digit it matched // for it to be a success. For a correct match, remove the last character, '3' from the pattern yield return new object[] { "[^0-9]+(?>[0-9]+)3", "abc123", RegexOptions.None, 0, 6, false, string.Empty }; // Using beginning/end of string chars \A, \Z: Actual - "\\Aaaa\\w+zzz\\Z" yield return new object[] { @"\Aaaa\w+zzz\Z", "aaaasdfajsdlfjzzz", RegexOptions.None, 0, 17, true, "aaaasdfajsdlfjzzz" }; // Using beginning/end of string chars \A, \Z: Actual - "\\Aaaa\\w+zzz\\Z" yield return new object[] { @"\Aaaa\w+zzz\Z", "aaaasdfajsdlfjzzza", RegexOptions.None, 0, 18, false, string.Empty }; // Using beginning/end of string chars \A, \Z: Actual - "\\Aaaa\\w+zzz\\Z" yield return new object[] { @"\A(line2\n)line3\Z", "line2\nline3\n", RegexOptions.Multiline, 0, 12, true, "line2\nline3" }; // Using beginning/end of string chars ^: Actual - "^b" yield return new object[] { "^b", "ab", RegexOptions.None, 0, 2, false, string.Empty }; // Actual - "(?<char>\\w)\\<char>" yield return new object[] { @"(?<char>\w)\<char>", "aa", RegexOptions.None, 0, 2, true, "aa" }; // Actual - "(?<43>\\w)\\43" yield return new object[] { @"(?<43>\w)\43", "aa", RegexOptions.None, 0, 2, true, "aa" }; // Actual - "abc(?(1)111|222)" yield return new object[] { "(abbc)(?(1)111|222)", "abbc222", RegexOptions.None, 0, 7, false, string.Empty }; // "x" option. Removes unescaped whitespace from the pattern: Actual - " ([^/]+) ","x" yield return new object[] { " ((.)+) ", "abc", RegexOptions.IgnorePatternWhitespace, 0, 3, true, "abc" }; // "x" option. Removes unescaped whitespace from the pattern. : Actual - "\x20([^/]+)\x20","x" yield return new object[] { "\x20([^/]+)\x20\x20\x20\x20\x20\x20\x20", " abc ", RegexOptions.IgnorePatternWhitespace, 0, 10, true, " abc " }; // Turning on case insensitive option in mid-pattern : Actual - "aaa(?i:match this)bbb" if ("i".ToUpper() == "I") { yield return new object[] { "aaa(?i:match this)bbb", "aaaMaTcH ThIsbbb", RegexOptions.None, 0, 16, true, "aaaMaTcH ThIsbbb" }; } // Turning off case insensitive option in mid-pattern : Actual - "aaa(?-i:match this)bbb", "i" yield return new object[] { "aaa(?-i:match this)bbb", "AaAmatch thisBBb", RegexOptions.IgnoreCase, 0, 16, true, "AaAmatch thisBBb" }; // Turning on/off all the options at once : Actual - "aaa(?imnsx-imnsx:match this)bbb", "i" yield return new object[] { "aaa(?-i:match this)bbb", "AaAmatcH thisBBb", RegexOptions.IgnoreCase, 0, 16, false, string.Empty }; // Actual - "aaa(?#ignore this completely)bbb" yield return new object[] { "aaa(?#ignore this completely)bbb", "aaabbb", RegexOptions.None, 0, 6, true, "aaabbb" }; // Trying empty string: Actual "[a-z0-9]+", "" yield return new object[] { "[a-z0-9]+", "", RegexOptions.None, 0, 0, false, string.Empty }; // Numbering pattern slots: "(?<1>\\d{3})(?<2>\\d{3})(?<3>\\d{4})" yield return new object[] { @"(?<1>\d{3})(?<2>\d{3})(?<3>\d{4})", "8885551111", RegexOptions.None, 0, 10, true, "8885551111" }; yield return new object[] { @"(?<1>\d{3})(?<2>\d{3})(?<3>\d{4})", "Invalid string", RegexOptions.None, 0, 14, false, string.Empty }; // Not naming pattern slots at all: "^(cat|chat)" yield return new object[] { "^(cat|chat)", "cats are bad", RegexOptions.None, 0, 12, true, "cat" }; yield return new object[] { "abc", "abc", RegexOptions.None, 0, 3, true, "abc" }; yield return new object[] { "abc", "aBc", RegexOptions.None, 0, 3, false, string.Empty }; yield return new object[] { "abc", "aBc", RegexOptions.IgnoreCase, 0, 3, true, "aBc" }; // Using *, +, ?, {}: Actual - "a+\\.?b*\\.?c{2}" yield return new object[] { @"a+\.?b*\.+c{2}", "ab.cc", RegexOptions.None, 0, 5, true, "ab.cc" }; // RightToLeft yield return new object[] { @"\s+\d+", "sdf 12sad", RegexOptions.RightToLeft, 0, 9, true, " 12" }; yield return new object[] { @"\s+\d+", " asdf12 ", RegexOptions.RightToLeft, 0, 6, false, string.Empty }; yield return new object[] { "aaa", "aaabbb", RegexOptions.None, 3, 3, false, string.Empty }; yield return new object[] { @"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 10, 3, false, string.Empty }; yield return new object[] { @"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 11, 21, false, string.Empty }; // IgnoreCase yield return new object[] { "AAA", "aaabbb", RegexOptions.IgnoreCase, 0, 6, true, "aaa" }; yield return new object[] { @"\p{Lu}", "1bc", RegexOptions.IgnoreCase, 0, 3, true, "b" }; yield return new object[] { @"\p{Ll}", "1bc", RegexOptions.IgnoreCase, 0, 3, true, "b" }; yield return new object[] { @"\p{Lt}", "1bc", RegexOptions.IgnoreCase, 0, 3, true, "b" }; yield return new object[] { @"\p{Lo}", "1bc", RegexOptions.IgnoreCase, 0, 3, false, string.Empty }; // "\D+" yield return new object[] { @"\D+", "12321", RegexOptions.None, 0, 5, false, string.Empty }; // Groups yield return new object[] { "(?<first_name>\\S+)\\s(?<last_name>\\S+)", "David Bau", RegexOptions.None, 0, 9, true, "David Bau" }; // "^b" yield return new object[] { "^b", "abc", RegexOptions.None, 0, 3, false, string.Empty }; // RightToLeft yield return new object[] { @"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 0, 32, true, "foo4567890" }; yield return new object[] { @"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 10, 22, true, "foo4567890" }; yield return new object[] { @"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 10, 4, true, "foo4" }; // Trim leading and trailing whitespace yield return new object[] { @"\s*(.*?)\s*$", " Hello World ", RegexOptions.None, 0, 13, true, " Hello World " }; // < in group yield return new object[] { @"(?<cat>cat)\w+(?<dog-0>dog)", "cat_Hello_World_dog", RegexOptions.None, 0, 19, false, string.Empty }; // Atomic Zero-Width Assertions \A \Z \z \G \b \B yield return new object[] { @"\A(cat)\s+(dog)", "cat \n\n\ncat dog", RegexOptions.None, 0, 20, false, string.Empty }; yield return new object[] { @"\A(cat)\s+(dog)", "cat \n\n\ncat dog", RegexOptions.Multiline, 0, 20, false, string.Empty }; yield return new object[] { @"\A(cat)\s+(dog)", "cat \n\n\ncat dog", RegexOptions.ECMAScript, 0, 20, false, string.Empty }; yield return new object[] { @"(cat)\s+(dog)\Z", "cat dog\n\n\ncat", RegexOptions.None, 0, 15, false, string.Empty }; yield return new object[] { @"(cat)\s+(dog)\Z", "cat dog\n\n\ncat ", RegexOptions.Multiline, 0, 20, false, string.Empty }; yield return new object[] { @"(cat)\s+(dog)\Z", "cat dog\n\n\ncat ", RegexOptions.ECMAScript, 0, 20, false, string.Empty }; yield return new object[] { @"(cat)\s+(dog)\z", "cat dog\n\n\ncat", RegexOptions.None, 0, 15, false, string.Empty }; yield return new object[] { @"(cat)\s+(dog)\z", "cat dog\n\n\ncat ", RegexOptions.Multiline, 0, 20, false, string.Empty }; yield return new object[] { @"(cat)\s+(dog)\z", "cat dog\n\n\ncat ", RegexOptions.ECMAScript, 0, 20, false, string.Empty }; yield return new object[] { @"(cat)\s+(dog)\z", "cat \n\n\n dog\n", RegexOptions.None, 0, 16, false, string.Empty }; yield return new object[] { @"(cat)\s+(dog)\z", "cat \n\n\n dog\n", RegexOptions.Multiline, 0, 16, false, string.Empty }; yield return new object[] { @"(cat)\s+(dog)\z", "cat \n\n\n dog\n", RegexOptions.ECMAScript, 0, 16, false, string.Empty }; yield return new object[] { @"\b@cat", "123START123;@catEND", RegexOptions.None, 0, 19, false, string.Empty }; yield return new object[] { @"\b<cat", "123START123'<catEND", RegexOptions.None, 0, 19, false, string.Empty }; yield return new object[] { @"\b,cat", "satwe,,,START',catEND", RegexOptions.None, 0, 21, false, string.Empty }; yield return new object[] { @"\b\[cat", "`12START123'[catEND", RegexOptions.None, 0, 19, false, string.Empty }; yield return new object[] { @"\B@cat", "123START123@catEND", RegexOptions.None, 0, 18, false, string.Empty }; yield return new object[] { @"\B<cat", "123START123<catEND", RegexOptions.None, 0, 18, false, string.Empty }; yield return new object[] { @"\B,cat", "satwe,,,START,catEND", RegexOptions.None, 0, 20, false, string.Empty }; yield return new object[] { @"\B\[cat", "`12START123[catEND", RegexOptions.None, 0, 18, false, string.Empty }; // Lazy operator Backtracking yield return new object[] { @"http://([a-zA-z0-9\-]*\.?)*?(:[0-9]*)??/", "http://www.msn.com", RegexOptions.IgnoreCase, 0, 18, false, string.Empty }; // Grouping Constructs Invalid Regular Expressions yield return new object[] { "(?!)", "(?!)cat", RegexOptions.None, 0, 7, false, string.Empty }; yield return new object[] { "(?<!)", "(?<!)cat", RegexOptions.None, 0, 8, false, string.Empty }; // Alternation construct yield return new object[] { "(?(cat)|dog)", "cat", RegexOptions.None, 0, 3, true, string.Empty }; yield return new object[] { "(?(cat)|dog)", "catdog", RegexOptions.None, 0, 6, true, string.Empty }; yield return new object[] { "(?(cat)dog1|dog2)", "catdog1", RegexOptions.None, 0, 7, false, string.Empty }; yield return new object[] { "(?(cat)dog1|dog2)", "catdog2", RegexOptions.None, 0, 7, true, "dog2" }; yield return new object[] { "(?(cat)dog1|dog2)", "catdog1dog2", RegexOptions.None, 0, 11, true, "dog2" }; yield return new object[] { "(?(dog2))", "dog2", RegexOptions.None, 0, 4, true, string.Empty }; yield return new object[] { "(?(cat)|dog)", "oof", RegexOptions.None, 0, 3, false, string.Empty }; yield return new object[] { "(?(a:b))", "a", RegexOptions.None, 0, 1, true, string.Empty }; yield return new object[] { "(?(a:))", "a", RegexOptions.None, 0, 1, true, string.Empty }; // No Negation yield return new object[] { "[abcd-[abcd]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { "[1234-[1234]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; // All Negation yield return new object[] { "[^abcd-[^abcd]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { "[^1234-[^1234]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; // No Negation yield return new object[] { "[a-z-[a-z]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { "[0-9-[0-9]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; // All Negation yield return new object[] { "[^a-z-[^a-z]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { "[^0-9-[^0-9]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; // No Negation yield return new object[] { @"[\w-[\w]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\W-[\W]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\s-[\s]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\S-[\S]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\d-[\d]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\D-[\D]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; // All Negation yield return new object[] { @"[^\w-[^\w]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[^\W-[^\W]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[^\s-[^\s]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[^\S-[^\S]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[^\d-[^\d]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[^\D-[^\D]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; // MixedNegation yield return new object[] { @"[^\w-[\W]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\w-[^\W]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[^\s-[\S]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\s-[^\S]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[^\d-[\D]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\d-[^\D]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; // No Negation yield return new object[] { @"[\p{Ll}-[\p{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\P{Ll}-[\P{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\p{Lu}-[\p{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\P{Lu}-[\P{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\p{Nd}-[\p{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\P{Nd}-[\P{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; // All Negation yield return new object[] { @"[^\p{Ll}-[^\p{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[^\P{Ll}-[^\P{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[^\p{Lu}-[^\p{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[^\P{Lu}-[^\P{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[^\p{Nd}-[^\p{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[^\P{Nd}-[^\P{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; // MixedNegation yield return new object[] { @"[^\p{Ll}-[\P{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\p{Ll}-[^\P{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[^\p{Lu}-[\P{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\p{Lu}-[^\P{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[^\p{Nd}-[\P{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\p{Nd}-[^\P{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; // Character Class Substraction yield return new object[] { @"[ab\-\[cd-[-[]]]]", "[]]", RegexOptions.None, 0, 3, false, string.Empty }; yield return new object[] { @"[ab\-\[cd-[-[]]]]", "-]]", RegexOptions.None, 0, 3, false, string.Empty }; yield return new object[] { @"[ab\-\[cd-[-[]]]]", "`]]", RegexOptions.None, 0, 3, false, string.Empty }; yield return new object[] { @"[ab\-\[cd-[-[]]]]", "e]]", RegexOptions.None, 0, 3, false, string.Empty }; yield return new object[] { @"[ab\-\[cd-[[]]]]", "']]", RegexOptions.None, 0, 3, false, string.Empty }; yield return new object[] { @"[ab\-\[cd-[[]]]]", "e]]", RegexOptions.None, 0, 3, false, string.Empty }; yield return new object[] { @"[a-[a-f]]", "abcdefghijklmnopqrstuvwxyz", RegexOptions.None, 0, 26, false, string.Empty }; // \c if (!PlatformDetection.IsFullFramework) // missing fix for #26501 yield return new object[] { @"(cat)(\c[*)(dog)", "asdlkcat\u00FFdogiwod", RegexOptions.None, 0, 15, false, string.Empty }; } [Theory] [MemberData(nameof(Match_Basic_TestData))] [MemberData(nameof(RegexCompilationHelper.TransformRegexOptions), nameof(Match_Basic_TestData), 2, MemberType = typeof(RegexCompilationHelper))] public void Match(string pattern, string input, RegexOptions options, int beginning, int length, bool expectedSuccess, string expectedValue) { bool isDefaultStart = RegexHelpers.IsDefaultStart(input, options, beginning); bool isDefaultCount = RegexHelpers.IsDefaultCount(input, options, length); if (options == RegexOptions.None) { if (isDefaultStart && isDefaultCount) { // Use Match(string) or Match(string, string) VerifyMatch(new Regex(pattern).Match(input), expectedSuccess, expectedValue); VerifyMatch(Regex.Match(input, pattern), expectedSuccess, expectedValue); Assert.Equal(expectedSuccess, new Regex(pattern).IsMatch(input)); Assert.Equal(expectedSuccess, Regex.IsMatch(input, pattern)); } if (beginning + length == input.Length) { // Use Match(string, int) VerifyMatch(new Regex(pattern).Match(input, beginning), expectedSuccess, expectedValue); Assert.Equal(expectedSuccess, new Regex(pattern).IsMatch(input, beginning)); } // Use Match(string, int, int) VerifyMatch(new Regex(pattern).Match(input, beginning, length), expectedSuccess, expectedValue); } if (isDefaultStart && isDefaultCount) { // Use Match(string) or Match(string, string, RegexOptions) VerifyMatch(new Regex(pattern, options).Match(input), expectedSuccess, expectedValue); VerifyMatch(Regex.Match(input, pattern, options), expectedSuccess, expectedValue); Assert.Equal(expectedSuccess, Regex.IsMatch(input, pattern, options)); } if (beginning + length == input.Length && (options & RegexOptions.RightToLeft) == 0) { // Use Match(string, int) VerifyMatch(new Regex(pattern, options).Match(input, beginning), expectedSuccess, expectedValue); } // Use Match(string, int, int) VerifyMatch(new Regex(pattern, options).Match(input, beginning, length), expectedSuccess, expectedValue); } public static void VerifyMatch(Match match, bool expectedSuccess, string expectedValue) { Assert.Equal(expectedSuccess, match.Success); Assert.Equal(expectedValue, match.Value); // Groups can never be empty Assert.True(match.Groups.Count >= 1); Assert.Equal(expectedSuccess, match.Groups[0].Success); Assert.Equal(expectedValue, match.Groups[0].Value); } [Fact] public void Match_Timeout() { Regex regex = new Regex(@"\p{Lu}", RegexOptions.IgnoreCase, TimeSpan.FromHours(1)); Match match = regex.Match("abc"); Assert.True(match.Success); Assert.Equal("a", match.Value); } [Fact] public void Match_Timeout_Throws() { RemoteInvoke(() => { const string Pattern = @"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@(([0-9a-zA-Z])+([-\w]*[0-9a-zA-Z])*\.)+[a-zA-Z]{2,9})$"; string input = new string('a', 50) + "@a.a"; AppDomain.CurrentDomain.SetData(RegexHelpers.DefaultMatchTimeout_ConfigKeyName, TimeSpan.FromMilliseconds(100)); Assert.Throws<RegexMatchTimeoutException>(() => new Regex(Pattern).Match(input)); return SuccessExitCode; }).Dispose(); } public static IEnumerable<object[]> Match_Advanced_TestData() { // \B special character escape: ".*\\B(SUCCESS)\\B.*" yield return new object[] { @".*\B(SUCCESS)\B.*", "adfadsfSUCCESSadsfadsf", RegexOptions.None, 0, 22, new CaptureData[] { new CaptureData("adfadsfSUCCESSadsfadsf", 0, 22), new CaptureData("SUCCESS", 7, 7) } }; // Using |, (), ^, $, .: Actual - "^aaa(bb.+)(d|c)$" yield return new object[] { "^aaa(bb.+)(d|c)$", "aaabb.cc", RegexOptions.None, 0, 8, new CaptureData[] { new CaptureData("aaabb.cc", 0, 8), new CaptureData("bb.c", 3, 4), new CaptureData("c", 7, 1) } }; // Using greedy quantifiers: Actual - "(a+)(b*)(c?)" yield return new object[] { "(a+)(b*)(c?)", "aaabbbccc", RegexOptions.None, 0, 9, new CaptureData[] { new CaptureData("aaabbbc", 0, 7), new CaptureData("aaa", 0, 3), new CaptureData("bbb", 3, 3), new CaptureData("c", 6, 1) } }; // Using lazy quantifiers: Actual - "(d+?)(e*?)(f??)" // Interesting match from this pattern and input. If needed to go to the end of the string change the ? to + in the last lazy quantifier yield return new object[] { "(d+?)(e*?)(f??)", "dddeeefff", RegexOptions.None, 0, 9, new CaptureData[] { new CaptureData("d", 0, 1), new CaptureData("d", 0, 1), new CaptureData(string.Empty, 1, 0), new CaptureData(string.Empty, 1, 0) } }; // Noncapturing group : Actual - "(a+)(?:b*)(ccc)" yield return new object[] { "(a+)(?:b*)(ccc)", "aaabbbccc", RegexOptions.None, 0, 9, new CaptureData[] { new CaptureData("aaabbbccc", 0, 9), new CaptureData("aaa", 0, 3), new CaptureData("ccc", 6, 3), } }; // Zero-width positive lookahead assertion: Actual - "abc(?=XXX)\\w+" yield return new object[] { @"abc(?=XXX)\w+", "abcXXXdef", RegexOptions.None, 0, 9, new CaptureData[] { new CaptureData("abcXXXdef", 0, 9) } }; // Backreferences : Actual - "(\\w)\\1" yield return new object[] { @"(\w)\1", "aa", RegexOptions.None, 0, 2, new CaptureData[] { new CaptureData("aa", 0, 2), new CaptureData("a", 0, 1), } }; // Alternation constructs: Actual - "(111|aaa)" yield return new object[] { "(111|aaa)", "aaa", RegexOptions.None, 0, 3, new CaptureData[] { new CaptureData("aaa", 0, 3), new CaptureData("aaa", 0, 3) } }; // Actual - "(?<1>\\d+)abc(?(1)222|111)" yield return new object[] { @"(?<MyDigits>\d+)abc(?(MyDigits)222|111)", "111abc222", RegexOptions.None, 0, 9, new CaptureData[] { new CaptureData("111abc222", 0, 9), new CaptureData("111", 0, 3) } }; // Using "n" Regex option. Only explicitly named groups should be captured: Actual - "([0-9]*)\\s(?<s>[a-z_A-Z]+)", "n" yield return new object[] { @"([0-9]*)\s(?<s>[a-z_A-Z]+)", "200 dollars", RegexOptions.ExplicitCapture, 0, 11, new CaptureData[] { new CaptureData("200 dollars", 0, 11), new CaptureData("dollars", 4, 7) } }; // Single line mode "s". Includes new line character: Actual - "([^/]+)","s" yield return new object[] { "(.*)", "abc\nsfc", RegexOptions.Singleline, 0, 7, new CaptureData[] { new CaptureData("abc\nsfc", 0, 7), new CaptureData("abc\nsfc", 0, 7), } }; // "([0-9]+(\\.[0-9]+){3})" yield return new object[] { @"([0-9]+(\.[0-9]+){3})", "209.25.0.111", RegexOptions.None, 0, 12, new CaptureData[] { new CaptureData("209.25.0.111", 0, 12), new CaptureData("209.25.0.111", 0, 12), new CaptureData(".111", 8, 4, new CaptureData[] { new CaptureData(".25", 3, 3), new CaptureData(".0", 6, 2), new CaptureData(".111", 8, 4), }), } }; // Groups and captures yield return new object[] { @"(?<A1>a*)(?<A2>b*)(?<A3>c*)", "aaabbccccccccccaaaabc", RegexOptions.None, 0, 21, new CaptureData[] { new CaptureData("aaabbcccccccccc", 0, 15), new CaptureData("aaa", 0, 3), new CaptureData("bb", 3, 2), new CaptureData("cccccccccc", 5, 10) } }; yield return new object[] { @"(?<A1>A*)(?<A2>B*)(?<A3>C*)", "aaabbccccccccccaaaabc", RegexOptions.IgnoreCase, 0, 21, new CaptureData[] { new CaptureData("aaabbcccccccccc", 0, 15), new CaptureData("aaa", 0, 3), new CaptureData("bb", 3, 2), new CaptureData("cccccccccc", 5, 10) } }; // Using |, (), ^, $, .: Actual - "^aaa(bb.+)(d|c)$" yield return new object[] { "^aaa(bb.+)(d|c)$", "aaabb.cc", RegexOptions.None, 0, 8, new CaptureData[] { new CaptureData("aaabb.cc", 0, 8), new CaptureData("bb.c", 3, 4), new CaptureData("c", 7, 1) } }; // Actual - ".*\\b(\\w+)\\b" yield return new object[] { @".*\b(\w+)\b", "XSP_TEST_FAILURE SUCCESS", RegexOptions.None, 0, 24, new CaptureData[] { new CaptureData("XSP_TEST_FAILURE SUCCESS", 0, 24), new CaptureData("SUCCESS", 17, 7) } }; // Mutliline yield return new object[] { "(line2$\n)line3", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24, new CaptureData[] { new CaptureData("line2\nline3", 6, 11), new CaptureData("line2\n", 6, 6) } }; // Mutliline yield return new object[] { "(line2\n^)line3", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24, new CaptureData[] { new CaptureData("line2\nline3", 6, 11), new CaptureData("line2\n", 6, 6) } }; // Mutliline yield return new object[] { "(line3\n$\n)line4", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24, new CaptureData[] { new CaptureData("line3\n\nline4", 12, 12), new CaptureData("line3\n\n", 12, 7) } }; // Mutliline yield return new object[] { "(line3\n^\n)line4", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24, new CaptureData[] { new CaptureData("line3\n\nline4", 12, 12), new CaptureData("line3\n\n", 12, 7) } }; // Mutliline yield return new object[] { "(line2$\n^)line3", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24, new CaptureData[] { new CaptureData("line2\nline3", 6, 11), new CaptureData("line2\n", 6, 6) } }; // RightToLeft yield return new object[] { "aaa", "aaabbb", RegexOptions.RightToLeft, 3, 3, new CaptureData[] { new CaptureData("aaa", 0, 3) } }; } [Theory] [MemberData(nameof(Match_Advanced_TestData))] public void Match(string pattern, string input, RegexOptions options, int beginning, int length, CaptureData[] expected) { bool isDefaultStart = RegexHelpers.IsDefaultStart(input, options, beginning); bool isDefaultCount = RegexHelpers.IsDefaultStart(input, options, length); if (options == RegexOptions.None) { if (isDefaultStart && isDefaultCount) { // Use Match(string) or Match(string, string) VerifyMatch(new Regex(pattern).Match(input), true, expected); VerifyMatch(Regex.Match(input, pattern), true, expected); Assert.True(new Regex(pattern).IsMatch(input)); Assert.True(Regex.IsMatch(input, pattern)); } if (beginning + length == input.Length) { // Use Match(string, int) VerifyMatch(new Regex(pattern).Match(input, beginning), true, expected); Assert.True(new Regex(pattern).IsMatch(input, beginning)); } else { // Use Match(string, int, int) VerifyMatch(new Regex(pattern).Match(input, beginning, length), true, expected); } } if (isDefaultStart && isDefaultCount) { // Use Match(string) or Match(string, string, RegexOptions) VerifyMatch(new Regex(pattern, options).Match(input), true, expected); VerifyMatch(Regex.Match(input, pattern, options), true, expected); Assert.True(Regex.IsMatch(input, pattern, options)); } if (beginning + length == input.Length) { // Use Match(string, int) VerifyMatch(new Regex(pattern, options).Match(input, beginning), true, expected); } if ((options & RegexOptions.RightToLeft) == 0) { // Use Match(string, int, int) VerifyMatch(new Regex(pattern, options).Match(input, beginning, length), true, expected); } } public static void VerifyMatch(Match match, bool expectedSuccess, CaptureData[] expected) { Assert.Equal(expectedSuccess, match.Success); Assert.Equal(expected[0].Value, match.Value); Assert.Equal(expected[0].Index, match.Index); Assert.Equal(expected[0].Length, match.Length); Assert.Equal(1, match.Captures.Count); Assert.Equal(expected[0].Value, match.Captures[0].Value); Assert.Equal(expected[0].Index, match.Captures[0].Index); Assert.Equal(expected[0].Length, match.Captures[0].Length); Assert.Equal(expected.Length, match.Groups.Count); for (int i = 0; i < match.Groups.Count; i++) { Assert.Equal(expectedSuccess, match.Groups[i].Success); Assert.Equal(expected[i].Value, match.Groups[i].Value); Assert.Equal(expected[i].Index, match.Groups[i].Index); Assert.Equal(expected[i].Length, match.Groups[i].Length); Assert.Equal(expected[i].Captures.Length, match.Groups[i].Captures.Count); for (int j = 0; j < match.Groups[i].Captures.Count; j++) { Assert.Equal(expected[i].Captures[j].Value, match.Groups[i].Captures[j].Value); Assert.Equal(expected[i].Captures[j].Index, match.Groups[i].Captures[j].Index); Assert.Equal(expected[i].Captures[j].Length, match.Groups[i].Captures[j].Length); } } } [Theory] [InlineData(@"(?<1>\d{1,2})/(?<2>\d{1,2})/(?<3>\d{2,4})\s(?<time>\S+)", "08/10/99 16:00", "${time}", "16:00")] [InlineData(@"(?<1>\d{1,2})/(?<2>\d{1,2})/(?<3>\d{2,4})\s(?<time>\S+)", "08/10/99 16:00", "${1}", "08")] [InlineData(@"(?<1>\d{1,2})/(?<2>\d{1,2})/(?<3>\d{2,4})\s(?<time>\S+)", "08/10/99 16:00", "${2}", "10")] [InlineData(@"(?<1>\d{1,2})/(?<2>\d{1,2})/(?<3>\d{2,4})\s(?<time>\S+)", "08/10/99 16:00", "${3}", "99")] [InlineData("abc", "abc", "abc", "abc")] public void Result(string pattern, string input, string replacement, string expected) { Assert.Equal(expected, new Regex(pattern).Match(input).Result(replacement)); } [Fact] public void Result_Invalid() { Match match = Regex.Match("foo", "foo"); AssertExtensions.Throws<ArgumentNullException>("replacement", () => match.Result(null)); Assert.Throws<NotSupportedException>(() => RegularExpressions.Match.Empty.Result("any")); } [Fact] public void Match_SpecialUnicodeCharacters_enUS() { RemoteInvoke(() => { CultureInfo.CurrentCulture = new CultureInfo("en-US"); Match("\u0131", "\u0049", RegexOptions.IgnoreCase, 0, 1, false, string.Empty); Match("\u0131", "\u0069", RegexOptions.IgnoreCase, 0, 1, false, string.Empty); return SuccessExitCode; }).Dispose(); } [Fact] public void Match_SpecialUnicodeCharacters_Invariant() { RemoteInvoke(() => { CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Match("\u0131", "\u0049", RegexOptions.IgnoreCase, 0, 1, false, string.Empty); Match("\u0131", "\u0069", RegexOptions.IgnoreCase, 0, 1, false, string.Empty); Match("\u0130", "\u0049", RegexOptions.IgnoreCase, 0, 1, false, string.Empty); Match("\u0130", "\u0069", RegexOptions.IgnoreCase, 0, 1, false, string.Empty); return SuccessExitCode; }).Dispose(); } [Fact] public void Match_Invalid() { // Input is null AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Match(null, "pattern")); AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Match(null, "pattern", RegexOptions.None)); AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Match(null, "pattern", RegexOptions.None, TimeSpan.FromSeconds(1))); AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").Match(null)); AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").Match(null, 0)); AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").Match(null, 0, 0)); // Pattern is null AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Match("input", null)); AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Match("input", null, RegexOptions.None)); AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Match("input", null, RegexOptions.None, TimeSpan.FromSeconds(1))); // Start is invalid Assert.Throws<ArgumentOutOfRangeException>(() => new Regex("pattern").Match("input", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => new Regex("pattern").Match("input", -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => new Regex("pattern").Match("input", 6)); Assert.Throws<ArgumentOutOfRangeException>(() => new Regex("pattern").Match("input", 6, 0)); // Length is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => new Regex("pattern").Match("input", 0, -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => new Regex("pattern").Match("input", 0, 6)); } [Theory] [InlineData(")")] [InlineData("())")] [InlineData("[a-z-[aeiuo]")] [InlineData("[a-z-[aeiuo")] [InlineData("[a-z-[b]")] [InlineData("[a-z-[b")] [InlineData("[b-a]")] [InlineData(@"[a-c]{2,1}")] [InlineData(@"\d{2147483648}")] [InlineData("[a-z-[b][")] [InlineData(@"\")] [InlineData("(?()|||||)")] public void Match_InvalidPattern(string pattern) { AssertExtensions.Throws<ArgumentException>(null, () => Regex.Match("input", pattern)); } [Fact] public void IsMatch_Invalid() { // Input is null AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.IsMatch(null, "pattern")); AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.IsMatch(null, "pattern", RegexOptions.None)); AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.IsMatch(null, "pattern", RegexOptions.None, TimeSpan.FromSeconds(1))); AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").IsMatch(null)); AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").IsMatch(null, 0)); // Pattern is null AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.IsMatch("input", null)); AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.IsMatch("input", null, RegexOptions.None)); AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.IsMatch("input", null, RegexOptions.None, TimeSpan.FromSeconds(1))); // Start is invalid Assert.Throws<ArgumentOutOfRangeException>(() => new Regex("pattern").IsMatch("input", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => new Regex("pattern").IsMatch("input", 6)); } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Runtime.Versioning; using NuGet.Resources; using NuGet.V3Interop; namespace NuGet { public static class PackageRepositoryExtensions { public static IPackage FindPackage( this IPackageRepository repository, string packageId, SemanticVersion version, IPackageConstraintProvider constraintProvider, bool allowPrereleaseVersions, bool allowUnlisted) { if (repository == null) { throw new ArgumentNullException("repository"); } if (packageId == null) { throw new ArgumentNullException("packageId"); } // if an explicit version is specified, disregard the 'allowUnlisted' argument // and always allow unlisted packages. if (version != null) { allowUnlisted = true; } else if (!allowUnlisted && (constraintProvider == null || constraintProvider == NullConstraintProvider.Instance)) { var packageLatestLookup = repository as ILatestPackageLookup; if (packageLatestLookup != null) { IPackage package; if (packageLatestLookup.TryFindLatestPackageById(packageId, allowPrereleaseVersions, out package)) { return package; } } } // If the repository implements it's own lookup then use that instead. // This is an optimization that we use so we don't have to enumerate packages for // sources that don't need to. var packageLookup = repository as IPackageLookup; if (packageLookup != null && version != null) { return packageLookup.FindPackage(packageId, version); } IEnumerable<IPackage> packages = repository.FindPackagesById(packageId); packages = packages.ToList() .OrderByDescending(p => p.Version); if (!allowUnlisted) { packages = packages.Where(PackageExtensions.IsListed); } if (version != null) { packages = packages.Where(p => p.Version == version); } else if (constraintProvider != null) { packages = FilterPackagesByConstraints(constraintProvider, packages, packageId, allowPrereleaseVersions); } return packages.FirstOrDefault(); } public static IDisposable StartOperation(this IPackageRepository self, string operation, string mainPackageId, string mainPackageVersion) { var packages = repository.FindPackages(packageId, versionSpec, allowPrereleaseVersions, allowUnlisted); if (constraintProvider != null) { packages = FilterPackagesByConstraints(constraintProvider, packages, packageId, allowPrereleaseVersions); } IOperationAwareRepository repo = self as IOperationAwareRepository; if (repo != null) { return repo.StartOperation(operation, mainPackageId, mainPackageVersion); } return DisposableAction.NoOp; } public static bool Exists(this IPackageRepository repository, IPackageName package) { return repository.Exists(package.Id, package.Version); } public static bool Exists(this IPackageRepository repository, string packageId) { return Exists(repository, packageId, version: null); } public static bool Exists(this IPackageRepository repository, string packageId, SemanticVersion version) { IPackageLookup packageLookup = repository as IPackageLookup; if ((packageLookup != null) && !String.IsNullOrEmpty(packageId) && (version != null)) { return packageLookup.Exists(packageId, version); } return repository.FindPackage(packageId, version) != null; } public static bool TryFindPackage(this IPackageRepository repository, string packageId, SemanticVersion version, out IPackage package) { package = repository.FindPackage(packageId, version); return package != null; } public static IPackage FindPackage(this IPackageRepository repository, string packageId) { return repository.FindPackage(packageId, version: null); } public static IPackage FindPackage(this IPackageRepository repository, string packageId, SemanticVersion version) { // Default allow pre release versions to true here because the caller typically wants to find all packages in this scenario for e.g when checking if a // a package is already installed in the local repository. The same applies to allowUnlisted. return FindPackage(repository, packageId, version, NullConstraintProvider.Instance, allowPrereleaseVersions: true, allowUnlisted: true); } public static IPackage FindPackage(this IPackageRepository repository, string packageId, SemanticVersion version, bool allowPrereleaseVersions, bool allowUnlisted) { return FindPackage(repository, packageId, version, NullConstraintProvider.Instance, allowPrereleaseVersions, allowUnlisted); } public static IPackage FindPackage(this IPackageRepository repository, string packageId, IVersionSpec versionSpec, IPackageConstraintProvider constraintProvider, bool allowPrereleaseVersions, bool allowUnlisted) { var packages = repository.FindPackages(packageId, versionSpec, allowPrereleaseVersions, allowUnlisted); if (constraintProvider != null) { packages = FilterPackagesByConstraints(constraintProvider, packages, packageId, allowPrereleaseVersions); } return packages.FirstOrDefault(); } public static IEnumerable<IPackage> FindPackages(this IPackageRepository repository, IEnumerable<string> packageIds) { if (packageIds == null) { throw new ArgumentNullException("packageIds"); } // If we're in V3-land, find packages using that API var v3Repo = repository as IV3InteropRepository; if (v3Repo != null) { return packageIds.SelectMany(id => v3Repo.FindPackagesById(id)).ToList(); } else { return FindPackages(repository, packageIds, GetFilterExpression); } } public static IEnumerable<IPackage> FindPackagesById(this IPackageRepository repository, string packageId) { var directRepo = repository as IV3InteropRepository; if (directRepo != null) { return directRepo.FindPackagesById(packageId); } var serviceBasedRepository = repository as IPackageLookup; if (serviceBasedRepository != null) { return serviceBasedRepository.FindPackagesById(packageId).ToList(); } else { return FindPackagesByIdCore(repository, packageId); } } internal static IEnumerable<IPackage> FindPackagesByIdCore(IPackageRepository repository, string packageId) { var cultureRepository = repository as ICultureAwareRepository; if (cultureRepository != null) { packageId = packageId.ToLower(cultureRepository.Culture); } else { packageId = packageId.ToLower(CultureInfo.CurrentCulture); } return (from p in repository.GetPackages() where p.Id.ToLower() == packageId orderby p.Id select p).ToList(); } /// <summary> /// Since Odata dies when our query for updates is too big. We query for updates 10 packages at a time /// and return the full list of packages. /// </summary> private static IEnumerable<IPackage> FindPackages<T>( this IPackageRepository repository, IEnumerable<T> items, Func<IEnumerable<T>, Expression<Func<IPackage, bool>>> filterSelector) { const int batchSize = 10; while (items.Any()) { IEnumerable<T> currentItems = items.Take(batchSize); Expression<Func<IPackage, bool>> filterExpression = filterSelector(currentItems); var query = repository.GetPackages() .Where(filterExpression) .OrderBy(p => p.Id); foreach (var package in query) { yield return package; } items = items.Skip(batchSize); } } public static IEnumerable<IPackage> FindPackages( this IPackageRepository repository, string packageId, IVersionSpec versionSpec, bool allowPrereleaseVersions, bool allowUnlisted) { if (repository == null) { throw new ArgumentNullException("repository"); } if (packageId == null) { throw new ArgumentNullException("packageId"); } IEnumerable<IPackage> packages = repository.FindPackagesById(packageId) .OrderByDescending(p => p.Version); if (!allowUnlisted) { packages = packages.Where(PackageExtensions.IsListed); } if (versionSpec != null) { packages = packages.FindByVersion(versionSpec); } packages = FilterPackagesByConstraints(NullConstraintProvider.Instance, packages, packageId, allowPrereleaseVersions); return packages; } public static IPackage FindPackage( this IPackageRepository repository, string packageId, IVersionSpec versionSpec, bool allowPrereleaseVersions, bool allowUnlisted) { return repository.FindPackages(packageId, versionSpec, allowPrereleaseVersions, allowUnlisted).FirstOrDefault(); } public static IEnumerable<IPackage> FindCompatiblePackages(this IPackageRepository repository, IPackageConstraintProvider constraintProvider, IEnumerable<string> packageIds, IPackage package, FrameworkName targetFramework, bool allowPrereleaseVersions) { return (from p in repository.FindPackages(packageIds) where allowPrereleaseVersions || p.IsReleaseVersion() let dependency = p.FindDependency(package.Id, targetFramework) let otherConstaint = constraintProvider.GetConstraint(p.Id) where dependency != null && dependency.VersionSpec.Satisfies(package.Version) && (otherConstaint == null || otherConstaint.Satisfies(package.Version)) select p); } public static PackageDependency FindDependency(this IPackageMetadata package, string packageId, FrameworkName targetFramework) { return (from dependency in package.GetCompatiblePackageDependencies(targetFramework) where dependency.Id.Equals(packageId, StringComparison.OrdinalIgnoreCase) select dependency).FirstOrDefault(); } public static IQueryable<IPackage> Search(this IPackageRepository repository, string searchTerm, bool allowPrereleaseVersions) { return Search(repository, searchTerm, targetFrameworks: Enumerable.Empty<string>(), allowPrereleaseVersions: allowPrereleaseVersions); } public static IQueryable<IPackage> Search(this IPackageRepository repository, string searchTerm, IEnumerable<string> targetFrameworks, bool allowPrereleaseVersions, bool includeDelisted = false) { if (targetFrameworks == null) { throw new ArgumentNullException("targetFrameworks"); } var serviceBasedRepository = repository as IServiceBasedRepository; if (serviceBasedRepository != null) { return serviceBasedRepository.Search(searchTerm, targetFrameworks, allowPrereleaseVersions, includeDelisted); } // Ignore the target framework if the repository doesn't support searching var result = repository .GetPackages() .Find(searchTerm) .FilterByPrerelease(allowPrereleaseVersions); if (includeDelisted == false) { result = result.Where(p => p.IsListed()); } return result.AsQueryable(); } public static IPackage ResolveDependency(this IPackageRepository repository, PackageDependency dependency, bool allowPrereleaseVersions, bool preferListedPackages) { return ResolveDependency(repository, dependency, constraintProvider: null, allowPrereleaseVersions: allowPrereleaseVersions, preferListedPackages: preferListedPackages, dependencyVersion: DependencyVersion.Lowest); } public static IPackage ResolveDependency(this IPackageRepository repository, PackageDependency dependency, IPackageConstraintProvider constraintProvider, bool allowPrereleaseVersions, bool preferListedPackages) { return ResolveDependency(repository, dependency, constraintProvider, allowPrereleaseVersions, preferListedPackages, dependencyVersion: DependencyVersion.Lowest); } public static IPackage ResolveDependency(this IPackageRepository repository, PackageDependency dependency, IPackageConstraintProvider constraintProvider, bool allowPrereleaseVersions, bool preferListedPackages, DependencyVersion dependencyVersion) { IDependencyResolver dependencyResolver = repository as IDependencyResolver; if (dependencyResolver != null) { return dependencyResolver.ResolveDependency(dependency, constraintProvider, allowPrereleaseVersions, preferListedPackages, dependencyVersion); } return ResolveDependencyCore(repository, dependency, constraintProvider, allowPrereleaseVersions, preferListedPackages, dependencyVersion); } internal static IPackage ResolveDependencyCore( this IPackageRepository repository, PackageDependency dependency, IPackageConstraintProvider constraintProvider, bool allowPrereleaseVersions, bool preferListedPackages, DependencyVersion dependencyVersion) { if (repository == null) { throw new ArgumentNullException("repository"); } if (dependency == null) { throw new ArgumentNullException("dependency"); } IEnumerable<IPackage> packages = repository.FindPackagesById(dependency.Id).ToList(); // Always filter by constraints when looking for dependencies packages = FilterPackagesByConstraints(constraintProvider, packages, dependency.Id, allowPrereleaseVersions); IList<IPackage> candidates = packages.ToList(); if (preferListedPackages) { // pick among Listed packages first IPackage listedSelectedPackage = ResolveDependencyCore( candidates.Where(PackageExtensions.IsListed), dependency, dependencyVersion); if (listedSelectedPackage != null) { return listedSelectedPackage; } } return ResolveDependencyCore(candidates, dependency, dependencyVersion); } /// <summary> /// From the list of packages <paramref name="packages"/>, selects the package that best /// matches the <paramref name="dependency"/>. /// </summary> /// <param name="packages">The list of packages.</param> /// <param name="dependency">The dependency used to select package from the list.</param> /// <param name="dependencyVersion">Indicates the method used to select dependency. /// Applicable only when dependency.VersionSpec is not null.</param> /// <returns>The selected package.</returns> private static IPackage ResolveDependencyCore( IEnumerable<IPackage> packages, PackageDependency dependency, DependencyVersion dependencyVersion) { // If version info was specified then use it if (dependency.VersionSpec != null) { packages = packages.FindByVersion(dependency.VersionSpec).OrderBy(p => p.Version); return packages.SelectDependency(dependencyVersion); } else { // BUG 840: If no version info was specified then pick the latest return packages.OrderByDescending(p => p.Version) .FirstOrDefault(); } } /// <summary> /// Returns updates for packages from the repository /// </summary> /// <param name="repository">The repository to search for updates</param> /// <param name="packages">Packages to look for updates</param> /// <param name="includePrerelease">Indicates whether to consider prerelease updates.</param> /// <param name="includeAllVersions">Indicates whether to include all versions of an update as opposed to only including the latest version.</param> public static IEnumerable<IPackage> GetUpdates( this IPackageRepository repository, IEnumerable<IPackageName> packages, bool includePrerelease, bool includeAllVersions, IEnumerable<FrameworkName> targetFrameworks = null, IEnumerable<IVersionSpec> versionConstraints = null) { if (packages.IsEmpty()) { return Enumerable.Empty<IPackage>(); } var serviceBasedRepository = repository as IServiceBasedRepository; return serviceBasedRepository != null ? serviceBasedRepository.GetUpdates(packages, includePrerelease, includeAllVersions, targetFrameworks, versionConstraints) : repository.GetUpdatesCore(packages, includePrerelease, includeAllVersions, targetFrameworks, versionConstraints); } public static IEnumerable<IPackage> GetUpdatesCore( this IPackageRepository repository, IEnumerable<IPackageName> packages, bool includePrerelease, bool includeAllVersions, IEnumerable<FrameworkName> targetFramework, IEnumerable<IVersionSpec> versionConstraints) { List<IPackageName> packageList = packages.ToList(); if (!packageList.Any()) { return Enumerable.Empty<IPackage>(); } IList<IVersionSpec> versionConstraintList; if (versionConstraints == null) { versionConstraintList = new IVersionSpec[packageList.Count]; } else { versionConstraintList = versionConstraints.ToList(); } if (packageList.Count != versionConstraintList.Count) { throw new ArgumentException(NuGetResources.GetUpdatesParameterMismatch); } // These are the packages that we need to look at for potential updates. ILookup<string, IPackage> sourcePackages = GetUpdateCandidates(repository, packageList, includePrerelease) .ToList() .ToLookup(package => package.Id, StringComparer.OrdinalIgnoreCase); var results = new List<IPackage>(); for (int i = 0; i < packageList.Count; i++) { var package = packageList[i]; var constraint = versionConstraintList[i]; var updates = from candidate in sourcePackages[package.Id] where (candidate.Version > package.Version) && SupportsTargetFrameworks(targetFramework, candidate) && (constraint == null || constraint.Satisfies(candidate.Version)) select candidate; results.AddRange(updates); } if (!includeAllVersions) { return results.CollapseById(); } return results; } private static bool SupportsTargetFrameworks(IEnumerable<FrameworkName> targetFramework, IPackage package) { return targetFramework.IsEmpty() || targetFramework.Any(t => VersionUtility.IsCompatible(t, package.GetSupportedFrameworks())); } public static IPackageRepository Clone(this IPackageRepository repository) { var cloneableRepository = repository as ICloneableRepository; if (cloneableRepository != null) { return cloneableRepository.Clone(); } return repository; } /// <summary> /// Since odata dies when our query for updates is too big. We query for updates 10 packages at a time /// and return the full list of candidates for updates. /// </summary> private static IEnumerable<IPackage> GetUpdateCandidates( IPackageRepository repository, IEnumerable<IPackageName> packages, bool includePrerelease) { var query = FindPackages(repository, packages, GetFilterExpression); if (!includePrerelease) { query = query.Where(p => p.IsReleaseVersion()); } // for updates, we never consider unlisted packages query = query.Where(PackageExtensions.IsListed); return query; } /// <summary> /// For the list of input packages generate an expression like: /// p => p.Id == 'package1id' or p.Id == 'package2id' or p.Id == 'package3id'... up to package n /// </summary> private static Expression<Func<IPackage, bool>> GetFilterExpression(IEnumerable<IPackageName> packages) { return GetFilterExpression(packages.Select(p => p.Id)); } [SuppressMessage("Microsoft.Globalization", "CA1304:SpecifyCultureInfo", MessageId = "System.String.ToLower", Justification = "This is for a linq query")] private static Expression<Func<IPackage, bool>> GetFilterExpression(IEnumerable<string> ids) { ParameterExpression parameterExpression = Expression.Parameter(typeof(IPackageName)); Expression expressionBody = ids.Select(id => GetCompareExpression(parameterExpression, id.ToLower())) .Aggregate(Expression.OrElse); return Expression.Lambda<Func<IPackage, bool>>(expressionBody, parameterExpression); } /// <summary> /// Builds the expression: package.Id.ToLower() == "somepackageid" /// </summary> private static Expression GetCompareExpression(Expression parameterExpression, object value) { // package.Id Expression propertyExpression = Expression.Property(parameterExpression, "Id"); // .ToLower() Expression toLowerExpression = Expression.Call(propertyExpression, typeof(string).GetMethod("ToLower", Type.EmptyTypes)); // == localPackage.Id return Expression.Equal(toLowerExpression, Expression.Constant(value)); } private static IEnumerable<IPackage> FilterPackagesByConstraints( IPackageConstraintProvider constraintProvider, IEnumerable<IPackage> packages, string packageId, bool allowPrereleaseVersions) { constraintProvider = constraintProvider ?? NullConstraintProvider.Instance; // Filter packages by this constraint IVersionSpec constraint = constraintProvider.GetConstraint(packageId); if (constraint != null) { packages = packages.FindByVersion(constraint); } if (!allowPrereleaseVersions) { packages = packages.Where(p => p.IsReleaseVersion()); } return packages; } /// <summary> /// Selects the dependency package from the list of candidate packages /// according to <paramref name="dependencyVersion"/>. /// </summary> /// <param name="packages">The list of candidate packages.</param> /// <param name="dependencyVersion">The rule used to select the package from /// <paramref name="packages"/> </param> /// <returns>The selected package.</returns> /// <remarks>Precondition: <paramref name="packages"/> are ordered by ascending version.</remarks> internal static IPackage SelectDependency(this IEnumerable<IPackage> packages, DependencyVersion dependencyVersion) { if (packages == null || !packages.Any()) { return null; } if (dependencyVersion == DependencyVersion.Lowest) { return packages.FirstOrDefault(); } else if (dependencyVersion == DependencyVersion.Highest) { return packages.LastOrDefault(); } else if (dependencyVersion == DependencyVersion.HighestPatch) { var groups = from p in packages group p by new { p.Version.Version.Major, p.Version.Version.Minor } into g orderby g.Key.Major, g.Key.Minor select g; return (from p in groups.First() orderby p.Version descending select p).FirstOrDefault(); } else if (dependencyVersion == DependencyVersion.HighestMinor) { var groups = from p in packages group p by new { p.Version.Version.Major } into g orderby g.Key.Major select g; return (from p in groups.First() orderby p.Version descending select p).FirstOrDefault(); } throw new ArgumentOutOfRangeException("dependencyVersion"); } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.PlatformAbstractions; namespace Microsoft.DotNet.Tools.Common { public static class PathUtility { public static bool IsPlaceholderFile(string path) { return string.Equals(Path.GetFileName(path), "_._", StringComparison.Ordinal); } public static bool IsChildOfDirectory(string dir, string candidate) { if (dir == null) { throw new ArgumentNullException(nameof(dir)); } if (candidate == null) { throw new ArgumentNullException(nameof(candidate)); } dir = Path.GetFullPath(dir); dir = EnsureTrailingSlash(dir); candidate = Path.GetFullPath(candidate); return candidate.StartsWith(dir, StringComparison.OrdinalIgnoreCase); } public static string EnsureTrailingSlash(string path) { return EnsureTrailingCharacter(path, Path.DirectorySeparatorChar); } public static string EnsureTrailingForwardSlash(string path) { return EnsureTrailingCharacter(path, '/'); } private static string EnsureTrailingCharacter(string path, char trailingCharacter) { if (path == null) { throw new ArgumentNullException(nameof(path)); } // if the path is empty, we want to return the original string instead of a single trailing character. if (path.Length == 0 || path[path.Length - 1] == trailingCharacter) { return path; } return path + trailingCharacter; } public static string EnsureNoTrailingDirectorySeparator(string path) { if (!string.IsNullOrEmpty(path)) { char lastChar = path[path.Length - 1]; if (lastChar == Path.DirectorySeparatorChar) { path = path.Substring(0, path.Length - 1); } } return path; } public static void EnsureParentDirectoryExists(string filePath) { string directory = Path.GetDirectoryName(filePath); EnsureDirectoryExists(directory); } public static void EnsureDirectoryExists(string directoryPath) { if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } } public static bool TryDeleteDirectory(string directoryPath) { try { Directory.Delete(directoryPath, true); return true; } catch { return false; } } /// <summary> /// Returns childItem relative to directory, with Path.DirectorySeparatorChar as separator /// </summary> public static string GetRelativePath(DirectoryInfo directory, FileSystemInfo childItem) { var path1 = EnsureTrailingSlash(directory.FullName); var path2 = childItem.FullName; return GetRelativePath(path1, path2, Path.DirectorySeparatorChar, true); } /// <summary> /// Returns path2 relative to path1, with Path.DirectorySeparatorChar as separator /// </summary> public static string GetRelativePath(string path1, string path2) { return GetRelativePath(path1, path2, Path.DirectorySeparatorChar, true); } /// <summary> /// Returns path2 relative to path1, with Path.DirectorySeparatorChar as separator but ignoring directory /// traversals. /// </summary> public static string GetRelativePathIgnoringDirectoryTraversals(string path1, string path2) { return GetRelativePath(path1, path2, Path.DirectorySeparatorChar, false); } /// <summary> /// Returns path2 relative to path1, with given path separator /// </summary> public static string GetRelativePath(string path1, string path2, char separator, bool includeDirectoryTraversals) { if (string.IsNullOrEmpty(path1)) { throw new ArgumentException("Path must have a value", nameof(path1)); } if (string.IsNullOrEmpty(path2)) { throw new ArgumentException("Path must have a value", nameof(path2)); } StringComparison compare; if (RuntimeEnvironment.OperatingSystemPlatform == Platform.Windows) { compare = StringComparison.OrdinalIgnoreCase; // check if paths are on the same volume if (!string.Equals(Path.GetPathRoot(path1), Path.GetPathRoot(path2), compare)) { // on different volumes, "relative" path is just path2 return path2; } } else { compare = StringComparison.Ordinal; } var index = 0; var path1Segments = path1.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); var path2Segments = path2.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); // if path1 does not end with / it is assumed the end is not a directory // we will assume that is isn't a directory by ignoring the last split var len1 = path1Segments.Length - 1; var len2 = path2Segments.Length; // find largest common absolute path between both paths var min = Math.Min(len1, len2); while (min > index) { if (!string.Equals(path1Segments[index], path2Segments[index], compare)) { break; } // Handle scenarios where folder and file have same name (only if os supports same name for file and directory) // e.g. /file/name /file/name/app else if ((len1 == index && len2 > index + 1) || (len1 > index && len2 == index + 1)) { break; } ++index; } var path = ""; // check if path2 ends with a non-directory separator and if path1 has the same non-directory at the end if (len1 + 1 == len2 && !string.IsNullOrEmpty(path1Segments[index]) && string.Equals(path1Segments[index], path2Segments[index], compare)) { return path; } if (includeDirectoryTraversals) { for (var i = index; len1 > i; ++i) { path += ".." + separator; } } for (var i = index; len2 - 1 > i; ++i) { path += path2Segments[i] + separator; } // if path2 doesn't end with an empty string it means it ended with a non-directory name, so we add it back if (!string.IsNullOrEmpty(path2Segments[len2 - 1])) { path += path2Segments[len2 - 1]; } return path; } public static string GetAbsolutePath(string basePath, string relativePath) { if (basePath == null) { throw new ArgumentNullException(nameof(basePath)); } if (relativePath == null) { throw new ArgumentNullException(nameof(relativePath)); } Uri resultUri = new Uri(new Uri(basePath), new Uri(relativePath, UriKind.Relative)); return resultUri.LocalPath; } public static string GetDirectoryName(string path) { path = path.TrimEnd(Path.DirectorySeparatorChar); return path.Substring(Path.GetDirectoryName(path).Length).Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); } public static string GetPathWithForwardSlashes(string path) { return path.Replace('\\', '/'); } public static string GetPathWithBackSlashes(string path) { return path.Replace('/', '\\'); } public static string GetPathWithDirectorySeparator(string path) { if (Path.DirectorySeparatorChar == '/') { return GetPathWithForwardSlashes(path); } else { return GetPathWithBackSlashes(path); } } public static string RemoveExtraPathSeparators(string path) { if (string.IsNullOrEmpty(path)) { return path; } var components = path.Split(Path.DirectorySeparatorChar); var result = string.Empty; foreach (var component in components) { if (string.IsNullOrEmpty(component)) { continue; } if (string.IsNullOrEmpty(result)) { result = component; // On Windows, manually append a separator for drive references because Path.Combine won't do so if (result.EndsWith(":") && RuntimeEnvironment.OperatingSystemPlatform == Platform.Windows) { result += Path.DirectorySeparatorChar; } } else { result = Path.Combine(result, component); } } if (path[path.Length-1] == Path.DirectorySeparatorChar) { result += Path.DirectorySeparatorChar; } return result; } public static bool HasExtension(this string filePath, string extension) { var comparison = StringComparison.Ordinal; if (RuntimeEnvironment.OperatingSystemPlatform == Platform.Windows) { comparison = StringComparison.OrdinalIgnoreCase; } return Path.GetExtension(filePath).Equals(extension, comparison); } /// <summary> /// Gets the fully-qualified path without failing if the /// path is empty. /// </summary> public static string GetFullPath(string path) { if (string.IsNullOrWhiteSpace(path)) { return path; } return Path.GetFullPath(path); } public static void EnsureAllPathsExist( IReadOnlyCollection<string> paths, string pathDoesNotExistLocalizedFormatString, bool allowDirectories = false) { var notExisting = new List<string>(); foreach (var p in paths) { if (!File.Exists(p) && (!allowDirectories || !Directory.Exists(p))) { notExisting.Add(p); } } if (notExisting.Count > 0) { throw new GracefulException( string.Join( Environment.NewLine, notExisting.Select(p => string.Format(pathDoesNotExistLocalizedFormatString, p)))); } } public static bool IsDirectory(this string path) => File.GetAttributes(path).HasFlag(FileAttributes.Directory); } }
using Lucene.Net.Analysis.Tokenattributes; using Lucene.Net.Support; using Lucene.Net.Util; using System; using System.Diagnostics; namespace Lucene.Net.Analysis { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Automaton = Lucene.Net.Util.Automaton.Automaton; using State = Lucene.Net.Util.Automaton.State; using Transition = Lucene.Net.Util.Automaton.Transition; // TODO: maybe also toFST? then we can translate atts into FST outputs/weights /// <summary> /// Consumes a TokenStream and creates an <seealso cref="Automaton"/> /// where the transition labels are UTF8 bytes (or Unicode /// code points if unicodeArcs is true) from the {@link /// TermToBytesRefAttribute}. Between tokens we insert /// POS_SEP and for holes we insert HOLE. /// /// @lucene.experimental /// </summary> public class TokenStreamToAutomaton { //backing variables private bool preservePositionIncrements; private bool unicodeArcs; /// <summary> /// Sole constructor. </summary> public TokenStreamToAutomaton() { this.preservePositionIncrements = true; } /// <summary> /// Whether to generate holes in the automaton for missing positions, <code>true</code> by default. </summary> public virtual bool PreservePositionIncrements { set { this.preservePositionIncrements = value; } } /// <summary> /// Whether to make transition labels Unicode code points instead of UTF8 bytes, /// <code>false</code> by default /// </summary> public virtual bool UnicodeArcs { set { this.unicodeArcs = value; } } private class Position : RollingBuffer.Resettable { // Any tokens that ended at our position arrive to this state: internal State Arriving; // Any tokens that start at our position leave from this state: internal State Leaving; public void Reset() { Arriving = null; Leaving = null; } } private class Positions : RollingBuffer<Position> { public Positions() : base(NewPosition) { } protected internal override Position NewInstance() { return NewPosition(); } private static Position NewPosition() { return new Position(); } } /// <summary> /// Subclass & implement this if you need to change the /// token (such as escaping certain bytes) before it's /// turned into a graph. /// </summary> protected internal virtual BytesRef ChangeToken(BytesRef @in) { return @in; } /// <summary> /// We create transition between two adjacent tokens. </summary> public const int POS_SEP = 0x001f; /// <summary> /// We add this arc to represent a hole. </summary> public const int HOLE = 0x001e; /// <summary> /// Pulls the graph (including {@link /// PositionLengthAttribute}) from the provided {@link /// TokenStream}, and creates the corresponding /// automaton where arcs are bytes (or Unicode code points /// if unicodeArcs = true) from each term. /// </summary> public virtual Automaton ToAutomaton(TokenStream @in) { var a = new Automaton(); bool deterministic = true; var posIncAtt = @in.AddAttribute<IPositionIncrementAttribute>(); var posLengthAtt = @in.AddAttribute<IPositionLengthAttribute>(); var offsetAtt = @in.AddAttribute<IOffsetAttribute>(); var termBytesAtt = @in.AddAttribute<ITermToBytesRefAttribute>(); BytesRef term = termBytesAtt.BytesRef; @in.Reset(); // Only temporarily holds states ahead of our current // position: RollingBuffer<Position> positions = new Positions(); int pos = -1; Position posData = null; int maxOffset = 0; while (@in.IncrementToken()) { int posInc = posIncAtt.PositionIncrement; if (!preservePositionIncrements && posInc > 1) { posInc = 1; } Debug.Assert(pos > -1 || posInc > 0); if (posInc > 0) { // New node: pos += posInc; posData = positions.Get(pos); Debug.Assert(posData.Leaving == null); if (posData.Arriving == null) { // No token ever arrived to this position if (pos == 0) { // OK: this is the first token posData.Leaving = a.InitialState; } else { // this means there's a hole (eg, StopFilter // does this): posData.Leaving = new State(); AddHoles(a.InitialState, positions, pos); } } else { posData.Leaving = new State(); posData.Arriving.AddTransition(new Transition(POS_SEP, posData.Leaving)); if (posInc > 1) { // A token spanned over a hole; add holes // "under" it: AddHoles(a.InitialState, positions, pos); } } positions.FreeBefore(pos); } else { // note: this isn't necessarily true. its just that we aren't surely det. // we could optimize this further (e.g. buffer and sort synonyms at a position) // but thats probably overkill. this is cheap and dirty deterministic = false; } int endPos = pos + posLengthAtt.PositionLength; termBytesAtt.FillBytesRef(); BytesRef termUTF8 = ChangeToken(term); int[] termUnicode = null; Position endPosData = positions.Get(endPos); if (endPosData.Arriving == null) { endPosData.Arriving = new State(); } State state = posData.Leaving; int termLen = termUTF8.Length; if (unicodeArcs) { string utf16 = termUTF8.Utf8ToString(); termUnicode = new int[Character.CodePointCount(utf16, 0, utf16.Length)]; termLen = termUnicode.Length; for (int cp, i = 0, j = 0; i < utf16.Length; i += Character.CharCount(cp)) { termUnicode[j++] = cp = Character.CodePointAt(utf16, i); } } else { termLen = termUTF8.Length; } for (int byteIDX = 0; byteIDX < termLen; byteIDX++) { State nextState = byteIDX == termLen - 1 ? endPosData.Arriving : new State(); int c; if (unicodeArcs) { c = termUnicode[byteIDX]; } else { c = termUTF8.Bytes[termUTF8.Offset + byteIDX] & 0xff; } state.AddTransition(new Transition(c, nextState)); state = nextState; } maxOffset = Math.Max(maxOffset, offsetAtt.EndOffset()); } @in.End(); State endState = null; if (offsetAtt.EndOffset() > maxOffset) { endState = new State(); endState.Accept = true; } pos++; while (pos <= positions.MaxPos) { posData = positions.Get(pos); if (posData.Arriving != null) { if (endState != null) { posData.Arriving.AddTransition(new Transition(POS_SEP, endState)); } else { posData.Arriving.Accept = true; } } pos++; } //toDot(a); a.Deterministic = deterministic; return a; } // for debugging! /* private static void toDot(Automaton a) throws IOException { final String s = a.toDot(); Writer w = new OutputStreamWriter(new FileOutputStream("/tmp/out.dot")); w.write(s); w.close(); System.out.println("TEST: saved to /tmp/out.dot"); } */ private static void AddHoles(State startState, RollingBuffer<Position> positions, int pos) { Position posData = positions.Get(pos); Position prevPosData = positions.Get(pos - 1); while (posData.Arriving == null || prevPosData.Leaving == null) { if (posData.Arriving == null) { posData.Arriving = new State(); posData.Arriving.AddTransition(new Transition(POS_SEP, posData.Leaving)); } if (prevPosData.Leaving == null) { if (pos == 1) { prevPosData.Leaving = startState; } else { prevPosData.Leaving = new State(); } if (prevPosData.Arriving != null) { prevPosData.Arriving.AddTransition(new Transition(POS_SEP, prevPosData.Leaving)); } } prevPosData.Leaving.AddTransition(new Transition(HOLE, posData.Arriving)); pos--; if (pos <= 0) { break; } posData = prevPosData; prevPosData = positions.Get(pos - 1); } } } }
// $Id$ // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // using System; using System.Collections.Generic; using Org.Apache.Etch.Bindings.Csharp.Msg; using Org.Apache.Etch.Bindings.Csharp.Support; using Org.Apache.Etch.Bindings.Csharp.Util; namespace Org.Apache.Etch.Bindings.Csharp.Transport { /// <summary> /// MailboxManager is a MessageHandler which accepts packets for /// possible delivery to a mailbox, or to another message handler /// if an appropriate mailbox cannot be found. MailboxManager is /// forwarding them to another MessageSource. If requested, a /// mailbox is created with a message's msgid and added to the /// set of mailboxes waiting for messages. /// </summary> public class PlainMailboxManager : MailboxManager { /// <summary> /// Constructs the PlainMailboxManager. /// </summary> /// <param name="transport">a transport to send messages </param> /// <param name="uri">the uri of this transport stack</param> /// <param name="resources">the resources of this transport stack</param> public PlainMailboxManager(TransportMessage transport, string uri, Resources resources) : this(transport, new URL(uri), resources) { // nothing else. } /// <summary> /// Constructs the PlainMailboxManager. /// </summary> /// <param name="transport">a transport to send messages </param> /// <param name="uri">the uri of this transport stack</param> /// <param name="resources">the resources of this transport stack</param> public PlainMailboxManager(TransportMessage transport, URL uri, Resources resources) { this.transport = transport; transport.SetSession(this); } private readonly TransportMessage transport; public override string ToString() { return String.Format( "PlainMailboxManager/{0} ", transport ); } private readonly IdGenerator idGen = new IdGenerator( DateTime.Now.Ticks, 37 ); ///////////////////// // Mailbox methods // ///////////////////// private Dictionary<long, Mailbox> mailboxes = new Dictionary<long, Mailbox>(); /// <summary> /// Adds a mailbox to the set of mailbox receiving responses /// to messages. /// </summary> /// <param name="mb"></param> public void Register( Mailbox mb ) { long msgid = mb.GetMessageId(); lock (mailboxes) { if (!up) throw new InvalidOperationException("connection down"); if (mailboxes.ContainsKey( msgid )) throw new ArgumentException( "dup msgid in mailboxes" ); mailboxes.Add( msgid, mb ); } } public void Unregister( Mailbox mb ) { lock ( mailboxes ) { mailboxes.Remove( mb.GetMessageId() ); } } private Mailbox GetMailbox( long msgid ) { lock ( mailboxes ) { return mailboxes[msgid]; } } public void Redeliver( Who sender, Message msg ) { session.SessionMessage(sender, msg); } public Object SessionQuery( Object query ) { return session.SessionQuery( query ); } public void SessionControl( Object control, Object value ) { session.SessionControl( control, value ); } public void SessionNotify( Object eventObj ) { if(eventObj.Equals(SessionConsts.UP)) { up = true; } else if (eventObj.Equals(SessionConsts.DOWN)) { up = false; UnRegisterAll(); } session.SessionNotify(eventObj); } private bool up; public Object TransportQuery( Object query ) { return transport.TransportQuery( query ); } public void TransportControl( Object control, Object value ) { transport.TransportControl( control, value ); } public void TransportNotify( Object eventObj ) { transport.TransportNotify( eventObj ); } public void UnRegisterAll() { Mailbox[] mbs; lock (mailboxes) { mbs = new Mailbox[mailboxes.Values.Count]; mailboxes.Values.CopyTo(mbs, 0); } foreach (Mailbox mb in mbs) { mb.CloseDelivery(); } } #region SessionMessage Members public bool SessionMessage(Who sender, Message msg) { long? msgid = msg.InReplyTo; if (msgid != null) { Mailbox mb; try { mb = GetMailbox(msgid.Value); } catch { mb = null; } if (mb != null) { try { return mb.Message(sender, msg); } catch (Exception) { // timeout or mailbox closed - fall through } } // no such mailbox - fall through return false; } // no such mailbox or no msgid - fall through return session.SessionMessage(sender, msg); } #endregion #region MailboxManager Members public Mailbox TransportCall(Who recipient, Message msg) { if (msg.MessageId != null) throw new Exception(" message has already been sent"); if (msg.InReplyTo != null) throw new Exception(" message is marked as a reply"); long mid = idGen.Next(); msg.MessageId = mid; Mailbox mb = new PlainMailbox(this, mid); Register(mb); try { transport.TransportMessage(recipient, msg); } catch(Exception e) { Unregister(mb); throw e; } return mb; } #endregion #region TransportMessage Members public void TransportMessage(Who recipient, Message msg) { transport.TransportMessage(recipient,msg); } #endregion #region Transport<SessionMessage> Members public void SetSession(SessionMessage session) { this.session = session; } public SessionMessage GetSession() { return this.session; } private SessionMessage session; #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Xml; using Orleans.MultiCluster; using Orleans.Runtime.Configuration; using Orleans.Runtime.MembershipService; using Orleans.Runtime.MultiClusterNetwork; namespace Orleans.Runtime.Management { /// <summary> /// Implementation class for the Orleans management grain. /// </summary> [OneInstancePerCluster] internal class ManagementGrain : Grain, IManagementGrain { private readonly GlobalConfiguration globalConfig; private readonly IMultiClusterOracle multiClusterOracle; private readonly IInternalGrainFactory internalGrainFactory; private readonly ISiloStatusOracle siloStatusOracle; private readonly MembershipTableFactory membershipTableFactory; private Logger logger; public ManagementGrain( GlobalConfiguration globalConfig, IMultiClusterOracle multiClusterOracle, IInternalGrainFactory internalGrainFactory, ISiloStatusOracle siloStatusOracle, MembershipTableFactory membershipTableFactory) { this.globalConfig = globalConfig; this.multiClusterOracle = multiClusterOracle; this.internalGrainFactory = internalGrainFactory; this.siloStatusOracle = siloStatusOracle; this.membershipTableFactory = membershipTableFactory; } public override Task OnActivateAsync() { logger = LogManager.GetLogger("ManagementGrain", LoggerType.Runtime); return Task.CompletedTask; } public async Task<Dictionary<SiloAddress, SiloStatus>> GetHosts(bool onlyActive = false) { // If the status oracle isn't MembershipOracle, then it is assumed that it does not use IMembershipTable. // In that event, return the approximate silo statuses from the status oracle. if (!(this.siloStatusOracle is MembershipOracle)) return this.siloStatusOracle.GetApproximateSiloStatuses(onlyActive); // Explicitly read the membership table and return the results. var table = await GetMembershipTable(); var members = await table.ReadAll(); var results = onlyActive ? members.Members.Where(item => item.Item1.Status == SiloStatus.Active) : members.Members; return results.ToDictionary(item => item.Item1.SiloAddress, item => item.Item1.Status); } public async Task<MembershipEntry[]> GetDetailedHosts(bool onlyActive = false) { logger.Info("GetDetailedHosts onlyActive={0}", onlyActive); var mTable = await GetMembershipTable(); var table = await mTable.ReadAll(); if (onlyActive) { return table.Members .Where(item => item.Item1.Status == SiloStatus.Active) .Select(x => x.Item1) .ToArray(); } return table.Members .Select(x => x.Item1) .ToArray(); } public Task SetSystemLogLevel(SiloAddress[] siloAddresses, int traceLevel) { var silos = GetSiloAddresses(siloAddresses); logger.Info("SetSystemTraceLevel={1} {0}", Utils.EnumerableToString(silos), traceLevel); List<Task> actionPromises = PerformPerSiloAction(silos, s => GetSiloControlReference(s).SetSystemLogLevel(traceLevel)); return Task.WhenAll(actionPromises); } public Task SetAppLogLevel(SiloAddress[] siloAddresses, int traceLevel) { var silos = GetSiloAddresses(siloAddresses); logger.Info("SetAppTraceLevel={1} {0}", Utils.EnumerableToString(silos), traceLevel); List<Task> actionPromises = PerformPerSiloAction(silos, s => GetSiloControlReference(s).SetAppLogLevel(traceLevel)); return Task.WhenAll(actionPromises); } public Task SetLogLevel(SiloAddress[] siloAddresses, string logName, int traceLevel) { var silos = GetSiloAddresses(siloAddresses); logger.Info("SetLogLevel[{1}]={2} {0}", Utils.EnumerableToString(silos), logName, traceLevel); List<Task> actionPromises = PerformPerSiloAction(silos, s => GetSiloControlReference(s).SetLogLevel(logName, traceLevel)); return Task.WhenAll(actionPromises); } public Task ForceGarbageCollection(SiloAddress[] siloAddresses) { var silos = GetSiloAddresses(siloAddresses); logger.Info("Forcing garbage collection on {0}", Utils.EnumerableToString(silos)); List<Task> actionPromises = PerformPerSiloAction(silos, s => GetSiloControlReference(s).ForceGarbageCollection()); return Task.WhenAll(actionPromises); } public Task ForceActivationCollection(SiloAddress[] siloAddresses, TimeSpan ageLimit) { var silos = GetSiloAddresses(siloAddresses); return Task.WhenAll(GetSiloAddresses(silos).Select(s => GetSiloControlReference(s).ForceActivationCollection(ageLimit))); } public async Task ForceActivationCollection(TimeSpan ageLimit) { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); SiloAddress[] silos = hosts.Keys.ToArray(); await ForceActivationCollection(silos, ageLimit); } public Task ForceRuntimeStatisticsCollection(SiloAddress[] siloAddresses) { var silos = GetSiloAddresses(siloAddresses); logger.Info("Forcing runtime statistics collection on {0}", Utils.EnumerableToString(silos)); List<Task> actionPromises = PerformPerSiloAction( silos, s => GetSiloControlReference(s).ForceRuntimeStatisticsCollection()); return Task.WhenAll(actionPromises); } public Task<SiloRuntimeStatistics[]> GetRuntimeStatistics(SiloAddress[] siloAddresses) { var silos = GetSiloAddresses(siloAddresses); if (logger.IsVerbose) logger.Verbose("GetRuntimeStatistics on {0}", Utils.EnumerableToString(silos)); var promises = new List<Task<SiloRuntimeStatistics>>(); foreach (SiloAddress siloAddress in silos) promises.Add(GetSiloControlReference(siloAddress).GetRuntimeStatistics()); return Task.WhenAll(promises); } public async Task<SimpleGrainStatistic[]> GetSimpleGrainStatistics(SiloAddress[] hostsIds) { var all = GetSiloAddresses(hostsIds).Select(s => GetSiloControlReference(s).GetSimpleGrainStatistics()).ToList(); await Task.WhenAll(all); return all.SelectMany(s => s.Result).ToArray(); } public async Task<SimpleGrainStatistic[]> GetSimpleGrainStatistics() { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); SiloAddress[] silos = hosts.Keys.ToArray(); return await GetSimpleGrainStatistics(silos); } public async Task<DetailedGrainStatistic[]> GetDetailedGrainStatistics(string[] types = null, SiloAddress[] hostsIds = null) { if (hostsIds == null) { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); hostsIds = hosts.Keys.ToArray(); } var all = GetSiloAddresses(hostsIds).Select(s => GetSiloControlReference(s).GetDetailedGrainStatistics(types)).ToList(); await Task.WhenAll(all); return all.SelectMany(s => s.Result).ToArray(); } public async Task<int> GetGrainActivationCount(GrainReference grainReference) { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); List<SiloAddress> hostsIds = hosts.Keys.ToList(); var tasks = new List<Task<DetailedGrainReport>>(); foreach (var silo in hostsIds) tasks.Add(GetSiloControlReference(silo).GetDetailedGrainReport(grainReference.GrainId)); await Task.WhenAll(tasks); return tasks.Select(s => s.Result).Select(r => r.LocalActivations.Count).Sum(); } public async Task UpdateConfiguration(SiloAddress[] hostIds, Dictionary<string, string> configuration, Dictionary<string, string> tracing) { var global = new[] { "Globals/", "/Globals/", "OrleansConfiguration/Globals/", "/OrleansConfiguration/Globals/" }; if (hostIds != null && configuration.Keys.Any(k => global.Any(k.StartsWith))) throw new ArgumentException("Must update global configuration settings on all silos"); var silos = GetSiloAddresses(hostIds); if (silos.Length == 0) return; var document = XPathValuesToXml(configuration); if (tracing != null) { AddXPathValue(document, new[] { "OrleansConfiguration", "Defaults", "Tracing" }, null); var parent = document["OrleansConfiguration"]["Defaults"]["Tracing"]; foreach (var trace in tracing) { var child = document.CreateElement("TraceLevelOverride"); child.SetAttribute("LogPrefix", trace.Key); child.SetAttribute("TraceLevel", trace.Value); parent.AppendChild(child); } } using(var sw = new StringWriter()) { using(var xw = XmlWriter.Create(sw)) { document.WriteTo(xw); xw.Flush(); var xml = sw.ToString(); // do first one, then all the rest to avoid spamming all the silos in case of a parameter error await GetSiloControlReference(silos[0]).UpdateConfiguration(xml); await Task.WhenAll(silos.Skip(1).Select(s => GetSiloControlReference(s).UpdateConfiguration(xml))); } } } public async Task UpdateStreamProviders(SiloAddress[] hostIds, IDictionary<string, ProviderCategoryConfiguration> streamProviderConfigurations) { SiloAddress[] silos = GetSiloAddresses(hostIds); List<Task> actionPromises = PerformPerSiloAction(silos, s => GetSiloControlReference(s).UpdateStreamProviders(streamProviderConfigurations)); await Task.WhenAll(actionPromises); } public async Task<string[]> GetActiveGrainTypes(SiloAddress[] hostsIds=null) { if (hostsIds == null) { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); SiloAddress[] silos = hosts.Keys.ToArray(); } var all = GetSiloAddresses(hostsIds).Select(s => GetSiloControlReference(s).GetGrainTypeList()).ToArray(); await Task.WhenAll(all); return all.SelectMany(s => s.Result).Distinct().ToArray(); } public async Task<int> GetTotalActivationCount() { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); List<SiloAddress> silos = hosts.Keys.ToList(); var tasks = new List<Task<int>>(); foreach (var silo in silos) tasks.Add(GetSiloControlReference(silo).GetActivationCount()); await Task.WhenAll(tasks); int sum = 0; foreach (Task<int> task in tasks) sum += task.Result; return sum; } public Task<object[]> SendControlCommandToProvider(string providerTypeFullName, string providerName, int command, object arg) { return ExecutePerSiloCall(isc => isc.SendControlCommandToProvider(providerTypeFullName, providerName, command, arg), String.Format("SendControlCommandToProvider of type {0} and name {1} command {2}.", providerTypeFullName, providerName, command)); } private async Task<object[]> ExecutePerSiloCall(Func<ISiloControl, Task<object>> action, string actionToLog) { var silos = await GetHosts(true); if(logger.IsVerbose) { logger.Verbose("Executing {0} against {1}", actionToLog, Utils.EnumerableToString(silos.Keys)); } var actionPromises = new List<Task<object>>(); foreach (SiloAddress siloAddress in silos.Keys.ToArray()) actionPromises.Add(action(GetSiloControlReference(siloAddress))); return await Task.WhenAll(actionPromises); } private Task<IMembershipTable> GetMembershipTable() { var membershipOracle = this.siloStatusOracle as MembershipOracle; if (!(this.siloStatusOracle is MembershipOracle)) throw new InvalidOperationException("The current membership oracle does not support detailed silo status reporting."); return this.membershipTableFactory.GetMembershipTable(); } private SiloAddress[] GetSiloAddresses(SiloAddress[] silos) { if (silos != null && silos.Length > 0) return silos; return this.siloStatusOracle .GetApproximateSiloStatuses(true).Select(s => s.Key).ToArray(); } /// <summary> /// Perform an action for each silo. /// </summary> /// <remarks> /// Because SiloControl contains a reference to a system target, each method call using that reference /// will get routed either locally or remotely to the appropriate silo instance auto-magically. /// </remarks> /// <param name="siloAddresses">List of silos to perform the action for</param> /// <param name="perSiloAction">The action functiona to be performed for each silo</param> /// <returns>Array containing one Task for each silo the action was performed for</returns> private List<Task> PerformPerSiloAction(SiloAddress[] siloAddresses, Func<SiloAddress, Task> perSiloAction) { var requestsToSilos = new List<Task>(); foreach (SiloAddress siloAddress in siloAddresses) requestsToSilos.Add( perSiloAction(siloAddress) ); return requestsToSilos; } private static XmlDocument XPathValuesToXml(Dictionary<string,string> values) { var doc = new XmlDocument(); if (values == null) return doc; foreach (var p in values) { var path = p.Key.Split('/').ToList(); if (path[0] == "") path.RemoveAt(0); if (path[0] != "OrleansConfiguration") path.Insert(0, "OrleansConfiguration"); if (!path[path.Count - 1].StartsWith("@")) throw new ArgumentException("XPath " + p.Key + " must end with @attribute"); AddXPathValue(doc, path, p.Value); } return doc; } private static void AddXPathValue(XmlNode xml, IEnumerable<string> path, string value) { if (path == null) return; var first = path.FirstOrDefault(); if (first == null) return; if (first.StartsWith("@")) { first = first.Substring(1); if (path.Count() != 1) throw new ArgumentException("Attribute " + first + " must be last in path"); var e = xml as XmlElement; if (e == null) throw new ArgumentException("Attribute " + first + " must be on XML element"); e.SetAttribute(first, value); return; } foreach (var child in xml.ChildNodes) { var e = child as XmlElement; if (e != null && e.LocalName == first) { AddXPathValue(e, path.Skip(1), value); return; } } var empty = (xml as XmlDocument ?? xml.OwnerDocument).CreateElement(first); xml.AppendChild(empty); AddXPathValue(empty, path.Skip(1), value); } private ISiloControl GetSiloControlReference(SiloAddress silo) { return this.internalGrainFactory.GetSystemTarget<ISiloControl>(Constants.SiloControlId, silo); } #region MultiCluster private IMultiClusterOracle GetMultiClusterOracle() { if (!this.globalConfig.HasMultiClusterNetwork) throw new OrleansException("No multicluster network configured"); return this.multiClusterOracle; } public Task<List<IMultiClusterGatewayInfo>> GetMultiClusterGateways() { return Task.FromResult(GetMultiClusterOracle().GetGateways().Cast<IMultiClusterGatewayInfo>().ToList()); } public Task<MultiClusterConfiguration> GetMultiClusterConfiguration() { return Task.FromResult(GetMultiClusterOracle().GetMultiClusterConfiguration()); } public async Task<MultiClusterConfiguration> InjectMultiClusterConfiguration(IEnumerable<string> clusters, string comment = "", bool checkForLaggingSilosFirst = true) { var multiClusterOracle = GetMultiClusterOracle(); var configuration = new MultiClusterConfiguration(DateTime.UtcNow, clusters.ToList(), comment); if (!MultiClusterConfiguration.OlderThan(multiClusterOracle.GetMultiClusterConfiguration(), configuration)) throw new OrleansException("Could not inject multi-cluster configuration: current configuration is newer than clock"); if (checkForLaggingSilosFirst) { try { var laggingSilos = await multiClusterOracle.FindLaggingSilos(multiClusterOracle.GetMultiClusterConfiguration()); if (laggingSilos.Count > 0) { var msg = string.Format("Found unstable silos {0}", string.Join(",", laggingSilos)); throw new OrleansException(msg); } } catch (Exception e) { throw new OrleansException("Could not inject multi-cluster configuration: stability check failed", e); } } await multiClusterOracle.InjectMultiClusterConfiguration(configuration); return configuration; } public Task<List<SiloAddress>> FindLaggingSilos() { var multiClusterOracle = GetMultiClusterOracle(); var expected = multiClusterOracle.GetMultiClusterConfiguration(); return multiClusterOracle.FindLaggingSilos(expected); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using Microsoft.Cci.MetadataReader.Errors; using Microsoft.Cci.MetadataReader.PEFile; using Microsoft.Cci.MetadataReader.PEFileFlags; using Microsoft.Cci.UtilityDataStructures; using Microsoft.Cci.Immutable; namespace Microsoft.Cci.MetadataReader.MethodBody { using Microsoft.Cci.MetadataReader.ObjectModelImplementation; internal sealed class MethodBody : IMethodBody { internal readonly MethodDefinition MethodDefinition; internal ILocalDefinition[]/*?*/ LocalVariables; internal IEnumerable<IOperation>/*?*/ cilInstructions; IEnumerable<IOperationExceptionInformation>/*?*/ cilExceptionInformation; internal readonly bool IsLocalsInited; internal readonly ushort StackSize; readonly uint bodySize; internal MethodBody(MethodDefinition methodDefinition, bool isLocalsInited, ushort stackSize, uint bodySize) { this.MethodDefinition = methodDefinition; this.IsLocalsInited = isLocalsInited; this.LocalVariables = null; this.StackSize = stackSize; this.bodySize = bodySize; } internal void SetLocalVariables(ILocalDefinition[] localVariables) { this.LocalVariables = localVariables; } internal void SetCilInstructions(IEnumerable<IOperation> cilInstructions) { this.cilInstructions = cilInstructions; } internal void SetExceptionInformation(IOperationExceptionInformation[] cilExceptionInformation) { this.cilExceptionInformation = IteratorHelper.GetReadonly(cilExceptionInformation); } #region IMethodBody Members IMethodDefinition IMethodBody.MethodDefinition { get { return this.MethodDefinition; } } public void Dispatch(IMetadataVisitor visitor) { visitor.Visit(this); } IEnumerable<ILocalDefinition> IMethodBody.LocalVariables { get { if (this.LocalVariables == null) return Enumerable<ILocalDefinition>.Empty; return IteratorHelper.GetReadonly(this.LocalVariables); } } bool IMethodBody.LocalsAreZeroed { get { return this.IsLocalsInited; } } public IEnumerable<IOperation> Operations { get { if (this.cilInstructions == null) return Enumerable<IOperation>.Empty; ILOperationList opList = cilInstructions as ILOperationList; // When Operations is first called on ILOperationList, convert to it normal IEnumerable<IOperation> and then throw away ILOperationList // When copying directly to mutable object model, we have special path to generate List<Operation> directly (in CopyMethodBody) if (opList != null) { cilInstructions = opList.GetAllOperations(); } return this.cilInstructions; } } public IEnumerable<ITypeDefinition> PrivateHelperTypes { get { return Enumerable<ITypeDefinition>.Empty; } } public ushort MaxStack { get { return this.StackSize; } } public IEnumerable<IOperationExceptionInformation> OperationExceptionInformation { get { if (this.cilExceptionInformation == null) return Enumerable<IOperationExceptionInformation>.Empty; return this.cilExceptionInformation; } } public uint Size { get { return this.bodySize; } } #endregion } internal sealed class LocalVariableDefinition : ILocalDefinition { internal LocalVariableDefinition(MethodBody methodBody, IEnumerable<ICustomModifier>/*?*/ customModifiers, bool isPinned, bool isReference, uint index, ITypeReference typeReference) { this.methodBody = methodBody; this.customModifiers = customModifiers; this.isPinned = isPinned; this.isReference = isReference; this.index = index; this.typeReference = typeReference; } readonly MethodBody methodBody; readonly IEnumerable<ICustomModifier>/*?*/ customModifiers; readonly bool isPinned; readonly bool isReference; readonly uint index; readonly ITypeReference typeReference; public override string ToString() { return this.Name.Value; } #region ILocalDefinition Members IMetadataConstant ILocalDefinition.CompileTimeValue { get { return Dummy.Constant; } } IEnumerable<ICustomModifier> ILocalDefinition.CustomModifiers { get { if (this.customModifiers == null) return Enumerable<ICustomModifier>.Empty; return this.customModifiers; } } bool ILocalDefinition.IsConstant { get { return false; } } bool ILocalDefinition.IsModified { get { return this.customModifiers != null; } } bool ILocalDefinition.IsPinned { get { return this.isPinned; } } bool ILocalDefinition.IsReference { get { return this.isReference; } } public IEnumerable<ILocation> Locations { get { MethodBodyLocation mbLoc = new MethodBodyLocation(methodBody.MethodDefinition.BodyDocument, this.index); return new SingletonList<ILocation>(mbLoc); } } public IMethodDefinition MethodDefinition { get { return this.methodBody.MethodDefinition; } } public ITypeReference Type { get { return this.typeReference; } } #endregion #region INamedEntity Members public IName Name { get { if (this.name == null) this.name = this.methodBody.MethodDefinition.PEFileToObjectModel.NameTable.GetNameFor(Toolbox.GetLocalName(this.index)); return this.name; } } IName/*?*/ name; #endregion } internal sealed class CilInstruction : IOperation, IILLocation { internal readonly OperationCode CilOpCode; MethodBodyDocument document; uint offset; internal readonly object/*?*/ Value; internal CilInstruction(OperationCode cilOpCode, MethodBodyDocument document, uint offset, object/*?*/ value) { this.CilOpCode = cilOpCode; this.document = document; this.offset = offset; this.Value = value; } #region ICilInstruction Members public OperationCode OperationCode { get { return this.CilOpCode; } } uint IOperation.Offset { get { return this.offset; } } ILocation IOperation.Location { get { return this; } } object/*?*/ IOperation.Value { get { return this.Value; } } #endregion #region IILLocation Members public IMethodDefinition MethodDefinition { get { return this.document.method; } } uint IILLocation.Offset { get { return this.offset; } } #endregion #region ILocation Members public IDocument Document { get { return this.document; } } #endregion } internal sealed class CilExceptionInformation : IOperationExceptionInformation { internal readonly HandlerKind HandlerKind; internal readonly ITypeReference ExceptionType; internal readonly uint TryStartOffset; internal readonly uint TryEndOffset; internal readonly uint FilterDecisionStartOffset; internal readonly uint HandlerStartOffset; internal readonly uint HandlerEndOffset; internal CilExceptionInformation( HandlerKind handlerKind, ITypeReference exceptionType, uint tryStartOffset, uint tryEndOffset, uint filterDecisionStartOffset, uint handlerStartOffset, uint handlerEndOffset ) { this.HandlerKind = handlerKind; this.ExceptionType = exceptionType; this.TryStartOffset = tryStartOffset; this.TryEndOffset = tryEndOffset; this.FilterDecisionStartOffset = filterDecisionStartOffset; this.HandlerStartOffset = handlerStartOffset; this.HandlerEndOffset = handlerEndOffset; } #region IOperationExceptionInformation Members HandlerKind IOperationExceptionInformation.HandlerKind { get { return this.HandlerKind; } } ITypeReference IOperationExceptionInformation.ExceptionType { get { return this.ExceptionType; } } uint IOperationExceptionInformation.TryStartOffset { get { return this.TryStartOffset; } } uint IOperationExceptionInformation.TryEndOffset { get { return this.TryEndOffset; } } uint IOperationExceptionInformation.FilterDecisionStartOffset { get { return this.FilterDecisionStartOffset; } } uint IOperationExceptionInformation.HandlerStartOffset { get { return this.HandlerStartOffset; } } uint IOperationExceptionInformation.HandlerEndOffset { get { return this.HandlerEndOffset; } } #endregion } internal sealed class LocalVariableSignatureConverter : SignatureConverter { internal readonly ILocalDefinition[] LocalVariables; readonly MethodBody OwningMethodBody; LocalVariableDefinition GetLocalVariable(uint index) { bool isPinned = false; bool isByReferenece = false; IEnumerable<ICustomModifier>/*?*/ customModifiers = null; byte currByte = this.SignatureMemoryReader.PeekByte(0); ITypeReference/*?*/ typeReference; if (currByte == ElementType.TypedReference) { this.SignatureMemoryReader.SkipBytes(1); typeReference = this.PEFileToObjectModel.PlatformType.SystemTypedReference; } else { customModifiers = this.GetCustomModifiers(out isPinned); currByte = this.SignatureMemoryReader.PeekByte(0); if (currByte == ElementType.ByReference) { this.SignatureMemoryReader.SkipBytes(1); isByReferenece = true; } typeReference = this.GetTypeReference(); } if (typeReference == null) typeReference = Dummy.TypeReference; return new LocalVariableDefinition(this.OwningMethodBody, customModifiers, isPinned, isByReferenece, index, typeReference); } internal LocalVariableSignatureConverter( PEFileToObjectModel peFileToObjectModel, MethodBody owningMethodBody, MemoryReader signatureMemoryReader ) : base(peFileToObjectModel, signatureMemoryReader, owningMethodBody.MethodDefinition) { this.OwningMethodBody = owningMethodBody; byte firstByte = this.SignatureMemoryReader.ReadByte(); if (!SignatureHeader.IsLocalVarSignature(firstByte)) { // MDError } int locVarCount = this.SignatureMemoryReader.ReadCompressedUInt32(); LocalVariableDefinition[] locVarArr = new LocalVariableDefinition[locVarCount]; for (int i = 0; i < locVarCount; ++i) { locVarArr[i] = this.GetLocalVariable((uint)i); } this.LocalVariables = locVarArr; } } internal sealed class StandAloneMethodSignatureConverter : SignatureConverter { internal readonly byte FirstByte; internal readonly IEnumerable<ICustomModifier>/*?*/ ReturnCustomModifiers; internal readonly ITypeReference/*?*/ ReturnTypeReference; internal readonly bool IsReturnByReference; internal readonly IEnumerable<IParameterTypeInformation> RequiredParameters; internal readonly IEnumerable<IParameterTypeInformation> VarArgParameters; internal StandAloneMethodSignatureConverter(PEFileToObjectModel peFileToObjectModel, MethodDefinition moduleMethodDef, MemoryReader signatureMemoryReader) : base(peFileToObjectModel, signatureMemoryReader, moduleMethodDef) { this.RequiredParameters = Enumerable<IParameterTypeInformation>.Empty; this.VarArgParameters = Enumerable<IParameterTypeInformation>.Empty; // TODO: Check minimum required size of the signature... this.FirstByte = this.SignatureMemoryReader.ReadByte(); int paramCount = this.SignatureMemoryReader.ReadCompressedUInt32(); bool dummyPinned; this.ReturnCustomModifiers = this.GetCustomModifiers(out dummyPinned); byte retByte = this.SignatureMemoryReader.PeekByte(0); if (retByte == ElementType.Void) { this.ReturnTypeReference = peFileToObjectModel.PlatformType.SystemVoid; this.SignatureMemoryReader.SkipBytes(1); } else if (retByte == ElementType.TypedReference) { this.ReturnTypeReference = peFileToObjectModel.PlatformType.SystemTypedReference; this.SignatureMemoryReader.SkipBytes(1); } else { if (retByte == ElementType.ByReference) { this.IsReturnByReference = true; this.SignatureMemoryReader.SkipBytes(1); } this.ReturnTypeReference = this.GetTypeReference(); } if (paramCount > 0) { IParameterTypeInformation[] reqModuleParamArr = this.GetModuleParameterTypeInformations(Dummy.Signature, paramCount); if (reqModuleParamArr.Length > 0) this.RequiredParameters = IteratorHelper.GetReadonly(reqModuleParamArr); IParameterTypeInformation[] varArgModuleParamArr = this.GetModuleParameterTypeInformations(Dummy.Signature, paramCount - reqModuleParamArr.Length); if (varArgModuleParamArr.Length > 0) this.VarArgParameters = IteratorHelper.GetReadonly(varArgModuleParamArr); } } } /// <summary> /// List of operations decoded on-demand /// </summary> /// <remarks>Offsets for each instruction is read first for IReadOnlyList implementation</remarks> internal class ILOperationList : VirtualReadOnlyList<IOperation> { ILReader m_reader; uint[] m_offsets; internal ILOperationList(ILReader reader, int count) : base(count) { m_reader = reader; } void LoadOffsets() { if (m_offsets == null) { MemoryReader memReader = new MemoryReader(m_reader.MethodIL.EncodedILMemoryBlock); m_offsets = new uint[this.Count]; // Populate m_offsets array ILReader.CountCilInstructions(memReader, m_offsets); } } internal void FreeOffsets() { m_offsets = null; } /// <summary> /// Read a single instruction for virtual read only list implementation /// </summary> /// <param name="index"></param> /// <returns></returns> public override IOperation GetItem(int index) { LoadOffsets(); return m_reader.GetIOperation(m_offsets[index]); } #if MERGED_DLL /// <summary> /// Generate a single mutable Operation /// </summary> internal MutableCodeModel.Operation GetOperation(int index) { LoadOffsets(); return m_reader.GetOperation(m_offsets[index]); } #endif /// <summary> /// Generate IEnumerable{IOperation} /// </summary> internal IEnumerable<IOperation> GetAllOperations() { LoadOffsets(); IOperation[] opers = new IOperation[this.Count]; for (int i = 0; i < this.Count; i ++) { opers[i] = m_reader.GetIOperation(m_offsets[i]); } return opers; } /// <summary> /// Retrieve from MethodBody without trigger conversion /// </summary> internal static ILOperationList RetrieveFrom(IMethodBody body) { MethodBody readerBody = body as MethodBody; if (readerBody != null) { return readerBody.cilInstructions as ILOperationList; } return null; } } internal sealed class ILReader { internal static readonly EnumerableArrayWrapper<LocalVariableDefinition, ILocalDefinition> EmptyLocalVariables = new EnumerableArrayWrapper<LocalVariableDefinition, ILocalDefinition>(new LocalVariableDefinition[0], Dummy.LocalVariable); static readonly HandlerKind[] HandlerKindMap = new HandlerKind[] { HandlerKind.Catch, // 0 HandlerKind.Filter, // 1 HandlerKind.Finally, // 2 HandlerKind.Illegal, // 3 HandlerKind.Fault, // 4 HandlerKind.Illegal, // 5+ }; internal readonly PEFileToObjectModel PEFileToObjectModel; internal readonly MethodDefinition MethodDefinition; internal readonly MethodBody MethodBody; internal readonly MethodIL MethodIL; internal readonly uint EndOfMethodOffset; internal ILReader( MethodDefinition methodDefinition, MethodIL methodIL ) { this.MethodDefinition = methodDefinition; this.PEFileToObjectModel = methodDefinition.PEFileToObjectModel; this.MethodIL = methodIL; this.EndOfMethodOffset = (uint)methodIL.EncodedILMemoryBlock.Length; this.MethodBody = new MethodBody(methodDefinition, methodIL.LocalVariablesInited, methodIL.MaxStack, this.EndOfMethodOffset); } bool LoadLocalSignature() { uint locVarRID = this.MethodIL.LocalSignatureToken & TokenTypeIds.RIDMask; if (locVarRID != 0x00000000) { StandAloneSigRow sigRow = this.PEFileToObjectModel.PEFileReader.StandAloneSigTable[locVarRID]; // TODO: error checking offset in range MemoryBlock signatureMemoryBlock = this.PEFileToObjectModel.PEFileReader.BlobStream.GetMemoryBlockAt(sigRow.Signature); // TODO: Error checking enough space in signature memoryBlock. MemoryReader memoryReader = new MemoryReader(signatureMemoryBlock); // TODO: Check if this is really local var signature there. LocalVariableSignatureConverter locVarSigConv = new LocalVariableSignatureConverter(this.PEFileToObjectModel, this.MethodBody, memoryReader); this.MethodBody.SetLocalVariables(locVarSigConv.LocalVariables); } return true; } string GetUserStringForToken( uint token ) { if ((token & TokenTypeIds.TokenTypeMask) != TokenTypeIds.String) { // Error... return string.Empty; } return this.PEFileToObjectModel.PEFileReader.UserStringStream[token & TokenTypeIds.RIDMask]; } FunctionPointerType/*?*/ GetStandAloneMethodSignature(uint standAloneMethodToken) { StandAloneSigRow sigRow = this.PEFileToObjectModel.PEFileReader.StandAloneSigTable[standAloneMethodToken & TokenTypeIds.RIDMask]; uint signatureBlobOffset = sigRow.Signature; // TODO: error checking offset in range MemoryBlock signatureMemoryBlock = this.PEFileToObjectModel.PEFileReader.BlobStream.GetMemoryBlockAt(signatureBlobOffset); // TODO: Error checking enough space in signature memoryBlock. MemoryReader memoryReader = new MemoryReader(signatureMemoryBlock); // TODO: Check if this is really field signature there. StandAloneMethodSignatureConverter standAloneSigConv = new StandAloneMethodSignatureConverter(this.PEFileToObjectModel, this.MethodDefinition, memoryReader); if (standAloneSigConv.ReturnTypeReference == null) return null; return new FunctionPointerType((CallingConvention)standAloneSigConv.FirstByte, standAloneSigConv.IsReturnByReference, standAloneSigConv.ReturnTypeReference, standAloneSigConv.ReturnCustomModifiers, standAloneSigConv.RequiredParameters, standAloneSigConv.VarArgParameters, this.PEFileToObjectModel.InternFactory); } IParameterDefinition/*?*/ GetParameter(uint rawParamNum) { if (!this.MethodDefinition.IsStatic) { if (rawParamNum == 0) return null; //this rawParamNum--; } IParameterDefinition[] mpa = this.MethodDefinition.RequiredModuleParameters; if (mpa != null && rawParamNum < mpa.Length) return mpa[rawParamNum]; // Error... return Dummy.ParameterDefinition; } ILocalDefinition GetLocal( uint rawLocNum ) { var locVarDef = this.MethodBody.LocalVariables; if (locVarDef != null && rawLocNum < locVarDef.Length) return locVarDef[rawLocNum]; // Error... return Dummy.LocalVariable; } IMethodReference GetMethod( uint methodToken ) { IMethodReference mmr = this.PEFileToObjectModel.GetMethodReferenceForToken(this.MethodDefinition, methodToken); return mmr; } IFieldReference GetField( uint fieldToken ) { IFieldReference mfr = this.PEFileToObjectModel.GetFieldReferenceForToken(this.MethodDefinition, fieldToken); return mfr; } ITypeReference GetType( uint typeToken ) { ITypeReference/*?*/ mtr = this.PEFileToObjectModel.GetTypeReferenceForToken(this.MethodDefinition, typeToken); if (mtr != null) return mtr; // Error... return Dummy.TypeReference; } IFunctionPointerTypeReference GetFunctionPointerType( uint standAloneSigToken ) { FunctionPointerType/*?*/ fpt = this.GetStandAloneMethodSignature(standAloneSigToken); if (fpt != null) return fpt; // Error... return Dummy.FunctionPointer; } object/*?*/ GetRuntimeHandleFromToken( uint token ) { return this.PEFileToObjectModel.GetReferenceForToken(this.MethodDefinition, token); } static object c_I4_M1 = -1; static object c_I4_0 = 0; static object c_I4_1 = 1; static object c_I4_2 = 2; static object c_I4_3 = 3; static object c_I4_4 = 4; static object c_I4_5 = 5; static object c_I4_6 = 6; static object c_I4_7 = 7; static object c_I4_8 = 8; MethodBodyDocument m_document; bool PopulateCilInstructions() { MemoryReader memReader = new MemoryReader(this.MethodIL.EncodedILMemoryBlock); var numInstructions = CountCilInstructions(memReader, null); if (numInstructions != 0) this.MethodBody.SetCilInstructions(new ILOperationList(this, numInstructions)); return true; } /// <summary> /// Read single instruction on-demand, returning an new object, for IEnumerable{IOperation} /// </summary> internal IOperation GetIOperation(uint offset) { OperationCode cilOpCode; object value = ReadInstruction(offset, out cilOpCode); if (m_document == null) { m_document = this.MethodDefinition.BodyDocument; } return new CilInstruction(cilOpCode, m_document, offset, value); } #if MERGED_DLL /// <summary> /// Read single instruction on-demand, returning an new object, for mutable object model /// </summary> internal MutableCodeModel.Operation GetOperation(uint offset) { OperationCode cilOpCode; object value = ReadInstruction(offset, out cilOpCode); if (m_document == null) { m_document = this.MethodDefinition.BodyDocument; } MutableCodeModel.Operation oper = new MutableCodeModel.Operation(m_document, offset, cilOpCode, value); return oper; } #endif /// <summary> /// Read single instruction on-demand /// </summary> private object ReadInstruction(uint offset, out OperationCode cilOpCode) { MemoryReader memReader = new MemoryReader(this.MethodIL.EncodedILMemoryBlock); memReader.SeekOffset((int) offset); cilOpCode = memReader.ReadOpcode(); object/*?*/ value = null; switch (cilOpCode) { case OperationCode.Nop: case OperationCode.Break: break; case OperationCode.Ldarg_0: case OperationCode.Ldarg_1: case OperationCode.Ldarg_2: case OperationCode.Ldarg_3: value = this.GetParameter((uint)(cilOpCode - OperationCode.Ldarg_0)); break; case OperationCode.Ldloc_0: case OperationCode.Ldloc_1: case OperationCode.Ldloc_2: case OperationCode.Ldloc_3: value = this.GetLocal((uint)(cilOpCode - OperationCode.Ldloc_0)); break; case OperationCode.Stloc_0: case OperationCode.Stloc_1: case OperationCode.Stloc_2: case OperationCode.Stloc_3: value = this.GetLocal((uint)(cilOpCode - OperationCode.Stloc_0)); break; case OperationCode.Ldarg_S: case OperationCode.Ldarga_S: case OperationCode.Starg_S: value = this.GetParameter(memReader.ReadByte()); break; case OperationCode.Ldloc_S: case OperationCode.Ldloca_S: case OperationCode.Stloc_S: value = this.GetLocal(memReader.ReadByte()); break; case OperationCode.Ldnull: break; case OperationCode.Ldc_I4_M1: value = c_I4_M1; break; case OperationCode.Ldc_I4_0: value = c_I4_0; break; case OperationCode.Ldc_I4_1: value = c_I4_1; break; case OperationCode.Ldc_I4_2: value = c_I4_2; break; case OperationCode.Ldc_I4_3: value = c_I4_3; break; case OperationCode.Ldc_I4_4: value = c_I4_4; break; case OperationCode.Ldc_I4_5: value = c_I4_5; break; case OperationCode.Ldc_I4_6: value = c_I4_6; break; case OperationCode.Ldc_I4_7: value = c_I4_7; break; case OperationCode.Ldc_I4_8: value = c_I4_8; break; case OperationCode.Ldc_I4_S: value = (int)memReader.ReadSByte(); break; case OperationCode.Ldc_I4: value = memReader.ReadInt32(); break; case OperationCode.Ldc_I8: value = memReader.ReadInt64(); break; case OperationCode.Ldc_R4: value = memReader.ReadSingle(); break; case OperationCode.Ldc_R8: value = memReader.ReadDouble(); break; case OperationCode.Dup: case OperationCode.Pop: break; case OperationCode.Jmp: value = this.GetMethod(memReader.ReadUInt32()); break; case OperationCode.Call: { IMethodReference methodReference = this.GetMethod(memReader.ReadUInt32()); IArrayTypeReference/*?*/ arrayType = methodReference.ContainingType as IArrayTypeReference; if (arrayType != null) { // For Get(), Set() and Address() on arrays, the runtime provides method implementations. // Hence, CCI2 replaces these with pseudo instructions Array_Set, Array_Get and Array_Addr. // All other methods on arrays will not use pseudo instruction and will have methodReference as their operand. if (methodReference.Name.UniqueKey == this.PEFileToObjectModel.NameTable.Set.UniqueKey) { cilOpCode = OperationCode.Array_Set; value = arrayType; } else if (methodReference.Name.UniqueKey == this.PEFileToObjectModel.NameTable.Get.UniqueKey) { cilOpCode = OperationCode.Array_Get; value = arrayType; } else if (methodReference.Name.UniqueKey == this.PEFileToObjectModel.NameTable.Address.UniqueKey) { cilOpCode = OperationCode.Array_Addr; value = arrayType; } else { value = methodReference; } } else { value = methodReference; } } break; case OperationCode.Calli: value = this.GetFunctionPointerType(memReader.ReadUInt32()); break; case OperationCode.Ret: break; case OperationCode.Br_S: case OperationCode.Brfalse_S: case OperationCode.Brtrue_S: case OperationCode.Beq_S: case OperationCode.Bge_S: case OperationCode.Bgt_S: case OperationCode.Ble_S: case OperationCode.Blt_S: case OperationCode.Bne_Un_S: case OperationCode.Bge_Un_S: case OperationCode.Bgt_Un_S: case OperationCode.Ble_Un_S: case OperationCode.Blt_Un_S: { uint jumpOffset = (uint)(memReader.Offset + 1 + memReader.ReadSByte()); if (jumpOffset >= this.EndOfMethodOffset) { // Error... } value = jumpOffset; } break; case OperationCode.Br: case OperationCode.Brfalse: case OperationCode.Brtrue: case OperationCode.Beq: case OperationCode.Bge: case OperationCode.Bgt: case OperationCode.Ble: case OperationCode.Blt: case OperationCode.Bne_Un: case OperationCode.Bge_Un: case OperationCode.Bgt_Un: case OperationCode.Ble_Un: case OperationCode.Blt_Un: { uint jumpOffset = (uint)(memReader.Offset + 4 + memReader.ReadInt32()); if (jumpOffset >= this.EndOfMethodOffset) { // Error... } value = jumpOffset; } break; case OperationCode.Switch: { uint numTargets = memReader.ReadUInt32(); uint[] result = new uint[numTargets]; uint asOffset = memReader.Offset + numTargets * 4; for (int i = 0; i < numTargets; i++) { uint targetAddress = memReader.ReadUInt32() + asOffset; if (targetAddress >= this.EndOfMethodOffset) { // Error... } result[i] = targetAddress; } value = result; } break; case OperationCode.Ldind_I1: case OperationCode.Ldind_U1: case OperationCode.Ldind_I2: case OperationCode.Ldind_U2: case OperationCode.Ldind_I4: case OperationCode.Ldind_U4: case OperationCode.Ldind_I8: case OperationCode.Ldind_I: case OperationCode.Ldind_R4: case OperationCode.Ldind_R8: case OperationCode.Ldind_Ref: case OperationCode.Stind_Ref: case OperationCode.Stind_I1: case OperationCode.Stind_I2: case OperationCode.Stind_I4: case OperationCode.Stind_I8: case OperationCode.Stind_R4: case OperationCode.Stind_R8: case OperationCode.Add: case OperationCode.Sub: case OperationCode.Mul: case OperationCode.Div: case OperationCode.Div_Un: case OperationCode.Rem: case OperationCode.Rem_Un: case OperationCode.And: case OperationCode.Or: case OperationCode.Xor: case OperationCode.Shl: case OperationCode.Shr: case OperationCode.Shr_Un: case OperationCode.Neg: case OperationCode.Not: case OperationCode.Conv_I1: case OperationCode.Conv_I2: case OperationCode.Conv_I4: case OperationCode.Conv_I8: case OperationCode.Conv_R4: case OperationCode.Conv_R8: case OperationCode.Conv_U4: case OperationCode.Conv_U8: break; case OperationCode.Callvirt: { IMethodReference methodReference = this.GetMethod(memReader.ReadUInt32()); IArrayTypeReference/*?*/ arrayType = methodReference.ContainingType as IArrayTypeReference; if (arrayType != null) { // For Get(), Set() and Address() on arrays, the runtime provides method implementations. // Hence, CCI2 replaces these with pseudo instructions Array_Set, Array_Get and Array_Addr. // All other methods on arrays will not use pseudo instruction and will have methodReference as their operand. if (methodReference.Name.UniqueKey == this.PEFileToObjectModel.NameTable.Set.UniqueKey) { cilOpCode = OperationCode.Array_Set; value = arrayType; } else if (methodReference.Name.UniqueKey == this.PEFileToObjectModel.NameTable.Get.UniqueKey) { cilOpCode = OperationCode.Array_Get; value = arrayType; } else if (methodReference.Name.UniqueKey == this.PEFileToObjectModel.NameTable.Address.UniqueKey) { cilOpCode = OperationCode.Array_Addr; value = arrayType; } else { value = methodReference; } } else { value = methodReference; } } break; case OperationCode.Cpobj: case OperationCode.Ldobj: value = this.GetType(memReader.ReadUInt32()); break; case OperationCode.Ldstr: value = this.GetUserStringForToken(memReader.ReadUInt32()); break; case OperationCode.Newobj: { IMethodReference methodReference = this.GetMethod(memReader.ReadUInt32()); IArrayTypeReference/*?*/ arrayType = methodReference.ContainingType as IArrayTypeReference; if (arrayType != null && !arrayType.IsVector) { uint numParam = IteratorHelper.EnumerableCount(methodReference.Parameters); if (numParam != arrayType.Rank) cilOpCode = OperationCode.Array_Create_WithLowerBound; else cilOpCode = OperationCode.Array_Create; value = arrayType; } else { value = methodReference; } } break; case OperationCode.Castclass: case OperationCode.Isinst: value = this.GetType(memReader.ReadUInt32()); break; case OperationCode.Conv_R_Un: break; case OperationCode.Unbox: value = this.GetType(memReader.ReadUInt32()); break; case OperationCode.Throw: break; case OperationCode.Ldfld: case OperationCode.Ldflda: case OperationCode.Stfld: value = this.GetField(memReader.ReadUInt32()); break; case OperationCode.Ldsfld: case OperationCode.Ldsflda: case OperationCode.Stsfld: value = this.GetField(memReader.ReadUInt32()); var fieldRef = value as FieldReference; if (fieldRef != null) fieldRef.isStatic = true; break; case OperationCode.Stobj: value = this.GetType(memReader.ReadUInt32()); break; case OperationCode.Conv_Ovf_I1_Un: case OperationCode.Conv_Ovf_I2_Un: case OperationCode.Conv_Ovf_I4_Un: case OperationCode.Conv_Ovf_I8_Un: case OperationCode.Conv_Ovf_U1_Un: case OperationCode.Conv_Ovf_U2_Un: case OperationCode.Conv_Ovf_U4_Un: case OperationCode.Conv_Ovf_U8_Un: case OperationCode.Conv_Ovf_I_Un: case OperationCode.Conv_Ovf_U_Un: break; case OperationCode.Box: value = this.GetType(memReader.ReadUInt32()); break; case OperationCode.Newarr: { var elementType = this.GetType(memReader.ReadUInt32()); if (elementType != null) value = Vector.GetVector(elementType, PEFileToObjectModel.InternFactory); else value = Dummy.ArrayType; } break; case OperationCode.Ldlen: break; case OperationCode.Ldelema: value = this.GetType(memReader.ReadUInt32()); break; case OperationCode.Ldelem_I1: case OperationCode.Ldelem_U1: case OperationCode.Ldelem_I2: case OperationCode.Ldelem_U2: case OperationCode.Ldelem_I4: case OperationCode.Ldelem_U4: case OperationCode.Ldelem_I8: case OperationCode.Ldelem_I: case OperationCode.Ldelem_R4: case OperationCode.Ldelem_R8: case OperationCode.Ldelem_Ref: case OperationCode.Stelem_I: case OperationCode.Stelem_I1: case OperationCode.Stelem_I2: case OperationCode.Stelem_I4: case OperationCode.Stelem_I8: case OperationCode.Stelem_R4: case OperationCode.Stelem_R8: case OperationCode.Stelem_Ref: break; case OperationCode.Ldelem: value = this.GetType(memReader.ReadUInt32()); break; case OperationCode.Stelem: value = this.GetType(memReader.ReadUInt32()); break; case OperationCode.Unbox_Any: value = this.GetType(memReader.ReadUInt32()); break; case OperationCode.Conv_Ovf_I1: case OperationCode.Conv_Ovf_U1: case OperationCode.Conv_Ovf_I2: case OperationCode.Conv_Ovf_U2: case OperationCode.Conv_Ovf_I4: case OperationCode.Conv_Ovf_U4: case OperationCode.Conv_Ovf_I8: case OperationCode.Conv_Ovf_U8: break; case OperationCode.Refanyval: value = this.GetType(memReader.ReadUInt32()); break; case OperationCode.Ckfinite: break; case OperationCode.Mkrefany: value = this.GetType(memReader.ReadUInt32()); break; case OperationCode.Ldtoken: value = this.GetRuntimeHandleFromToken(memReader.ReadUInt32()); break; case OperationCode.Conv_U2: case OperationCode.Conv_U1: case OperationCode.Conv_I: case OperationCode.Conv_Ovf_I: case OperationCode.Conv_Ovf_U: case OperationCode.Add_Ovf: case OperationCode.Add_Ovf_Un: case OperationCode.Mul_Ovf: case OperationCode.Mul_Ovf_Un: case OperationCode.Sub_Ovf: case OperationCode.Sub_Ovf_Un: case OperationCode.Endfinally: break; case OperationCode.Leave: { uint leaveOffset = (uint)(memReader.Offset + 4 + memReader.ReadInt32()); if (leaveOffset >= this.EndOfMethodOffset) { // Error... } value = leaveOffset; } break; case OperationCode.Leave_S: { uint leaveOffset = (uint)(memReader.Offset + 1 + memReader.ReadSByte()); if (leaveOffset >= this.EndOfMethodOffset) { // Error... } value = leaveOffset; } break; case OperationCode.Stind_I: case OperationCode.Conv_U: case OperationCode.Arglist: case OperationCode.Ceq: case OperationCode.Cgt: case OperationCode.Cgt_Un: case OperationCode.Clt: case OperationCode.Clt_Un: break; case OperationCode.Ldftn: case OperationCode.Ldvirtftn: value = this.GetMethod(memReader.ReadUInt32()); break; case OperationCode.Ldarg: case OperationCode.Ldarga: case OperationCode.Starg: value = this.GetParameter(memReader.ReadUInt16()); break; case OperationCode.Ldloc: case OperationCode.Ldloca: case OperationCode.Stloc: value = this.GetLocal(memReader.ReadUInt16()); break; case OperationCode.Localloc: break; case OperationCode.Endfilter: break; case OperationCode.Unaligned_: value = memReader.ReadByte(); break; case OperationCode.Volatile_: case OperationCode.Tail_: break; case OperationCode.Initobj: value = this.GetType(memReader.ReadUInt32()); break; case OperationCode.Constrained_: value = this.GetType(memReader.ReadUInt32()); break; case OperationCode.Cpblk: case OperationCode.Initblk: break; case OperationCode.No_: value = (OperationCheckFlags)memReader.ReadByte(); break; case OperationCode.Rethrow: break; case OperationCode.Sizeof: value = this.GetType(memReader.ReadUInt32()); break; case OperationCode.Refanytype: case OperationCode.Readonly_: break; default: this.PEFileToObjectModel.PEFileReader.ErrorContainer.AddILError(this.MethodDefinition, offset, MetadataReaderErrorKind.UnknownILInstruction); break; } return value; } internal static int CountCilInstructions(MemoryReader memReader, uint[] offsets) { int count = 0; while (memReader.NotEndOfBytes) { if (offsets != null) offsets[count] = (uint)memReader.Offset; count++; OperationCode cilOpCode = memReader.ReadOpcode(); switch (cilOpCode) { case OperationCode.Ldarg_S: case OperationCode.Ldarga_S: case OperationCode.Starg_S: case OperationCode.Ldloc_S: case OperationCode.Ldloca_S: case OperationCode.Stloc_S: case OperationCode.Ldc_I4_S: case OperationCode.Br_S: case OperationCode.Brfalse_S: case OperationCode.Brtrue_S: case OperationCode.Beq_S: case OperationCode.Bge_S: case OperationCode.Bgt_S: case OperationCode.Ble_S: case OperationCode.Blt_S: case OperationCode.Bne_Un_S: case OperationCode.Bge_Un_S: case OperationCode.Bgt_Un_S: case OperationCode.Ble_Un_S: case OperationCode.Blt_Un_S: case OperationCode.Leave_S: case OperationCode.Unaligned_: case OperationCode.No_: memReader.SkipBytes(1); break; case OperationCode.Ldarg: case OperationCode.Ldarga: case OperationCode.Starg: case OperationCode.Ldloc: case OperationCode.Ldloca: case OperationCode.Stloc: memReader.SkipBytes(2); break; case OperationCode.Ldc_I4: case OperationCode.Jmp: case OperationCode.Call: case OperationCode.Calli: case OperationCode.Br: case OperationCode.Brfalse: case OperationCode.Brtrue: case OperationCode.Beq: case OperationCode.Bge: case OperationCode.Bgt: case OperationCode.Ble: case OperationCode.Blt: case OperationCode.Bne_Un: case OperationCode.Bge_Un: case OperationCode.Bgt_Un: case OperationCode.Ble_Un: case OperationCode.Blt_Un: case OperationCode.Callvirt: case OperationCode.Cpobj: case OperationCode.Ldobj: case OperationCode.Ldstr: case OperationCode.Newobj: case OperationCode.Castclass: case OperationCode.Isinst: case OperationCode.Unbox: case OperationCode.Ldfld: case OperationCode.Ldflda: case OperationCode.Stfld: case OperationCode.Ldsfld: case OperationCode.Ldsflda: case OperationCode.Stsfld: case OperationCode.Stobj: case OperationCode.Box: case OperationCode.Newarr: case OperationCode.Ldelema: case OperationCode.Ldelem: case OperationCode.Stelem: case OperationCode.Unbox_Any: case OperationCode.Refanyval: case OperationCode.Mkrefany: case OperationCode.Ldtoken: case OperationCode.Leave: case OperationCode.Ldftn: case OperationCode.Ldvirtftn: case OperationCode.Initobj: case OperationCode.Constrained_: case OperationCode.Sizeof: case OperationCode.Ldc_R4: memReader.SkipBytes(4); break; case OperationCode.Ldc_I8: case OperationCode.Ldc_R8: memReader.SkipBytes(8); break; case OperationCode.Switch: int numTargets = (int)memReader.ReadUInt32(); memReader.SkipBytes(4*numTargets); break; default: break; } } memReader.SeekOffset(0); return count; } bool PopulateExceptionInformation() { SEHTableEntry[]/*?*/ sehTable = this.MethodIL.SEHTable; if (sehTable != null) { int n = sehTable.Length; var exceptions = new IOperationExceptionInformation[n]; for (int i = 0; i < n; i++) { SEHTableEntry sehTableEntry = sehTable[i]; int sehFlag = (int)sehTableEntry.SEHFlags; int handlerKindIndex = sehFlag >= ILReader.HandlerKindMap.Length ? ILReader.HandlerKindMap.Length - 1 : sehFlag; ITypeReference exceptionType = Dummy.TypeReference; uint filterDecisionStart = 0; HandlerKind handlerKind = ILReader.HandlerKindMap[handlerKindIndex]; uint tryStart = sehTableEntry.TryOffset; uint tryEnd = sehTableEntry.TryOffset + sehTableEntry.TryLength; uint handlerStart = sehTableEntry.HandlerOffset; uint handlerEnd = sehTableEntry.HandlerOffset + sehTableEntry.HandlerLength; if (sehTableEntry.SEHFlags == SEHFlags.Catch) { ITypeReference/*?*/ typeRef = this.PEFileToObjectModel.GetTypeReferenceForToken(this.MethodDefinition, sehTableEntry.ClassTokenOrFilterOffset); if (typeRef == null) { // Error return false; } else { exceptionType = typeRef; } } else if (sehTableEntry.SEHFlags == SEHFlags.Filter) { exceptionType = this.PEFileToObjectModel.PlatformType.SystemObject; filterDecisionStart = sehTableEntry.ClassTokenOrFilterOffset; } exceptions[i] = new CilExceptionInformation(handlerKind, exceptionType, tryStart, tryEnd, filterDecisionStart, handlerStart, handlerEnd); } this.MethodBody.SetExceptionInformation(exceptions); } return true; } internal bool ReadIL() { if (!this.LoadLocalSignature()) return false; if (!this.PopulateCilInstructions()) return false; if (!this.PopulateExceptionInformation()) return false; return true; } } } namespace Microsoft.Cci.MetadataReader { using Microsoft.Cci.MetadataReader.ObjectModelImplementation; /// <summary> /// /// </summary> public sealed class MethodBodyDocument : IMethodBodyDocument { /// <summary> /// /// </summary> internal MethodBodyDocument(MethodDefinition method) { this.method = method; } /// <summary> /// /// </summary> /// <param name="standAloneSignatureToken"></param> /// <returns></returns> public ITypeReference GetTypeFromToken(uint standAloneSignatureToken) { ITypeReference/*?*/ result = this.method.PEFileToObjectModel.GetTypeReferenceFromStandaloneSignatureToken(this.method, standAloneSignatureToken); if (result != null) return result; return Dummy.TypeReference; } /// <summary> /// The location where this document was found, or where it should be stored. /// This will also uniquely identify the source document within an instance of compilation host. /// </summary> public string Location { get { return this.method.PEFileToObjectModel.Module.ModuleIdentity.Location; } } internal MethodDefinition method; /// <summary> /// /// </summary> public uint MethodToken { get { return this.method.TokenValue; } } /// <summary> /// The name of the document. For example the name of the file if the document corresponds to a file. /// </summary> public IName Name { get { return this.method.PEFileToObjectModel.Module.ModuleIdentity.Name; } } /// <summary> /// Returns a token decoder for the method associated with this document. /// </summary> public ITokenDecoder TokenDecoder { get { return this.method; } } } /// <summary> /// Represents a location in IL operation stream. /// </summary> internal sealed class MethodBodyLocation : IILLocation { /// <summary> /// Allocates an object that represents a location in IL operation stream. /// </summary> /// <param name="document">The document containing this method whose body contains this location.</param> /// <param name="offset">Offset into the IL Stream.</param> internal MethodBodyLocation(MethodBodyDocument document, uint offset) { this.document = document; this.offset = offset; } /// <summary> /// The document containing this method whose body contains this location. /// </summary> public MethodBodyDocument Document { get { return this.document; } } readonly MethodBodyDocument document; /// <summary> /// The method whose body contains this IL operation whose location this is. /// </summary> /// <value></value> public IMethodDefinition MethodDefinition { get { return this.document.method; } } /// <summary> /// Offset into the IL Stream. /// </summary> public uint Offset { get { return this.offset; } } readonly uint offset; #region ILocation Members IDocument ILocation.Document { get { return this.Document; } } #endregion } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V9.Resources { /// <summary>Resource name for the <c>IncomeRangeView</c> resource.</summary> public sealed partial class IncomeRangeViewName : gax::IResourceName, sys::IEquatable<IncomeRangeViewName> { /// <summary>The possible contents of <see cref="IncomeRangeViewName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/incomeRangeViews/{ad_group_id}~{criterion_id}</c> /// . /// </summary> CustomerAdGroupCriterion = 1, } private static gax::PathTemplate s_customerAdGroupCriterion = new gax::PathTemplate("customers/{customer_id}/incomeRangeViews/{ad_group_id_criterion_id}"); /// <summary>Creates a <see cref="IncomeRangeViewName"/> 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="IncomeRangeViewName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static IncomeRangeViewName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new IncomeRangeViewName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="IncomeRangeViewName"/> with the pattern /// <c>customers/{customer_id}/incomeRangeViews/{ad_group_id}~{criterion_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="IncomeRangeViewName"/> constructed from the provided ids.</returns> public static IncomeRangeViewName FromCustomerAdGroupCriterion(string customerId, string adGroupId, string criterionId) => new IncomeRangeViewName(ResourceNameType.CustomerAdGroupCriterion, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="IncomeRangeViewName"/> with pattern /// <c>customers/{customer_id}/incomeRangeViews/{ad_group_id}~{criterion_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="IncomeRangeViewName"/> with pattern /// <c>customers/{customer_id}/incomeRangeViews/{ad_group_id}~{criterion_id}</c>. /// </returns> public static string Format(string customerId, string adGroupId, string criterionId) => FormatCustomerAdGroupCriterion(customerId, adGroupId, criterionId); /// <summary> /// Formats the IDs into the string representation of this <see cref="IncomeRangeViewName"/> with pattern /// <c>customers/{customer_id}/incomeRangeViews/{ad_group_id}~{criterion_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="IncomeRangeViewName"/> with pattern /// <c>customers/{customer_id}/incomeRangeViews/{ad_group_id}~{criterion_id}</c>. /// </returns> public static string FormatCustomerAdGroupCriterion(string customerId, string adGroupId, string criterionId) => s_customerAdGroupCriterion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)))}"); /// <summary> /// Parses the given resource name string into a new <see cref="IncomeRangeViewName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/incomeRangeViews/{ad_group_id}~{criterion_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="incomeRangeViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="IncomeRangeViewName"/> if successful.</returns> public static IncomeRangeViewName Parse(string incomeRangeViewName) => Parse(incomeRangeViewName, false); /// <summary> /// Parses the given resource name string into a new <see cref="IncomeRangeViewName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/incomeRangeViews/{ad_group_id}~{criterion_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="incomeRangeViewName">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="IncomeRangeViewName"/> if successful.</returns> public static IncomeRangeViewName Parse(string incomeRangeViewName, bool allowUnparsed) => TryParse(incomeRangeViewName, allowUnparsed, out IncomeRangeViewName 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="IncomeRangeViewName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/incomeRangeViews/{ad_group_id}~{criterion_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="incomeRangeViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="IncomeRangeViewName"/>, 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 incomeRangeViewName, out IncomeRangeViewName result) => TryParse(incomeRangeViewName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="IncomeRangeViewName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/incomeRangeViews/{ad_group_id}~{criterion_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="incomeRangeViewName">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="IncomeRangeViewName"/>, 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 incomeRangeViewName, bool allowUnparsed, out IncomeRangeViewName result) { gax::GaxPreconditions.CheckNotNull(incomeRangeViewName, nameof(incomeRangeViewName)); gax::TemplatedResourceName resourceName; if (s_customerAdGroupCriterion.TryParseName(incomeRangeViewName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerAdGroupCriterion(resourceName[0], split1[0], split1[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(incomeRangeViewName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private IncomeRangeViewName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string adGroupId = null, string criterionId = null, string customerId = null) { Type = type; UnparsedResource = unparsedResourceName; AdGroupId = adGroupId; CriterionId = criterionId; CustomerId = customerId; } /// <summary> /// Constructs a new instance of a <see cref="IncomeRangeViewName"/> class from the component parts of pattern /// <c>customers/{customer_id}/incomeRangeViews/{ad_group_id}~{criterion_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> public IncomeRangeViewName(string customerId, string adGroupId, string criterionId) : this(ResourceNameType.CustomerAdGroupCriterion, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId))) { } /// <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>AdGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AdGroupId { get; } /// <summary> /// The <c>Criterion</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CriterionId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary>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.CustomerAdGroupCriterion: return s_customerAdGroupCriterion.Expand(CustomerId, $"{AdGroupId}~{CriterionId}"); 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 IncomeRangeViewName); /// <inheritdoc/> public bool Equals(IncomeRangeViewName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(IncomeRangeViewName a, IncomeRangeViewName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(IncomeRangeViewName a, IncomeRangeViewName b) => !(a == b); } public partial class IncomeRangeView { /// <summary> /// <see cref="IncomeRangeViewName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal IncomeRangeViewName ResourceNameAsIncomeRangeViewName { get => string.IsNullOrEmpty(ResourceName) ? null : IncomeRangeViewName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } } }
// Fetched from http://archive.msdn.microsoft.com/SilverlightMD5 //Copyright (c) Microsoft Corporation. All rights reserved. using System; using System.Text; // ************************************************************** // * Raw implementation of the MD5 hash algorithm // * from RFC 1321. // * // * Written By: Reid Borsuk and Jenny Zheng // * Copyright (c) Microsoft Corporation. All rights reserved. // ************************************************************** namespace Akavache { // Simple struct for the (a,b,c,d) which is used to compute the mesage digest. internal struct ABCDStruct { public uint A; public uint B; public uint C; public uint D; } public sealed class MD5Core { //Prevent CSC from adding a default public constructor MD5Core() { } public static byte[] GetHash(string input, Encoding encoding) { if (null == input) throw new System.ArgumentNullException("input", "Unable to calculate hash over null input data"); if (null == encoding) throw new System.ArgumentNullException("encoding", "Unable to calculate hash over a string without a default encoding. Consider using the GetHash(string) overload to use UTF8 Encoding"); byte[] target = encoding.GetBytes(input); return GetHash(target); } public static byte[] GetHash(string input) { return GetHash(input, new UTF8Encoding()); } public static string GetHashString(byte[] input) { if (null == input) throw new System.ArgumentNullException("input", "Unable to calculate hash over null input data"); string retval = BitConverter.ToString(GetHash(input)); retval = retval.Replace("-", ""); return retval; } public static string GetHashString(string input, Encoding encoding) { if (null == input) throw new System.ArgumentNullException("input", "Unable to calculate hash over null input data"); if (null == encoding) throw new System.ArgumentNullException("encoding", "Unable to calculate hash over a string without a default encoding. Consider using the GetHashString(string) overload to use UTF8 Encoding"); byte[] target = encoding.GetBytes(input); return GetHashString(target); } public static string GetHashString(string input) { return GetHashString(input, new UTF8Encoding()); } public static byte[] GetHash(byte[] input) { if (null == input) throw new System.ArgumentNullException("input", "Unable to calculate hash over null input data"); //Intitial values defined in RFC 1321 ABCDStruct abcd = new ABCDStruct(); abcd.A = 0x67452301; abcd.B = 0xefcdab89; abcd.C = 0x98badcfe; abcd.D = 0x10325476; //We pass in the input array by block, the final block of data must be handled specialy for padding & length embeding int startIndex = 0; while (startIndex <= input.Length - 64) { MD5Core.GetHashBlock(input, ref abcd, startIndex); startIndex += 64; } // The final data block. return MD5Core.GetHashFinalBlock(input, startIndex, input.Length - startIndex, abcd, (Int64) input.Length*8); } internal static byte[] GetHashFinalBlock(byte[] input, int ibStart, int cbSize, ABCDStruct ABCD, Int64 len) { byte[] working = new byte[64]; byte[] length = BitConverter.GetBytes(len); //Padding is a single bit 1, followed by the number of 0s required to make size congruent to 448 modulo 512. Step 1 of RFC 1321 //The CLR ensures that our buffer is 0-assigned, we don't need to explicitly set it. This is why it ends up being quicker to just //use a temporary array rather then doing in-place assignment (5% for small inputs) Array.Copy(input, ibStart, working, 0, cbSize); working[cbSize] = 0x80; //We have enough room to store the length in this chunk if (cbSize < 56) { Array.Copy(length, 0, working, 56, 8); GetHashBlock(working, ref ABCD, 0); } else //We need an aditional chunk to store the length { GetHashBlock(working, ref ABCD, 0); //Create an entirely new chunk due to the 0-assigned trick mentioned above, to avoid an extra function call clearing the array working = new byte[64]; Array.Copy(length, 0, working, 56, 8); GetHashBlock(working, ref ABCD, 0); } byte[] output = new byte[16]; Array.Copy(BitConverter.GetBytes(ABCD.A), 0, output, 0, 4); Array.Copy(BitConverter.GetBytes(ABCD.B), 0, output, 4, 4); Array.Copy(BitConverter.GetBytes(ABCD.C), 0, output, 8, 4); Array.Copy(BitConverter.GetBytes(ABCD.D), 0, output, 12, 4); return output; } // Performs a single block transform of MD5 for a given set of ABCD inputs /* If implementing your own hashing framework, be sure to set the initial ABCD correctly according to RFC 1321: // A = 0x67452301; // B = 0xefcdab89; // C = 0x98badcfe; // D = 0x10325476; */ internal static void GetHashBlock(byte[] input, ref ABCDStruct ABCDValue, int ibStart) { uint[] temp = Converter(input, ibStart); uint a = ABCDValue.A; uint b = ABCDValue.B; uint c = ABCDValue.C; uint d = ABCDValue.D; a = r1(a, b, c, d, temp[0], 7, 0xd76aa478); d = r1(d, a, b, c, temp[1], 12, 0xe8c7b756); c = r1(c, d, a, b, temp[2], 17, 0x242070db); b = r1(b, c, d, a, temp[3], 22, 0xc1bdceee); a = r1(a, b, c, d, temp[4], 7, 0xf57c0faf); d = r1(d, a, b, c, temp[5], 12, 0x4787c62a); c = r1(c, d, a, b, temp[6], 17, 0xa8304613); b = r1(b, c, d, a, temp[7], 22, 0xfd469501); a = r1(a, b, c, d, temp[8], 7, 0x698098d8); d = r1(d, a, b, c, temp[9], 12, 0x8b44f7af); c = r1(c, d, a, b, temp[10], 17, 0xffff5bb1); b = r1(b, c, d, a, temp[11], 22, 0x895cd7be); a = r1(a, b, c, d, temp[12], 7, 0x6b901122); d = r1(d, a, b, c, temp[13], 12, 0xfd987193); c = r1(c, d, a, b, temp[14], 17, 0xa679438e); b = r1(b, c, d, a, temp[15], 22, 0x49b40821); a = r2(a, b, c, d, temp[1], 5, 0xf61e2562); d = r2(d, a, b, c, temp[6], 9, 0xc040b340); c = r2(c, d, a, b, temp[11], 14, 0x265e5a51); b = r2(b, c, d, a, temp[0], 20, 0xe9b6c7aa); a = r2(a, b, c, d, temp[5], 5, 0xd62f105d); d = r2(d, a, b, c, temp[10], 9, 0x02441453); c = r2(c, d, a, b, temp[15], 14, 0xd8a1e681); b = r2(b, c, d, a, temp[4], 20, 0xe7d3fbc8); a = r2(a, b, c, d, temp[9], 5, 0x21e1cde6); d = r2(d, a, b, c, temp[14], 9, 0xc33707d6); c = r2(c, d, a, b, temp[3], 14, 0xf4d50d87); b = r2(b, c, d, a, temp[8], 20, 0x455a14ed); a = r2(a, b, c, d, temp[13], 5, 0xa9e3e905); d = r2(d, a, b, c, temp[2], 9, 0xfcefa3f8); c = r2(c, d, a, b, temp[7], 14, 0x676f02d9); b = r2(b, c, d, a, temp[12], 20, 0x8d2a4c8a); a = r3(a, b, c, d, temp[5], 4, 0xfffa3942); d = r3(d, a, b, c, temp[8], 11, 0x8771f681); c = r3(c, d, a, b, temp[11], 16, 0x6d9d6122); b = r3(b, c, d, a, temp[14], 23, 0xfde5380c); a = r3(a, b, c, d, temp[1], 4, 0xa4beea44); d = r3(d, a, b, c, temp[4], 11, 0x4bdecfa9); c = r3(c, d, a, b, temp[7], 16, 0xf6bb4b60); b = r3(b, c, d, a, temp[10], 23, 0xbebfbc70); a = r3(a, b, c, d, temp[13], 4, 0x289b7ec6); d = r3(d, a, b, c, temp[0], 11, 0xeaa127fa); c = r3(c, d, a, b, temp[3], 16, 0xd4ef3085); b = r3(b, c, d, a, temp[6], 23, 0x04881d05); a = r3(a, b, c, d, temp[9], 4, 0xd9d4d039); d = r3(d, a, b, c, temp[12], 11, 0xe6db99e5); c = r3(c, d, a, b, temp[15], 16, 0x1fa27cf8); b = r3(b, c, d, a, temp[2], 23, 0xc4ac5665); a = r4(a, b, c, d, temp[0], 6, 0xf4292244); d = r4(d, a, b, c, temp[7], 10, 0x432aff97); c = r4(c, d, a, b, temp[14], 15, 0xab9423a7); b = r4(b, c, d, a, temp[5], 21, 0xfc93a039); a = r4(a, b, c, d, temp[12], 6, 0x655b59c3); d = r4(d, a, b, c, temp[3], 10, 0x8f0ccc92); c = r4(c, d, a, b, temp[10], 15, 0xffeff47d); b = r4(b, c, d, a, temp[1], 21, 0x85845dd1); a = r4(a, b, c, d, temp[8], 6, 0x6fa87e4f); d = r4(d, a, b, c, temp[15], 10, 0xfe2ce6e0); c = r4(c, d, a, b, temp[6], 15, 0xa3014314); b = r4(b, c, d, a, temp[13], 21, 0x4e0811a1); a = r4(a, b, c, d, temp[4], 6, 0xf7537e82); d = r4(d, a, b, c, temp[11], 10, 0xbd3af235); c = r4(c, d, a, b, temp[2], 15, 0x2ad7d2bb); b = r4(b, c, d, a, temp[9], 21, 0xeb86d391); ABCDValue.A = unchecked(a + ABCDValue.A); ABCDValue.B = unchecked(b + ABCDValue.B); ABCDValue.C = unchecked(c + ABCDValue.C); ABCDValue.D = unchecked(d + ABCDValue.D); return; } //Manually unrolling these equations nets us a 20% performance improvement static uint r1(uint a, uint b, uint c, uint d, uint x, int s, uint t) { // (b + LSR((a + F(b, c, d) + x + t), s)) //F(x, y, z) ((x & y) | ((x ^ 0xFFFFFFFF) & z)) return unchecked(b + LSR((a + ((b & c) | ((b ^ 0xFFFFFFFF) & d)) + x + t), s)); } static uint r2(uint a, uint b, uint c, uint d, uint x, int s, uint t) { // (b + LSR((a + G(b, c, d) + x + t), s)) //G(x, y, z) ((x & z) | (y & (z ^ 0xFFFFFFFF))) return unchecked(b + LSR((a + ((b & d) | (c & (d ^ 0xFFFFFFFF))) + x + t), s)); } static uint r3(uint a, uint b, uint c, uint d, uint x, int s, uint t) { // (b + LSR((a + H(b, c, d) + k + i), s)) //H(x, y, z) (x ^ y ^ z) return unchecked(b + LSR((a + (b ^ c ^ d) + x + t), s)); } static uint r4(uint a, uint b, uint c, uint d, uint x, int s, uint t) { // (b + LSR((a + I(b, c, d) + k + i), s)) //I(x, y, z) (y ^ (x | (z ^ 0xFFFFFFFF))) return unchecked(b + LSR((a + (c ^ (b | (d ^ 0xFFFFFFFF))) + x + t), s)); } // Implementation of left rotate // s is an int instead of a uint becuase the CLR requires the argument passed to >>/<< is of // type int. Doing the demoting inside this function would add overhead. static uint LSR(uint i, int s) { return ((i << s) | (i >> (32 - s))); } //Convert input array into array of UInts static uint[] Converter(byte[] input, int ibStart) { if (null == input) throw new System.ArgumentNullException("input", "Unable convert null array to array of uInts"); uint[] result = new uint[16]; for (int i = 0; i < 16; i++) { result[i] = (uint) input[ibStart + i*4]; result[i] += (uint) input[ibStart + i*4 + 1] << 8; result[i] += (uint) input[ibStart + i*4 + 2] << 16; result[i] += (uint) input[ibStart + i*4 + 3] << 24; } return result; } } }
namespace Nancy.Tests.Unit.ViewEngines { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using FakeItEasy; using Nancy.Extensions; using Nancy.ViewEngines; using Xunit; public class ResourceViewLocationProviderFixture { private readonly IResourceReader reader; private readonly IResourceAssemblyProvider resourceAssemblyProvider; private readonly ResourceViewLocationProvider viewProvider; public ResourceViewLocationProviderFixture() { ResourceViewLocationProvider.Ignore.Clear(); this.reader = A.Fake<IResourceReader>(); this.resourceAssemblyProvider = A.Fake<IResourceAssemblyProvider>(); this.viewProvider = new ResourceViewLocationProvider(this.reader, this.resourceAssemblyProvider); if (!ResourceViewLocationProvider.RootNamespaces.ContainsKey(this.GetType().GetAssembly())) { ResourceViewLocationProvider.RootNamespaces.Add(this.GetType().GetAssembly(), "Some.Resource"); } A.CallTo(() => this.resourceAssemblyProvider.GetAssembliesToScan()).Returns(new[] { this.GetType().GetAssembly() }); } [Fact] public void Should_return_empty_result_when_supported_view_extensions_is_null() { // Given IEnumerable<string> extensions = null; // When var result = this.viewProvider.GetLocatedViews(extensions); // Then result.ShouldHaveCount(0); } [Fact] public void Should_return_empty_result_when_supported_view_extensions_is_empty() { // Given var extensions = Enumerable.Empty<string>(); // When var result = this.viewProvider.GetLocatedViews(extensions); // Then result.ShouldHaveCount(0); } [Fact] public void Should_return_empty_result_when_view_resources_could_be_found() { // Given var extensions = new[] { "html" }; // When var result = this.viewProvider.GetLocatedViews(extensions); // Then result.ShouldHaveCount(0); } [Fact] public void Should_return_view_location_result_with_file_name_set() { // Given var extensions = new[] { "html" }; var match = new Tuple<string, Func<StreamReader>>( "Some.Resource.View.html", () => null); A.CallTo(() => this.reader.GetResourceStreamMatches(A<Assembly>._, A<IEnumerable<string>>._)).Returns(new[] {match}); // When var result = this.viewProvider.GetLocatedViews(extensions); // Then result.First().Name.ShouldEqual("View"); } [Fact] public void Should_return_view_location_result_with_content_set() { // Given var extensions = new[] { "html" }; var match = new Tuple<string, Func<StreamReader>>( "Some.Resource.View.html", () => null); A.CallTo(() => this.reader.GetResourceStreamMatches(A<Assembly>._, A<IEnumerable<string>>._)).Returns(new[] { match }); // When var result = this.viewProvider.GetLocatedViews(extensions); // Then result.First().Contents.ShouldNotBeNull(); } [Fact] public void Should_throw_invalid_operation_exception_if_only_one_view_was_found_and_no_root_namespace_has_been_defined() { // Given var extensions = new[] { "html" }; ResourceViewLocationProvider.RootNamespaces.Remove(this.GetType().GetAssembly()); var match = new Tuple<string, Func<StreamReader>>( "Some.Resource.View.html", () => null); A.CallTo(() => this.reader.GetResourceStreamMatches(A<Assembly>._, A<IEnumerable<string>>._)).Returns(new[] { match }); // When var exception = Record.Exception(() => this.viewProvider.GetLocatedViews(extensions).ToList()); // Then exception.ShouldBeOfType<InvalidOperationException>(); } [Fact] public void Should_set_error_message_when_throwing_invalid_operation_exception_due_to_not_being_able_to_figure_out_common_namespace() { // Given var extensions = new[] { "html" }; ResourceViewLocationProvider.RootNamespaces.Remove(this.GetType().GetAssembly()); var match = new Tuple<string, Func<StreamReader>>( "Some.Resource.View.html", () => null); A.CallTo(() => this.reader.GetResourceStreamMatches(A<Assembly>._, A<IEnumerable<string>>._)).Returns(new[] { match }); var expectedErrorMessage = string.Format("Only one view was found in assembly {0}, but no rootnamespace had been registered.", this.GetType().GetAssembly().FullName); // When var exception = Record.Exception(() => this.viewProvider.GetLocatedViews(extensions).ToList()); // Then exception.Message.ShouldEqual(expectedErrorMessage); } [Fact] public void Should_return_view_location_result_where_location_is_set_in_platform_neutral_format() { // Given var extensions = new[] { "html" }; var match = new Tuple<string, Func<StreamReader>>( "Some.Resource.Path.With.Sub.Folder.View.html", () => null); A.CallTo(() => this.reader.GetResourceStreamMatches(A<Assembly>._, A<IEnumerable<string>>._)).Returns(new[] { match }); // When var result = this.viewProvider.GetLocatedViews(extensions); // Then result.First().Location.ShouldEqual("Path/With/Sub/Folder"); } [Fact] public void Should_scan_assemblies_returned_by_assembly_provider() { // Given A.CallTo(() => this.resourceAssemblyProvider.GetAssembliesToScan()).Returns(new[] { typeof(NancyEngine).GetAssembly(), this.GetType().GetAssembly() }); var extensions = new[] { "html" }; // When this.viewProvider.GetLocatedViews(extensions).ToList(); // Then A.CallTo(() => this.reader.GetResourceStreamMatches(this.GetType().GetAssembly(), A<IEnumerable<string>>._)).MustHaveHappened(); A.CallTo(() => this.reader.GetResourceStreamMatches(typeof(NancyEngine).GetAssembly(), A<IEnumerable<string>>._)).MustHaveHappened(); } [Fact] public void Should_not_scan_ignored_assemblies() { // Given A.CallTo(() => this.resourceAssemblyProvider.GetAssembliesToScan()).Returns(new[] { typeof(NancyEngine).GetAssembly(), this.GetType().GetAssembly() }); ResourceViewLocationProvider.Ignore.Add(this.GetType().GetAssembly()); var extensions = new[] { "html" }; // When this.viewProvider.GetLocatedViews(extensions).ToList(); // Then A.CallTo(() => this.reader.GetResourceStreamMatches(this.GetType().GetAssembly(), A<IEnumerable<string>>._)).MustNotHaveHappened(); A.CallTo(() => this.reader.GetResourceStreamMatches(typeof(NancyEngine).GetAssembly(), A<IEnumerable<string>>._)).MustHaveHappened(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.IO; using System.Text; using System.Windows.Forms; using CslaGenerator.Controls; using CslaGenerator.Metadata; using CslaGenerator.Properties; using CslaGenerator.Util; using CslaGenerator.Util.PropertyBags; using WeifenLuo.WinFormsUI.Docking; namespace CslaGenerator { /// <summary> /// Summary description for MainForm. /// </summary> internal partial class MainForm : Form { #region Private fields private const string BaseFormText = "Csla Generator Fork"; private bool _isNewProject = true; private bool _showingStartPage; private bool _generating; private bool _appClosing; private bool _resetLayout; private bool _retrieveSummariesRememberAnswer; private DialogResult _retrieveSummariesDialogResult; private GeneratorController _controller = null; private ICodeGenerator _generator; private ProjectPanel _projectPanel = new ProjectPanel(); private ObjectInfo _objectInfoPanel = new ObjectInfo(); private StartPage _webBrowserDockPanel = new StartPage(); private GlobalSettings _globalSettingsPanel = new GlobalSettings(); private ObjectRelationsBuilder _objectRelationsBuilderPanel = new ObjectRelationsBuilder(); private ProjectProperties _projectPropertiesPanel = null; private DbSchemaPanel _dbSchemaPanel = null; private OutputWindow _outputPanel = new OutputWindow(); private GenerationReportViewer _errorPannel = new GenerationReportViewer(); private GenerationReportViewer _warningPannel = new GenerationReportViewer(); private DeserializeDockContent _deserializeDockContent; private string _previousProjectFilePath = string.Empty; #endregion #region Properties internal bool Generating { get { return _generating; } set { _generating = value; newToolStripMenuItem.Enabled = !value; openToolStripMenuItem.Enabled = !value; mruItem0.Enabled = !value; mruItem1.Enabled = !value; mruItem2.Enabled = !value; mruItem3.Enabled = !value; mruItem4.Enabled = !value; newProjectButton.Enabled = !value; openProjectButton.Enabled = !value; cancelButton.Enabled = value; generateButton.Enabled = !value; progressBar.Visible = value; } } internal string DockSettingsFile { get { return Application.LocalUserAppDataPath.Substring(0, Application.LocalUserAppDataPath.LastIndexOf("\\")) + @"\DockSettings.xml"; } } internal PropertyGrid ObjectInfoGrid { get { return _objectInfoPanel.propertyGrid; } } internal TextBox ProjectNameTextBox { get { return _projectPanel.ProjectNameTextBox; } } internal Button TargetDirectoryButton { get { return _projectPanel.TargetDirectoryButton; } } internal TextBox TargetDirectoryTextBox { get { return _projectPanel.TargetDirectory; } } internal ProjectPanel ProjectPanel { get { return _projectPanel; } } internal StartPage WebBrowserDockPanel { get { return _webBrowserDockPanel; } } internal GlobalSettings GlobalSettingsPanel { get { return _globalSettingsPanel; } set { _globalSettingsPanel = value; } } internal ObjectRelationsBuilder ObjectRelationsBuilderPanel { get { return _objectRelationsBuilderPanel; } } internal ProjectProperties ProjectPropertiesPanel { get { return _projectPropertiesPanel; } set { _projectPropertiesPanel = value; } } internal DbSchemaPanel DbSchemaPanel { get { return _dbSchemaPanel; } set { _dbSchemaPanel = value; } } internal DockPanel DockPanel { get { return dockPanel; } } internal DeserializeDockContent DeserializeDockContent { get { return _deserializeDockContent; } set { _deserializeDockContent = value; } } #endregion #region Constructor internal MainForm(GeneratorController controller) { InitializeComponent(); _controller = controller; _deserializeDockContent = GetContentFromPersistString; _errorPannel.Icon = Icon.FromHandle(Resources.Error_List.GetHicon()); _warningPannel.Icon = Icon.FromHandle(Resources.Warning_List.GetHicon()); } #endregion #region Loading private bool ForceLoadCodeSmith() { if (!CodeSmithExists()) Windows7Security.StartCodeSmithHandler(); return CodeSmithExists(); } private bool CodeSmithExists() { return File.Exists(Application.StartupPath + @"\CodeSmith.Engine.dll"); } private static void ShieldBitmap(object sender, PaintEventArgs e) { if (!Windows7Security.IsVistaOrHigher()) return; // Construct an Icon. Bitmap bmp; using (var icon1 = new Icon(SystemIcons.Shield, 16, 16)) { bmp = icon1.ToBitmap(); } // Draw the bitmap. e.Graphics.DrawImage(bmp, new Point(5, 3)); } private IDockContent GetContentFromPersistString(string persistString) { if (persistString == typeof(StartPage).ToString()) return _webBrowserDockPanel; if (persistString == typeof(OutputWindow).ToString()) return _outputPanel; if (persistString == typeof(ProjectPanel).ToString()) return _projectPanel; if (persistString == typeof(ObjectInfo).ToString()) return _objectInfoPanel; return new DockContent(); } private void MainForm_Load(object sender, EventArgs e) { if (File.Exists(DockSettingsFile)) dockPanel.LoadFromXml(DockSettingsFile, _deserializeDockContent); ShowStartPage(); PanelsSetUp(); LoadMru(); } private void ShowStartPage() { _showingStartPage = true; var startupPath = Application.StartupPath; var idx = startupPath.IndexOf(@"\bin"); string url; if (idx == -1) url = startupPath + @"\" + @"StartPage\startpage.html"; else url = startupPath.Substring(0, idx) + @"\" + @"StartPage\startpage.html"; // Web Browser _webBrowserDockPanel.webBrowser.TabIndex = 1; _webBrowserDockPanel.webBrowser.Navigating += WebBrowser_Navigating; _webBrowserDockPanel.MdiParent = this; _webBrowserDockPanel.VisibleChanged += delegate(object sender, EventArgs e) { startPageToolStripMenuItem.Checked = ((DockContent) sender).Visible; }; _webBrowserDockPanel.FormClosing += PaneFormClosing; _webBrowserDockPanel.webBrowser.Navigate(url); _webBrowserDockPanel.Show(dockPanel); _showingStartPage = false; } private void PanelsSetUp() { Text = BaseFormText; saveFileDialog.Filter = @"Csla Gen files (*.xml) | *.xml"; saveFileDialog.DefaultExt = "xml"; openFileDialog.Filter = saveFileDialog.Filter; openFileDialog.DefaultExt = saveFileDialog.DefaultExt; dockPanel.BringToFront(); // Output panel _outputPanel.VisibleChanged += delegate(object sender, EventArgs e) { outputWindowToolStripMenuItem.Checked = ((DockContent) sender).Visible; }; _outputPanel.FormClosing += PaneFormClosing; _outputPanel.Show(dockPanel); // ProjectPanel _projectPanel.TabIndex = 0; _projectPanel.ProjectNameTextBox.Enabled = false; _projectPanel.ProjectNameTextBox.Text = @"Load or create a project"; _projectPanel.TargetDirectory.Enabled = false; _projectPanel.TargetDirectoryButton.Enabled = false; _projectPanel.TargetDirChanged += ProjectPanel_TargetDirChanged; _projectPanel.SelectedItemsChanged += ProjectPanel_SelectedItemsChanged; _projectPanel.VisibleChanged += delegate(object sender, EventArgs e) { projectPanelToolStripMenuItem.Checked = ((DockContent) sender).Visible; }; _projectPanel.FormClosing += PaneFormClosing; _projectPanel.Show(dockPanel); // CslaObjectInfo PropertyGrid _objectInfoPanel.TabIndex = 1; _objectInfoPanel.Icon = Icon.FromHandle(Resources.Properties.GetHicon()); _objectInfoPanel.propertyGrid.SelectedObject = null; _objectInfoPanel.propertyGrid.PropertySortChanged += OnSort; _objectInfoPanel.propertyGrid.SelectedGridItemChanged += OnSelectedGridItemChanged; _objectInfoPanel.VisibleChanged += delegate(object sender, EventArgs e) { objectPropertiesPanelToolStripMenuItem.Checked = ((DockContent) sender).Visible; }; _objectInfoPanel.FormClosing += PaneFormClosing; _objectInfoPanel.Show(dockPanel); // Object Relations Builder _objectRelationsBuilderPanel.AssociativeEntities = null; _objectRelationsBuilderPanel.TabIndex = 1; _objectRelationsBuilderPanel.Dock = DockStyle.Fill; _objectRelationsBuilderPanel.DockAreas = DockAreas.Float | DockAreas.Document; _objectRelationsBuilderPanel.MdiParent = this; _objectRelationsBuilderPanel.VisibleChanged += delegate(object sender, EventArgs e) { objectRelationsBuilderPageToolStripMenuItem.Checked = ((DockContent) sender).Visible; }; _objectRelationsBuilderPanel.FormClosing += PaneFormClosing; _webBrowserDockPanel.BringToFront(); } /// <summary> /// Activate and show the Project Properties panel. /// </summary> internal void ActivateShowProjectProperties() { _projectPropertiesPanel.MdiParent = this; _projectPropertiesPanel.VisibleChanged += delegate(object sender, EventArgs e) { projectPropertiesPageToolStripMenuItem.Checked = ((DockContent) sender).Visible; }; _projectPropertiesPanel.FormClosing += PaneFormClosing; _projectPropertiesPanel.Show(dockPanel); } /// <summary> /// Activate and show the Global Settings panel. /// </summary> internal void ActivateShowGlobalSettings() { _globalSettingsPanel.MdiParent = this; _globalSettingsPanel.VisibleChanged += delegate(object sender, EventArgs e) { globalSettingsPageToolStripMenuItem.Checked = ((DockContent) sender).Visible; }; _globalSettingsPanel.FormClosing += PaneFormClosing; _globalSettingsPanel.Show(dockPanel); LoadGlobalSettings(); } /// <summary> /// Activate and show the Schema panel. /// </summary> /// <remarks> /// Used by GeneratorController.BuildSchemaTree. /// </remarks> internal void ActivateShowSchema() { _dbSchemaPanel.MdiParent = this; _dbSchemaPanel.VisibleChanged += delegate(object sender, EventArgs e) { schemaPageToolStripMenuItem.Checked = ((DockContent) sender).Visible; }; _dbSchemaPanel.FormClosing += PaneFormClosing; _dbSchemaPanel.Show(dockPanel); } private void LoadMru() { _controller.MruItems = new List<string>(); _controller.MruItems = ConfigTools.SharedAppConfigGetMru(); MruDisplay(); } private void LoadGlobalSettings() { if (!File.Exists(ConfigTools.GlobalXml)) { _globalSettingsPanel.cmdResetToFactory.PerformClick(); _globalSettingsPanel.cmdSave.PerformClick(); } _globalSettingsPanel.GlobalParamsInitialLoad(); } #endregion #region Manage project state internal void GetProjectState() { if (_projectPanel != null) _projectPanel.GetState(); if (_objectInfoPanel != null) _objectInfoPanel.GetState(); GeneratorController.Current.CurrentUnitLayout.StartPageMainTabHidden = true; GeneratorController.Current.CurrentUnitLayout.GlobalSettingsMainTabHidden = true; GeneratorController.Current.CurrentUnitLayout.RelationsBuilderTabHidden = true; GeneratorController.Current.CurrentUnitLayout.ProjectPropertiesMainTabHidden = true; foreach (var dockContent in DockPanel.Documents) { var docType = dockContent.GetType().UnderlyingSystemType; if (dockContent.DockHandler.IsActivated) _controller.CurrentUnitLayout.ActiveDocument = docType.Name; if (docType == typeof(StartPage)) { var startPage = dockContent as StartPage; if (startPage != null) startPage.GetState(); } else if (docType == typeof(GlobalSettings)) { var globalSettings = dockContent as GlobalSettings; if (globalSettings != null) globalSettings.GetState(); } else if (docType == typeof(ObjectRelationsBuilder)) { var objectRelationsBuilder = dockContent as ObjectRelationsBuilder; if (objectRelationsBuilder != null) objectRelationsBuilder.GetState(); } else if (docType == typeof(ProjectProperties)) { var projectProperties = dockContent as ProjectProperties; if (projectProperties != null) projectProperties.GetState(); } else if (docType == typeof(DbSchemaPanel)) { var dbSchemaPanel = dockContent as DbSchemaPanel; if (dbSchemaPanel != null) dbSchemaPanel.GetState(); } } } internal void SetProjectState() { if (_projectPanel != null) _projectPanel.SetState(); if (_objectInfoPanel != null) _objectInfoPanel.SetState(); foreach (var dockContent in dockPanel.Documents) { if (dockContent.GetType().ToString() == "CslaGenerator.Controls." + _controller.CurrentUnitLayout.ActiveDocument) dockContent.DockHandler.Show(); var docType = dockContent.GetType().UnderlyingSystemType; if (docType == typeof(StartPage)) { var startPage = dockContent as StartPage; if (startPage != null) { if (GeneratorController.Current.CurrentUnitLayout.StartPageMainTabHidden) startPage.Hide(); } } else if (docType == typeof(GlobalSettings)) { var globalSettings = dockContent as GlobalSettings; if (globalSettings != null) { globalSettings.TurnOnFormLevelDoubleBuffering(); globalSettings.SetState(); globalSettings.TurnOffFormLevelDoubleBuffering(); if (GeneratorController.Current.CurrentUnitLayout.GlobalSettingsMainTabHidden) globalSettings.Hide(); } } else if (docType == typeof(ObjectRelationsBuilder)) { var objectRelationsBuilder = dockContent as ObjectRelationsBuilder; if (objectRelationsBuilder != null) { objectRelationsBuilder.TurnOnFormLevelDoubleBuffering(); objectRelationsBuilder.SetState(); objectRelationsBuilder.TurnOffFormLevelDoubleBuffering(); if (GeneratorController.Current.CurrentUnitLayout.RelationsBuilderTabHidden) objectRelationsBuilder.Hide(); } } else if (docType == typeof(ProjectProperties)) { var projectProperties = dockContent as ProjectProperties; if (projectProperties != null) { projectProperties.TurnOnFormLevelDoubleBuffering(); projectProperties.SetState(); projectProperties.TurnOffFormLevelDoubleBuffering(); if (GeneratorController.Current.CurrentUnitLayout.ProjectPropertiesMainTabHidden) projectProperties.Hide(); } } else if (docType == typeof(DbSchemaPanel)) { var dbSchemaPanel = dockContent as DbSchemaPanel; if (dbSchemaPanel != null) { dbSchemaPanel.TurnOnFormLevelDoubleBuffering(); dbSchemaPanel.SetState(); dbSchemaPanel.TurnOffFormLevelDoubleBuffering(); } } } } #endregion #region Closing private void MainForm_Closing(object sender, CancelEventArgs e) { _appClosing = true; if (_controller.CurrentProjectProperties != null) _controller.CurrentProjectProperties.Close(); _objectRelationsBuilderPanel.Close(); _globalSettingsPanel.Close(); _errorPannel.Close(); _warningPannel.Close(); if (DbSchemaPanel != null) DbSchemaPanel.Close(); if (_resetLayout) File.Delete(DockSettingsFile); else dockPanel.SaveAsXml(DockSettingsFile, Encoding.UTF8); } private void PaneFormClosing(object sender, FormClosingEventArgs e) { if (_appClosing) return; // individual controls on the form are closing SaveBeforeClose(true); e.Cancel = true; ((DockContent) sender).Hide(); } private DialogResult SaveBeforeClose(bool isClosing) { DialogResult result = DialogResult.None; if (_controller.CurrentProjectProperties != null && _controller.CurrentProjectProperties.IsDirty) { result = MessageBox.Show( @"There are unsaved changes in the project properties tab. Would you like to save the project now?", @"CslaGenerator", isClosing ? MessageBoxButtons.YesNo : MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (result == DialogResult.Yes) { _controller.CurrentProjectProperties.cmdApply.PerformClick(); SaveToolStripMenuItem_Click(this, new EventArgs()); } } _globalSettingsPanel.ForceSaveGlobalSettings(); return result; } #endregion #region Misc events private void MainForm_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.F5 && !Generating) Generate(); } private void WebBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e) { if (!_showingStartPage) { e.Cancel = true; Process.Start(e.Url.AbsolutePath); } } #endregion #region Generation private void Generate() { if (!Directory.Exists(_controller.TemplatesDirectory)) { MessageBox.Show(@"You must set the templates directory path before generating.", "Invalid Generate Order", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (_controller.CurrentUnit == null) { MessageBox.Show(@"You must open a project before generating.", "Invalid Generate Order", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (Generating) { MessageBox.Show(@"The Generation process is already running.", "Invalid Generate Order", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (!ApplyProjectProperties()) return; _globalSettingsPanel.ForceSaveGlobalSettings(); ClearErrorsAndWarnings(); var targetDir = _controller.CurrentUnit.TargetBaseFullPath; if (targetDir.StartsWith("ERROR")) { MessageBox.Show(this, targetDir, "Fatal error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } globalStatus.Image = Resources.RefreshArrow_Green; globalStatus.ToolTipText = @"Generating..."; statusStrip.Refresh(); if (_controller.CurrentUnit.GenerationParams.SaveBeforeGenerate) SaveToolStripMenuItem_Click(this, EventArgs.Empty); Generating = true; if (_generator != null) { _generator.Step -= GeneratorStep; } _generator = new CodeGen.AdvancedGenerator(targetDir, _controller.TemplatesDirectory); _generator.Step += GeneratorStep; var i = 0; foreach (var obj in _controller.CurrentUnit.CslaObjects) { if (obj.Generate) i++; } progressBar.Value = 0; progressBar.Maximum = i; backgroundWorker.RunWorkerAsync(); } private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { _generator.GenerateProject(_controller.CurrentUnit); } private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { var timer = _controller.CurrentUnit.GenerationTimer.Elapsed; generatingTimer.Text = String.Format("Generating: {0}:{1},{2}", timer.Minutes.ToString("00"), timer.Seconds.ToString("00"), timer.Milliseconds.ToString("000")); Generating = false; if (!_controller.HasErrors && !_controller.HasWarnings) { globalStatus.Image = Resources.Green; globalStatus.ToolTipText = @"Generation terminated."; } else { if (_controller.HasWarnings) { globalStatus.Image = Resources.Orange; globalStatus.ToolTipText = @"Generation with issues."; warnings.Image = Resources.Warning_List; warnings.DoubleClickEnabled = true; warnings.ToolTipText = @"Double click to get the warning list."; warnings.AutoToolTip = true; } if (_controller.HasErrors) { globalStatus.Image = Resources.Red; globalStatus.ToolTipText = @"Generation with errors."; errors.Image = Resources.Error_List; errors.DoubleClickEnabled = true; errors.ToolTipText = @"Double click to get the error list."; errors.AutoToolTip = true; } } statusStrip.Refresh(); } private void GeneratorStep(string e) { if (progressBar.Value < progressBar.Maximum) { Invoke((MethodInvoker) delegate { progressBar.Value++; }); } } internal bool ApplyProjectProperties() { if (_controller.CurrentProjectProperties == null) return false; if (!_controller.CurrentProjectProperties.ValidateOptions()) return false; return _controller.CurrentProjectProperties.ApplyProjectProperties(); } #endregion #region Project panel private void ProjectPanel_TargetDirChanged(string path) { _controller.CurrentUnit.TargetDirectory = path; } private void ProjectPanel_SelectedItemsChanged(object sender, EventArgs e) { ConditonalButtonsAndMenus(); } #endregion #region CslaObjectInfo panel internal void OnSort(object sender, EventArgs e) { if (_objectInfoPanel.propertyGrid.PropertySort == PropertySort.CategorizedAlphabetical) _objectInfoPanel.propertyGrid.PropertySort = PropertySort.Categorized; } private void OnSelectedGridItemChanged(object sender, SelectedGridItemChangedEventArgs e) { CslaObjectInfo cslaObj = ((PropertyBag) ((PropertyGrid) sender).SelectedObject).SelectedObject[0]; switch (e.NewSelection.Label) { case "Create Authorization Type": cslaObj.ActionProperty = AuthorizationActions.CreateObject; break; case "Get Authorization Type": cslaObj.ActionProperty = AuthorizationActions.GetObject; break; case "Update Authorization Type": cslaObj.ActionProperty = AuthorizationActions.EditObject; break; case "Delete Authorization Type": cslaObj.ActionProperty = AuthorizationActions.DeleteObject; break; } } #endregion #region General toolbar and menu handlers private void AfterOpenEnableButtonsAndMenus() { saveasToolStripMenuItem.Enabled = true; saveToolStripMenuItem.Enabled = true; saveProjectButton.Enabled = true; addObjectButton.Enabled = true; connectDatabaseButton.Enabled = true; projectToolStripMenuItem.Enabled = true; dataBaseToolStripMenuItem.Enabled = true; fixPrimaryKeys.Enabled = true; reSyncNullable.Enabled = true; changeTimestampToReadOnlyNotUndoable.Enabled = true; changeSimpleAuditToReadOnlyNotUndoable.Enabled = true; convertDateTimeToSmartDate.Enabled = true; forceBackingFieldSmartDate.Enabled = true; convertPropertiesAndCriteriaToSilverlight.Enabled = true; convertProjectToNewPublicPolicy.Enabled = true; ConditonalButtonsAndMenus(); } private void ConditonalButtonsAndMenus() { bool objectSelected = (ProjectPanel.ListObjects.SelectedIndices.Count != 0); deleteObjectButton.Enabled = objectSelected; duplicateObjectButton.Enabled = objectSelected; moveuUpObjectButton.Enabled = (objectSelected && ProjectPanel.SortOptionsNone.Checked && ProjectPanel.ListObjects.SelectedIndex > 0) || ProjectPanel.ListObjects.SelectedIndices.Count > 1; moveDownObjectButton.Enabled = (objectSelected && ProjectPanel.SortOptionsNone.Checked && ProjectPanel.ListObjects.SelectedIndex < ProjectPanel.ListObjects.Items.Count - 1) || ProjectPanel.ListObjects.SelectedIndices.Count > 1; newObjectRelationButton.Enabled = objectSelected; addToObjectRelationButton.Enabled = objectSelected; bool objectsPresent = (ProjectPanel.Objects.Count > 0); generateButton.Enabled = objectsPresent; // Menus removeSelectedObjectToolStripMenuItem.Enabled = objectSelected; duplicateObjectToolStripMenuItem.Enabled = objectSelected; newObjectRelationToolStripMenuItem.Enabled = objectSelected; addToObjectRelationToolStripMenuItem.Enabled = objectSelected; } #endregion #region Toolbar private void NewProjectButton_Click(object sender, EventArgs e) { NewToolStripMenuItem_Click(sender, e); } private void OpenProjectButton_Click(object sender, EventArgs e) { OpenToolStripMenuItem_Click(sender, e); } private void SaveProjectButton_Click(object sender, EventArgs e) { SaveToolStripMenuItem_Click(sender, e); } private void AddObjectButton_Click(object sender, EventArgs e) { _projectPanel.AddNewObject(); } private void DeleteObjectButton_Click(object sender, EventArgs e) { _projectPanel.RemoveSelected(); } private void DuplicateObjectButton_Click(object sender, EventArgs e) { _projectPanel.DuplicateSelected(); } private void MoveuUpObjectButton_Click(object sender, EventArgs e) { _projectPanel.MoveUpSelected(); } private void MoveDownObjectButton_Click(object sender, EventArgs e) { _projectPanel.MoveDownSelected(); } private void NewObjectRelationButton_Click(object sender, EventArgs e) { _projectPanel.AddNewObjectRelation(); } private void AddToObjectRelationButton_Click(object sender, EventArgs e) { _projectPanel.AddToObjectRelationBuilder(); } private void ConnectDatabaseButton_Click(object sender, EventArgs e) { Connect(); } private void GenerateButton_Click(object sender, EventArgs e) { Generate(); } private void CancelButton_Click(object sender, EventArgs e) { if (Generating) _generator.Abort(); } #endregion #region File menu private void NewToolStripMenuItem_Click(object sender, EventArgs e) { if (ForceLoadCodeSmith()) { if (_controller.CurrentUnit != null) _controller.SaveProjectLayout(openFileDialog.FileName); _controller.NewCslaUnit(); _isNewProject = true; openFileDialog.FileName = string.Empty; Text = BaseFormText; if (!File.Exists(ConfigTools.DefaultXml)) { _controller.CurrentProjectProperties.cmdResetToFactory.PerformClick(); _controller.CurrentProjectProperties.cmdSetDefault.PerformClick(); } if (_controller.CurrentProjectProperties != null) _controller.CurrentProjectProperties.cmdGetDefault.PerformClick(); AfterOpenEnableButtonsAndMenus(); if (_controller.IsDBConnected) { globalStatus.Image = Resources.Blue; globalStatus.ToolTipText = @"New project."; } else { globalStatus.Image = Resources.Orange; globalStatus.ToolTipText = @"New project has no database connection."; } loadingTimer.Text = "Loading:"; FillObjects(); ClearErrorsAndWarnings(); statusStrip.Refresh(); } } private void OpenToolStripMenuItem_Click(object sender, EventArgs e) { _previousProjectFilePath = openFileDialog.FileName; if (ForceLoadCodeSmith()) { openFileDialog.InitialDirectory = _controller.ProjectsDirectory; DialogResult result = openFileDialog.ShowDialog(this); if (result == DialogResult.OK) { _controller.ProjectsDirectory = openFileDialog.FileName.Substring(0, openFileDialog.FileName.LastIndexOf('\\')); ConfigTools.SharedAppConfigChange("ProjectsDirectory", _controller.ProjectsDirectory); Application.DoEvents(); Cursor.Current = Cursors.WaitCursor; OpenProjectFile(openFileDialog.FileName); HandleMruItemsNewCurrent(openFileDialog.FileName); Cursor.Current = Cursors.Default; Text = _controller.CurrentUnit.ProjectName + @" - " + BaseFormText; AfterOpenEnableButtonsAndMenus(); } } } private void SaveToolStripMenuItem_Click(object sender, EventArgs e) { Application.DoEvents(); if (!_isNewProject && openFileDialog.FileName.Length > 1) { Cursor.Current = Cursors.WaitCursor; Application.DoEvents(); _controller.Save(openFileDialog.FileName); HandleMruItemsNewCurrent(openFileDialog.FileName); Cursor.Current = Cursors.Default; Text = _controller.CurrentUnit.ProjectName + @" - " + BaseFormText; return; } SaveAsToolStripMenuItem_Click(sender, e); } private void SaveAsToolStripMenuItem_Click(object sender, EventArgs e) { Application.DoEvents(); if (openFileDialog.FileName.Length > 1) saveFileDialog.FileName = GeneratorController.ExtractFilename(openFileDialog.FileName); else if (_controller.CurrentUnit != null) saveFileDialog.FileName = _controller.CurrentUnit.ProjectName + ".xml"; else saveFileDialog.FileName = "Project.xml"; saveFileDialog.InitialDirectory = _controller.ProjectsDirectory; var result = saveFileDialog.ShowDialog(this); if (result == DialogResult.OK) { _controller.ProjectsDirectory = saveFileDialog.FileName.Substring(0, saveFileDialog.FileName.LastIndexOf('\\')); ConfigTools.SharedAppConfigChange("ProjectsDirectory", _controller.ProjectsDirectory); Cursor.Current = Cursors.WaitCursor; Application.DoEvents(); _controller.Save(saveFileDialog.FileName); openFileDialog.FileName = saveFileDialog.FileName; HandleMruItemsNewCurrent(openFileDialog.FileName); _isNewProject = false; Cursor.Current = Cursors.Default; Text = _controller.CurrentUnit.ProjectName + @" - " + BaseFormText; } } private void MruItem0_Click(object sender, EventArgs e) { HanddleMruItem(0); } private void MruItem1_Click(object sender, EventArgs e) { HanddleMruItem(1); } private void MruItem2_Click(object sender, EventArgs e) { HanddleMruItem(2); } private void MruItem3_Click(object sender, EventArgs e) { HanddleMruItem(3); } private void MruItem4_Click(object sender, EventArgs e) { HanddleMruItem(4); } private void ExitResetLayoutToolStripMenuItem_Click(object sender, EventArgs e) { _resetLayout = true; DialogResult result = SaveBeforeClose(false); if (result == DialogResult.Cancel) return; Close(); } private void ExitToolStripMenuItem_Click(object sender, EventArgs e) { DialogResult result = SaveBeforeClose(false); if (result == DialogResult.Cancel) return; Close(); } #region MRU helpers private void HanddleMruItem(int mruItem) { _previousProjectFilePath = openFileDialog.FileName; if (_controller.MruItems.Count > mruItem) { if (ForceLoadCodeSmith()) { if (!File.Exists(_controller.MruItems[mruItem])) HandleMruItemsMissing(mruItem); else { openFileDialog.FileName = _controller.MruItems[mruItem]; _controller.ProjectsDirectory = openFileDialog.FileName.Substring(0, openFileDialog.FileName.LastIndexOf('\\')); ConfigTools.SharedAppConfigChange("ProjectsDirectory", _controller.ProjectsDirectory); Application.DoEvents(); Cursor.Current = Cursors.WaitCursor; OpenProjectFile(openFileDialog.FileName); HandleMruItemsNewCurrent(openFileDialog.FileName); Cursor.Current = Cursors.Default; Text = _controller.CurrentUnit.ProjectName + @" - " + BaseFormText; AfterOpenEnableButtonsAndMenus(); } } } } private void HandleMruItemsNewCurrent(string filename) { _controller.MruItems.Insert(0, filename); _controller.ReSortMruItems(); MruDisplay(); } private void HandleMruItemsMissing(int mruItem) { var message = _controller.MruItems[mruItem] + Environment.NewLine + @"project file wasn't found." + Environment.NewLine + Environment.NewLine + @"Do you want to remove it from the recently used list?"; if (MessageBox.Show(message, @"Project file not found.", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.Yes) { _controller.MruItems.RemoveAt(mruItem); MruDisplay(); } } private void MruDisplay() { mruItem0.Text = string.Empty; mruItem0.Visible = false; mruItem1.Text = string.Empty; mruItem1.Visible = false; mruItem2.Text = string.Empty; mruItem2.Visible = false; mruItem3.Text = string.Empty; mruItem3.Visible = false; mruItem4.Text = string.Empty; mruItem4.Visible = false; for (var i = 0; i < 5; i++) { if (i == _controller.MruItems.Count) break; var tooltip = _controller.MruItems[i]; var text = "&" + (i + 1) + " ...\\" + tooltip.Substring(tooltip.LastIndexOf('\\') + 1); switch (i) { case 0: mruItem0.ToolTipText = tooltip; mruItem0.Text = text; mruItem0.Visible = true; break; case 1: mruItem1.ToolTipText = tooltip; mruItem1.Text = text; mruItem1.Visible = true; break; case 2: mruItem2.ToolTipText = tooltip; mruItem2.Text = text; mruItem2.Visible = true; break; case 3: mruItem3.ToolTipText = tooltip; mruItem3.Text = text; mruItem3.Visible = true; break; case 4: mruItem4.ToolTipText = tooltip; mruItem4.Text = text; mruItem4.Visible = true; break; } } HandleMruSeparator(); } private void HandleMruSeparator() { if (_controller.MruItems.Count == 0) mruSeparator.Visible = false; else mruSeparator.Visible = true; } #endregion #endregion #region File menu helpers internal void OpenProjectFile(string fileName) { if (_controller.CurrentUnit != null) _controller.SaveProjectLayout(_previousProjectFilePath); globalStatus.Image = Resources.RefreshArrow_Green; globalStatus.ToolTipText = @"Loading..."; loadingTimer.Text = "Loading:"; ClearErrorsAndWarnings(); statusStrip.Refresh(); _controller.NewCslaUnit(); _controller.Load(fileName); var timer = _controller.LoadingTimer.Elapsed; loadingTimer.Text = String.Format("Loading: {0}:{1},{2}", timer.Minutes.ToString("00"), timer.Seconds.ToString("00"), timer.Milliseconds.ToString("000")); _isNewProject = false; // if we are calling this from the controller, then the // file dialog will not have been used to open the file, and since other code relies // on the file dialog having been used (no local/controller storage for file name) ... if (openFileDialog.FileName != fileName) { openFileDialog.FileName = fileName; } FillDatabaseObjects(); FillObjects(); if (_controller.IsDBConnected) { globalStatus.Image = Resources.Blue; globalStatus.ToolTipText = @"Project loaded."; } else { globalStatus.Image = Resources.Orange; globalStatus.ToolTipText = @"No database connection."; } statusStrip.Refresh(); } #endregion #region Project menu private void AddAnewObjectToolStripMenuItem_Click(object sender, EventArgs e) { _projectPanel.AddNewObject(); } private void RemoveSelectedObjectToolStripMenuItem_Click(object sender, EventArgs e) { _projectPanel.RemoveSelected(); } private void DuplicateObjectToolStripMenuItem_Click(object sender, EventArgs e) { _projectPanel.DuplicateSelected(); } private void SelectAllObjectsToolStripMenuItem_Click(object sender, EventArgs e) { _projectPanel.SelectAll(); } private void NewObjectRelationToolStripMenuItem_Click(object sender, EventArgs e) { _projectPanel.AddNewObjectRelation(); } private void AddToObjectRelationToolStripMenuItem_Click(object sender, EventArgs e) { _projectPanel.AddToObjectRelationBuilder(); } private void PropertiesToolStripMenuItem_Click(object sender, EventArgs e) { if (_controller.CurrentUnit != null) { if (_controller.CurrentProjectProperties != null) { if (_controller.CurrentProjectProperties.Visible) _controller.CurrentProjectProperties.Focus(); else _controller.CurrentProjectProperties.Show(dockPanel); } } else { MessageBox.Show(@"You need to open or create a project to set its properties.", @"Project properties", MessageBoxButtons.OK, MessageBoxIcon.Information); } } #endregion #region Database menu private void ConnectToolStripMenuItem_Click(object sender, EventArgs e) { Connect(); } private void RefreshSchemaToolStripMenuItem_Click(object sender, EventArgs e) { if (_dbSchemaPanel != null) _dbSchemaPanel.BuildSchemaTree(); } private void RetrieveSummariesToolStripMenuItem_Click(object sender, EventArgs e) { if (!_retrieveSummariesRememberAnswer) { string msg = @"Do you want to retrieve summaries" + Environment.NewLine + "just for the current object or for all objects?"; using (var messageBox = new MessageBoxEx(msg, @"Csla Generator", MessageBoxIcon.Question)) { messageBox.SetButtons(new[] {"Current", "All", "Cancel"}, new[] {DialogResult.No, DialogResult.Yes, DialogResult.Cancel}, 2); messageBox.SetCheckbox("Do not ask again."); messageBox.ShowDialog(); _retrieveSummariesRememberAnswer = messageBox.CheckboxChecked; _retrieveSummariesDialogResult = messageBox.DialogResult; } } if (_retrieveSummariesDialogResult == DialogResult.Cancel) { _retrieveSummariesRememberAnswer = false; } else { if (_retrieveSummariesDialogResult == DialogResult.Yes) { foreach (CslaObjectInfo info in _controller.CurrentUnit.CslaObjects) { foreach (ValueProperty vp in info.ValueProperties) vp.RetrieveSummaryFromColumnDefinition(); } } else { foreach (ValueProperty vp in _dbSchemaPanel.CurrentCslaObject.ValueProperties) vp.RetrieveSummaryFromColumnDefinition(); } } } #endregion #region Database helpers private void Connect() { if (_controller.CurrentUnit != null) { Application.DoEvents(); _controller.Connect(); FillDatabaseObjects(); if (_controller.IsDBConnected) { globalStatus.Image = Resources.Blue; if (globalStatus.ToolTipText == @"New project has no database connection.") globalStatus.ToolTipText = @"New project."; } } else MessageBox.Show(@"You must load or start a new project before connecting to a database", @"CslaGenerator", MessageBoxButtons.OK, MessageBoxIcon.Information); } #endregion #region Tools menu private void FixPrimaryKeys_Click(object sender, EventArgs e) { _outputPanel.AddOutputInfo(Environment.NewLine + "Fix Primary Key properties..." + Environment.NewLine); foreach (var info in _controller.CurrentUnit.CslaObjects) { if (info.IsBaseClass() || info.IsPlaceHolder()) continue; var counter = 0; foreach (ValueProperty prop in info.ValueProperties) { var tempCounter = 0; if (prop.DbBindColumn.IsPrimaryKey) { if (prop.Undoable) { prop.Undoable = false; tempCounter++; } if (prop.DbBindColumn.IsIdentity) { if (prop.PrimaryKey != ValueProperty.UserDefinedKeyBehaviour.DBProvidedPK) { prop.PrimaryKey = ValueProperty.UserDefinedKeyBehaviour.DBProvidedPK; tempCounter++; } if (!prop.ReadOnly) { prop.ReadOnly = true; tempCounter++; } if (prop.PropSetAccessibility != AccessorVisibility.Default) { prop.PropSetAccessibility = AccessorVisibility.Default; tempCounter++; } } else { if (prop.PrimaryKey != ValueProperty.UserDefinedKeyBehaviour.UserProvidedPK) { prop.PrimaryKey = ValueProperty.UserDefinedKeyBehaviour.UserProvidedPK; tempCounter++; } if (prop.DbBindColumn.IsIdentity && prop.ReadOnly) { prop.ReadOnly = false; tempCounter++; } } } else { if (prop.PrimaryKey != ValueProperty.UserDefinedKeyBehaviour.Default) { prop.PrimaryKey = ValueProperty.UserDefinedKeyBehaviour.Default; tempCounter++; } } if (tempCounter > 0) counter++; } if (counter > 0) _outputPanel.AddOutputInfo(info.ObjectName + ": fixed " + counter + " Primary Key properties."); } _outputPanel.AddOutputInfo(Environment.NewLine + "Fix Primary Key properties is done." + Environment.NewLine); } private void reSyncNullable_Click(object sender, EventArgs e) { _outputPanel.AddOutputInfo(Environment.NewLine + "Re-sync Nullable properties..." + Environment.NewLine); foreach (var info in _controller.CurrentUnit.CslaObjects) { if (info.IsBaseClass() || info.IsPlaceHolder()) continue; var counter = 0; foreach (ValueProperty prop in info.ValueProperties) { if (prop.IsDatabaseBound) { var tempCounter = 0; if (prop.Nullable != prop.DbBindColumn.IsNullable) { prop.Nullable = prop.DbBindColumn.IsNullable; tempCounter++; } if (tempCounter > 0) counter++; } } if (counter > 0) _outputPanel.AddOutputInfo(info.ObjectName + ": changed " + counter + " Nullable properties."); } _outputPanel.AddOutputInfo(Environment.NewLine + "Re-sync Nullable properties is done." + Environment.NewLine); } private void ChangeTimestampToReadOnlyNotUndoable_Click(object sender, EventArgs e) { _outputPanel.AddOutputInfo(Environment.NewLine + "Changing ReadOnly and not Undoable on timestamp properties..." + Environment.NewLine); foreach (var info in _controller.CurrentUnit.CslaObjects) { if (info.IsBaseClass() || info.IsPlaceHolder()) continue; var counter = 0; foreach (ValueProperty prop in info.ValueProperties) { if (prop.DbBindColumn.NativeType == "timestamp" && (!prop.ReadOnly || prop.Undoable)) { prop.ReadOnly = true; prop.Undoable = false; counter++; } } if (counter > 0) _outputPanel.AddOutputInfo(info.ObjectName + ": changed " + counter + " properties of type \"timestamp\" to \"ReadOnly\" and not \"Undoable\"."); } _outputPanel.AddOutputInfo(Environment.NewLine + "Change ReadOnly and not Undoable on timestamp properties is done." + Environment.NewLine); } private void ChangeSimpleAuditToReadOnlyNotUndoable_Click(object sender, EventArgs e) { _outputPanel.AddOutputInfo(Environment.NewLine + "Changing ReadOnly and not Undoable on Simple Audit properties..." + Environment.NewLine); foreach (var info in _controller.CurrentUnit.CslaObjects) { if (info.IsBaseClass() || info.IsPlaceHolder()) continue; var counter = 0; foreach (ValueProperty prop in info.ValueProperties) { if ((_controller.CurrentUnit.Params.CreationDateColumn == prop.Name || _controller.CurrentUnit.Params.CreationUserColumn == prop.Name || _controller.CurrentUnit.Params.ChangedDateColumn == prop.Name || _controller.CurrentUnit.Params.ChangedUserColumn == prop.Name) && (!prop.ReadOnly || prop.Undoable)) { prop.ReadOnly = true; prop.Undoable = false; counter++; } } if (counter > 0) _outputPanel.AddOutputInfo(info.ObjectName + ": changed " + counter + " Simple Audit properties to \"ReadOnly\" and not \"Undoable\"."); } _outputPanel.AddOutputInfo(Environment.NewLine + "Change ReadOnly and not Undoable on Simple Audit properties is done." + Environment.NewLine); } private void ConvertDateTimeToSmartDate_Click(object sender, EventArgs e) { _outputPanel.AddOutputInfo(Environment.NewLine + "Converting DateTime/DateTimeOffset to SmartDate properties..." + Environment.NewLine); foreach (var info in _controller.CurrentUnit.CslaObjects) { if (info.IsBaseClass() || info.IsPlaceHolder()) continue; var counter = 0; foreach (ValueProperty prop in info.ValueProperties) { if (prop.PropertyType == TypeCodeEx.DateTime || prop.PropertyType == TypeCodeEx.DateTimeOffset) { prop.PropertyType = TypeCodeEx.SmartDate; counter++; } } if (counter > 0) _outputPanel.AddOutputInfo(info.ObjectName + ": converted " + counter + " properties of type DateTime/DateTimeOffset to SmartDate."); } _outputPanel.AddOutputInfo(Environment.NewLine + "Convert DateTime/DateTimeOffset to SmartDate properties is done." + Environment.NewLine); } private void ForceBackingFieldSmartDate_Click(object sender, EventArgs e) { _outputPanel.AddOutputInfo(Environment.NewLine + "Forcing backing field on SmartDate properties..." + Environment.NewLine); foreach (var info in _controller.CurrentUnit.CslaObjects) { if (info.IsBaseClass() || info.IsPlaceHolder()) continue; var counter = 0; var simpleAuditCounter = 0; foreach (ValueProperty prop in info.AllValueProperties) { if (prop.PropertyType == TypeCodeEx.SmartDate) { if (prop.Name == _controller.CurrentUnit.Params.CreationDateColumn || prop.Name == _controller.CurrentUnit.Params.ChangedDateColumn) { simpleAuditCounter++; continue; } if (prop.DeclarationMode == PropertyDeclaration.ClassicProperty || prop.DeclarationMode == PropertyDeclaration.AutoProperty) { prop.DeclarationMode = PropertyDeclaration.ClassicPropertyWithTypeConversion; } else if (prop.DeclarationMode == PropertyDeclaration.Managed) { prop.DeclarationMode = PropertyDeclaration.ManagedWithTypeConversion; } else if (prop.DeclarationMode == PropertyDeclaration.Unmanaged) { prop.DeclarationMode = PropertyDeclaration.UnmanagedWithTypeConversion; } prop.PropertyType = TypeCodeEx.String; prop.BackingFieldType = TypeCodeEx.SmartDate; counter++; } } if (counter > 0) _outputPanel.AddOutputInfo(info.ObjectName + ": added " + counter + " backing fields."); if (simpleAuditCounter > 0) _outputPanel.AddOutputInfo(info.ObjectName + ": " + simpleAuditCounter + " Simple Audit properties unchanged."); } _outputPanel.AddOutputInfo(Environment.NewLine + "Force backing field on SmartDate properties is done." + Environment.NewLine); } private void ConvertPropertiesAndCriteriaToSilverlight_Click(object sender, EventArgs e) { _outputPanel.AddOutputInfo(Environment.NewLine + "Converting Properties and Criteria to be Silverlight compatible..." + Environment.NewLine); foreach (var info in _controller.CurrentUnit.CslaObjects) { if (info.IsBaseClass() || info.IsPlaceHolder()) continue; var counterAutoProperty = 0; var counterClassicProperty = 0; var counterClassicPropertyWithTypeConversion = 0; var counterNoProperty = 0; var counterCriteria = 0; foreach (var prop in info.ValueProperties) { if (prop.DeclarationMode == PropertyDeclaration.AutoProperty) { prop.DeclarationMode = PropertyDeclaration.Managed; counterAutoProperty++; } else if (prop.DeclarationMode == PropertyDeclaration.ClassicProperty) { prop.DeclarationMode = PropertyDeclaration.Managed; counterClassicProperty++; } else if (prop.DeclarationMode == PropertyDeclaration.ClassicPropertyWithTypeConversion) { prop.DeclarationMode = PropertyDeclaration.ManagedWithTypeConversion; counterClassicPropertyWithTypeConversion++; } else if (prop.DeclarationMode == PropertyDeclaration.NoProperty) { prop.DeclarationMode = PropertyDeclaration.Managed; counterNoProperty++; } } foreach (var prop in info.AllChildProperties) { if (prop.DeclarationMode == PropertyDeclaration.AutoProperty) { prop.DeclarationMode = PropertyDeclaration.Managed; counterAutoProperty++; } else if (prop.DeclarationMode == PropertyDeclaration.ClassicProperty) { prop.DeclarationMode = PropertyDeclaration.Managed; counterClassicProperty++; } else if (prop.DeclarationMode == PropertyDeclaration.ClassicPropertyWithTypeConversion) { prop.DeclarationMode = PropertyDeclaration.ManagedWithTypeConversion; counterClassicPropertyWithTypeConversion++; } else if (prop.DeclarationMode == PropertyDeclaration.NoProperty) { prop.DeclarationMode = PropertyDeclaration.Managed; counterNoProperty++; } } foreach (var prop in info.UnitOfWorkProperties) { if (prop.DeclarationMode == PropertyDeclaration.AutoProperty) { prop.DeclarationMode = PropertyDeclaration.Managed; counterAutoProperty++; } else if (prop.DeclarationMode == PropertyDeclaration.ClassicProperty) { prop.DeclarationMode = PropertyDeclaration.Managed; counterClassicProperty++; } else if (prop.DeclarationMode == PropertyDeclaration.ClassicPropertyWithTypeConversion) { prop.DeclarationMode = PropertyDeclaration.ManagedWithTypeConversion; counterClassicPropertyWithTypeConversion++; } else if (prop.DeclarationMode == PropertyDeclaration.NoProperty) { prop.DeclarationMode = PropertyDeclaration.Managed; counterNoProperty++; } } foreach (var criteria in info.CriteriaObjects) { if (criteria.Properties.Count > 1) { if (criteria.CriteriaClassMode == CriteriaMode.Simple) { bool nested = criteria.NestedClass; criteria.CriteriaClassMode = CriteriaMode.CriteriaBase; criteria.NestedClass = nested; counterCriteria++; } } } if (counterAutoProperty > 0) _outputPanel.AddOutputInfo(info.ObjectName + ": converted " + counterAutoProperty + " \"PropertyDeclaration.AutoProperty\" properties."); if (counterClassicProperty > 0) _outputPanel.AddOutputInfo(info.ObjectName + ": converted " + counterClassicProperty + " \"PropertyDeclaration.ClassicProperty\" properties."); if (counterClassicPropertyWithTypeConversion > 0) _outputPanel.AddOutputInfo(info.ObjectName + ": converted " + counterClassicPropertyWithTypeConversion + " \"PropertyDeclaration.ClassicPropertyWithTypeConversion\" properties."); if (counterNoProperty > 0) _outputPanel.AddOutputInfo(info.ObjectName + ": converted " + counterNoProperty + " \"PropertyDeclaration.NoProperty\" properties."); if (counterCriteria > 0) _outputPanel.AddOutputInfo(info.ObjectName + ": converted " + counterCriteria + " \"CriteriaMode.Simple\" criteria."); } _outputPanel.AddOutputInfo(Environment.NewLine + "Convert Properties and Criteria to be Silverlight compatible is done." + Environment.NewLine); } private void ConvertProjectToNewPublicPolicy_Click(object sender, EventArgs e) { _outputPanel.AddOutputInfo(Environment.NewLine + "Convert Constructors and PropertyInfo to Public..." + Environment.NewLine); foreach (var info in _controller.CurrentUnit.CslaObjects) { if (info.IsBaseClass() || info.IsPlaceHolder()) continue; if (info.ConstructorVisibility != ConstructorVisibility.Default) { info.ConstructorVisibility = ConstructorVisibility.Default; _outputPanel.AddOutputInfo(info.ObjectName + ": converted constructor to Default (public)."); } } if (!_controller.CurrentUnit.GenerationParams.UsePublicPropertyInfo) { _controller.CurrentUnit.GenerationParams.UsePublicPropertyInfo = true; _outputPanel.AddOutputInfo("Generation parameter \"Use public PropertyInfo\" changed to check."); } _outputPanel.AddOutputInfo(Environment.NewLine + "Convert Constructors and PropertyInfo to Public is done." + Environment.NewLine); } private void LocateToolStripMenuItem_Click(object sender, EventArgs e) { using (var tDirDialog = new FolderBrowserDialog()) { tDirDialog.Description = @"Current folder location of the CslaGenFork templates is:" + Environment.NewLine + _controller.TemplatesDirectory + Environment.NewLine + @"Select a new folder location and press OK."; tDirDialog.ShowNewFolderButton = false; if (!string.IsNullOrEmpty(_controller.TemplatesDirectory)) tDirDialog.SelectedPath = _controller.TemplatesDirectory; else tDirDialog.RootFolder = Environment.SpecialFolder.Desktop; DialogResult dialogResult = tDirDialog.ShowDialog(); if (dialogResult == DialogResult.OK) { string tdir = tDirDialog.SelectedPath; if (tDirDialog.SelectedPath.LastIndexOf('\\') != tDirDialog.SelectedPath.Length - 1) tdir += @"\"; _controller.TemplatesDirectory = tdir; ConfigTools.SharedAppConfigChange("TemplatesDirectory", _controller.TemplatesDirectory); } } } private void CodeSmithExtensionToolStripMenuItem_Click(object sender, EventArgs e) { Windows7Security.StartCodeSmithHandler(); } #endregion #region View menu private void ProjectPanelToolStripMenuItem_Click(object sender, EventArgs e) { if (projectPanelToolStripMenuItem.Checked) _projectPanel.Hide(); else _projectPanel.Show(dockPanel); } private void StartPageToolStripMenuItem_Click(object sender, EventArgs e) { if (startPageToolStripMenuItem.Checked) _webBrowserDockPanel.Hide(); else _webBrowserDockPanel.Show(dockPanel); } private void GlobalSettingsPageToolStripMenuItemClick(object sender, EventArgs e) { if (GlobalSettingsPanel == null) return; if (globalSettingsPageToolStripMenuItem.Checked) GlobalSettingsPanel.Hide(); else { if (_controller.CurrentUnit != null) GlobalSettingsPanel.Show(dockPanel); } } private void ObjectRelationsBuilderPageToolStripMenuItemClick(object sender, EventArgs e) { if (objectRelationsBuilderPageToolStripMenuItem.Checked) ObjectRelationsBuilderPanel.Hide(); else { if (_controller.CurrentUnit != null) ObjectRelationsBuilderPanel.Show(dockPanel); } } private void ProjectPropertiesPageToolStripMenuItemClick(object sender, EventArgs e) { if (ProjectPropertiesPanel == null) return; if (projectPropertiesPageToolStripMenuItem.Checked) ProjectPropertiesPanel.Hide(); else { if (_controller.CurrentUnit != null) ProjectPropertiesPanel.Show(dockPanel); } } private void SchemaPageToolStripMenuItemClick(object sender, EventArgs e) { if (DbSchemaPanel == null) return; if (schemaPageToolStripMenuItem.Checked) DbSchemaPanel.Hide(); else { if (_controller.CurrentUnit != null) DbSchemaPanel.Show(dockPanel); } } private void ObjectPropertiesPanelToolStripMenuItem_Click(object sender, EventArgs e) { if (objectPropertiesPanelToolStripMenuItem.Checked) _objectInfoPanel.Hide(); else _objectInfoPanel.Show(dockPanel); } private void OutputWindowToolStripMenuItem_Click(object sender, EventArgs e) { if (outputWindowToolStripMenuItem.Checked) OutputWindow.Current.Hide(); else OutputWindow.Current.Show(dockPanel); } #endregion #region Help menu private void AboutToolStripMenuItem_Click(object sender, EventArgs e) { using (var frm = new AboutBox()) { frm.ShowDialog(); } } #endregion #region Status bar private void ClearErrorsAndWarnings() { generatingTimer.Text = "Generating:"; _errorPannel.Empty(); _errorPannel.Hide(); _warningPannel.Empty(); _warningPannel.Hide(); errors.Image = null; warnings.Image = null; errors.DoubleClickEnabled = false; warnings.DoubleClickEnabled = false; errors.ToolTipText = string.Empty; warnings.ToolTipText = string.Empty; errors.AutoToolTip = false; warnings.AutoToolTip = false; } private void FillDatabaseObjects() { if (_controller.IsDBConnected) { tables.Text = string.Format("Tables: {0}", _controller.Tables); views.Text = string.Format("Views: {0}", _controller.Views); sprocs.Text = string.Format("SProcs: {0}", _controller.Sprocs); } else { tables.Text = "Tables:"; views.Text = "Views:"; sprocs.Text = "SProcs:"; } } internal void FillObjects() { objects.Text = string.Format("Objects: {0}", _controller.CurrentUnit.CslaObjects.Count); } private void Errors_DoubleClick(object sender, EventArgs e) { _errorPannel.Fill(_generator.ErrorReport); _errorPannel.TabText = @"Errors"; //_errorPannel.VisibleChanged += delegate(object sender, EventArgs e) { outputWindowToolStripMenuItem.Checked = ((DockContent)sender).Visible; }; _errorPannel.FormClosing += PaneFormClosing; _errorPannel.Show(_outputPanel.Pane, _outputPanel); } private void Warnings_DoubleClick(object sender, EventArgs e) { _warningPannel.Fill(_generator.WarningReport); _warningPannel.TabText = @"Warnings"; //_warningPannel.VisibleChanged += delegate(object sender, EventArgs e) { outputWindowToolStripMenuItem.Checked = ((DockContent)sender).Visible; }; _warningPannel.FormClosing += PaneFormClosing; _warningPannel.Show(_outputPanel.Pane, _outputPanel); } #endregion } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using Newtonsoft.Json; namespace XenAPI { /// <summary> /// A virtual TPM device /// First published in XenServer 4.0. /// </summary> public partial class VTPM : XenObject<VTPM> { #region Constructors public VTPM() { } public VTPM(string uuid, XenRef<VM> VM, XenRef<VM> backend) { this.uuid = uuid; this.VM = VM; this.backend = backend; } /// <summary> /// Creates a new VTPM from a Hashtable. /// Note that the fields not contained in the Hashtable /// will be created with their default values. /// </summary> /// <param name="table"></param> public VTPM(Hashtable table) : this() { UpdateFrom(table); } /// <summary> /// Creates a new VTPM from a Proxy_VTPM. /// </summary> /// <param name="proxy"></param> public VTPM(Proxy_VTPM proxy) { UpdateFrom(proxy); } #endregion /// <summary> /// Updates each field of this instance with the value of /// the corresponding field of a given VTPM. /// </summary> public override void UpdateFrom(VTPM record) { uuid = record.uuid; VM = record.VM; backend = record.backend; } internal void UpdateFrom(Proxy_VTPM proxy) { uuid = proxy.uuid == null ? null : proxy.uuid; VM = proxy.VM == null ? null : XenRef<VM>.Create(proxy.VM); backend = proxy.backend == null ? null : XenRef<VM>.Create(proxy.backend); } /// <summary> /// Given a Hashtable with field-value pairs, it updates the fields of this VTPM /// with the values listed in the Hashtable. Note that only the fields contained /// in the Hashtable will be updated and the rest will remain the same. /// </summary> /// <param name="table"></param> public void UpdateFrom(Hashtable table) { if (table.ContainsKey("uuid")) uuid = Marshalling.ParseString(table, "uuid"); if (table.ContainsKey("VM")) VM = Marshalling.ParseRef<VM>(table, "VM"); if (table.ContainsKey("backend")) backend = Marshalling.ParseRef<VM>(table, "backend"); } public Proxy_VTPM ToProxy() { Proxy_VTPM result_ = new Proxy_VTPM(); result_.uuid = uuid ?? ""; result_.VM = VM ?? ""; result_.backend = backend ?? ""; return result_; } public bool DeepEquals(VTPM other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._VM, other._VM) && Helper.AreEqual2(this._backend, other._backend); } public override string SaveChanges(Session session, string opaqueRef, VTPM server) { if (opaqueRef == null) { var reference = create(session, this); return reference == null ? null : reference.opaque_ref; } else { throw new InvalidOperationException("This type has no read/write properties"); } } /// <summary> /// Get a record containing the current state of the given VTPM. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vtpm">The opaque_ref of the given vtpm</param> public static VTPM get_record(Session session, string _vtpm) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vtpm_get_record(session.opaque_ref, _vtpm); else return new VTPM(session.XmlRpcProxy.vtpm_get_record(session.opaque_ref, _vtpm ?? "").parse()); } /// <summary> /// Get a reference to the VTPM instance with the specified UUID. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<VTPM> get_by_uuid(Session session, string _uuid) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vtpm_get_by_uuid(session.opaque_ref, _uuid); else return XenRef<VTPM>.Create(session.XmlRpcProxy.vtpm_get_by_uuid(session.opaque_ref, _uuid ?? "").parse()); } /// <summary> /// Create a new VTPM instance, and return its handle. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_record">All constructor arguments</param> public static XenRef<VTPM> create(Session session, VTPM _record) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vtpm_create(session.opaque_ref, _record); else return XenRef<VTPM>.Create(session.XmlRpcProxy.vtpm_create(session.opaque_ref, _record.ToProxy()).parse()); } /// <summary> /// Create a new VTPM instance, and return its handle. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_record">All constructor arguments</param> public static XenRef<Task> async_create(Session session, VTPM _record) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_vtpm_create(session.opaque_ref, _record); else return XenRef<Task>.Create(session.XmlRpcProxy.async_vtpm_create(session.opaque_ref, _record.ToProxy()).parse()); } /// <summary> /// Destroy the specified VTPM instance. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vtpm">The opaque_ref of the given vtpm</param> public static void destroy(Session session, string _vtpm) { if (session.JsonRpcClient != null) session.JsonRpcClient.vtpm_destroy(session.opaque_ref, _vtpm); else session.XmlRpcProxy.vtpm_destroy(session.opaque_ref, _vtpm ?? "").parse(); } /// <summary> /// Destroy the specified VTPM instance. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vtpm">The opaque_ref of the given vtpm</param> public static XenRef<Task> async_destroy(Session session, string _vtpm) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_vtpm_destroy(session.opaque_ref, _vtpm); else return XenRef<Task>.Create(session.XmlRpcProxy.async_vtpm_destroy(session.opaque_ref, _vtpm ?? "").parse()); } /// <summary> /// Get the uuid field of the given VTPM. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vtpm">The opaque_ref of the given vtpm</param> public static string get_uuid(Session session, string _vtpm) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vtpm_get_uuid(session.opaque_ref, _vtpm); else return session.XmlRpcProxy.vtpm_get_uuid(session.opaque_ref, _vtpm ?? "").parse(); } /// <summary> /// Get the VM field of the given VTPM. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vtpm">The opaque_ref of the given vtpm</param> public static XenRef<VM> get_VM(Session session, string _vtpm) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vtpm_get_vm(session.opaque_ref, _vtpm); else return XenRef<VM>.Create(session.XmlRpcProxy.vtpm_get_vm(session.opaque_ref, _vtpm ?? "").parse()); } /// <summary> /// Get the backend field of the given VTPM. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vtpm">The opaque_ref of the given vtpm</param> public static XenRef<VM> get_backend(Session session, string _vtpm) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vtpm_get_backend(session.opaque_ref, _vtpm); else return XenRef<VM>.Create(session.XmlRpcProxy.vtpm_get_backend(session.opaque_ref, _vtpm ?? "").parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; NotifyPropertyChanged("uuid"); } } } private string _uuid = ""; /// <summary> /// the virtual machine /// </summary> [JsonConverter(typeof(XenRefConverter<VM>))] public virtual XenRef<VM> VM { get { return _VM; } set { if (!Helper.AreEqual(value, _VM)) { _VM = value; NotifyPropertyChanged("VM"); } } } private XenRef<VM> _VM = new XenRef<VM>(Helper.NullOpaqueRef); /// <summary> /// the domain where the backend is located /// </summary> [JsonConverter(typeof(XenRefConverter<VM>))] public virtual XenRef<VM> backend { get { return _backend; } set { if (!Helper.AreEqual(value, _backend)) { _backend = value; NotifyPropertyChanged("backend"); } } } private XenRef<VM> _backend = new XenRef<VM>(Helper.NullOpaqueRef); } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Reflection; using MySql.Data.MySqlClient; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Data; using RegionFlags = OpenSim.Framework.RegionFlags; namespace OpenSim.Data.MySQL { public class MySqlRegionData : MySqlFramework, IRegionData { private string m_Realm; private List<string> m_ColumnNames; //private string m_connectionString; protected virtual Assembly Assembly { get { return GetType().Assembly; } } public MySqlRegionData(string connectionString, string realm) : base(connectionString) { m_Realm = realm; m_connectionString = connectionString; using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); Migration m = new Migration(dbcon, Assembly, "GridStore"); m.Update(); } } public List<RegionData> Get(string regionName, UUID scopeID) { string command = "select * from `"+m_Realm+"` where regionName like ?regionName"; if (scopeID != UUID.Zero) command += " and ScopeID = ?scopeID"; command += " order by regionName"; using (MySqlCommand cmd = new MySqlCommand(command)) { cmd.Parameters.AddWithValue("?regionName", regionName); cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString()); return RunCommand(cmd); } } public RegionData Get(int posX, int posY, UUID scopeID) { string command = "select * from `"+m_Realm+"` where locX = ?posX and locY = ?posY"; if (scopeID != UUID.Zero) command += " and ScopeID = ?scopeID"; using (MySqlCommand cmd = new MySqlCommand(command)) { cmd.Parameters.AddWithValue("?posX", posX.ToString()); cmd.Parameters.AddWithValue("?posY", posY.ToString()); cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString()); List<RegionData> ret = RunCommand(cmd); if (ret.Count == 0) return null; return ret[0]; } } public RegionData Get(UUID regionID, UUID scopeID) { string command = "select * from `"+m_Realm+"` where uuid = ?regionID"; if (scopeID != UUID.Zero) command += " and ScopeID = ?scopeID"; using (MySqlCommand cmd = new MySqlCommand(command)) { cmd.Parameters.AddWithValue("?regionID", regionID.ToString()); cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString()); List<RegionData> ret = RunCommand(cmd); if (ret.Count == 0) return null; return ret[0]; } } public List<RegionData> Get(int startX, int startY, int endX, int endY, UUID scopeID) { string command = "select * from `"+m_Realm+"` where locX between ?startX and ?endX and locY between ?startY and ?endY"; if (scopeID != UUID.Zero) command += " and ScopeID = ?scopeID"; using (MySqlCommand cmd = new MySqlCommand(command)) { cmd.Parameters.AddWithValue("?startX", startX.ToString()); cmd.Parameters.AddWithValue("?startY", startY.ToString()); cmd.Parameters.AddWithValue("?endX", endX.ToString()); cmd.Parameters.AddWithValue("?endY", endY.ToString()); cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString()); return RunCommand(cmd); } } public List<RegionData> RunCommand(MySqlCommand cmd) { List<RegionData> retList = new List<RegionData>(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); cmd.Connection = dbcon; using (IDataReader result = cmd.ExecuteReader()) { while (result.Read()) { RegionData ret = new RegionData(); ret.Data = new Dictionary<string, object>(); ret.RegionID = DBGuid.FromDB(result["uuid"]); ret.ScopeID = DBGuid.FromDB(result["ScopeID"]); ret.RegionName = result["regionName"].ToString(); ret.posX = Convert.ToInt32(result["locX"]); ret.posY = Convert.ToInt32(result["locY"]); ret.sizeX = Convert.ToInt32(result["sizeX"]); ret.sizeY = Convert.ToInt32(result["sizeY"]); CheckColumnNames(result); foreach (string s in m_ColumnNames) { if (s == "uuid") continue; if (s == "ScopeID") continue; if (s == "regionName") continue; if (s == "locX") continue; if (s == "locY") continue; object value = result[s]; if (value is DBNull) ret.Data[s] = null; else ret.Data[s] = result[s].ToString(); } retList.Add(ret); } } } return retList; } private void CheckColumnNames(IDataReader result) { if (m_ColumnNames != null) return; List<string> columnNames = new List<string>(); DataTable schemaTable = result.GetSchemaTable(); foreach (DataRow row in schemaTable.Rows) { if (row["ColumnName"] != null) columnNames.Add(row["ColumnName"].ToString()); } m_ColumnNames = columnNames; } public bool Store(RegionData data) { if (data.Data.ContainsKey("uuid")) data.Data.Remove("uuid"); if (data.Data.ContainsKey("ScopeID")) data.Data.Remove("ScopeID"); if (data.Data.ContainsKey("regionName")) data.Data.Remove("regionName"); if (data.Data.ContainsKey("posX")) data.Data.Remove("posX"); if (data.Data.ContainsKey("posY")) data.Data.Remove("posY"); if (data.Data.ContainsKey("sizeX")) data.Data.Remove("sizeX"); if (data.Data.ContainsKey("sizeY")) data.Data.Remove("sizeY"); if (data.Data.ContainsKey("locX")) data.Data.Remove("locX"); if (data.Data.ContainsKey("locY")) data.Data.Remove("locY"); if (data.RegionName.Length > 128) data.RegionName = data.RegionName.Substring(0, 128); string[] fields = new List<string>(data.Data.Keys).ToArray(); using (MySqlCommand cmd = new MySqlCommand()) { string update = "update `" + m_Realm + "` set locX=?posX, locY=?posY, sizeX=?sizeX, sizeY=?sizeY"; foreach (string field in fields) { update += ", "; update += "`" + field + "` = ?" + field; cmd.Parameters.AddWithValue("?" + field, data.Data[field]); } update += " where uuid = ?regionID"; if (data.ScopeID != UUID.Zero) update += " and ScopeID = ?scopeID"; cmd.CommandText = update; cmd.Parameters.AddWithValue("?regionID", data.RegionID.ToString()); cmd.Parameters.AddWithValue("?regionName", data.RegionName); cmd.Parameters.AddWithValue("?scopeID", data.ScopeID.ToString()); cmd.Parameters.AddWithValue("?posX", data.posX.ToString()); cmd.Parameters.AddWithValue("?posY", data.posY.ToString()); cmd.Parameters.AddWithValue("?sizeX", data.sizeX.ToString()); cmd.Parameters.AddWithValue("?sizeY", data.sizeY.ToString()); if (ExecuteNonQuery(cmd) < 1) { string insert = "insert into `" + m_Realm + "` (`uuid`, `ScopeID`, `locX`, `locY`, `sizeX`, `sizeY`, `regionName`, `" + String.Join("`, `", fields) + "`) values ( ?regionID, ?scopeID, ?posX, ?posY, ?sizeX, ?sizeY, ?regionName, ?" + String.Join(", ?", fields) + ")"; cmd.CommandText = insert; if (ExecuteNonQuery(cmd) < 1) { return false; } } } return true; } public bool SetDataItem(UUID regionID, string item, string value) { using (MySqlCommand cmd = new MySqlCommand("update `" + m_Realm + "` set `" + item + "` = ?" + item + " where uuid = ?UUID")) { cmd.Parameters.AddWithValue("?" + item, value); cmd.Parameters.AddWithValue("?UUID", regionID.ToString()); if (ExecuteNonQuery(cmd) > 0) return true; } return false; } public bool Delete(UUID regionID) { using (MySqlCommand cmd = new MySqlCommand("delete from `" + m_Realm + "` where uuid = ?UUID")) { cmd.Parameters.AddWithValue("?UUID", regionID.ToString()); if (ExecuteNonQuery(cmd) > 0) return true; } return false; } public List<RegionData> GetDefaultRegions(UUID scopeID) { return Get((int)RegionFlags.DefaultRegion, scopeID); } public List<RegionData> GetFallbackRegions(UUID scopeID, int x, int y) { List<RegionData> regions = Get((int)RegionFlags.FallbackRegion, scopeID); RegionDataDistanceCompare distanceComparer = new RegionDataDistanceCompare(x, y); regions.Sort(distanceComparer); return regions; } public List<RegionData> GetHyperlinks(UUID scopeID) { return Get((int)RegionFlags.Hyperlink, scopeID); } private List<RegionData> Get(int regionFlags, UUID scopeID) { string command = "select * from `" + m_Realm + "` where (flags & " + regionFlags.ToString() + ") <> 0"; if (scopeID != UUID.Zero) command += " and ScopeID = ?scopeID"; using (MySqlCommand cmd = new MySqlCommand(command)) { cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString()); return RunCommand(cmd); } } } }
#region License // Copyright 2006 James Newton-King // http://www.newtonsoft.com // // This work is licensed under the Creative Commons Attribution 2.5 License // http://creativecommons.org/licenses/by/2.5/ // // You are free: // * to copy, distribute, display, and perform the work // * to make derivative works // * to make commercial use of the work // // Under the following conditions: // * You must attribute the work in the manner specified by the author or licensor: // - If you find this component useful a link to http://www.newtonsoft.com would be appreciated. // * For any reuse or distribution, you must make clear to others the license terms of this work. // * Any of these conditions can be waived if you get permission from the copyright holder. #endregion using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.IO; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json { /// <summary> /// Specifies reference loop handling options for the <see cref="JsonWriter"/>. /// </summary> public enum ReferenceLoopHandling { /// <summary> /// Throw a <see cref="JsonSerializationException"/> when a loop is encountered. /// </summary> Error = 0, /// <summary> /// Ignore loop references and do not serialize. /// </summary> Ignore = 1, /// <summary> /// Serialize loop references. /// </summary> Serialize = 2 } /// <summary> /// Serializes and deserializes objects into and from the Json format. /// The <see cref="JsonSerializer"/> enables you to control how objects are encoded into Json. /// </summary> public class JsonSerializer { private ReferenceLoopHandling _referenceLoopHandling; private int _level; private JsonConverterCollection _converters; /// <summary> /// Get or set how reference loops (e.g. a class referencing itself) is handled. /// </summary> public ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling; } set { if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize) { throw new ArgumentOutOfRangeException("value"); } _referenceLoopHandling = value; } } public JsonConverterCollection Converters { get { if (_converters == null) _converters = new JsonConverterCollection(); return _converters; } } /// <summary> /// Initializes a new instance of the <see cref="JsonSerializer"/> class. /// </summary> public JsonSerializer() { _referenceLoopHandling = ReferenceLoopHandling.Error; } #region Deserialize /// <summary> /// Deserializes the Json structure contained by the specified <see cref="JsonReader"/>. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> that contains the Json structure to deserialize.</param> /// <returns>The <see cref="Object"/> being deserialized.</returns> public object Deserialize(JsonReader reader) { return Deserialize(reader, null); } /// <summary> /// Deserializes the Json structure contained by the specified <see cref="JsonReader"/> /// into an instance of the specified type. /// </summary> /// <param name="reader">The type of object to create.</param> /// <param name="objectType">The <see cref="Type"/> of object being deserialized.</param> /// <returns>The instance of <paramref name="objectType"/> being deserialized.</returns> public object Deserialize(JsonReader reader, Type objectType, params object[] args) { if (reader == null) throw new ArgumentNullException("reader"); if (!reader.Read()) return null; return GetObject(reader, objectType, args); } private JavaScriptArray PopulateJavaScriptArray(JsonReader reader) { JavaScriptArray jsArray = new JavaScriptArray(); while (reader.Read()) { switch (reader.TokenType) { case JsonToken.EndArray: return jsArray; case JsonToken.Comment: break; default: object value = GetObject(reader, null); jsArray.Add(value); break; } } throw new JsonSerializationException("Unexpected end while deserializing array."); } private JavaScriptObject PopulateJavaScriptObject(JsonReader reader) { JavaScriptObject jsObject = new JavaScriptObject(); while (reader.Read()) { switch (reader.TokenType) { case JsonToken.PropertyName: string memberName = reader.Value.ToString(); // move to the value token. skip comments do { if (!reader.Read()) throw new Exception("Unexpected end while deserializing object."); } while (reader.TokenType == JsonToken.Comment); object value = GetObject(reader, null); jsObject[memberName] = value; break; case JsonToken.EndObject: return jsObject; case JsonToken.Comment: break; default: throw new JsonSerializationException("Unexpected token while deserializing object: " + reader.TokenType); } } throw new JsonSerializationException("Unexpected end while deserializing object."); } private object GetObject(JsonReader reader, Type objectType, params object[] args) { _level++; object value; JsonConverter converter; if (HasMatchingConverter(objectType, out converter)) { return converter.ReadJson(reader, objectType); } else { switch (reader.TokenType) { // populate a typed object or generic dictionary/array // depending upon whether an objectType was supplied case JsonToken.StartObject: value = (objectType != null) ? PopulateObject(reader, objectType, args) : PopulateJavaScriptObject(reader); break; case JsonToken.StartArray: value = (objectType != null) ? PopulateList(reader, objectType) : PopulateJavaScriptArray(reader); break; case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Date: value = EnsureType(reader.Value, objectType); break; case JsonToken.Constructor: value = reader.Value.ToString(); break; case JsonToken.Null: case JsonToken.Undefined: value = null; break; default: throw new JsonSerializationException("Unexpected token whil deserializing object: " + reader.TokenType); } } _level--; return value; } private object EnsureType(object value, Type targetType) { // do something about null value when the targetType is a valuetype? if (value == null) return null; if (targetType == null) return value; Type valueType = value.GetType(); // type of value and type of target don't match // attempt to convert value's type to target's type if (valueType != targetType) { if (valueType == typeof(string) && targetType == typeof(DateTime)) { // arreglamos formato var rex = Regex.Split((string)value, @"(?<Date>\d{4}-\d{2}-\d{2})\w{1}(?<Time>\d{2}:\d{2}:\d{2})", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.CultureInvariant); /* var tmpValue = string.Empty; foreach (Group item in rex.Groups) { tmpValue = string.Concat(tmpValue, item.Value); } */ value = String.Join(" ", rex, 1, 2); } TypeConverter targetConverter = TypeDescriptor.GetConverter(targetType); if (!targetConverter.CanConvertFrom(valueType)) { if (targetConverter.CanConvertFrom(typeof(string))) { string valueString = TypeDescriptor.GetConverter(value).ConvertToInvariantString(value); return targetConverter.ConvertFromInvariantString(valueString); } if (!targetType.IsAssignableFrom(valueType)) throw new InvalidOperationException(string.Format("Cannot convert object of type '{0}' to type '{1}'", value.GetType(), targetType)); return value; } return targetConverter.ConvertFrom(value); } else { return value; } } private void SetObjectMember(JsonReader reader, object target, Type targetType, string memberName) { if (!reader.Read()) throw new JsonSerializationException(string.Format("Unexpected end when setting {0}'s value.", memberName)); MemberInfo[] memberCollection = targetType.GetMember(memberName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetField | BindingFlags.SetProperty); Type memberType; object value; // test if a member with memberName exists on the type if (!CollectionUtils.IsNullOrEmpty<MemberInfo>(memberCollection)) { // get the member's underlying type MemberInfo member = targetType.GetMember(memberName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetField | BindingFlags.SetProperty)[0]; memberType = ReflectionUtils.GetMemberUnderlyingType(member); value = GetObject(reader, memberType); ReflectionUtils.SetMemberValue(member, target, value); } else if (typeof(IDictionary).IsAssignableFrom(targetType)) { // attempt to the IDictionary's type memberType = ReflectionUtils.GetDictionaryValueType(target); value = GetObject(reader, memberType); ((IDictionary)target).Add(memberName, value); } else { throw new JsonSerializationException(string.Format("Could not find member '{0}' on object of type '{1}'", memberName, targetType.GetType().Name)); } } private object PopulateList(JsonReader reader, Type objectType) { IList list; Type elementType = ReflectionUtils.GetListType(objectType); if (objectType.IsArray || objectType == typeof(ArrayList) || objectType == typeof(object)) // array or arraylist. // have to use an arraylist when creating array because there is no way to know the size until it is finised list = new ArrayList(); else if (ReflectionUtils.IsInstantiatableType(objectType) && typeof(IList).IsAssignableFrom(objectType)) // non-generic typed list list = (IList)Activator.CreateInstance(objectType); else if (ReflectionUtils.IsSubClass(objectType, typeof(List<>))) // generic list list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(elementType)); else throw new JsonSerializationException(string.Format("Deserializing list type '{0}' not supported.", objectType.GetType().Name)); while (reader.Read()) { switch (reader.TokenType) { case JsonToken.EndArray: ArrayList arrayList = list as ArrayList; if (arrayList != null) { // convert back into array now that it is finised if (objectType.IsArray) list = arrayList.ToArray(elementType); else if (objectType == typeof(object)) list = arrayList.ToArray(); } return list; case JsonToken.Comment: break; default: object value = GetObject(reader, elementType); list.Add(value); break; } } throw new JsonSerializationException("Unexpected end when deserializing array."); } private object PopulateObject(JsonReader reader, Type objectType, params object[] args) { object newObject = Activator.CreateInstance(objectType, args); while (reader.Read()) { switch (reader.TokenType) { case JsonToken.PropertyName: string memberName = reader.Value.ToString(); if (memberName.CompareTo(JsonConfig.memberNameForTypeName) != 0) SetObjectMember(reader, newObject, objectType, memberName); else { if (!reader.Read()) throw new JsonSerializationException(string.Format("Unexpected end when setting {0}'s value.", memberName)); } break; case JsonToken.EndObject: return newObject; default: throw new JsonSerializationException("Unexpected token when deserializing object: " + reader.TokenType); } } throw new JsonSerializationException("Unexpected end when deserializing object."); } #endregion #region Serialize /// <summary> /// Serializes the specified <see cref="Object"/> and writes the Json structure /// to a <c>Stream</c> using the specified <see cref="TextWriter"/>. /// </summary> /// <param name="textWriter">The <see cref="TextWriter"/> used to write the Json structure.</param> /// <param name="value">The <see cref="Object"/> to serialize.</param> public void Serialize(TextWriter textWriter, object value) { Serialize(new JsonWriter(textWriter), value); } /// <summary> /// Serializes the specified <see cref="Object"/> and writes the Json structure /// to a <c>Stream</c> using the specified <see cref="JsonWriter"/>. /// </summary> /// <param name="jsonWriter">The <see cref="JsonWriter"/> used to write the Json structure.</param> /// <param name="value">The <see cref="Object"/> to serialize.</param> public void Serialize(JsonWriter jsonWriter, object value) { if (jsonWriter == null) throw new ArgumentNullException("jsonWriter"); if (value == null) throw new ArgumentNullException("value"); SerializeValue(jsonWriter, value); } private void SerializeValue(JsonWriter writer, object value) { JsonConverter converter; if (value == null) { writer.WriteNull(); } else if (HasMatchingConverter(value.GetType(), out converter)) { converter.WriteJson(writer, value); } else if (value is IConvertible) { IConvertible convertible = value as IConvertible; switch (convertible.GetTypeCode()) { case TypeCode.String: writer.WriteValue((string)convertible); break; case TypeCode.Char: writer.WriteValue((char)convertible); break; case TypeCode.Boolean: writer.WriteValue((bool)convertible); break; case TypeCode.SByte: writer.WriteValue((sbyte)convertible); break; case TypeCode.Int16: writer.WriteValue((short)convertible); break; case TypeCode.UInt16: writer.WriteValue((ushort)convertible); break; case TypeCode.Int32: writer.WriteValue((int)convertible); break; case TypeCode.Byte: writer.WriteValue((byte)convertible); break; case TypeCode.UInt32: writer.WriteValue((uint)convertible); break; case TypeCode.Int64: writer.WriteValue((long)convertible); break; case TypeCode.UInt64: writer.WriteValue((ulong)convertible); break; case TypeCode.Single: writer.WriteValue((float)convertible); break; case TypeCode.Double: writer.WriteValue((double)convertible); break; case TypeCode.DateTime: writer.WriteValue((DateTime)convertible); break; case TypeCode.Decimal: writer.WriteValue((decimal)convertible); break; default: SerializeObject(writer, value); break; } } else if (value is DataSet) { SerializeDataSet(writer, (DataSet)value); } else if (value is DataTable) { SerializeDataTable(writer, (DataTable)value); } else if (value is IList) { SerializeList(writer, (IList)value); } else if (value is IDictionary) { SerializeDictionary(writer, (IDictionary)value); } else if (value is ICollection) { SerializeCollection(writer, (ICollection)value); } else if (value is Identifier) { writer.WriteRaw(value.ToString()); } else { Type valueType = value.GetType(); SerializeObject(writer, value); } } private bool HasMatchingConverter(Type type, out JsonConverter matchingConverter) { if (_converters != null) { for (int i = 0; i < _converters.Count; i++) { JsonConverter converter = _converters[i]; if (converter.CanConvert(type)) { matchingConverter = converter; return true; } } } matchingConverter = null; return false; } private void WriteMemberInfoProperty(JsonWriter writer, object value, MemberInfo member) { if (!ReflectionUtils.IsIndexedProperty(member)) { object memberValue = ReflectionUtils.GetMemberValue(member, value); if (writer.SerializeStack.IndexOf(memberValue) != -1) { switch (_referenceLoopHandling) { case ReferenceLoopHandling.Error: throw new JsonSerializationException("Self referencing loop"); case ReferenceLoopHandling.Ignore: // return from method return; case ReferenceLoopHandling.Serialize: // continue break; default: throw new InvalidOperationException(string.Format("Unexpected ReferenceLoopHandling value: '{0}'", _referenceLoopHandling)); } } writer.WritePropertyName(member.Name); SerializeValue(writer, memberValue); } } private void SerializeObject(JsonWriter writer, object value) { Type objectType = value.GetType(); TypeConverter converter = TypeDescriptor.GetConverter(objectType); // use the objectType's TypeConverter if it has one and can convert to a string if (converter != null && !(converter is ComponentConverter) && converter.GetType() != typeof(TypeConverter)) { if (converter.CanConvertTo(typeof(string))) { writer.WriteValue(converter.ConvertToInvariantString(value)); return; } } writer.SerializeStack.Add(value); writer.WriteStartObject(); List<MemberInfo> members = ReflectionUtils.GetFieldsAndProperties(objectType, BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetField | BindingFlags.GetProperty); foreach (MemberInfo member in members) { WriteMemberInfoProperty(writer, value, member); } // nombre del tipo writer.WritePropertyName(JsonConfig.memberNameForTypeName); SerializeValue(writer, objectType.Name); writer.WriteEndObject(); writer.SerializeStack.Remove(value); } private void SerializeDataSet(JsonWriter writer, DataSet value) { writer.WriteStartArray(); foreach (DataTable table in value.Tables) { SerializeDataTable(writer, table); } writer.WriteEndArray(); } private void SerializeDataTable(JsonWriter writer, DataTable value) { writer.WriteStartObject(); writer.WritePropertyName("TableName"); SerializeValue(writer, value.TableName); writer.WritePropertyName("Results"); int x = 0; writer.WriteStartArray(); foreach (DataRow row in value.Rows) { SerializeDataRow(writer, row); x++; } writer.WriteEndArray(); writer.WriteEndObject(); } private void SerializeDataRow(JsonWriter writer, DataRow value) { writer.WriteStartObject(); foreach (DataColumn column in value.Table.Columns) { writer.WritePropertyName(column.ColumnName); SerializeValue(writer, value[column.ColumnName]); } writer.WriteEndObject(); } private void SerializeCollection(JsonWriter writer, ICollection values) { object[] collectionValues = new object[values.Count]; values.CopyTo(collectionValues, 0); SerializeList(writer, collectionValues); } private void SerializeList(JsonWriter writer, IList values) { writer.WriteStartArray(); for (int i = 0; i < values.Count; i++) { SerializeValue(writer, values[i]); } writer.WriteEndArray(); } private void SerializeDictionary(JsonWriter writer, IDictionary values) { writer.WriteStartObject(); foreach (DictionaryEntry entry in values) { writer.WritePropertyName(entry.Key.ToString()); SerializeValue(writer, entry.Value); } writer.WriteEndObject(); } #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 { [Microsoft.Xrm.Sdk.Client.EntityLogicalName("sdkmessageprocessingstep")] [DataContract] [GeneratedCode("CrmSvcUtil", "7.1.0001.3108")] public partial class SdkMessageProcessingStep : Entity, INotifyPropertyChanging, INotifyPropertyChanged { public const string EntityLogicalName = "sdkmessageprocessingstep"; public const int EntityTypeCode = 4608; [AttributeLogicalName("asyncautodelete")] public bool? AsyncAutoDelete { get { return this.GetAttributeValue<bool?>("asyncautodelete"); } set { this.OnPropertyChanging("AsyncAutoDelete"); this.SetAttributeValue("asyncautodelete", (object) value); this.OnPropertyChanged("AsyncAutoDelete"); } } [AttributeLogicalName("canusereadonlyconnection")] public bool? CanUseReadOnlyConnection { get { return this.GetAttributeValue<bool?>("canusereadonlyconnection"); } set { this.OnPropertyChanging("CanUseReadOnlyConnection"); this.SetAttributeValue("canusereadonlyconnection", (object) value); this.OnPropertyChanged("CanUseReadOnlyConnection"); } } [AttributeLogicalName("componentstate")] public OptionSetValue ComponentState { get { return this.GetAttributeValue<OptionSetValue>("componentstate"); } } [AttributeLogicalName("configuration")] public string Configuration { get { return this.GetAttributeValue<string>("configuration"); } set { this.OnPropertyChanging("Configuration"); this.SetAttributeValue("configuration", (object) value); this.OnPropertyChanged("Configuration"); } } [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("customizationlevel")] public int? CustomizationLevel { get { return this.GetAttributeValue<int?>("customizationlevel"); } } [AttributeLogicalName("description")] public string Description { get { return this.GetAttributeValue<string>("description"); } set { this.OnPropertyChanging("Description"); this.SetAttributeValue("description", (object) value); this.OnPropertyChanged("Description"); } } [AttributeLogicalName("eventhandler")] public EntityReference EventHandler { get { return this.GetAttributeValue<EntityReference>("eventhandler"); } set { this.OnPropertyChanging("EventHandler"); this.SetAttributeValue("eventhandler", (object) value); this.OnPropertyChanged("EventHandler"); } } [AttributeLogicalName("filteringattributes")] public string FilteringAttributes { get { return this.GetAttributeValue<string>("filteringattributes"); } set { this.OnPropertyChanging("FilteringAttributes"); this.SetAttributeValue("filteringattributes", (object) value); this.OnPropertyChanged("FilteringAttributes"); } } [AttributeLogicalName("impersonatinguserid")] public EntityReference ImpersonatingUserId { get { return this.GetAttributeValue<EntityReference>("impersonatinguserid"); } set { this.OnPropertyChanging("ImpersonatingUserId"); this.SetAttributeValue("impersonatinguserid", (object) value); this.OnPropertyChanged("ImpersonatingUserId"); } } [AttributeLogicalName("introducedversion")] public string IntroducedVersion { get { return this.GetAttributeValue<string>("introducedversion"); } set { this.OnPropertyChanging("IntroducedVersion"); this.SetAttributeValue("introducedversion", (object) value); this.OnPropertyChanged("IntroducedVersion"); } } [AttributeLogicalName("invocationsource")] [Obsolete] public OptionSetValue InvocationSource { get { return this.GetAttributeValue<OptionSetValue>("invocationsource"); } set { this.OnPropertyChanging("InvocationSource"); this.SetAttributeValue("invocationsource", (object) value); this.OnPropertyChanged("InvocationSource"); } } [AttributeLogicalName("iscustomizable")] public BooleanManagedProperty IsCustomizable { get { return this.GetAttributeValue<BooleanManagedProperty>("iscustomizable"); } set { this.OnPropertyChanging("IsCustomizable"); this.SetAttributeValue("iscustomizable", (object) value); this.OnPropertyChanged("IsCustomizable"); } } [AttributeLogicalName("ishidden")] public BooleanManagedProperty IsHidden { get { return this.GetAttributeValue<BooleanManagedProperty>("ishidden"); } set { this.OnPropertyChanging("IsHidden"); this.SetAttributeValue("ishidden", (object) value); this.OnPropertyChanged("IsHidden"); } } [AttributeLogicalName("ismanaged")] public bool? IsManaged { get { return this.GetAttributeValue<bool?>("ismanaged"); } } [AttributeLogicalName("mode")] public OptionSetValue Mode { get { return this.GetAttributeValue<OptionSetValue>("mode"); } set { this.OnPropertyChanging("Mode"); this.SetAttributeValue("mode", (object) value); this.OnPropertyChanged("Mode"); } } [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("name")] public string Name { get { return this.GetAttributeValue<string>("name"); } set { this.OnPropertyChanging("Name"); this.SetAttributeValue("name", (object) value); this.OnPropertyChanged("Name"); } } [AttributeLogicalName("organizationid")] public EntityReference OrganizationId { get { return this.GetAttributeValue<EntityReference>("organizationid"); } } [AttributeLogicalName("overwritetime")] public DateTime? OverwriteTime { get { return this.GetAttributeValue<DateTime?>("overwritetime"); } } [AttributeLogicalName("plugintypeid")] [Obsolete] public EntityReference PluginTypeId { get { return this.GetAttributeValue<EntityReference>("plugintypeid"); } set { this.OnPropertyChanging("PluginTypeId"); this.SetAttributeValue("plugintypeid", (object) value); this.OnPropertyChanged("PluginTypeId"); } } [AttributeLogicalName("rank")] public int? Rank { get { return this.GetAttributeValue<int?>("rank"); } set { this.OnPropertyChanging("Rank"); this.SetAttributeValue("rank", (object) value); this.OnPropertyChanged("Rank"); } } [AttributeLogicalName("sdkmessagefilterid")] public EntityReference SdkMessageFilterId { get { return this.GetAttributeValue<EntityReference>("sdkmessagefilterid"); } set { this.OnPropertyChanging("SdkMessageFilterId"); this.SetAttributeValue("sdkmessagefilterid", (object) value); this.OnPropertyChanged("SdkMessageFilterId"); } } [AttributeLogicalName("sdkmessageid")] public EntityReference SdkMessageId { get { return this.GetAttributeValue<EntityReference>("sdkmessageid"); } set { this.OnPropertyChanging("SdkMessageId"); this.SetAttributeValue("sdkmessageid", (object) value); this.OnPropertyChanged("SdkMessageId"); } } [AttributeLogicalName("sdkmessageprocessingstepid")] public Guid? SdkMessageProcessingStepId { get { return this.GetAttributeValue<Guid?>("sdkmessageprocessingstepid"); } set { this.OnPropertyChanging("SdkMessageProcessingStepId"); this.SetAttributeValue("sdkmessageprocessingstepid", (object) value); if (value.HasValue) base.Id = value.Value; else base.Id = Guid.Empty; this.OnPropertyChanged("SdkMessageProcessingStepId"); } } [AttributeLogicalName("sdkmessageprocessingstepid")] public override Guid Id { get { return base.Id; } set { this.SdkMessageProcessingStepId = new Guid?(value); } } [AttributeLogicalName("sdkmessageprocessingstepidunique")] public Guid? SdkMessageProcessingStepIdUnique { get { return this.GetAttributeValue<Guid?>("sdkmessageprocessingstepidunique"); } } [AttributeLogicalName("sdkmessageprocessingstepsecureconfigid")] public EntityReference SdkMessageProcessingStepSecureConfigId { get { return this.GetAttributeValue<EntityReference>("sdkmessageprocessingstepsecureconfigid"); } set { this.OnPropertyChanging("SdkMessageProcessingStepSecureConfigId"); this.SetAttributeValue("sdkmessageprocessingstepsecureconfigid", (object) value); this.OnPropertyChanged("SdkMessageProcessingStepSecureConfigId"); } } [AttributeLogicalName("solutionid")] public Guid? SolutionId { get { return this.GetAttributeValue<Guid?>("solutionid"); } } [AttributeLogicalName("stage")] public OptionSetValue Stage { get { return this.GetAttributeValue<OptionSetValue>("stage"); } set { this.OnPropertyChanging("Stage"); this.SetAttributeValue("stage", (object) value); this.OnPropertyChanged("Stage"); } } [AttributeLogicalName("statecode")] public SdkMessageProcessingStepState? StateCode { get { OptionSetValue attributeValue = this.GetAttributeValue<OptionSetValue>("statecode"); if (attributeValue != null) return new SdkMessageProcessingStepState?((SdkMessageProcessingStepState) Enum.ToObject(typeof (SdkMessageProcessingStepState), attributeValue.Value)); return new SdkMessageProcessingStepState?(); } 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("supporteddeployment")] public OptionSetValue SupportedDeployment { get { return this.GetAttributeValue<OptionSetValue>("supporteddeployment"); } set { this.OnPropertyChanging("SupportedDeployment"); this.SetAttributeValue("supporteddeployment", (object) value); this.OnPropertyChanged("SupportedDeployment"); } } [AttributeLogicalName("versionnumber")] public long? VersionNumber { get { return this.GetAttributeValue<long?>("versionnumber"); } } [RelationshipSchemaName("SdkMessageProcessingStep_AsyncOperations")] public IEnumerable<AsyncOperation> SdkMessageProcessingStep_AsyncOperations { get { return this.GetRelatedEntities<AsyncOperation>("SdkMessageProcessingStep_AsyncOperations", new EntityRole?()); } set { this.OnPropertyChanging("SdkMessageProcessingStep_AsyncOperations"); this.SetRelatedEntities<AsyncOperation>("SdkMessageProcessingStep_AsyncOperations", new EntityRole?(), value); this.OnPropertyChanged("SdkMessageProcessingStep_AsyncOperations"); } } [RelationshipSchemaName("sdkmessageprocessingstepid_sdkmessageprocessingstepimage")] public IEnumerable<SdkMessageProcessingStepImage> sdkmessageprocessingstepid_sdkmessageprocessingstepimage { get { return this.GetRelatedEntities<SdkMessageProcessingStepImage>("sdkmessageprocessingstepid_sdkmessageprocessingstepimage", new EntityRole?()); } set { this.OnPropertyChanging("sdkmessageprocessingstepid_sdkmessageprocessingstepimage"); this.SetRelatedEntities<SdkMessageProcessingStepImage>("sdkmessageprocessingstepid_sdkmessageprocessingstepimage", new EntityRole?(), value); this.OnPropertyChanged("sdkmessageprocessingstepid_sdkmessageprocessingstepimage"); } } [RelationshipSchemaName("createdby_sdkmessageprocessingstep")] [AttributeLogicalName("createdby")] public SystemUser createdby_sdkmessageprocessingstep { get { return this.GetRelatedEntity<SystemUser>("createdby_sdkmessageprocessingstep", new EntityRole?()); } } [RelationshipSchemaName("impersonatinguserid_sdkmessageprocessingstep")] [AttributeLogicalName("impersonatinguserid")] public SystemUser impersonatinguserid_sdkmessageprocessingstep { get { return this.GetRelatedEntity<SystemUser>("impersonatinguserid_sdkmessageprocessingstep", new EntityRole?()); } set { this.OnPropertyChanging("impersonatinguserid_sdkmessageprocessingstep"); this.SetRelatedEntity<SystemUser>("impersonatinguserid_sdkmessageprocessingstep", new EntityRole?(), value); this.OnPropertyChanged("impersonatinguserid_sdkmessageprocessingstep"); } } [RelationshipSchemaName("lk_sdkmessageprocessingstep_createdonbehalfby")] [AttributeLogicalName("createdonbehalfby")] public SystemUser lk_sdkmessageprocessingstep_createdonbehalfby { get { return this.GetRelatedEntity<SystemUser>("lk_sdkmessageprocessingstep_createdonbehalfby", new EntityRole?()); } } [AttributeLogicalName("modifiedonbehalfby")] [RelationshipSchemaName("lk_sdkmessageprocessingstep_modifiedonbehalfby")] public SystemUser lk_sdkmessageprocessingstep_modifiedonbehalfby { get { return this.GetRelatedEntity<SystemUser>("lk_sdkmessageprocessingstep_modifiedonbehalfby", new EntityRole?()); } } [RelationshipSchemaName("modifiedby_sdkmessageprocessingstep")] [AttributeLogicalName("modifiedby")] public SystemUser modifiedby_sdkmessageprocessingstep { get { return this.GetRelatedEntity<SystemUser>("modifiedby_sdkmessageprocessingstep", new EntityRole?()); } } [AttributeLogicalName("eventhandler")] [RelationshipSchemaName("plugintype_sdkmessageprocessingstep")] public PluginType plugintype_sdkmessageprocessingstep { get { return this.GetRelatedEntity<PluginType>("plugintype_sdkmessageprocessingstep", new EntityRole?()); } set { this.OnPropertyChanging("plugintype_sdkmessageprocessingstep"); this.SetRelatedEntity<PluginType>("plugintype_sdkmessageprocessingstep", new EntityRole?(), value); this.OnPropertyChanged("plugintype_sdkmessageprocessingstep"); } } [RelationshipSchemaName("plugintypeid_sdkmessageprocessingstep")] [AttributeLogicalName("plugintypeid")] public PluginType plugintypeid_sdkmessageprocessingstep { get { return this.GetRelatedEntity<PluginType>("plugintypeid_sdkmessageprocessingstep", new EntityRole?()); } set { this.OnPropertyChanging("plugintypeid_sdkmessageprocessingstep"); this.SetRelatedEntity<PluginType>("plugintypeid_sdkmessageprocessingstep", new EntityRole?(), value); this.OnPropertyChanged("plugintypeid_sdkmessageprocessingstep"); } } [RelationshipSchemaName("sdkmessagefilterid_sdkmessageprocessingstep")] [AttributeLogicalName("sdkmessagefilterid")] public SdkMessageFilter sdkmessagefilterid_sdkmessageprocessingstep { get { return this.GetRelatedEntity<SdkMessageFilter>("sdkmessagefilterid_sdkmessageprocessingstep", new EntityRole?()); } set { this.OnPropertyChanging("sdkmessagefilterid_sdkmessageprocessingstep"); this.SetRelatedEntity<SdkMessageFilter>("sdkmessagefilterid_sdkmessageprocessingstep", new EntityRole?(), value); this.OnPropertyChanged("sdkmessagefilterid_sdkmessageprocessingstep"); } } [RelationshipSchemaName("sdkmessageid_sdkmessageprocessingstep")] [AttributeLogicalName("sdkmessageid")] public SdkMessage sdkmessageid_sdkmessageprocessingstep { get { return this.GetRelatedEntity<SdkMessage>("sdkmessageid_sdkmessageprocessingstep", new EntityRole?()); } set { this.OnPropertyChanging("sdkmessageid_sdkmessageprocessingstep"); this.SetRelatedEntity<SdkMessage>("sdkmessageid_sdkmessageprocessingstep", new EntityRole?(), value); this.OnPropertyChanged("sdkmessageid_sdkmessageprocessingstep"); } } [AttributeLogicalName("sdkmessageprocessingstepsecureconfigid")] [RelationshipSchemaName("sdkmessageprocessingstepsecureconfigid_sdkmessageprocessingstep")] public SdkMessageProcessingStepSecureConfig sdkmessageprocessingstepsecureconfigid_sdkmessageprocessingstep { get { return this.GetRelatedEntity<SdkMessageProcessingStepSecureConfig>("sdkmessageprocessingstepsecureconfigid_sdkmessageprocessingstep", new EntityRole?()); } set { this.OnPropertyChanging("sdkmessageprocessingstepsecureconfigid_sdkmessageprocessingstep"); this.SetRelatedEntity<SdkMessageProcessingStepSecureConfig>("sdkmessageprocessingstepsecureconfigid_sdkmessageprocessingstep", new EntityRole?(), value); this.OnPropertyChanged("sdkmessageprocessingstepsecureconfigid_sdkmessageprocessingstep"); } } [AttributeLogicalName("eventhandler")] [RelationshipSchemaName("serviceendpoint_sdkmessageprocessingstep")] public ServiceEndpoint serviceendpoint_sdkmessageprocessingstep { get { return this.GetRelatedEntity<ServiceEndpoint>("serviceendpoint_sdkmessageprocessingstep", new EntityRole?()); } set { this.OnPropertyChanging("serviceendpoint_sdkmessageprocessingstep"); this.SetRelatedEntity<ServiceEndpoint>("serviceendpoint_sdkmessageprocessingstep", new EntityRole?(), value); this.OnPropertyChanged("serviceendpoint_sdkmessageprocessingstep"); } } public event PropertyChangedEventHandler PropertyChanged; public event PropertyChangingEventHandler PropertyChanging; public SdkMessageProcessingStep() : base("sdkmessageprocessingstep") { } 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. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsHttp { using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for HttpClientFailure. /// </summary> public static partial class HttpClientFailureExtensions { /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Head400(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Head400Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Head400Async(this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Head400WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Get400(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get400Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Get400Async(this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get400WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Put400(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Put400Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Put400Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Put400WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Patch400(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Patch400Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Patch400Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Patch400WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Post400(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Post400Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Post400Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Post400WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Delete400(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Delete400Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Delete400Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Delete400WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 401 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Head401(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Head401Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 401 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Head401Async(this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Head401WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 402 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Get402(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get402Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 402 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Get402Async(this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get402WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 403 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Get403(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get403Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 403 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Get403Async(this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get403WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 404 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Put404(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Put404Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 404 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Put404Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Put404WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 405 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Patch405(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Patch405Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 405 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Patch405Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Patch405WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 406 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Post406(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Post406Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 406 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Post406Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Post406WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 407 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Delete407(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Delete407Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 407 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Delete407Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Delete407WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 409 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Put409(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Put409Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 409 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Put409Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Put409WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 410 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Head410(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Head410Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 410 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Head410Async(this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Head410WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 411 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Get411(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get411Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 411 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Get411Async(this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get411WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 412 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Get412(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get412Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 412 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Get412Async(this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get412WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 413 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Put413(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Put413Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 413 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Put413Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Put413WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 414 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Patch414(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Patch414Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 414 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Patch414Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Patch414WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 415 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Post415(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Post415Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 415 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Post415Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Post415WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 416 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Get416(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get416Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 416 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Get416Async(this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get416WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 417 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Delete417(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Delete417Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 417 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Delete417Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Delete417WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 429 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Head429(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Head429Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 429 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Head429Async(this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Head429WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
/* * 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 elasticbeanstalk-2010-12-01.normal.json service model. */ using System; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.ElasticBeanstalk.Model; using Amazon.ElasticBeanstalk.Model.Internal.MarshallTransformations; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.ElasticBeanstalk { /// <summary> /// Implementation for accessing ElasticBeanstalk /// /// AWS Elastic Beanstalk /// <para> /// This is the AWS Elastic Beanstalk API Reference. This guide provides detailed information /// about AWS Elastic Beanstalk actions, data types, parameters, and errors. /// </para> /// /// <para> /// AWS Elastic Beanstalk is a tool that makes it easy for you to create, deploy, and /// manage scalable, fault-tolerant applications running on Amazon Web Services cloud /// resources. /// </para> /// /// <para> /// For more information about this product, go to the <a href="http://aws.amazon.com/elasticbeanstalk/">AWS /// Elastic Beanstalk</a> details page. The location of the latest AWS Elastic Beanstalk /// WSDL is <a href="http://elasticbeanstalk.s3.amazonaws.com/doc/2010-12-01/AWSElasticBeanstalk.wsdl">http://elasticbeanstalk.s3.amazonaws.com/doc/2010-12-01/AWSElasticBeanstalk.wsdl</a>. /// To install the Software Development Kits (SDKs), Integrated Development Environment /// (IDE) Toolkits, and command line tools that enable you to access the API, go to <a /// href="https://aws.amazon.com/tools/">Tools for Amazon Web Services</a>. /// </para> /// /// <para> /// <b>Endpoints</b> /// </para> /// /// <para> /// For a list of region-specific endpoints that AWS Elastic Beanstalk supports, go to /// <a href="http://docs.aws.amazon.com/general/latest/gr/rande.html#elasticbeanstalk_region">Regions /// and Endpoints</a> in the <i>Amazon Web Services Glossary</i>. /// </para> /// </summary> public partial class AmazonElasticBeanstalkClient : AmazonServiceClient, IAmazonElasticBeanstalk { #region Constructors /// <summary> /// Constructs AmazonElasticBeanstalkClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonElasticBeanstalkClient(AWSCredentials credentials) : this(credentials, new AmazonElasticBeanstalkConfig()) { } /// <summary> /// Constructs AmazonElasticBeanstalkClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonElasticBeanstalkClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonElasticBeanstalkConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonElasticBeanstalkClient with AWS Credentials and an /// AmazonElasticBeanstalkClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonElasticBeanstalkClient Configuration Object</param> public AmazonElasticBeanstalkClient(AWSCredentials credentials, AmazonElasticBeanstalkConfig clientConfig) : base(credentials, clientConfig) { } /// <summary> /// Constructs AmazonElasticBeanstalkClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> public AmazonElasticBeanstalkClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonElasticBeanstalkConfig()) { } /// <summary> /// Constructs AmazonElasticBeanstalkClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="region">The region to connect.</param> public AmazonElasticBeanstalkClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonElasticBeanstalkConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonElasticBeanstalkClient with AWS Access Key ID, AWS Secret Key and an /// AmazonElasticBeanstalkClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonElasticBeanstalkClient Configuration Object</param> public AmazonElasticBeanstalkClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonElasticBeanstalkConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig) { } /// <summary> /// Constructs AmazonElasticBeanstalkClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> public AmazonElasticBeanstalkClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonElasticBeanstalkConfig()) { } /// <summary> /// Constructs AmazonElasticBeanstalkClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="region">The region to connect.</param> public AmazonElasticBeanstalkClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonElasticBeanstalkConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonElasticBeanstalkClient with AWS Access Key ID, AWS Secret Key and an /// AmazonElasticBeanstalkClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="clientConfig">The AmazonElasticBeanstalkClient Configuration Object</param> public AmazonElasticBeanstalkClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonElasticBeanstalkConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig) { } #endregion #region Overrides /// <summary> /// Creates the signer for the service. /// </summary> protected override AbstractAWSSigner CreateSigner() { return new AWS4Signer(); } #endregion #region Dispose /// <summary> /// Disposes the service client. /// </summary> protected override void Dispose(bool disposing) { base.Dispose(disposing); } #endregion #region AbortEnvironmentUpdate internal AbortEnvironmentUpdateResponse AbortEnvironmentUpdate(AbortEnvironmentUpdateRequest request) { var marshaller = new AbortEnvironmentUpdateRequestMarshaller(); var unmarshaller = AbortEnvironmentUpdateResponseUnmarshaller.Instance; return Invoke<AbortEnvironmentUpdateRequest,AbortEnvironmentUpdateResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AbortEnvironmentUpdate operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AbortEnvironmentUpdate operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<AbortEnvironmentUpdateResponse> AbortEnvironmentUpdateAsync(AbortEnvironmentUpdateRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AbortEnvironmentUpdateRequestMarshaller(); var unmarshaller = AbortEnvironmentUpdateResponseUnmarshaller.Instance; return InvokeAsync<AbortEnvironmentUpdateRequest,AbortEnvironmentUpdateResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CheckDNSAvailability internal CheckDNSAvailabilityResponse CheckDNSAvailability(CheckDNSAvailabilityRequest request) { var marshaller = new CheckDNSAvailabilityRequestMarshaller(); var unmarshaller = CheckDNSAvailabilityResponseUnmarshaller.Instance; return Invoke<CheckDNSAvailabilityRequest,CheckDNSAvailabilityResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CheckDNSAvailability operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CheckDNSAvailability operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<CheckDNSAvailabilityResponse> CheckDNSAvailabilityAsync(CheckDNSAvailabilityRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CheckDNSAvailabilityRequestMarshaller(); var unmarshaller = CheckDNSAvailabilityResponseUnmarshaller.Instance; return InvokeAsync<CheckDNSAvailabilityRequest,CheckDNSAvailabilityResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateApplication internal CreateApplicationResponse CreateApplication(CreateApplicationRequest request) { var marshaller = new CreateApplicationRequestMarshaller(); var unmarshaller = CreateApplicationResponseUnmarshaller.Instance; return Invoke<CreateApplicationRequest,CreateApplicationResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateApplication operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateApplication operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<CreateApplicationResponse> CreateApplicationAsync(CreateApplicationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateApplicationRequestMarshaller(); var unmarshaller = CreateApplicationResponseUnmarshaller.Instance; return InvokeAsync<CreateApplicationRequest,CreateApplicationResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateApplicationVersion internal CreateApplicationVersionResponse CreateApplicationVersion(CreateApplicationVersionRequest request) { var marshaller = new CreateApplicationVersionRequestMarshaller(); var unmarshaller = CreateApplicationVersionResponseUnmarshaller.Instance; return Invoke<CreateApplicationVersionRequest,CreateApplicationVersionResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateApplicationVersion operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateApplicationVersion operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<CreateApplicationVersionResponse> CreateApplicationVersionAsync(CreateApplicationVersionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateApplicationVersionRequestMarshaller(); var unmarshaller = CreateApplicationVersionResponseUnmarshaller.Instance; return InvokeAsync<CreateApplicationVersionRequest,CreateApplicationVersionResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateConfigurationTemplate internal CreateConfigurationTemplateResponse CreateConfigurationTemplate(CreateConfigurationTemplateRequest request) { var marshaller = new CreateConfigurationTemplateRequestMarshaller(); var unmarshaller = CreateConfigurationTemplateResponseUnmarshaller.Instance; return Invoke<CreateConfigurationTemplateRequest,CreateConfigurationTemplateResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateConfigurationTemplate operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateConfigurationTemplate operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<CreateConfigurationTemplateResponse> CreateConfigurationTemplateAsync(CreateConfigurationTemplateRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateConfigurationTemplateRequestMarshaller(); var unmarshaller = CreateConfigurationTemplateResponseUnmarshaller.Instance; return InvokeAsync<CreateConfigurationTemplateRequest,CreateConfigurationTemplateResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateEnvironment internal CreateEnvironmentResponse CreateEnvironment(CreateEnvironmentRequest request) { var marshaller = new CreateEnvironmentRequestMarshaller(); var unmarshaller = CreateEnvironmentResponseUnmarshaller.Instance; return Invoke<CreateEnvironmentRequest,CreateEnvironmentResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateEnvironment operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateEnvironment operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<CreateEnvironmentResponse> CreateEnvironmentAsync(CreateEnvironmentRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateEnvironmentRequestMarshaller(); var unmarshaller = CreateEnvironmentResponseUnmarshaller.Instance; return InvokeAsync<CreateEnvironmentRequest,CreateEnvironmentResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateStorageLocation internal CreateStorageLocationResponse CreateStorageLocation() { return CreateStorageLocation(new CreateStorageLocationRequest()); } internal CreateStorageLocationResponse CreateStorageLocation(CreateStorageLocationRequest request) { var marshaller = new CreateStorageLocationRequestMarshaller(); var unmarshaller = CreateStorageLocationResponseUnmarshaller.Instance; return Invoke<CreateStorageLocationRequest,CreateStorageLocationResponse>(request, marshaller, unmarshaller); } /// <summary> /// Creates the Amazon S3 storage location for the account. /// /// /// <para> /// This location is used to store user log files. /// </para> /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateStorageLocation service method, as returned by ElasticBeanstalk.</returns> /// <exception cref="Amazon.ElasticBeanstalk.Model.InsufficientPrivilegesException"> /// Unable to perform the specified operation because the user does not have enough privileges /// for one of more downstream aws services /// </exception> /// <exception cref="Amazon.ElasticBeanstalk.Model.S3SubscriptionRequiredException"> /// The caller does not have a subscription to Amazon S3. /// </exception> /// <exception cref="Amazon.ElasticBeanstalk.Model.TooManyBucketsException"> /// The web service attempted to create a bucket in an Amazon S3 account that already /// has 100 buckets. /// </exception> public Task<CreateStorageLocationResponse> CreateStorageLocationAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { return CreateStorageLocationAsync(new CreateStorageLocationRequest(), cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the CreateStorageLocation operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateStorageLocation operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<CreateStorageLocationResponse> CreateStorageLocationAsync(CreateStorageLocationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateStorageLocationRequestMarshaller(); var unmarshaller = CreateStorageLocationResponseUnmarshaller.Instance; return InvokeAsync<CreateStorageLocationRequest,CreateStorageLocationResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteApplication internal DeleteApplicationResponse DeleteApplication(DeleteApplicationRequest request) { var marshaller = new DeleteApplicationRequestMarshaller(); var unmarshaller = DeleteApplicationResponseUnmarshaller.Instance; return Invoke<DeleteApplicationRequest,DeleteApplicationResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteApplication operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteApplication operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeleteApplicationResponse> DeleteApplicationAsync(DeleteApplicationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteApplicationRequestMarshaller(); var unmarshaller = DeleteApplicationResponseUnmarshaller.Instance; return InvokeAsync<DeleteApplicationRequest,DeleteApplicationResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteApplicationVersion internal DeleteApplicationVersionResponse DeleteApplicationVersion(DeleteApplicationVersionRequest request) { var marshaller = new DeleteApplicationVersionRequestMarshaller(); var unmarshaller = DeleteApplicationVersionResponseUnmarshaller.Instance; return Invoke<DeleteApplicationVersionRequest,DeleteApplicationVersionResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteApplicationVersion operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteApplicationVersion operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeleteApplicationVersionResponse> DeleteApplicationVersionAsync(DeleteApplicationVersionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteApplicationVersionRequestMarshaller(); var unmarshaller = DeleteApplicationVersionResponseUnmarshaller.Instance; return InvokeAsync<DeleteApplicationVersionRequest,DeleteApplicationVersionResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteConfigurationTemplate internal DeleteConfigurationTemplateResponse DeleteConfigurationTemplate(DeleteConfigurationTemplateRequest request) { var marshaller = new DeleteConfigurationTemplateRequestMarshaller(); var unmarshaller = DeleteConfigurationTemplateResponseUnmarshaller.Instance; return Invoke<DeleteConfigurationTemplateRequest,DeleteConfigurationTemplateResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteConfigurationTemplate operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteConfigurationTemplate operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeleteConfigurationTemplateResponse> DeleteConfigurationTemplateAsync(DeleteConfigurationTemplateRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteConfigurationTemplateRequestMarshaller(); var unmarshaller = DeleteConfigurationTemplateResponseUnmarshaller.Instance; return InvokeAsync<DeleteConfigurationTemplateRequest,DeleteConfigurationTemplateResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteEnvironmentConfiguration internal DeleteEnvironmentConfigurationResponse DeleteEnvironmentConfiguration(DeleteEnvironmentConfigurationRequest request) { var marshaller = new DeleteEnvironmentConfigurationRequestMarshaller(); var unmarshaller = DeleteEnvironmentConfigurationResponseUnmarshaller.Instance; return Invoke<DeleteEnvironmentConfigurationRequest,DeleteEnvironmentConfigurationResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteEnvironmentConfiguration operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteEnvironmentConfiguration operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeleteEnvironmentConfigurationResponse> DeleteEnvironmentConfigurationAsync(DeleteEnvironmentConfigurationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteEnvironmentConfigurationRequestMarshaller(); var unmarshaller = DeleteEnvironmentConfigurationResponseUnmarshaller.Instance; return InvokeAsync<DeleteEnvironmentConfigurationRequest,DeleteEnvironmentConfigurationResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeApplications internal DescribeApplicationsResponse DescribeApplications() { return DescribeApplications(new DescribeApplicationsRequest()); } internal DescribeApplicationsResponse DescribeApplications(DescribeApplicationsRequest request) { var marshaller = new DescribeApplicationsRequestMarshaller(); var unmarshaller = DescribeApplicationsResponseUnmarshaller.Instance; return Invoke<DescribeApplicationsRequest,DescribeApplicationsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Returns the descriptions of existing applications. /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeApplications service method, as returned by ElasticBeanstalk.</returns> public Task<DescribeApplicationsResponse> DescribeApplicationsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { return DescribeApplicationsAsync(new DescribeApplicationsRequest(), cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the DescribeApplications operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeApplications operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeApplicationsResponse> DescribeApplicationsAsync(DescribeApplicationsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeApplicationsRequestMarshaller(); var unmarshaller = DescribeApplicationsResponseUnmarshaller.Instance; return InvokeAsync<DescribeApplicationsRequest,DescribeApplicationsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeApplicationVersions internal DescribeApplicationVersionsResponse DescribeApplicationVersions() { return DescribeApplicationVersions(new DescribeApplicationVersionsRequest()); } internal DescribeApplicationVersionsResponse DescribeApplicationVersions(DescribeApplicationVersionsRequest request) { var marshaller = new DescribeApplicationVersionsRequestMarshaller(); var unmarshaller = DescribeApplicationVersionsResponseUnmarshaller.Instance; return Invoke<DescribeApplicationVersionsRequest,DescribeApplicationVersionsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Returns descriptions for existing application versions. /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeApplicationVersions service method, as returned by ElasticBeanstalk.</returns> public Task<DescribeApplicationVersionsResponse> DescribeApplicationVersionsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { return DescribeApplicationVersionsAsync(new DescribeApplicationVersionsRequest(), cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the DescribeApplicationVersions operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeApplicationVersions operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeApplicationVersionsResponse> DescribeApplicationVersionsAsync(DescribeApplicationVersionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeApplicationVersionsRequestMarshaller(); var unmarshaller = DescribeApplicationVersionsResponseUnmarshaller.Instance; return InvokeAsync<DescribeApplicationVersionsRequest,DescribeApplicationVersionsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeConfigurationOptions internal DescribeConfigurationOptionsResponse DescribeConfigurationOptions() { return DescribeConfigurationOptions(new DescribeConfigurationOptionsRequest()); } internal DescribeConfigurationOptionsResponse DescribeConfigurationOptions(DescribeConfigurationOptionsRequest request) { var marshaller = new DescribeConfigurationOptionsRequestMarshaller(); var unmarshaller = DescribeConfigurationOptionsResponseUnmarshaller.Instance; return Invoke<DescribeConfigurationOptionsRequest,DescribeConfigurationOptionsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Describes the configuration options that are used in a particular configuration template /// or environment, or that a specified solution stack defines. The description includes /// the values the options, their default values, and an indication of the required action /// on a running environment if an option value is changed. /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeConfigurationOptions service method, as returned by ElasticBeanstalk.</returns> public Task<DescribeConfigurationOptionsResponse> DescribeConfigurationOptionsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { return DescribeConfigurationOptionsAsync(new DescribeConfigurationOptionsRequest(), cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the DescribeConfigurationOptions operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeConfigurationOptions operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeConfigurationOptionsResponse> DescribeConfigurationOptionsAsync(DescribeConfigurationOptionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeConfigurationOptionsRequestMarshaller(); var unmarshaller = DescribeConfigurationOptionsResponseUnmarshaller.Instance; return InvokeAsync<DescribeConfigurationOptionsRequest,DescribeConfigurationOptionsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeConfigurationSettings internal DescribeConfigurationSettingsResponse DescribeConfigurationSettings(DescribeConfigurationSettingsRequest request) { var marshaller = new DescribeConfigurationSettingsRequestMarshaller(); var unmarshaller = DescribeConfigurationSettingsResponseUnmarshaller.Instance; return Invoke<DescribeConfigurationSettingsRequest,DescribeConfigurationSettingsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeConfigurationSettings operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeConfigurationSettings operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeConfigurationSettingsResponse> DescribeConfigurationSettingsAsync(DescribeConfigurationSettingsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeConfigurationSettingsRequestMarshaller(); var unmarshaller = DescribeConfigurationSettingsResponseUnmarshaller.Instance; return InvokeAsync<DescribeConfigurationSettingsRequest,DescribeConfigurationSettingsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeEnvironmentHealth internal DescribeEnvironmentHealthResponse DescribeEnvironmentHealth(DescribeEnvironmentHealthRequest request) { var marshaller = new DescribeEnvironmentHealthRequestMarshaller(); var unmarshaller = DescribeEnvironmentHealthResponseUnmarshaller.Instance; return Invoke<DescribeEnvironmentHealthRequest,DescribeEnvironmentHealthResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeEnvironmentHealth operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeEnvironmentHealth operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeEnvironmentHealthResponse> DescribeEnvironmentHealthAsync(DescribeEnvironmentHealthRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeEnvironmentHealthRequestMarshaller(); var unmarshaller = DescribeEnvironmentHealthResponseUnmarshaller.Instance; return InvokeAsync<DescribeEnvironmentHealthRequest,DescribeEnvironmentHealthResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeEnvironmentResources internal DescribeEnvironmentResourcesResponse DescribeEnvironmentResources(DescribeEnvironmentResourcesRequest request) { var marshaller = new DescribeEnvironmentResourcesRequestMarshaller(); var unmarshaller = DescribeEnvironmentResourcesResponseUnmarshaller.Instance; return Invoke<DescribeEnvironmentResourcesRequest,DescribeEnvironmentResourcesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeEnvironmentResources operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeEnvironmentResources operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeEnvironmentResourcesResponse> DescribeEnvironmentResourcesAsync(DescribeEnvironmentResourcesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeEnvironmentResourcesRequestMarshaller(); var unmarshaller = DescribeEnvironmentResourcesResponseUnmarshaller.Instance; return InvokeAsync<DescribeEnvironmentResourcesRequest,DescribeEnvironmentResourcesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeEnvironments internal DescribeEnvironmentsResponse DescribeEnvironments() { return DescribeEnvironments(new DescribeEnvironmentsRequest()); } internal DescribeEnvironmentsResponse DescribeEnvironments(DescribeEnvironmentsRequest request) { var marshaller = new DescribeEnvironmentsRequestMarshaller(); var unmarshaller = DescribeEnvironmentsResponseUnmarshaller.Instance; return Invoke<DescribeEnvironmentsRequest,DescribeEnvironmentsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Returns descriptions for existing environments. /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeEnvironments service method, as returned by ElasticBeanstalk.</returns> public Task<DescribeEnvironmentsResponse> DescribeEnvironmentsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { return DescribeEnvironmentsAsync(new DescribeEnvironmentsRequest(), cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the DescribeEnvironments operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeEnvironments operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeEnvironmentsResponse> DescribeEnvironmentsAsync(DescribeEnvironmentsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeEnvironmentsRequestMarshaller(); var unmarshaller = DescribeEnvironmentsResponseUnmarshaller.Instance; return InvokeAsync<DescribeEnvironmentsRequest,DescribeEnvironmentsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeEvents internal DescribeEventsResponse DescribeEvents() { return DescribeEvents(new DescribeEventsRequest()); } internal DescribeEventsResponse DescribeEvents(DescribeEventsRequest request) { var marshaller = new DescribeEventsRequestMarshaller(); var unmarshaller = DescribeEventsResponseUnmarshaller.Instance; return Invoke<DescribeEventsRequest,DescribeEventsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Returns list of event descriptions matching criteria up to the last 6 weeks. /// /// <note> This action returns the most recent 1,000 events from the specified <code>NextToken</code>. /// </note> /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeEvents service method, as returned by ElasticBeanstalk.</returns> public Task<DescribeEventsResponse> DescribeEventsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { return DescribeEventsAsync(new DescribeEventsRequest(), cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the DescribeEvents operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeEvents operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeEventsResponse> DescribeEventsAsync(DescribeEventsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeEventsRequestMarshaller(); var unmarshaller = DescribeEventsResponseUnmarshaller.Instance; return InvokeAsync<DescribeEventsRequest,DescribeEventsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeInstancesHealth internal DescribeInstancesHealthResponse DescribeInstancesHealth(DescribeInstancesHealthRequest request) { var marshaller = new DescribeInstancesHealthRequestMarshaller(); var unmarshaller = DescribeInstancesHealthResponseUnmarshaller.Instance; return Invoke<DescribeInstancesHealthRequest,DescribeInstancesHealthResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeInstancesHealth operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeInstancesHealth operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeInstancesHealthResponse> DescribeInstancesHealthAsync(DescribeInstancesHealthRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeInstancesHealthRequestMarshaller(); var unmarshaller = DescribeInstancesHealthResponseUnmarshaller.Instance; return InvokeAsync<DescribeInstancesHealthRequest,DescribeInstancesHealthResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListAvailableSolutionStacks internal ListAvailableSolutionStacksResponse ListAvailableSolutionStacks() { return ListAvailableSolutionStacks(new ListAvailableSolutionStacksRequest()); } internal ListAvailableSolutionStacksResponse ListAvailableSolutionStacks(ListAvailableSolutionStacksRequest request) { var marshaller = new ListAvailableSolutionStacksRequestMarshaller(); var unmarshaller = ListAvailableSolutionStacksResponseUnmarshaller.Instance; return Invoke<ListAvailableSolutionStacksRequest,ListAvailableSolutionStacksResponse>(request, marshaller, unmarshaller); } /// <summary> /// Returns a list of the available solution stack names. /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListAvailableSolutionStacks service method, as returned by ElasticBeanstalk.</returns> public Task<ListAvailableSolutionStacksResponse> ListAvailableSolutionStacksAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { return ListAvailableSolutionStacksAsync(new ListAvailableSolutionStacksRequest(), cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the ListAvailableSolutionStacks operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListAvailableSolutionStacks operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ListAvailableSolutionStacksResponse> ListAvailableSolutionStacksAsync(ListAvailableSolutionStacksRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListAvailableSolutionStacksRequestMarshaller(); var unmarshaller = ListAvailableSolutionStacksResponseUnmarshaller.Instance; return InvokeAsync<ListAvailableSolutionStacksRequest,ListAvailableSolutionStacksResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region RebuildEnvironment internal RebuildEnvironmentResponse RebuildEnvironment(RebuildEnvironmentRequest request) { var marshaller = new RebuildEnvironmentRequestMarshaller(); var unmarshaller = RebuildEnvironmentResponseUnmarshaller.Instance; return Invoke<RebuildEnvironmentRequest,RebuildEnvironmentResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the RebuildEnvironment operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RebuildEnvironment operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<RebuildEnvironmentResponse> RebuildEnvironmentAsync(RebuildEnvironmentRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new RebuildEnvironmentRequestMarshaller(); var unmarshaller = RebuildEnvironmentResponseUnmarshaller.Instance; return InvokeAsync<RebuildEnvironmentRequest,RebuildEnvironmentResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region RequestEnvironmentInfo internal RequestEnvironmentInfoResponse RequestEnvironmentInfo(RequestEnvironmentInfoRequest request) { var marshaller = new RequestEnvironmentInfoRequestMarshaller(); var unmarshaller = RequestEnvironmentInfoResponseUnmarshaller.Instance; return Invoke<RequestEnvironmentInfoRequest,RequestEnvironmentInfoResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the RequestEnvironmentInfo operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RequestEnvironmentInfo operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<RequestEnvironmentInfoResponse> RequestEnvironmentInfoAsync(RequestEnvironmentInfoRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new RequestEnvironmentInfoRequestMarshaller(); var unmarshaller = RequestEnvironmentInfoResponseUnmarshaller.Instance; return InvokeAsync<RequestEnvironmentInfoRequest,RequestEnvironmentInfoResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region RestartAppServer internal RestartAppServerResponse RestartAppServer(RestartAppServerRequest request) { var marshaller = new RestartAppServerRequestMarshaller(); var unmarshaller = RestartAppServerResponseUnmarshaller.Instance; return Invoke<RestartAppServerRequest,RestartAppServerResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the RestartAppServer operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RestartAppServer operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<RestartAppServerResponse> RestartAppServerAsync(RestartAppServerRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new RestartAppServerRequestMarshaller(); var unmarshaller = RestartAppServerResponseUnmarshaller.Instance; return InvokeAsync<RestartAppServerRequest,RestartAppServerResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region RetrieveEnvironmentInfo internal RetrieveEnvironmentInfoResponse RetrieveEnvironmentInfo(RetrieveEnvironmentInfoRequest request) { var marshaller = new RetrieveEnvironmentInfoRequestMarshaller(); var unmarshaller = RetrieveEnvironmentInfoResponseUnmarshaller.Instance; return Invoke<RetrieveEnvironmentInfoRequest,RetrieveEnvironmentInfoResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the RetrieveEnvironmentInfo operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RetrieveEnvironmentInfo operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<RetrieveEnvironmentInfoResponse> RetrieveEnvironmentInfoAsync(RetrieveEnvironmentInfoRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new RetrieveEnvironmentInfoRequestMarshaller(); var unmarshaller = RetrieveEnvironmentInfoResponseUnmarshaller.Instance; return InvokeAsync<RetrieveEnvironmentInfoRequest,RetrieveEnvironmentInfoResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region SwapEnvironmentCNAMEs internal SwapEnvironmentCNAMEsResponse SwapEnvironmentCNAMEs(SwapEnvironmentCNAMEsRequest request) { var marshaller = new SwapEnvironmentCNAMEsRequestMarshaller(); var unmarshaller = SwapEnvironmentCNAMEsResponseUnmarshaller.Instance; return Invoke<SwapEnvironmentCNAMEsRequest,SwapEnvironmentCNAMEsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the SwapEnvironmentCNAMEs operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SwapEnvironmentCNAMEs operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<SwapEnvironmentCNAMEsResponse> SwapEnvironmentCNAMEsAsync(SwapEnvironmentCNAMEsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new SwapEnvironmentCNAMEsRequestMarshaller(); var unmarshaller = SwapEnvironmentCNAMEsResponseUnmarshaller.Instance; return InvokeAsync<SwapEnvironmentCNAMEsRequest,SwapEnvironmentCNAMEsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region TerminateEnvironment internal TerminateEnvironmentResponse TerminateEnvironment(TerminateEnvironmentRequest request) { var marshaller = new TerminateEnvironmentRequestMarshaller(); var unmarshaller = TerminateEnvironmentResponseUnmarshaller.Instance; return Invoke<TerminateEnvironmentRequest,TerminateEnvironmentResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the TerminateEnvironment operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the TerminateEnvironment operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<TerminateEnvironmentResponse> TerminateEnvironmentAsync(TerminateEnvironmentRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new TerminateEnvironmentRequestMarshaller(); var unmarshaller = TerminateEnvironmentResponseUnmarshaller.Instance; return InvokeAsync<TerminateEnvironmentRequest,TerminateEnvironmentResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdateApplication internal UpdateApplicationResponse UpdateApplication(UpdateApplicationRequest request) { var marshaller = new UpdateApplicationRequestMarshaller(); var unmarshaller = UpdateApplicationResponseUnmarshaller.Instance; return Invoke<UpdateApplicationRequest,UpdateApplicationResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdateApplication operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateApplication operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<UpdateApplicationResponse> UpdateApplicationAsync(UpdateApplicationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new UpdateApplicationRequestMarshaller(); var unmarshaller = UpdateApplicationResponseUnmarshaller.Instance; return InvokeAsync<UpdateApplicationRequest,UpdateApplicationResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdateApplicationVersion internal UpdateApplicationVersionResponse UpdateApplicationVersion(UpdateApplicationVersionRequest request) { var marshaller = new UpdateApplicationVersionRequestMarshaller(); var unmarshaller = UpdateApplicationVersionResponseUnmarshaller.Instance; return Invoke<UpdateApplicationVersionRequest,UpdateApplicationVersionResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdateApplicationVersion operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateApplicationVersion operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<UpdateApplicationVersionResponse> UpdateApplicationVersionAsync(UpdateApplicationVersionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new UpdateApplicationVersionRequestMarshaller(); var unmarshaller = UpdateApplicationVersionResponseUnmarshaller.Instance; return InvokeAsync<UpdateApplicationVersionRequest,UpdateApplicationVersionResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdateConfigurationTemplate internal UpdateConfigurationTemplateResponse UpdateConfigurationTemplate(UpdateConfigurationTemplateRequest request) { var marshaller = new UpdateConfigurationTemplateRequestMarshaller(); var unmarshaller = UpdateConfigurationTemplateResponseUnmarshaller.Instance; return Invoke<UpdateConfigurationTemplateRequest,UpdateConfigurationTemplateResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdateConfigurationTemplate operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateConfigurationTemplate operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<UpdateConfigurationTemplateResponse> UpdateConfigurationTemplateAsync(UpdateConfigurationTemplateRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new UpdateConfigurationTemplateRequestMarshaller(); var unmarshaller = UpdateConfigurationTemplateResponseUnmarshaller.Instance; return InvokeAsync<UpdateConfigurationTemplateRequest,UpdateConfigurationTemplateResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdateEnvironment internal UpdateEnvironmentResponse UpdateEnvironment(UpdateEnvironmentRequest request) { var marshaller = new UpdateEnvironmentRequestMarshaller(); var unmarshaller = UpdateEnvironmentResponseUnmarshaller.Instance; return Invoke<UpdateEnvironmentRequest,UpdateEnvironmentResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdateEnvironment operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateEnvironment operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<UpdateEnvironmentResponse> UpdateEnvironmentAsync(UpdateEnvironmentRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new UpdateEnvironmentRequestMarshaller(); var unmarshaller = UpdateEnvironmentResponseUnmarshaller.Instance; return InvokeAsync<UpdateEnvironmentRequest,UpdateEnvironmentResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ValidateConfigurationSettings internal ValidateConfigurationSettingsResponse ValidateConfigurationSettings(ValidateConfigurationSettingsRequest request) { var marshaller = new ValidateConfigurationSettingsRequestMarshaller(); var unmarshaller = ValidateConfigurationSettingsResponseUnmarshaller.Instance; return Invoke<ValidateConfigurationSettingsRequest,ValidateConfigurationSettingsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ValidateConfigurationSettings operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ValidateConfigurationSettings operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ValidateConfigurationSettingsResponse> ValidateConfigurationSettingsAsync(ValidateConfigurationSettingsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ValidateConfigurationSettingsRequestMarshaller(); var unmarshaller = ValidateConfigurationSettingsResponseUnmarshaller.Instance; return InvokeAsync<ValidateConfigurationSettingsRequest,ValidateConfigurationSettingsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion } }
// Copyright 2005, 2006 - Morten Nielsen (www.iter.dk) // Copyright 2007 - Paul den Dulk (Geodan) - Created TiledWmsLayer from WmsLayer // // This file is part of SharpMap. // SharpMap is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // SharpMap is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public License // along with SharpMap; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Net; using System.Text; using NetTopologySuite.Geometries; using SharpMap.Rendering.Exceptions; using SharpMap.Utilities; using SharpMap.Web.Wms; using SharpMap.Web.Wms.Tiling; using Common.Logging; namespace SharpMap.Layers { /// <summary> /// Client layer for WMS-C service /// </summary> /// <remarks> /// Initialize the TiledWmsLayer with the url to the capabilities document /// and it will set the remaining BoundingBox property and proper requests that changes between the requests. /// See the example below. /// </remarks> /// <example> /// The following example creates a map with a TiledWmsLayer the metacarta tile server /// <code lang="C#"> /// map = new SharpMap.Map(mapImage1.Size); /// string url = "http://labs.metacarta.com/wms-c/tilecache.py?version=1.1.1&amp;request=GetCapabilities&amp;service=wms-c"; /// TiledWmsLayer tiledWmsLayer = new TiledWmsLayer("Metacarta", url); /// tiledWmsLayer.TileSetsActive.Add(tiledWmsLayer.TileSets["satellite"].Name); /// map.Layers.Add(tiledWmsLayer); /// map.ZoomToBox(new NetTopologySuite.Geometries.Envelope(-180.0, 180.0, -90.0, 90.0)); /// </code> /// </example> [Obsolete("use TileLayer instead") ] public class TiledWmsLayer : Layer, ILayer { ILog logger = LogManager.GetLogger(typeof(TiledWmsLayer)); #region Fields private Boolean _ContinueOnError; private ICredentials _Credentials; private Dictionary<string, string> _CustomParameters = new Dictionary<string, string>(); private ImageAttributes _ImageAttributes = new ImageAttributes(); private WebProxy _Proxy; private SortedList<string, TileSet> _TileSets = new SortedList<string, TileSet>(); private Collection<string> _TileSetsActive = new Collection<string>(); private int _TimeOut; private Client _WmsClient; #endregion #region Constructors /// <summary> /// Initializes a new layer, and downloads and parses the service description /// </summary> /// <remarks>In and ASP.NET application the service description is automatically cached for 24 hours when not specified</remarks> /// <param name="layername">Layername</param> /// <param name="url">Url of WMS server's Capabilities</param> public TiledWmsLayer(string layername, string url) : this(layername, url, new TimeSpan(24, 0, 0)) { _ImageAttributes.SetWrapMode(WrapMode.TileFlipXY); } /// <summary> /// Initializes a new layer, and downloads and parses the service description /// </summary> /// <param name="layername">Layername</param> /// <param name="url">Url of WMS server's Capabilities</param> /// <param name="cachetime">Time for caching Service Description (ASP.NET only)</param> public TiledWmsLayer(string layername, string url, TimeSpan cachetime) : this(layername, url, cachetime, null) { } /// <summary> /// Initializes a new layer, and downloads and parses the service description /// </summary> /// <remarks>In and ASP.NET application the service description is automatically cached for 24 hours when not specified</remarks> /// <param name="layername">Layername</param> /// <param name="url">Url of WMS server's Capabilities</param> /// <param name="proxy">Proxy</param> public TiledWmsLayer(string layername, string url, WebProxy proxy) : this(layername, url, new TimeSpan(24, 0, 0), proxy) { } /// <summary> /// Initializes a new layer, and downloads and parses the service description /// </summary> /// <param name="layername">Layername</param> /// <param name="url">Url of WMS server's Capabilities</param> /// <param name="cachetime">Time for caching Service Description (ASP.NET only)</param> /// <param name="proxy">Proxy</param> public TiledWmsLayer(string layername, string url, TimeSpan cachetime, WebProxy proxy) { _Proxy = proxy; _TimeOut = 10000; LayerName = layername; _ContinueOnError = true; if (!Web.HttpCacheUtility.TryGetValue("SharpMap_WmsClient_" + url, out _WmsClient)) { if (logger.IsDebugEnabled) logger.Debug("Creating new client for url " + url); _WmsClient = new Client(url, _Proxy, _Credentials); if (!Web.HttpCacheUtility.TryAddValue("SharpMap_WmsClient_" + url, _WmsClient)) { if (logger.IsDebugEnabled) logger.Debug("Adding client to Cache for url " + url + " failed"); } } _TileSets = TileSet.ParseVendorSpecificCapabilitiesNode(_WmsClient.VendorSpecificCapabilities); } #endregion #region Properties /// <summary> /// Provides the base authentication interface for retrieving credentials for Web client authentication. /// </summary> public ICredentials Credentials { get { return _Credentials; } set { _Credentials = value; } } /// <summary> /// Gets or sets the proxy used for requesting a webresource /// </summary> public WebProxy Proxy { get { return _Proxy; } set { _Proxy = value; } } /// <summary> /// Timeout of webrequest in milliseconds. Defaults to 10 seconds /// </summary> public int TimeOut { get { return _TimeOut; } set { _TimeOut = value; } } /// <summary> /// Gets a list of tile sets that are currently active /// </summary> public Collection<string> TileSetsActive { get { return _TileSetsActive; } } /// <summary> /// Gets the collection of TileSets that will be rendered /// </summary> public SortedList<string, TileSet> TileSets { get { return _TileSets; } } /// <summary> /// Specifies whether to throw an exception if the Wms request failed, or to just skip rendering the layer. /// </summary> public Boolean ContinueOnError { get { return _ContinueOnError; } set { _ContinueOnError = value; } } /// <summary> /// Gets the list of available formats /// </summary> public Collection<string> OutputFormats { get { return _WmsClient.GetMapOutputFormats; } } #endregion // <summary> #region ILayer Members /// <summary> /// Renders the layer /// </summary> /// <param name="g">Graphics object reference</param> /// <param name="map">Map which is rendered</param> public override void Render(Graphics g, MapViewport map) { Bitmap bitmap = null; try { foreach (string key in _TileSetsActive) { TileSet tileSet = _TileSets[key]; tileSet.Verify(); List<Envelope> tileExtents = TileExtents.GetTileExtents(tileSet, map.Envelope, map.PixelSize); if (logger.IsDebugEnabled) logger.DebugFormat("TileCount: {0}", tileExtents.Count); //TODO: Retrieve several tiles at the same time asynchronously to improve performance. PDD. foreach (Envelope tileExtent in tileExtents) { if (bitmap != null) { bitmap.Dispose(); } if ((tileSet.TileCache != null) && (tileSet.TileCache.ContainsTile(tileExtent))) { bitmap = tileSet.TileCache.GetTile(tileExtent); } else { bitmap = WmsGetMap(tileExtent, tileSet); if ((tileSet.TileCache != null) && (bitmap != null)) { tileSet.TileCache.AddTile(tileExtent, bitmap); } } if (bitmap != null) { PointF destMin = map.WorldToImage(tileExtent.Min()); PointF destMax = map.WorldToImage(tileExtent.Max()); double minX = (int) Math.Round(destMin.X); double minY = (int) Math.Round(destMax.Y); double maxX = (int) Math.Round(destMax.X); double maxY = (int) Math.Round(destMin.Y); g.DrawImage(bitmap, new Rectangle((int) minX, (int) minY, (int) (maxX - minX), (int) (maxY - minY)), 0, 0, tileSet.Width, tileSet.Height, GraphicsUnit.Pixel, _ImageAttributes); } } } } finally { if (bitmap != null) { bitmap.Dispose(); } } } /// <summary> /// Returns the extent of the layer /// </summary> /// <returns>Bounding box corresponding to the extent of the features in the layer</returns> public override Envelope Envelope { get { return _WmsClient.Layer.LatLonBoundingBox; //TODO: no box is allowed in capabilities so check for it } } #endregion #region Methods /// <summary> /// Appends a custom parameter name-value pair to the WMS request /// </summary> /// <param name="name">Name of custom parameter</param> /// <param name="value">Value of custom parameter</param> public void AddCustomParameter(string name, string value) { _CustomParameters.Add(name, value); } /// <summary> /// Removes a custom parameter name-value pair from the WMS request /// </summary> /// <param name="name">Name of the custom parameter to remove</param> public void RemoveCustomParameter(string name) { _CustomParameters.Remove(name); } /// <summary> /// Removes all custom parameter from the WMS request /// </summary> public void RemoveAllCustomParameters() { _CustomParameters.Clear(); } private string GetRequestUrl(Envelope box, TileSet tileSet) { Client.WmsOnlineResource resource = GetPreferredMethod(); StringBuilder strReq = new StringBuilder(resource.OnlineResource); if (!resource.OnlineResource.Contains("?")) strReq.Append("?"); if (!strReq.ToString().EndsWith("&") && !strReq.ToString().EndsWith("?")) strReq.Append("&"); strReq.AppendFormat(Map.NumberFormatEnUs, "&REQUEST=GetMap&BBOX={0},{1},{2},{3}", box.MinX, box.MinY, box.MaxX, box.MaxY); strReq.AppendFormat("&WIDTH={0}&Height={1}", tileSet.Width, tileSet.Height); strReq.Append("&LAYERS="); // LAYERS is set in caps because the current version of tilecache.py does not accept mixed case (a little bug) if (tileSet.Layers != null && tileSet.Layers.Count > 0) { foreach (string layer in tileSet.Layers) strReq.AppendFormat("{0},", layer); strReq.Remove(strReq.Length - 1, 1); } strReq.AppendFormat("&FORMAT={0}", tileSet.Format); if (_WmsClient.WmsVersion == "1.3.0") strReq.AppendFormat("&CRS={0}", tileSet.Srs); else strReq.AppendFormat("&SRS={0}", tileSet.Srs); strReq.AppendFormat("&VERSION={0}", _WmsClient.WmsVersion); if (tileSet.Styles != null && tileSet.Styles.Count > 0) { strReq.Append("&STYLES="); foreach (string style in tileSet.Styles) strReq.AppendFormat("{0},", style); strReq.Remove(strReq.Length - 1, 1); } if (_CustomParameters != null && _CustomParameters.Count > 0) { foreach (string name in _CustomParameters.Keys) { string value = _CustomParameters[name]; strReq.AppendFormat("&{0}={1}", name, value); } } return strReq.ToString(); } private Bitmap WmsGetMap(Envelope extent, TileSet tileSet) { Stream responseStream = null; Bitmap bitmap = null; Client.WmsOnlineResource resource = GetPreferredMethod(); string requestUrl = GetRequestUrl(extent, tileSet); Uri myUri = new Uri(requestUrl); WebRequest webRequest = WebRequest.Create(myUri); webRequest.Method = resource.Type; webRequest.Timeout = TimeOut; if (Credentials != null) webRequest.Credentials = Credentials; else webRequest.Credentials = CredentialCache.DefaultCredentials; if (Proxy != null) webRequest.Proxy = Proxy; HttpWebResponse webResponse = null; try { webResponse = (HttpWebResponse) webRequest.GetResponse(); if (webResponse.ContentType.StartsWith("image")) { responseStream = webResponse.GetResponseStream(); bitmap = (Bitmap) Bitmap.FromStream(responseStream); return (Bitmap) bitmap; } else { //if the result was not an image retrieve content anyway for debugging. responseStream = webResponse.GetResponseStream(); StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8); StringWriter stringWriter = new StringWriter(); stringWriter.Write(readStream.ReadToEnd()); string message = "Failed to retrieve image from the WMS in layer '" + LayerName + "'. Was expecting image but received this: " + stringWriter.ToString(); HandleGetMapException(message, null); ; return null; } } catch (WebException webEx) { string message = "There was a problem connecting to the WMS server when rendering layer '" + LayerName + "'"; HandleGetMapException(message, webEx); } catch (Exception ex) { string message = "There was a problem while retrieving the image from the WMS in layer '" + LayerName + "'"; HandleGetMapException(message, ex); } finally { if (webResponse != null) { webResponse.Close(); } if (responseStream != null) { responseStream.Close(); responseStream.Dispose(); } } return bitmap; } private void HandleGetMapException(string message, Exception ex) { if (ContinueOnError) { Trace.Write(message); } else { throw (new RenderException(message, ex)); } } private Client.WmsOnlineResource GetPreferredMethod() { //We prefer get. Seek for supported 'get' method for (int i = 0; i < _WmsClient.GetMapRequests.Length; i++) if (_WmsClient.GetMapRequests[i].Type.ToLower() == "get") return _WmsClient.GetMapRequests[i]; //Next we prefer the 'post' method for (int i = 0; i < _WmsClient.GetMapRequests.Length; i++) if (_WmsClient.GetMapRequests[i].Type.ToLower() == "post") return _WmsClient.GetMapRequests[i]; return _WmsClient.GetMapRequests[0]; } #endregion private static Rectangle RoundRectangle(RectangleF dest) { double minX = Math.Round(dest.X); double minY = Math.Round(dest.Y); double maxX = Math.Round(dest.Right); double maxY = Math.Round(dest.Bottom); return new Rectangle((int) minX, (int) minY, (int) (maxX - minX), (int) (maxY - minY)); } } }
using System.Collections.Generic; namespace Pathfinding.Voxels { public partial class Voxelize { public ushort[] ExpandRegions (int maxIterations, uint level, ushort[] srcReg, ushort[] srcDist, ushort[] dstReg, ushort[] dstDist, List<int> stack) { AstarProfiler.StartProfile("---Expand 1"); int w = voxelArea.width; int d = voxelArea.depth; int wd = w*d; #if ASTAR_RECAST_BFS && FALSE List<int> st1 = new List<int>(); List<int> st2 = new List<int>(); for (int z = 0, pz = 0; z < wd; z += w, pz++) { for (int x = 0; x < voxelArea.width; x++) { CompactVoxelCell c = voxelArea.compactCells[z+x]; for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; i++) { if (voxelArea.dist[i] >= level && srcReg[i] == 0 && voxelArea.areaTypes[i] != UnwalkableArea) { st2.Add(x); st2.Add(z); st2.Add(i); //Debug.DrawRay (ConvertPosition(x,z,i),Vector3.up*0.5F,Color.cyan); } } } } throw new System.NotImplementedException(); return null; #else // Find cells revealed by the raised level. stack.Clear(); for (int z = 0, pz = 0; z < wd; z += w, pz++) { for (int x = 0; x < voxelArea.width; x++) { CompactVoxelCell c = voxelArea.compactCells[z+x]; for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; i++) { if (voxelArea.dist[i] >= level && srcReg[i] == 0 && voxelArea.areaTypes[i] != UnwalkableArea) { stack.Add(x); stack.Add(z); stack.Add(i); //Debug.DrawRay (ConvertPosition(x,z,i),Vector3.up*0.5F,Color.cyan); } } } } AstarProfiler.EndProfile("---Expand 1"); AstarProfiler.StartProfile("---Expand 2"); int iter = 0; int stCount = stack.Count; if (stCount > 0) while (true) { int failed = 0; AstarProfiler.StartProfile("---- Copy"); // Copy srcReg and srcDist to dstReg and dstDist (but faster than a normal loop) System.Buffer.BlockCopy(srcReg, 0, dstReg, 0, srcReg.Length*sizeof(ushort)); System.Buffer.BlockCopy(srcDist, 0, dstDist, 0, dstDist.Length*sizeof(ushort)); AstarProfiler.EndProfile("---- Copy"); for (int j = 0; j < stCount; j += 3) { if (j >= stCount) break; int x = stack[j]; int z = stack[j+1]; int i = stack[j+2]; if (i < 0) { //Debug.DrawRay (ConvertPosition(x,z,i),Vector3.up*2,Color.blue); failed++; continue; } ushort r = srcReg[i]; ushort d2 = 0xffff; CompactVoxelSpan s = voxelArea.compactSpans[i]; int area = voxelArea.areaTypes[i]; for (int dir = 0; dir < 4; dir++) { if (s.GetConnection(dir) == NotConnected) { continue; } int nx = x + voxelArea.DirectionX[dir]; int nz = z + voxelArea.DirectionZ[dir]; int ni = (int)voxelArea.compactCells[nx+nz].index + s.GetConnection(dir); if (area != voxelArea.areaTypes[ni]) { continue; } if (srcReg[ni] > 0 && (srcReg[ni] & BorderReg) == 0) { if ((int)srcDist[ni]+2 < (int)d2) { r = srcReg[ni]; d2 = (ushort)(srcDist[ni]+2); } } } if (r != 0) { stack[j+2] = -1; // mark as used dstReg[i] = r; dstDist[i] = d2; } else { failed++; //Debug.DrawRay (ConvertPosition(x,z,i),Vector3.up*2,Color.red); } } // Swap source and dest. ushort[] tmp = srcReg; srcReg = dstReg; dstReg = tmp; tmp = srcDist; srcDist = dstDist; dstDist = tmp; if (failed*3 >= stCount) { //Debug.Log("Failed count broke "+failed); break; } if (level > 0) { iter++; if (iter >= maxIterations) { //Debug.Log("Iterations broke"); break; } } } AstarProfiler.EndProfile("---Expand 2"); return srcReg; #endif } public bool FloodRegion (int x, int z, int i, uint level, ushort r, ushort[] srcReg, ushort[] srcDist, List<int> stack) { int area = voxelArea.areaTypes[i]; // Flood fill mark region. stack.Clear(); stack.Add(x); stack.Add(z); stack.Add(i); srcReg[i] = r; srcDist[i] = 0; int lev = (int)(level >= 2 ? level-2 : 0); int count = 0; while (stack.Count > 0) { //Similar to the Pop operation of an array, but Pop is not implemented in List<> int ci = stack[stack.Count-1]; stack.RemoveAt(stack.Count-1); int cz = stack[stack.Count-1]; stack.RemoveAt(stack.Count-1); int cx = stack[stack.Count-1]; stack.RemoveAt(stack.Count-1); CompactVoxelSpan cs = voxelArea.compactSpans[ci]; //Debug.DrawRay (ConvertPosition(cx,cz,ci),Vector3.up, Color.cyan); // Check if any of the neighbours already have a valid region set. ushort ar = 0; // Loop through four neighbours // then check one neighbour of the neighbour // to get the diagonal neighbour for (int dir = 0; dir < 4; dir++) { // 8 connected if (cs.GetConnection(dir) != NotConnected) { int ax = cx + voxelArea.DirectionX[dir]; int az = cz + voxelArea.DirectionZ[dir]; int ai = (int)voxelArea.compactCells[ax+az].index + cs.GetConnection(dir); if (voxelArea.areaTypes[ai] != area) continue; ushort nr = srcReg[ai]; if ((nr & BorderReg) == BorderReg) // Do not take borders into account. continue; if (nr != 0 && nr != r) { ar = nr; // Found a valid region, skip checking the rest break; } CompactVoxelSpan aspan = voxelArea.compactSpans[ai]; // Rotate dir 90 degrees int dir2 = (dir+1) & 0x3; // Check the diagonal connection if (aspan.GetConnection(dir2) != NotConnected) { int ax2 = ax + voxelArea.DirectionX[dir2]; int az2 = az + voxelArea.DirectionZ[dir2]; int ai2 = (int)voxelArea.compactCells[ax2+az2].index + aspan.GetConnection(dir2); if (voxelArea.areaTypes[ai2] != area) continue; ushort nr2 = srcReg[ai2]; if (nr2 != 0 && nr2 != r) { ar = nr2; // Found a valid region, skip checking the rest break; } } } } if (ar != 0) { srcReg[ci] = 0; continue; } count++; // Expand neighbours. for (int dir = 0; dir < 4; ++dir) { if (cs.GetConnection(dir) != NotConnected) { int ax = cx + voxelArea.DirectionX[dir]; int az = cz + voxelArea.DirectionZ[dir]; int ai = (int)voxelArea.compactCells[ax+az].index + cs.GetConnection(dir); if (voxelArea.areaTypes[ai] != area) continue; if (voxelArea.dist[ai] >= lev && srcReg[ai] == 0) { srcReg[ai] = r; srcDist[ai] = 0; stack.Add(ax); stack.Add(az); stack.Add(ai); } } } } return count > 0; } public void MarkRectWithRegion (int minx, int maxx, int minz, int maxz, ushort region, ushort[] srcReg) { int md = maxz * voxelArea.width; for (int z = minz*voxelArea.width; z < md; z += voxelArea.width) { for (int x = minx; x < maxx; x++) { CompactVoxelCell c = voxelArea.compactCells[z+x]; for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; i++) { if (voxelArea.areaTypes[i] != UnwalkableArea) { srcReg[i] = region; } } } } } public ushort CalculateDistanceField (ushort[] src) { int wd = voxelArea.width*voxelArea.depth; //Mark boundary cells for (int z = 0; z < wd; z += voxelArea.width) { for (int x = 0; x < voxelArea.width; x++) { CompactVoxelCell c = voxelArea.compactCells[x+z]; for (int i = (int)c.index, ci = (int)(c.index+c.count); i < ci; i++) { CompactVoxelSpan s = voxelArea.compactSpans[i]; int nc = 0; for (int d = 0; d < 4; d++) { if (s.GetConnection(d) != NotConnected) { //This function (CalculateDistanceField) is used for both ErodeWalkableArea and by itself. //The C++ recast source uses different code for those two cases, but I have found it works with one function //the voxelArea.areaTypes[ni] will actually only be one of two cases when used from ErodeWalkableArea //so it will have the same effect as // if (area != UnwalkableArea) { //This line is the one where the differ most nc++; #if FALSE if (area == voxelArea.areaTypes[ni]) { nc++; } else { //No way we can reach 4 break; } #endif } else { break; } } if (nc != 4) { src[i] = 0; } } } } //Pass 1 for (int z = 0; z < wd; z += voxelArea.width) { for (int x = 0; x < voxelArea.width; x++) { CompactVoxelCell c = voxelArea.compactCells[x+z]; for (int i = (int)c.index, ci = (int)(c.index+c.count); i < ci; i++) { CompactVoxelSpan s = voxelArea.compactSpans[i]; if (s.GetConnection(0) != NotConnected) { // (-1,0) int nx = x+voxelArea.DirectionX[0]; int nz = z+voxelArea.DirectionZ[0]; int ni = (int)(voxelArea.compactCells[nx+nz].index+s.GetConnection(0)); if (src[ni]+2 < src[i]) { src[i] = (ushort)(src[ni]+2); } CompactVoxelSpan ns = voxelArea.compactSpans[ni]; if (ns.GetConnection(3) != NotConnected) { // (-1,0) + (0,-1) = (-1,-1) int nnx = nx+voxelArea.DirectionX[3]; int nnz = nz+voxelArea.DirectionZ[3]; int nni = (int)(voxelArea.compactCells[nnx+nnz].index+ns.GetConnection(3)); if (src[nni]+3 < src[i]) { src[i] = (ushort)(src[nni]+3); } } } if (s.GetConnection(3) != NotConnected) { // (0,-1) int nx = x+voxelArea.DirectionX[3]; int nz = z+voxelArea.DirectionZ[3]; int ni = (int)(voxelArea.compactCells[nx+nz].index+s.GetConnection(3)); if (src[ni]+2 < src[i]) { src[i] = (ushort)(src[ni]+2); } CompactVoxelSpan ns = voxelArea.compactSpans[ni]; if (ns.GetConnection(2) != NotConnected) { // (0,-1) + (1,0) = (1,-1) int nnx = nx+voxelArea.DirectionX[2]; int nnz = nz+voxelArea.DirectionZ[2]; int nni = (int)(voxelArea.compactCells[nnx+nnz].index+ns.GetConnection(2)); if (src[nni]+3 < src[i]) { src[i] = (ushort)(src[nni]+3); } } } } } } //Pass 2 for (int z = wd-voxelArea.width; z >= 0; z -= voxelArea.width) { for (int x = voxelArea.width-1; x >= 0; x--) { CompactVoxelCell c = voxelArea.compactCells[x+z]; for (int i = (int)c.index, ci = (int)(c.index+c.count); i < ci; i++) { CompactVoxelSpan s = voxelArea.compactSpans[i]; if (s.GetConnection(2) != NotConnected) { // (-1,0) int nx = x+voxelArea.DirectionX[2]; int nz = z+voxelArea.DirectionZ[2]; int ni = (int)(voxelArea.compactCells[nx+nz].index+s.GetConnection(2)); if (src[ni]+2 < src[i]) { src[i] = (ushort)(src[ni]+2); } CompactVoxelSpan ns = voxelArea.compactSpans[ni]; if (ns.GetConnection(1) != NotConnected) { // (-1,0) + (0,-1) = (-1,-1) int nnx = nx+voxelArea.DirectionX[1]; int nnz = nz+voxelArea.DirectionZ[1]; int nni = (int)(voxelArea.compactCells[nnx+nnz].index+ns.GetConnection(1)); if (src[nni]+3 < src[i]) { src[i] = (ushort)(src[nni]+3); } } } if (s.GetConnection(1) != NotConnected) { // (0,-1) int nx = x+voxelArea.DirectionX[1]; int nz = z+voxelArea.DirectionZ[1]; int ni = (int)(voxelArea.compactCells[nx+nz].index+s.GetConnection(1)); if (src[ni]+2 < src[i]) { src[i] = (ushort)(src[ni]+2); } CompactVoxelSpan ns = voxelArea.compactSpans[ni]; if (ns.GetConnection(0) != NotConnected) { // (0,-1) + (1,0) = (1,-1) int nnx = nx+voxelArea.DirectionX[0]; int nnz = nz+voxelArea.DirectionZ[0]; int nni = (int)(voxelArea.compactCells[nnx+nnz].index+ns.GetConnection(0)); if (src[nni]+3 < src[i]) { src[i] = (ushort)(src[nni]+3); } } } } } } ushort maxDist = 0; for (int i = 0; i < voxelArea.compactSpanCount; i++) { maxDist = System.Math.Max(src[i], maxDist); } return maxDist; } public ushort[] BoxBlur (ushort[] src, ushort[] dst) { ushort thr = 20; int wd = voxelArea.width*voxelArea.depth; for (int z = wd-voxelArea.width; z >= 0; z -= voxelArea.width) { for (int x = voxelArea.width-1; x >= 0; x--) { CompactVoxelCell c = voxelArea.compactCells[x+z]; for (int i = (int)c.index, ci = (int)(c.index+c.count); i < ci; i++) { CompactVoxelSpan s = voxelArea.compactSpans[i]; ushort cd = src[i]; if (cd < thr) { dst[i] = cd; continue; } int total = (int)cd; for (int d = 0; d < 4; d++) { if (s.GetConnection(d) != NotConnected) { int nx = x+voxelArea.DirectionX[d]; int nz = z+voxelArea.DirectionZ[d]; int ni = (int)(voxelArea.compactCells[nx+nz].index+s.GetConnection(d)); total += (int)src[ni]; CompactVoxelSpan ns = voxelArea.compactSpans[ni]; int d2 = (d+1) & 0x3; if (ns.GetConnection(d2) != NotConnected) { int nnx = nx+voxelArea.DirectionX[d2]; int nnz = nz+voxelArea.DirectionZ[d2]; int nni = (int)(voxelArea.compactCells[nnx+nnz].index+ns.GetConnection(d2)); total += (int)src[nni]; } else { total += cd; } } else { total += cd*2; } } dst[i] = (ushort)((total+5)/9F); } } } return dst; } void FloodOnes (List<Int3> st1, ushort[] regs, uint level, ushort reg) { for (int j = 0; j < st1.Count; j++) { int x = st1[j].x; int i = st1[j].y; int z = st1[j].z; regs[i] = reg; CompactVoxelSpan s = voxelArea.compactSpans[i]; int area = voxelArea.areaTypes[i]; for (int dir = 0; dir < 4; dir++) { if (s.GetConnection(dir) == NotConnected) { continue; } int nx = x + voxelArea.DirectionX[dir]; int nz = z + voxelArea.DirectionZ[dir]; int ni = (int)voxelArea.compactCells[nx+nz].index + s.GetConnection(dir); if (area != voxelArea.areaTypes[ni]) { continue; } if (regs[ni] == 1) { regs[ni] = reg; st1.Add(new Int3(nx, ni, nz)); } } } } public void BuildRegions () { AstarProfiler.StartProfile("Build Regions"); int w = voxelArea.width; int d = voxelArea.depth; int wd = w*d; int spanCount = voxelArea.compactSpanCount; #if ASTAR_RECAST_BFS ushort[] srcReg = voxelArea.tmpUShortArr; if (srcReg.Length < spanCount) { srcReg = voxelArea.tmpUShortArr = new ushort[spanCount]; } Pathfinding.Util.Memory.MemSet<ushort>(srcReg, 0, sizeof(ushort)); #else int expandIterations = 8; List<int> stack = Pathfinding.Util.ListPool<int>.Claim(1024); ushort[] srcReg = new ushort[spanCount]; ushort[] srcDist = new ushort[spanCount]; ushort[] dstReg = new ushort[spanCount]; ushort[] dstDist = new ushort[spanCount]; #endif ushort regionId = 2; MarkRectWithRegion(0, borderSize, 0, d, (ushort)(regionId | BorderReg), srcReg); regionId++; MarkRectWithRegion(w-borderSize, w, 0, d, (ushort)(regionId | BorderReg), srcReg); regionId++; MarkRectWithRegion(0, w, 0, borderSize, (ushort)(regionId | BorderReg), srcReg); regionId++; MarkRectWithRegion(0, w, d-borderSize, d, (ushort)(regionId | BorderReg), srcReg); regionId++; #if ASTAR_RECAST_BFS uint level = 0; List<Int3> basins = Pathfinding.Util.ListPool<Int3>.Claim(100); // Find "basins" for (int z = 0, pz = 0; z < wd; z += w, pz++) { for (int x = 0; x < voxelArea.width; x++) { CompactVoxelCell c = voxelArea.compactCells[z+x]; for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; i++) { CompactVoxelSpan s = voxelArea.compactSpans[i]; bool anyBelow = false; if (voxelArea.areaTypes[i] == UnwalkableArea || srcReg[i] != 0) continue; for (int dir = 0; dir < 4; dir++) { if (s.GetConnection(dir) != NotConnected) { int nx = x+voxelArea.DirectionX[dir]; int nz = z+voxelArea.DirectionZ[dir]; int ni2 = (int)(voxelArea.compactCells[nx+nz].index+s.GetConnection(dir)); if (voxelArea.dist[i] < voxelArea.dist[ni2]) { anyBelow = true; break; } //CompactVoxelSpan ns = voxelArea.compactSpans[ni]; } } if (!anyBelow) { basins.Add(new Int3(x, i, z)); level = System.Math.Max(level, voxelArea.dist[i]); } } } } //Start at maximum possible distance. & ~1 is rounding down to an even value level = (uint)((level+1) & ~1); List<Int3> st1 = Pathfinding.Util.ListPool<Int3>.Claim(300); List<Int3> st2 = Pathfinding.Util.ListPool<Int3>.Claim(300); // Some debug code //bool visited = new bool[voxelArea.compactSpanCount]; for (;; level -= 2) { int ocount = st1.Count; int expandCount = 0; if (ocount == 0) { //int c = 0; for (int q = 0; q < basins.Count; q++) { if (srcReg[basins[q].y] == 0 && voxelArea.dist[basins[q].y] >= level) { srcReg[basins[q].y] = 1; st1.Add(basins[q]); // Some debug code //c++; //visited[basins[i].y] = true; } } } for (int j = 0; j < st1.Count; j++) { int x = st1[j].x; int i = st1[j].y; int z = st1[j].z; ushort r = srcReg[i]; CompactVoxelSpan s = voxelArea.compactSpans[i]; int area = voxelArea.areaTypes[i]; bool anyAbove = false; for (int dir = 0; dir < 4; dir++) { if (s.GetConnection(dir) == NotConnected) { continue; } int nx = x + voxelArea.DirectionX[dir]; int nz = z + voxelArea.DirectionZ[dir]; int ni = (int)voxelArea.compactCells[nx+nz].index + s.GetConnection(dir); if (area != voxelArea.areaTypes[ni]) { continue; } if (voxelArea.dist[ni] < level) { anyAbove = true; continue; } if (srcReg[ni] == 0) { bool same = false; for (int v = (int)voxelArea.compactCells[nx+nz].index, vt = (int)voxelArea.compactCells[nx+nz].index+(int)voxelArea.compactCells[nx+nz].count; v < vt; v++) { if (srcReg[v] == srcReg[i]) { same = true; break; } } if (!same) { srcReg[ni] = r; //Debug.DrawRay (ConvertPosition(x,z,i),Vector3.up,AstarMath.IntToColor((int)level,0.6f)); st1.Add(new Int3(nx, ni, nz)); } } } //Still on the edge if (anyAbove) { st2.Add(st1[j]); } if (j == ocount-1) { expandCount++; ocount = st1.Count; if (expandCount == 8 || j == st1.Count-1) { //int c = 0; for (int q = 0; q < basins.Count; q++) { if (srcReg[basins[q].y] == 0 && voxelArea.dist[basins[q].y] >= level) { srcReg[basins[q].y] = 1; st1.Add(basins[q]); // Debug code //c++; //visited[basins[i].y] = true; } } } } } List<Int3> tmpList = st1; st1 = st2; st2 = tmpList; st2.Clear(); //System.Console.WriteLine ("Flooding basins"); for (int i = 0; i < basins.Count; i++) { if (srcReg[basins[i].y] == 1) { st2.Add(basins[i]); FloodOnes(st2, srcReg, level, regionId); regionId++; st2.Clear(); } } if (level == 0) break; } Pathfinding.Util.ListPool<Int3>.Release(st1); Pathfinding.Util.ListPool<Int3>.Release(st2); Pathfinding.Util.ListPool<Int3>.Release(basins); // Filter out small regions. voxelArea.maxRegions = regionId; FilterSmallRegions(srcReg, minRegionSize, voxelArea.maxRegions); // Write the result out. for (int i = 0; i < voxelArea.compactSpanCount; i++) { voxelArea.compactSpans[i].reg = srcReg[i]; } #else /// ====== Use original recast code ====== // //Start at maximum possible distance. & ~1 is rounding down to an even value uint level = (uint)((voxelArea.maxDistance+1) & ~1); int count = 0; while (level > 0) { level = level >= 2 ? level-2 : 0; AstarProfiler.StartProfile("--Expand Regions"); if (ExpandRegions(expandIterations, level, srcReg, srcDist, dstReg, dstDist, stack) != srcReg) { ushort[] tmp = srcReg; srcReg = dstReg; dstReg = tmp; tmp = srcDist; srcDist = dstDist; dstDist = tmp; } AstarProfiler.EndProfile("--Expand Regions"); AstarProfiler.StartProfile("--Mark Regions"); // Mark new regions with IDs. // Find "basins" for (int z = 0, pz = 0; z < wd; z += w, pz++) { for (int x = 0; x < voxelArea.width; x++) { CompactVoxelCell c = voxelArea.compactCells[z+x]; for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; i++) { if (voxelArea.dist[i] < level || srcReg[i] != 0 || voxelArea.areaTypes[i] == UnwalkableArea) continue; if (FloodRegion(x, z, i, level, regionId, srcReg, srcDist, stack)) regionId++; } } } AstarProfiler.EndProfile("--Mark Regions"); count++; } if (ExpandRegions(expandIterations*8, 0, srcReg, srcDist, dstReg, dstDist, stack) != srcReg) { ushort[] tmp = srcReg; srcReg = dstReg; dstReg = tmp; tmp = srcDist; srcDist = dstDist; dstDist = tmp; } // Filter out small regions. voxelArea.maxRegions = regionId; FilterSmallRegions(srcReg, minRegionSize, voxelArea.maxRegions); // Write the result out. for (int i = 0; i < voxelArea.compactSpanCount; i++) { voxelArea.compactSpans[i].reg = srcReg[i]; } Pathfinding.Util.ListPool<int>.Release(ref stack); // Some debug code not currently used /* * int sCount = voxelArea.GetSpanCount (); * Vector3[] debugPointsTop = new Vector3[sCount]; * Vector3[] debugPointsBottom = new Vector3[sCount]; * Color[] debugColors = new Color[sCount]; * * int debugPointsCount = 0; * //int wd = voxelArea.width*voxelArea.depth; * * for (int z=0, pz = 0;z < wd;z += voxelArea.width, pz++) { * for (int x=0;x < voxelArea.width;x++) { * * Vector3 p = new Vector3(x,0,pz)*cellSize+forcedBounds.min; * * //CompactVoxelCell c = voxelArea.compactCells[x+z]; * CompactVoxelCell c = voxelArea.compactCells[x+z]; * //if (c.count == 0) { * // Debug.DrawRay (p,Vector3.up,Color.red); * //} * * //for (int i=(int)c.index, ni = (int)(c.index+c.count);i<ni;i++) * * for (int i = (int)c.index; i < c.index+c.count; i++) { * CompactVoxelSpan s = voxelArea.compactSpans[i]; * //CompactVoxelSpan s = voxelArea.compactSpans[i]; * * p.y = ((float)(s.y+0.1F))*cellHeight+forcedBounds.min.y; * * debugPointsTop[debugPointsCount] = p; * * p.y = ((float)s.y)*cellHeight+forcedBounds.min.y; * debugPointsBottom[debugPointsCount] = p; * * debugColors[debugPointsCount] = Pathfinding.AstarMath.IntToColor(s.reg,0.7f);//s.reg == 1 ? Color.green : (s.reg == 2 ? Color.yellow : Color.red); * debugPointsCount++; * * //Debug.DrawRay (p,Vector3.up*0.5F,Color.green); * } * } * } * * DebugUtility.DrawCubes (debugPointsTop,debugPointsBottom,debugColors, cellSize);*/ #endif AstarProfiler.EndProfile("Build Regions"); } /** Find method in the UnionFind data structure. * \see https://en.wikipedia.org/wiki/Disjoint-set_data_structure */ static int union_find_find (int[] arr, int x) { if (arr[x] < 0) return x; return arr[x] = union_find_find(arr, arr[x]); } /** Join method in the UnionFind data structure. * \see https://en.wikipedia.org/wiki/Disjoint-set_data_structure */ static void union_find_union (int[] arr, int a, int b) { a = union_find_find(arr, a); b = union_find_find(arr, b); if (a == b) return; if (arr[a] > arr[b]) { int tmp = a; a = b; b = tmp; } arr[a] += arr[b]; arr[b] = a; } /** Filters out or merges small regions. */ public void FilterSmallRegions (ushort[] reg, int minRegionSize, int maxRegions) { RelevantGraphSurface c = RelevantGraphSurface.Root; // Need to use ReferenceEquals because it might be called from another thread bool anySurfaces = !RelevantGraphSurface.ReferenceEquals(c, null) && (relevantGraphSurfaceMode != RecastGraph.RelevantGraphSurfaceMode.DoNotRequire); // Nothing to do here if (!anySurfaces && minRegionSize <= 0) { return; } int[] counter = new int[maxRegions]; ushort[] bits = voxelArea.tmpUShortArr; if (bits == null || bits.Length < maxRegions) { bits = voxelArea.tmpUShortArr = new ushort[maxRegions]; } Util.Memory.MemSet(counter, -1, sizeof(int)); Util.Memory.MemSet(bits, (ushort)0, maxRegions, sizeof(ushort)); int nReg = counter.Length; int wd = voxelArea.width*voxelArea.depth; const int RelevantSurfaceSet = 1 << 1; const int BorderBit = 1 << 0; // Mark RelevantGraphSurfaces // If they can also be adjacent to tile borders, this will also include the BorderBit int RelevantSurfaceCheck = RelevantSurfaceSet | ((relevantGraphSurfaceMode == RecastGraph.RelevantGraphSurfaceMode.OnlyForCompletelyInsideTile) ? BorderBit : 0x0); if (anySurfaces) { // Need to use ReferenceEquals because it might be called from another thread while (!RelevantGraphSurface.ReferenceEquals(c, null)) { int x, z; this.VectorToIndex(c.Position, out x, out z); // Check for out of bounds if (x >= 0 && z >= 0 && x < voxelArea.width && z < voxelArea.depth) { int y = (int)((c.Position.y - voxelOffset.y)/cellHeight); int rad = (int)(c.maxRange / cellHeight); CompactVoxelCell cell = voxelArea.compactCells[x+z*voxelArea.width]; for (int i = (int)cell.index; i < cell.index+cell.count; i++) { CompactVoxelSpan s = voxelArea.compactSpans[i]; if (System.Math.Abs(s.y - y) <= rad && reg[i] != 0) { bits[union_find_find(counter, (int)reg[i] & ~BorderReg)] |= RelevantSurfaceSet; } } } c = c.Next; } } for (int z = 0, pz = 0; z < wd; z += voxelArea.width, pz++) { for (int x = 0; x < voxelArea.width; x++) { CompactVoxelCell cell = voxelArea.compactCells[x+z]; for (int i = (int)cell.index; i < cell.index+cell.count; i++) { CompactVoxelSpan s = voxelArea.compactSpans[i]; int r = (int)reg[i]; if ((r & ~BorderReg) == 0) continue; if (r >= nReg) { //Probably border bits[union_find_find(counter, r & ~BorderReg)] |= BorderBit; continue; } int k = union_find_find(counter, r); // Count this span counter[k]--; for (int dir = 0; dir < 4; dir++) { if (s.GetConnection(dir) == NotConnected) { continue; } int nx = x + voxelArea.DirectionX[dir]; int nz = z + voxelArea.DirectionZ[dir]; int ni = (int)voxelArea.compactCells[nx+nz].index + s.GetConnection(dir); int r2 = (int)reg[ni]; if (r != r2 && (r2 & ~BorderReg) != 0) { if ((r2 & BorderReg) != 0) { bits[k] |= BorderBit; } else { union_find_union(counter, k, r2); } //counter[r] = minRegionSize; } } //counter[r]++; } } } // Propagate bits for (int i = 0; i < counter.Length; i++) bits[union_find_find(counter, i)] |= bits[i]; for (int i = 0; i < counter.Length; i++) { int ctr = union_find_find(counter, i); // Adjacent to border if ((bits[ctr] & BorderBit) != 0) counter[ctr] = -minRegionSize-2; // Not in any relevant surface // or it is adjacent to a border (see RelevantSurfaceCheck) if (anySurfaces && (bits[ctr] & RelevantSurfaceCheck) == 0) counter[ctr] = -1; } for (int i = 0; i < voxelArea.compactSpanCount; i++) { int r = (int)reg[i]; if (r >= nReg) { continue; } if (counter[union_find_find(counter, r)] >= -minRegionSize-1) { reg[i] = 0; } } } } }