context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: booking/pricing/price_night.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace HOLMS.Types.Booking.Pricing { /// <summary>Holder for reflection information generated from booking/pricing/price_night.proto</summary> public static partial class PriceNightReflection { #region Descriptor /// <summary>File descriptor for booking/pricing/price_night.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static PriceNightReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiFib29raW5nL3ByaWNpbmcvcHJpY2VfbmlnaHQucHJvdG8SG2hvbG1zLnR5", "cGVzLmJvb2tpbmcucHJpY2luZxodcHJpbWl0aXZlL3BiX2xvY2FsX2RhdGUu", "cHJvdG8aH3ByaW1pdGl2ZS9tb25ldGFyeV9hbW91bnQucHJvdG8idwoKUHJp", "Y2VOaWdodBIzCgdvcHNkYXRlGAEgASgLMiIuaG9sbXMudHlwZXMucHJpbWl0", "aXZlLlBiTG9jYWxEYXRlEjQKBXByaWNlGAIgASgLMiUuaG9sbXMudHlwZXMu", "cHJpbWl0aXZlLk1vbmV0YXJ5QW1vdW50Qi9aD2Jvb2tpbmcvcHJpY2luZ6oC", "G0hPTE1TLlR5cGVzLkJvb2tpbmcuUHJpY2luZ2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.Primitive.PbLocalDateReflection.Descriptor, global::HOLMS.Types.Primitive.MonetaryAmountReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.Pricing.PriceNight), global::HOLMS.Types.Booking.Pricing.PriceNight.Parser, new[]{ "Opsdate", "Price" }, null, null, null) })); } #endregion } #region Messages public sealed partial class PriceNight : pb::IMessage<PriceNight> { private static readonly pb::MessageParser<PriceNight> _parser = new pb::MessageParser<PriceNight>(() => new PriceNight()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<PriceNight> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Booking.Pricing.PriceNightReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PriceNight() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PriceNight(PriceNight other) : this() { Opsdate = other.opsdate_ != null ? other.Opsdate.Clone() : null; Price = other.price_ != null ? other.Price.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PriceNight Clone() { return new PriceNight(this); } /// <summary>Field number for the "opsdate" field.</summary> public const int OpsdateFieldNumber = 1; private global::HOLMS.Types.Primitive.PbLocalDate opsdate_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.PbLocalDate Opsdate { get { return opsdate_; } set { opsdate_ = value; } } /// <summary>Field number for the "price" field.</summary> public const int PriceFieldNumber = 2; private global::HOLMS.Types.Primitive.MonetaryAmount price_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.MonetaryAmount Price { get { return price_; } set { price_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as PriceNight); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(PriceNight other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Opsdate, other.Opsdate)) return false; if (!object.Equals(Price, other.Price)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (opsdate_ != null) hash ^= Opsdate.GetHashCode(); if (price_ != null) hash ^= Price.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (opsdate_ != null) { output.WriteRawTag(10); output.WriteMessage(Opsdate); } if (price_ != null) { output.WriteRawTag(18); output.WriteMessage(Price); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (opsdate_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Opsdate); } if (price_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Price); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(PriceNight other) { if (other == null) { return; } if (other.opsdate_ != null) { if (opsdate_ == null) { opsdate_ = new global::HOLMS.Types.Primitive.PbLocalDate(); } Opsdate.MergeFrom(other.Opsdate); } if (other.price_ != null) { if (price_ == null) { price_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } Price.MergeFrom(other.Price); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (opsdate_ == null) { opsdate_ = new global::HOLMS.Types.Primitive.PbLocalDate(); } input.ReadMessage(opsdate_); break; } case 18: { if (price_ == null) { price_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } input.ReadMessage(price_); break; } } } } } #endregion } #endregion Designer generated code
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_3_5 || UNITY_3_4 || UNITY_3_3 #define UNITY_LE_4_3 #endif #if !UNITY_3_5 && !UNITY_3_4 && !UNITY_3_3 #define UNITY_4 #endif using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using Pathfinding; [CustomEditor(typeof(GraphUpdateScene))] /** Editor for GraphUpdateScene */ public class GraphUpdateSceneEditor : Editor { int selectedPoint = -1; #if !UNITY_LE_4_3 int lastUndoGroup = 0; #endif const float pointGizmosRadius = 0.09F; static Color PointColor = new Color (1,0.36F,0,0.6F); static Color PointSelectedColor = new Color (1,0.24F,0,1.0F); public override void OnInspectorGUI () { GraphUpdateScene script = target as GraphUpdateScene; #if !UNITY_LE_4_3 Undo.RecordObject (script, "modify settings on GraphUpdateObject"); #endif if (script.points == null) script.points = new Vector3[0]; if (script.points == null || script.points.Length == 0) { if (script.collider != null) { EditorGUILayout.HelpBox ("No points, using collider.bounds", MessageType.Info); } else if (script.renderer != null) { EditorGUILayout.HelpBox ("No points, using renderer.bounds", MessageType.Info); } else { EditorGUILayout.HelpBox ("No points and no collider or renderer attached, will not affect anything", MessageType.Warning); } } Vector3[] prePoints = script.points; #if UNITY_4 EditorGUILayout.PropertyField (serializedObject.FindProperty("points"), true ); #else DrawDefaultInspector (); #endif #if UNITY_LE_4_3 EditorGUI.indentLevel = 1; #else EditorGUI.indentLevel = 0; #endif script.updatePhysics = EditorGUILayout.Toggle (new GUIContent ("Update Physics", "Perform similar calculations on the nodes as during scan.\n" + "Grid Graphs will update the position of the nodes and also check walkability using collision.\nSee online documentation for more info."), script.updatePhysics ); if ( script.updatePhysics ) { EditorGUI.indentLevel++; script.resetPenaltyOnPhysics = EditorGUILayout.Toggle ( new GUIContent ("Reset Penalty On Physics", "Will reset the penalty to the default value during the update."), script.resetPenaltyOnPhysics ); EditorGUI.indentLevel--; } script.updateErosion = EditorGUILayout.Toggle (new GUIContent ("Update Erosion", "Recalculate erosion for grid graphs.\nSee online documentation for more info"), script.updateErosion ); if (prePoints != script.points) { script.RecalcConvex (); HandleUtility.Repaint (); } bool preConvex = script.convex; script.convex = EditorGUILayout.Toggle (new GUIContent ("Convex","Sets if only the convex hull of the points should be used or the whole polygon"),script.convex); if (script.convex != preConvex) { script.RecalcConvex (); HandleUtility.Repaint (); } script.minBoundsHeight = EditorGUILayout.FloatField (new GUIContent ("Min Bounds Height","Defines a minimum height to be used for the bounds of the GUO.\nUseful if you define points in 2D (which would give height 0)"), script.minBoundsHeight); script.applyOnStart = EditorGUILayout.Toggle ("Apply On Start",script.applyOnStart); script.applyOnScan = EditorGUILayout.Toggle ("Apply On Scan",script.applyOnScan); script.modifyWalkability = EditorGUILayout.Toggle (new GUIContent ("Modify walkability","If true, walkability of all nodes will be modified"),script.modifyWalkability); if (script.modifyWalkability) { EditorGUI.indentLevel++; script.setWalkability = EditorGUILayout.Toggle (new GUIContent ("Walkability","Nodes' walkability will be set to this value"),script.setWalkability); EditorGUI.indentLevel--; } script.penaltyDelta = EditorGUILayout.IntField (new GUIContent ("Penalty Delta", "A penalty will be added to the nodes, usually you need very large values, at least 1000-10000.\n" + "A higher penalty will mean that agents will try to avoid those nodes."),script.penaltyDelta); if (script.penaltyDelta < 0) { EditorGUILayout.HelpBox ("Be careful when lowering the penalty. Negative penalties are not supported and will instead underflow and get really high.\n" + "You can set an initial penalty on graphs (see their settings) and then lower them like this to get regions which are easier to traverse.", MessageType.Warning); } #if ConfigureTagsAsMultiple script.modifyTag = EditorGUILayout.Toggle (new GUIContent ("Modify Tags","Should the tags of the nodes be modified"),script.modifyTag); EditorGUILayoutx.TagsMaskField (new GUIContent ("Tags Change","Which tags to change the value of. The values the tags will gain can be set below"), new GUIContent ("Tags Set","What to set the tag to if it is going to be changed"),ref script.tags); #else script.modifyTag = EditorGUILayout.Toggle (new GUIContent ("Modify Tags","Should the tags of the nodes be modified"),script.modifyTag); if (script.modifyTag) { EditorGUI.indentLevel++; script.setTag = EditorGUILayout.Popup ("Set Tag",script.setTag,AstarPath.FindTagNames ()); EditorGUI.indentLevel--; } #endif if (GUILayout.Button ("Tags can be used to restrict which units can walk on what ground. Click here for more info","HelpBox")) { Application.OpenURL (AstarPathEditor.GetURL ("tags")); } EditorGUILayout.Separator (); bool worldSpace = EditorGUILayout.Toggle (new GUIContent ("Use World Space","Specify coordinates in world space or local space. When using local space you can move the GameObject " + "around and the points will follow.\n" + "Some operations, like calculating the convex hull, and snapping to Y will change axis depending on how the object is rotated if world space is not used." ), script.useWorldSpace); if (worldSpace != script.useWorldSpace) { #if !UNITY_LE_4_3 Undo.RecordObject (script, "switch use-world-space"); #endif script.ToggleUseWorldSpace (); } #if UNITY_4 EditorGUI.BeginChangeCheck (); #endif script.lockToY = EditorGUILayout.Toggle ("Lock to Y",script.lockToY); if (script.lockToY) { EditorGUI.indentLevel++; script.lockToYValue = EditorGUILayout.FloatField ("Lock to Y value",script.lockToYValue); EditorGUI.indentLevel--; #if !UNITY_LE_4_3 if ( EditorGUI.EndChangeCheck () ) { Undo.RecordObject (script, "change Y locking"); } #endif script.LockToY (); } EditorGUILayout.Separator (); if (GUI.changed) { #if UNITY_LE_4_3 Undo.RegisterUndo (script,"Modify Settings on GraphUpdateObject"); #endif EditorUtility.SetDirty (target); } if (GUILayout.Button ("Clear all points")) { #if UNITY_LE_4_3 Undo.RegisterUndo (script,"Removed All Points"); #endif script.points = new Vector3[0]; EditorUtility.SetDirty (target); script.RecalcConvex (); } } public void OnSceneGUI () { GraphUpdateScene script = target as GraphUpdateScene; if (script.points == null) script.points = new Vector3[0]; List<Vector3> points = Pathfinding.Util.ListPool<Vector3>.Claim (); points.AddRange (script.points); Matrix4x4 invMatrix = script.useWorldSpace ? Matrix4x4.identity : script.transform.worldToLocalMatrix; if (!script.useWorldSpace) { Matrix4x4 matrix = script.transform.localToWorldMatrix; for (int i=0;i<points.Count;i++) points[i] = matrix.MultiplyPoint3x4(points[i]); } if (Tools.current != Tool.View && Event.current.type == EventType.Layout) { for (int i=0;i<script.points.Length;i++) { HandleUtility.AddControl (-i - 1,HandleUtility.DistanceToLine (points[i],points[i])); } } if (Tools.current != Tool.View) HandleUtility.AddDefaultControl (0); for (int i=0;i<points.Count;i++) { if (i == selectedPoint && Tools.current == Tool.Move) { Handles.color = PointSelectedColor; #if UNITY_LE_4_3 Undo.SetSnapshotTarget(script, "Moved Point"); #else Undo.RecordObject(script, "Moved Point"); #endif Handles.SphereCap (-i-1,points[i],Quaternion.identity,HandleUtility.GetHandleSize (points[i])*pointGizmosRadius*2); Vector3 pre = points[i]; Vector3 post = Handles.PositionHandle (points[i],Quaternion.identity); if (pre != post) { script.points[i] = invMatrix.MultiplyPoint3x4(post); } } else { Handles.color = PointColor; Handles.SphereCap (-i-1,points[i],Quaternion.identity,HandleUtility.GetHandleSize (points[i])*pointGizmosRadius); } } #if UNITY_LE_4_3 if(Input.GetMouseButtonDown(0)) { // Register the undos when we press the Mouse button. Undo.CreateSnapshot(); Undo.RegisterSnapshot(); } #endif if (Event.current.type == EventType.MouseDown) { int pre = selectedPoint; selectedPoint = -(HandleUtility.nearestControl+1); if (pre != selectedPoint) GUI.changed = true; } if (Event.current.type == EventType.MouseDown && Event.current.shift && Tools.current == Tool.Move) { if (((int)Event.current.modifiers & (int)EventModifiers.Alt) != 0) { //int nearestControl = -(HandleUtility.nearestControl+1); if (selectedPoint >= 0 && selectedPoint < points.Count) { #if UNITY_LE_4_3 Undo.RegisterUndo (script,"Removed Point"); #else Undo.RecordObject (script,"Removed Point"); #endif List<Vector3> arr = new List<Vector3>(script.points); arr.RemoveAt (selectedPoint); points.RemoveAt (selectedPoint); script.points = arr.ToArray (); script.RecalcConvex (); GUI.changed = true; } } else if (((int)Event.current.modifiers & (int)EventModifiers.Control) != 0 && points.Count > 1) { int minSeg = 0; float minDist = float.PositiveInfinity; for (int i=0;i<points.Count;i++) { float dist = HandleUtility.DistanceToLine (points[i],points[(i+1)%points.Count]); if (dist < minDist) { minSeg = i; minDist = dist; } } System.Object hit = HandleUtility.RaySnap (HandleUtility.GUIPointToWorldRay(Event.current.mousePosition)); if (hit != null) { RaycastHit rayhit = (RaycastHit)hit; #if UNITY_LE_4_3 Undo.RegisterUndo (script,"Added Point"); #else Undo.RecordObject (script,"Added Point"); #endif List<Vector3> arr = Pathfinding.Util.ListPool<Vector3>.Claim (); arr.AddRange (script.points); points.Insert (minSeg+1,rayhit.point); if (!script.useWorldSpace) rayhit.point = invMatrix.MultiplyPoint3x4 (rayhit.point); arr.Insert (minSeg+1,rayhit.point); script.points = arr.ToArray (); script.RecalcConvex (); Pathfinding.Util.ListPool<Vector3>.Release (arr); GUI.changed = true; } } else { System.Object hit = HandleUtility.RaySnap (HandleUtility.GUIPointToWorldRay(Event.current.mousePosition)); if (hit != null) { RaycastHit rayhit = (RaycastHit)hit; #if UNITY_LE_4_3 Undo.RegisterUndo (script,"Added Point"); #else Undo.RecordObject (script,"Added Point"); #endif Vector3[] arr = new Vector3[script.points.Length+1]; for (int i=0;i<script.points.Length;i++) { arr[i] = script.points[i]; } points.Add (rayhit.point); if (!script.useWorldSpace) rayhit.point = invMatrix.MultiplyPoint3x4 (rayhit.point); arr[script.points.Length] = rayhit.point; script.points = arr; script.RecalcConvex (); GUI.changed = true; } } Event.current.Use (); } if (Event.current.shift && Event.current.type == EventType.MouseDrag) { //Event.current.Use (); } #if !UNITY_LE_4_3 if ( lastUndoGroup != Undo.GetCurrentGroup () ) { script.RecalcConvex (); } #endif Pathfinding.Util.ListPool<Vector3>.Release (points); if (GUI.changed) { HandleUtility.Repaint (); EditorUtility.SetDirty (target); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Collections.Generic; using System.Linq; namespace Test { public class SelectSelectManyTests { // // Select // [Fact] public static void RunSelectTests() { RunSelectTest1(0); RunSelectTest1(1); RunSelectTest1(32); RunSelectTest1(1024); RunSelectTest1(1024 * 2); RunSelectTest2(0); RunSelectTest2(1); RunSelectTest2(32); RunSelectTest2(1024); RunSelectTest2(1024 * 2); } [Fact] public static void RunIndexedSelectTest() { RunIndexedSelectTest1(0); RunIndexedSelectTest1(1); RunIndexedSelectTest1(32); RunIndexedSelectTest2(0); RunIndexedSelectTest2(1); RunIndexedSelectTest2(32); } [Fact] [OuterLoop] public static void RunIndexedSelectTest_LongRunning() { RunIndexedSelectTest1(1024); RunIndexedSelectTest1(1024 * 2); RunIndexedSelectTest1(1024 * 1024 * 4); RunIndexedSelectTest2(1024); RunIndexedSelectTest2(1024 * 2); RunIndexedSelectTest2(1024 * 1024 * 4); } private static void RunSelectTest1(int dataSize) { string methodFailed = string.Format("RunSelectTest1(dataSize = {0}) - async/pipeline: FAILED. ", dataSize); int[] data = new int[dataSize]; for (int i = 0; i < data.Length; i++) data[i] = i; // Select the square. We will validate it during results. IEnumerable<Pair<int, int>> q = data.AsParallel().Select<int, Pair<int, int>>( delegate (int x) { return new Pair<int, int>(x, x * x); }); int cnt = 0; foreach (Pair<int, int> p in q) { if (p.Second != p.First * p.First) { Assert.True(false, string.Format(methodFailed + " > **Failure: {0} is not the square of {1} ({2})", p.Second, p.First, p.First * p.First)); } cnt++; } if (cnt != dataSize) Assert.True(false, string.Format(methodFailed + " > Saw expected count? Saw = {0}, expect = {1}: FAILED", cnt, dataSize)); } private static void RunSelectTest2(int dataSize) { string methodFailed = string.Format("RunSelectTest2(dataSize = {0}) - NO pipelining: FAILED. ", dataSize); int[] data = new int[dataSize]; for (int i = 0; i < data.Length; i++) data[i] = i; // Select the square. We will validate it during results. ParallelQuery<Pair<int, int>> q = data.AsParallel().Select<int, Pair<int, int>>( delegate (int x) { return new Pair<int, int>(x, x * x); }); int cnt = 0; List<Pair<int, int>> r = q.ToList<Pair<int, int>>(); foreach (Pair<int, int> p in r) { if (p.Second != p.First * p.First) { Assert.True(false, string.Format(methodFailed + " > **Failure: {0} is not the square of {1} ({2})", p.Second, p.First, p.First * p.First)); // plz } cnt++; } if (cnt != dataSize) Assert.True(false, string.Format(methodFailed + " > Saw expected count? Saw = {0}, expect = {1}: FAILED", cnt, dataSize)); } // // Uses an element's index to calculate an output value. If order preservation isn't // working, this would PROBABLY fail. Unfortunately, this isn't deterministic. But choosing // larger input sizes increases the probability that it will. // private static void RunIndexedSelectTest1(int dataSize) { string methodFailed = string.Format("RunIndexedSelectTest1(dataSize = {0}) - async/pipelining: FAILED. ", dataSize); int[] data = new int[dataSize]; for (int i = 0; i < data.Length; i++) data[i] = i; // Select the square. We will validate it during results. IEnumerable<Pair<int, Pair<int, int>>> q = data.AsParallel().AsOrdered().Select<int, Pair<int, Pair<int, int>>>( delegate (int x, int idx) { return new Pair<int, Pair<int, int>>(x, new Pair<int, int>(idx, x * x)); }); int cnt = 0; foreach (Pair<int, Pair<int, int>> p in q) { if (p.Second.First != cnt) { Assert.True(false, string.Format(methodFailed + " > **Failure: results not increasing in index order (expect {0}, saw {1})", cnt, p.Second.First)); } if (p.First != p.Second.First) { Assert.True(false, string.Format(methodFailed + " > **Failure: expected element value {0} to equal index {1}", p.First, p.Second.First)); } if (p.Second.Second != p.First * p.First) { Assert.True(false, string.Format(methodFailed + " > **Failure: {0} is not the square of {1} ({2})", p.Second.Second, p.First, p.First * p.First)); } cnt++; } if (cnt != dataSize) Assert.True(false, string.Format(methodFailed + " > Saw expected count? Saw = {0}, expect = {1}: FAILED", cnt, dataSize)); } // // Uses an element's index to calculate an output value. If order preservation isn't // working, this would PROBABLY fail. Unfortunately, this isn't deterministic. But choosing // larger input sizes increases the probability that it will. // private static void RunIndexedSelectTest2(int dataSize) { string methodFailed = string.Format("RunIndexedSelectTest2(dataSize = {0}) - NO pipelining: FAILED. ", dataSize); int[] data = new int[dataSize]; for (int i = 0; i < data.Length; i++) data[i] = i; // Select the square. We will validate it during results. ParallelQuery<Pair<int, Pair<int, int>>> q = data.AsParallel().AsOrdered().Select<int, Pair<int, Pair<int, int>>>( delegate (int x, int idx) { return new Pair<int, Pair<int, int>>(x, new Pair<int, int>(idx, x * x)); }); int cnt = 0; List<Pair<int, Pair<int, int>>> r = q.ToList<Pair<int, Pair<int, int>>>(); foreach (Pair<int, Pair<int, int>> p in r) { if (p.Second.First != cnt) { Assert.True(false, string.Format(methodFailed + " > **Failure: results not increasing in index order (expect {0}, saw {1})", cnt, p.Second.First)); } if (p.First != p.Second.First) { Assert.True(false, string.Format(methodFailed + " > **Failure: expected element value {0} to equal index {1}", p.First, p.Second.First)); } if (p.Second.Second != p.First * p.First) { Assert.True(false, string.Format(methodFailed + " > **Failure: {0} is not the square of {1} ({2})", p.Second.Second, p.First, p.First * p.First)); } cnt++; } if (cnt != dataSize) Assert.True(false, string.Format(methodFailed + " > Saw expected count? Saw = {0}, expect = {1}: FAILED", cnt, dataSize)); } // // SelectMany // [Fact] public static void RunSelectManyTest1() { RunSelectManyTest1Core(0, 0); RunSelectManyTest1Core(1, 0); RunSelectManyTest1Core(0, 1); RunSelectManyTest1Core(1, 1); RunSelectManyTest1Core(32, 32); } [Fact] [OuterLoop] public static void RunSelectManyTest1_LongRunning() { RunSelectManyTest1Core(1024 * 2, 1024); RunSelectManyTest1Core(1024, 1024 * 2); RunSelectManyTest1Core(1024 * 2, 1024 * 2); } [Fact] public static void RunSelectManyTest2() { RunSelectManyTest2Core(0, 0); RunSelectManyTest2Core(1, 0); RunSelectManyTest2Core(0, 1); RunSelectManyTest2Core(1, 1); RunSelectManyTest2Core(32, 32); } [Fact] [OuterLoop] public static void RunSelectManyTest2_LongRunning() { RunSelectManyTest2Core(1024 * 2, 1024); RunSelectManyTest2Core(1024, 1024 * 2); RunSelectManyTest2Core(1024 * 2, 1024 * 2); } [Fact] public static void RunSelectManyTest3() { RunSelectManyTest3Core(10, ParallelExecutionMode.Default); RunSelectManyTest3Core(123, ParallelExecutionMode.Default); RunSelectManyTest3Core(10, ParallelExecutionMode.ForceParallelism); RunSelectManyTest3Core(123, ParallelExecutionMode.ForceParallelism); } private static void RunSelectManyTest1Core(int outerSize, int innerSize) { string methodFailed = string.Format("RunSelectManyTest1(outerSize = {0}, innerSize = {1}) - async/pipeline: FAILED. ", outerSize, innerSize); int[] left = new int[outerSize]; int[] right = new int[innerSize]; for (int i = 0; i < left.Length; i++) left[i] = i; for (int i = 0; i < right.Length; i++) right[i] = i * 8; //Assert.True(false, string.Format(" > Invoking SelectMany of {0} outer elems with {1} inner elems", left.Length, right.Length)); IEnumerable<int> results = left.AsParallel().AsOrdered().SelectMany<int, int, int>(x => right.AsParallel(), delegate (int x, int y) { return x + y; }); // Just validate the count. int cnt = 0; foreach (int p in results) cnt++; int expect = outerSize * innerSize; if (cnt != expect) Assert.True(false, string.Format(methodFailed + " > Saw expected count? Saw = {0}, expect = {1}: FAILED", cnt, expect)); } private static void RunSelectManyTest2Core(int outerSize, int innerSize) { string methodFailed = string.Format("RunSelectManyTest2(outerSize = {0}, innerSize = {1}) - sync/ no pipeline: FAILED. ", outerSize, innerSize); int[] left = new int[outerSize]; int[] right = new int[innerSize]; for (int i = 0; i < left.Length; i++) left[i] = i; for (int i = 0; i < right.Length; i++) right[i] = i * 8; //Assert.True(false, string.Format(" > Invoking SelectMany of {0} outer elems with {1} inner elems", left.Length, right.Length)); ParallelQuery<int> results = left.AsParallel().AsOrdered().SelectMany<int, int, int>(x => right.AsParallel(), delegate (int x, int y) { return x + y; }); List<int> r = results.ToList<int>(); // Just validate the count. int cnt = 0; foreach (int p in r) cnt++; int expect = outerSize * innerSize; if (cnt != expect) Assert.True(false, string.Format(methodFailed + " > Saw expected count? Saw = {0}, expect = {1}: FAILED.", cnt, expect)); } /// <summary> /// Tests OrderBy() followed by a SelectMany, where the outer input sequence /// contains duplicates. /// </summary> private static void RunSelectManyTest3Core(int size, ParallelExecutionMode mode) { int[] srcOuter = Enumerable.Repeat(0, size).ToArray(); int[] srcInner = Enumerable.Range(0, size).ToArray(); IEnumerable<int> query = srcOuter.AsParallel() .WithExecutionMode(mode) .OrderBy(x => x) .SelectMany(x => srcInner); int next = 0; foreach (var x in query) { if (x != next) { Assert.True(false, string.Format("RunSelectManyTest3(size = {2}: FAILED. expected {0} got {1}", next, x, size)); } next = (next + 1) % size; } } #region Helper Classes / Methods //----------------------------------------------------------------------------------- // A pair just wraps two bits of data into a single addressable unit. This is a // value type to ensure it remains very lightweight, since it is frequently used // with other primitive data types as well. // // Note: this class is another copy of the Pair<T, U> class defined in CommonDataTypes.cs. // For now, we have a copy of the class here, because we can't import the System.Linq.Parallel // namespace. // private struct Pair<T, U> { // The first and second bits of data. internal T m_first; internal U m_second; //----------------------------------------------------------------------------------- // A simple constructor that initializes the first/second fields. // public Pair(T first, U second) { m_first = first; m_second = second; } //----------------------------------------------------------------------------------- // Accessors for the left and right data. // public T First { get { return m_first; } set { m_first = value; } } public U Second { get { return m_second; } set { m_second = value; } } } #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! namespace Google.Cloud.Compute.V1.Snippets { using Google.Api.Gax; using System; using System.Linq; using System.Threading.Tasks; using lro = Google.LongRunning; /// <summary>Generated snippets.</summary> public sealed class GeneratedRegionTargetHttpProxiesClientSnippets { /// <summary>Snippet for Delete</summary> public void DeleteRequestObject() { // Snippet: Delete(DeleteRegionTargetHttpProxyRequest, CallSettings) // Create client RegionTargetHttpProxiesClient regionTargetHttpProxiesClient = RegionTargetHttpProxiesClient.Create(); // Initialize request argument(s) DeleteRegionTargetHttpProxyRequest request = new DeleteRegionTargetHttpProxyRequest { RequestId = "", Region = "", TargetHttpProxy = "", Project = "", }; // Make the request lro::Operation<Operation, Operation> response = regionTargetHttpProxiesClient.Delete(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = regionTargetHttpProxiesClient.PollOnceDelete(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteRequestObjectAsync() { // Snippet: DeleteAsync(DeleteRegionTargetHttpProxyRequest, CallSettings) // Additional: DeleteAsync(DeleteRegionTargetHttpProxyRequest, CancellationToken) // Create client RegionTargetHttpProxiesClient regionTargetHttpProxiesClient = await RegionTargetHttpProxiesClient.CreateAsync(); // Initialize request argument(s) DeleteRegionTargetHttpProxyRequest request = new DeleteRegionTargetHttpProxyRequest { RequestId = "", Region = "", TargetHttpProxy = "", Project = "", }; // Make the request lro::Operation<Operation, Operation> response = await regionTargetHttpProxiesClient.DeleteAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await regionTargetHttpProxiesClient.PollOnceDeleteAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Delete</summary> public void Delete() { // Snippet: Delete(string, string, string, CallSettings) // Create client RegionTargetHttpProxiesClient regionTargetHttpProxiesClient = RegionTargetHttpProxiesClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; string targetHttpProxy = ""; // Make the request lro::Operation<Operation, Operation> response = regionTargetHttpProxiesClient.Delete(project, region, targetHttpProxy); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = regionTargetHttpProxiesClient.PollOnceDelete(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteAsync() { // Snippet: DeleteAsync(string, string, string, CallSettings) // Additional: DeleteAsync(string, string, string, CancellationToken) // Create client RegionTargetHttpProxiesClient regionTargetHttpProxiesClient = await RegionTargetHttpProxiesClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; string targetHttpProxy = ""; // Make the request lro::Operation<Operation, Operation> response = await regionTargetHttpProxiesClient.DeleteAsync(project, region, targetHttpProxy); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await regionTargetHttpProxiesClient.PollOnceDeleteAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Get</summary> public void GetRequestObject() { // Snippet: Get(GetRegionTargetHttpProxyRequest, CallSettings) // Create client RegionTargetHttpProxiesClient regionTargetHttpProxiesClient = RegionTargetHttpProxiesClient.Create(); // Initialize request argument(s) GetRegionTargetHttpProxyRequest request = new GetRegionTargetHttpProxyRequest { Region = "", TargetHttpProxy = "", Project = "", }; // Make the request TargetHttpProxy response = regionTargetHttpProxiesClient.Get(request); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetRequestObjectAsync() { // Snippet: GetAsync(GetRegionTargetHttpProxyRequest, CallSettings) // Additional: GetAsync(GetRegionTargetHttpProxyRequest, CancellationToken) // Create client RegionTargetHttpProxiesClient regionTargetHttpProxiesClient = await RegionTargetHttpProxiesClient.CreateAsync(); // Initialize request argument(s) GetRegionTargetHttpProxyRequest request = new GetRegionTargetHttpProxyRequest { Region = "", TargetHttpProxy = "", Project = "", }; // Make the request TargetHttpProxy response = await regionTargetHttpProxiesClient.GetAsync(request); // End snippet } /// <summary>Snippet for Get</summary> public void Get() { // Snippet: Get(string, string, string, CallSettings) // Create client RegionTargetHttpProxiesClient regionTargetHttpProxiesClient = RegionTargetHttpProxiesClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; string targetHttpProxy = ""; // Make the request TargetHttpProxy response = regionTargetHttpProxiesClient.Get(project, region, targetHttpProxy); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetAsync() { // Snippet: GetAsync(string, string, string, CallSettings) // Additional: GetAsync(string, string, string, CancellationToken) // Create client RegionTargetHttpProxiesClient regionTargetHttpProxiesClient = await RegionTargetHttpProxiesClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; string targetHttpProxy = ""; // Make the request TargetHttpProxy response = await regionTargetHttpProxiesClient.GetAsync(project, region, targetHttpProxy); // End snippet } /// <summary>Snippet for Insert</summary> public void InsertRequestObject() { // Snippet: Insert(InsertRegionTargetHttpProxyRequest, CallSettings) // Create client RegionTargetHttpProxiesClient regionTargetHttpProxiesClient = RegionTargetHttpProxiesClient.Create(); // Initialize request argument(s) InsertRegionTargetHttpProxyRequest request = new InsertRegionTargetHttpProxyRequest { TargetHttpProxyResource = new TargetHttpProxy(), RequestId = "", Region = "", Project = "", }; // Make the request lro::Operation<Operation, Operation> response = regionTargetHttpProxiesClient.Insert(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = regionTargetHttpProxiesClient.PollOnceInsert(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InsertAsync</summary> public async Task InsertRequestObjectAsync() { // Snippet: InsertAsync(InsertRegionTargetHttpProxyRequest, CallSettings) // Additional: InsertAsync(InsertRegionTargetHttpProxyRequest, CancellationToken) // Create client RegionTargetHttpProxiesClient regionTargetHttpProxiesClient = await RegionTargetHttpProxiesClient.CreateAsync(); // Initialize request argument(s) InsertRegionTargetHttpProxyRequest request = new InsertRegionTargetHttpProxyRequest { TargetHttpProxyResource = new TargetHttpProxy(), RequestId = "", Region = "", Project = "", }; // Make the request lro::Operation<Operation, Operation> response = await regionTargetHttpProxiesClient.InsertAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await regionTargetHttpProxiesClient.PollOnceInsertAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Insert</summary> public void Insert() { // Snippet: Insert(string, string, TargetHttpProxy, CallSettings) // Create client RegionTargetHttpProxiesClient regionTargetHttpProxiesClient = RegionTargetHttpProxiesClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; TargetHttpProxy targetHttpProxyResource = new TargetHttpProxy(); // Make the request lro::Operation<Operation, Operation> response = regionTargetHttpProxiesClient.Insert(project, region, targetHttpProxyResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = regionTargetHttpProxiesClient.PollOnceInsert(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InsertAsync</summary> public async Task InsertAsync() { // Snippet: InsertAsync(string, string, TargetHttpProxy, CallSettings) // Additional: InsertAsync(string, string, TargetHttpProxy, CancellationToken) // Create client RegionTargetHttpProxiesClient regionTargetHttpProxiesClient = await RegionTargetHttpProxiesClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; TargetHttpProxy targetHttpProxyResource = new TargetHttpProxy(); // Make the request lro::Operation<Operation, Operation> response = await regionTargetHttpProxiesClient.InsertAsync(project, region, targetHttpProxyResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await regionTargetHttpProxiesClient.PollOnceInsertAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for List</summary> public void ListRequestObject() { // Snippet: List(ListRegionTargetHttpProxiesRequest, CallSettings) // Create client RegionTargetHttpProxiesClient regionTargetHttpProxiesClient = RegionTargetHttpProxiesClient.Create(); // Initialize request argument(s) ListRegionTargetHttpProxiesRequest request = new ListRegionTargetHttpProxiesRequest { Region = "", OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedEnumerable<TargetHttpProxyList, TargetHttpProxy> response = regionTargetHttpProxiesClient.List(request); // Iterate over all response items, lazily performing RPCs as required foreach (TargetHttpProxy item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (TargetHttpProxyList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TargetHttpProxy item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<TargetHttpProxy> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (TargetHttpProxy item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListRequestObjectAsync() { // Snippet: ListAsync(ListRegionTargetHttpProxiesRequest, CallSettings) // Create client RegionTargetHttpProxiesClient regionTargetHttpProxiesClient = await RegionTargetHttpProxiesClient.CreateAsync(); // Initialize request argument(s) ListRegionTargetHttpProxiesRequest request = new ListRegionTargetHttpProxiesRequest { Region = "", OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedAsyncEnumerable<TargetHttpProxyList, TargetHttpProxy> response = regionTargetHttpProxiesClient.ListAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((TargetHttpProxy item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((TargetHttpProxyList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TargetHttpProxy item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<TargetHttpProxy> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (TargetHttpProxy item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for List</summary> public void List() { // Snippet: List(string, string, string, int?, CallSettings) // Create client RegionTargetHttpProxiesClient regionTargetHttpProxiesClient = RegionTargetHttpProxiesClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; // Make the request PagedEnumerable<TargetHttpProxyList, TargetHttpProxy> response = regionTargetHttpProxiesClient.List(project, region); // Iterate over all response items, lazily performing RPCs as required foreach (TargetHttpProxy item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (TargetHttpProxyList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TargetHttpProxy item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<TargetHttpProxy> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (TargetHttpProxy item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListAsync() { // Snippet: ListAsync(string, string, string, int?, CallSettings) // Create client RegionTargetHttpProxiesClient regionTargetHttpProxiesClient = await RegionTargetHttpProxiesClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; // Make the request PagedAsyncEnumerable<TargetHttpProxyList, TargetHttpProxy> response = regionTargetHttpProxiesClient.ListAsync(project, region); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((TargetHttpProxy item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((TargetHttpProxyList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TargetHttpProxy item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<TargetHttpProxy> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (TargetHttpProxy item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for SetUrlMap</summary> public void SetUrlMapRequestObject() { // Snippet: SetUrlMap(SetUrlMapRegionTargetHttpProxyRequest, CallSettings) // Create client RegionTargetHttpProxiesClient regionTargetHttpProxiesClient = RegionTargetHttpProxiesClient.Create(); // Initialize request argument(s) SetUrlMapRegionTargetHttpProxyRequest request = new SetUrlMapRegionTargetHttpProxyRequest { RequestId = "", Region = "", TargetHttpProxy = "", Project = "", UrlMapReferenceResource = new UrlMapReference(), }; // Make the request lro::Operation<Operation, Operation> response = regionTargetHttpProxiesClient.SetUrlMap(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = regionTargetHttpProxiesClient.PollOnceSetUrlMap(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for SetUrlMapAsync</summary> public async Task SetUrlMapRequestObjectAsync() { // Snippet: SetUrlMapAsync(SetUrlMapRegionTargetHttpProxyRequest, CallSettings) // Additional: SetUrlMapAsync(SetUrlMapRegionTargetHttpProxyRequest, CancellationToken) // Create client RegionTargetHttpProxiesClient regionTargetHttpProxiesClient = await RegionTargetHttpProxiesClient.CreateAsync(); // Initialize request argument(s) SetUrlMapRegionTargetHttpProxyRequest request = new SetUrlMapRegionTargetHttpProxyRequest { RequestId = "", Region = "", TargetHttpProxy = "", Project = "", UrlMapReferenceResource = new UrlMapReference(), }; // Make the request lro::Operation<Operation, Operation> response = await regionTargetHttpProxiesClient.SetUrlMapAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await regionTargetHttpProxiesClient.PollOnceSetUrlMapAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for SetUrlMap</summary> public void SetUrlMap() { // Snippet: SetUrlMap(string, string, string, UrlMapReference, CallSettings) // Create client RegionTargetHttpProxiesClient regionTargetHttpProxiesClient = RegionTargetHttpProxiesClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; string targetHttpProxy = ""; UrlMapReference urlMapReferenceResource = new UrlMapReference(); // Make the request lro::Operation<Operation, Operation> response = regionTargetHttpProxiesClient.SetUrlMap(project, region, targetHttpProxy, urlMapReferenceResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = regionTargetHttpProxiesClient.PollOnceSetUrlMap(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for SetUrlMapAsync</summary> public async Task SetUrlMapAsync() { // Snippet: SetUrlMapAsync(string, string, string, UrlMapReference, CallSettings) // Additional: SetUrlMapAsync(string, string, string, UrlMapReference, CancellationToken) // Create client RegionTargetHttpProxiesClient regionTargetHttpProxiesClient = await RegionTargetHttpProxiesClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; string targetHttpProxy = ""; UrlMapReference urlMapReferenceResource = new UrlMapReference(); // Make the request lro::Operation<Operation, Operation> response = await regionTargetHttpProxiesClient.SetUrlMapAsync(project, region, targetHttpProxy, urlMapReferenceResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await regionTargetHttpProxiesClient.PollOnceSetUrlMapAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.ServiceModel.Dispatcher { using System.Collections; using System.Collections.Generic; using System.Runtime; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.Xml; using System.Linq; static class DataContractSerializerDefaults { internal const bool IgnoreExtensionDataObject = false; internal const int MaxItemsInObjectGraph = int.MaxValue; internal static DataContractSerializer CreateSerializer(Type type, int maxItems) { return CreateSerializer(type, null, maxItems); } internal static DataContractSerializer CreateSerializer(Type type, IList<Type> knownTypes, int maxItems) { return new DataContractSerializer( type, knownTypes, maxItems, DataContractSerializerDefaults.IgnoreExtensionDataObject, false/*preserveObjectReferences*/, null/*dataContractSurrage*/); } internal static DataContractSerializer CreateSerializer(Type type, string rootName, string rootNs, int maxItems) { return CreateSerializer(type, null, rootName, rootNs, maxItems); } internal static DataContractSerializer CreateSerializer(Type type, IList<Type> knownTypes, string rootName, string rootNs, int maxItems) { return new DataContractSerializer( type, rootName, rootNs, knownTypes, maxItems, DataContractSerializerDefaults.IgnoreExtensionDataObject, false/*preserveObjectReferences*/, null/*dataContractSurrage*/); } internal static DataContractSerializer CreateSerializer(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNs, int maxItems) { return CreateSerializer(type, null, rootName, rootNs, maxItems); } internal static DataContractSerializer CreateSerializer(Type type, IList<Type> knownTypes, XmlDictionaryString rootName, XmlDictionaryString rootNs, int maxItems) { return new DataContractSerializer( type, rootName, rootNs, knownTypes, maxItems, DataContractSerializerDefaults.IgnoreExtensionDataObject, false/*preserveObjectReferences*/, null/*dataContractSurrage*/); } } class DataContractSerializerOperationFormatter : OperationFormatter { static Type typeOfIQueryable = typeof(IQueryable); static Type typeOfIQueryableGeneric = typeof(IQueryable<>); static Type typeOfIEnumerable = typeof(IEnumerable); static Type typeOfIEnumerableGeneric = typeof(IEnumerable<>); protected MessageInfo requestMessageInfo; protected MessageInfo replyMessageInfo; IList<Type> knownTypes; XsdDataContractExporter dataContractExporter; DataContractSerializerOperationBehavior serializerFactory; public DataContractSerializerOperationFormatter(OperationDescription description, DataContractFormatAttribute dataContractFormatAttribute, DataContractSerializerOperationBehavior serializerFactory) : base(description, dataContractFormatAttribute.Style == OperationFormatStyle.Rpc, false/*isEncoded*/) { if (description == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("description"); this.serializerFactory = serializerFactory ?? new DataContractSerializerOperationBehavior(description); foreach (Type type in description.KnownTypes) { if (knownTypes == null) knownTypes = new List<Type>(); if (type == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxKnownTypeNull, description.Name))); ValidateDataContractType(type); knownTypes.Add(type); } requestMessageInfo = CreateMessageInfo(dataContractFormatAttribute, RequestDescription, this.serializerFactory); if (ReplyDescription != null) replyMessageInfo = CreateMessageInfo(dataContractFormatAttribute, ReplyDescription, this.serializerFactory); } MessageInfo CreateMessageInfo(DataContractFormatAttribute dataContractFormatAttribute, MessageDescription messageDescription, DataContractSerializerOperationBehavior serializerFactory) { if (messageDescription.IsUntypedMessage) return null; MessageInfo messageInfo = new MessageInfo(); MessageBodyDescription body = messageDescription.Body; if (body.WrapperName != null) { messageInfo.WrapperName = AddToDictionary(body.WrapperName); messageInfo.WrapperNamespace = AddToDictionary(body.WrapperNamespace); } MessagePartDescriptionCollection parts = body.Parts; messageInfo.BodyParts = new PartInfo[parts.Count]; for (int i = 0; i < parts.Count; i++) messageInfo.BodyParts[i] = CreatePartInfo(parts[i], dataContractFormatAttribute.Style, serializerFactory); if (IsValidReturnValue(messageDescription.Body.ReturnValue)) messageInfo.ReturnPart = CreatePartInfo(messageDescription.Body.ReturnValue, dataContractFormatAttribute.Style, serializerFactory); messageInfo.HeaderDescriptionTable = new MessageHeaderDescriptionTable(); messageInfo.HeaderParts = new PartInfo[messageDescription.Headers.Count]; for (int i = 0; i < messageDescription.Headers.Count; i++) { MessageHeaderDescription headerDescription = messageDescription.Headers[i]; if (headerDescription.IsUnknownHeaderCollection) messageInfo.UnknownHeaderDescription = headerDescription; else { ValidateDataContractType(headerDescription.Type); messageInfo.HeaderDescriptionTable.Add(headerDescription.Name, headerDescription.Namespace, headerDescription); } messageInfo.HeaderParts[i] = CreatePartInfo(headerDescription, OperationFormatStyle.Document, serializerFactory); } messageInfo.AnyHeaders = messageInfo.UnknownHeaderDescription != null || messageInfo.HeaderDescriptionTable.Count > 0; return messageInfo; } private void ValidateDataContractType(Type type) { if (dataContractExporter == null) { dataContractExporter = new XsdDataContractExporter(); if (serializerFactory != null && serializerFactory.DataContractSurrogate != null) { ExportOptions options = new ExportOptions(); options.DataContractSurrogate = serializerFactory.DataContractSurrogate; dataContractExporter.Options = options; } } dataContractExporter.GetSchemaTypeName(type); //Throws if the type is not a valid data contract } PartInfo CreatePartInfo(MessagePartDescription part, OperationFormatStyle style, DataContractSerializerOperationBehavior serializerFactory) { string ns = (style == OperationFormatStyle.Rpc || part.Namespace == null) ? string.Empty : part.Namespace; PartInfo partInfo = new PartInfo(part, AddToDictionary(part.Name), AddToDictionary(ns), knownTypes, serializerFactory); ValidateDataContractType(partInfo.ContractType); return partInfo; } protected override void AddHeadersToMessage(Message message, MessageDescription messageDescription, object[] parameters, bool isRequest) { MessageInfo messageInfo = isRequest ? requestMessageInfo : replyMessageInfo; PartInfo[] headerParts = messageInfo.HeaderParts; if (headerParts == null || headerParts.Length == 0) return; MessageHeaders headers = message.Headers; for (int i = 0; i < headerParts.Length; i++) { PartInfo headerPart = headerParts[i]; MessageHeaderDescription headerDescription = (MessageHeaderDescription)headerPart.Description; object headerValue = parameters[headerDescription.Index]; if (headerDescription.Multiple) { if (headerValue != null) { bool isXmlElement = headerDescription.Type == typeof(XmlElement); foreach (object headerItemValue in (IEnumerable)headerValue) AddMessageHeaderForParameter(headers, headerPart, message.Version, headerItemValue, isXmlElement); } } else AddMessageHeaderForParameter(headers, headerPart, message.Version, headerValue, false/*isXmlElement*/); } } void AddMessageHeaderForParameter(MessageHeaders headers, PartInfo headerPart, MessageVersion messageVersion, object parameterValue, bool isXmlElement) { string actor; bool mustUnderstand; bool relay; MessageHeaderDescription headerDescription = (MessageHeaderDescription)headerPart.Description; object valueToSerialize = GetContentOfMessageHeaderOfT(headerDescription, parameterValue, out mustUnderstand, out relay, out actor); if (isXmlElement) { if (valueToSerialize == null) return; XmlElement xmlElement = (XmlElement)valueToSerialize; headers.Add(new XmlElementMessageHeader(this, messageVersion, xmlElement.LocalName, xmlElement.NamespaceURI, mustUnderstand, actor, relay, xmlElement)); return; } headers.Add(new DataContractSerializerMessageHeader(headerPart, valueToSerialize, mustUnderstand, actor, relay)); } protected override void SerializeBody(XmlDictionaryWriter writer, MessageVersion version, string action, MessageDescription messageDescription, object returnValue, object[] parameters, bool isRequest) { if (writer == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("writer")); if (parameters == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("parameters")); MessageInfo messageInfo; if (isRequest) messageInfo = requestMessageInfo; else messageInfo = replyMessageInfo; if (messageInfo.WrapperName != null) writer.WriteStartElement(messageInfo.WrapperName, messageInfo.WrapperNamespace); if (messageInfo.ReturnPart != null) SerializeParameter(writer, messageInfo.ReturnPart, returnValue); SerializeParameters(writer, messageInfo.BodyParts, parameters); if (messageInfo.WrapperName != null) writer.WriteEndElement(); } void SerializeParameters(XmlDictionaryWriter writer, PartInfo[] parts, object[] parameters) { for (int i = 0; i < parts.Length; i++) { PartInfo part = parts[i]; object graph = parameters[part.Description.Index]; SerializeParameter(writer, part, graph); } } void SerializeParameter(XmlDictionaryWriter writer, PartInfo part, object graph) { if (part.Description.Multiple) { if (graph != null) { foreach (object item in (IEnumerable)graph) SerializeParameterPart(writer, part, item); } } else SerializeParameterPart(writer, part, graph); } void SerializeParameterPart(XmlDictionaryWriter writer, PartInfo part, object graph) { try { part.Serializer.WriteObject(writer, graph); } catch (SerializationException sx) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException( SR.GetString(SR.SFxInvalidMessageBodyErrorSerializingParameter, part.Description.Namespace, part.Description.Name, sx.Message), sx)); } } protected override void GetHeadersFromMessage(Message message, MessageDescription messageDescription, object[] parameters, bool isRequest) { MessageInfo messageInfo = isRequest ? requestMessageInfo : replyMessageInfo; if (!messageInfo.AnyHeaders) return; MessageHeaders headers = message.Headers; KeyValuePair<Type, ArrayList>[] multipleHeaderValues = null; ArrayList elementList = null; if (messageInfo.UnknownHeaderDescription != null) elementList = new ArrayList(); for (int i = 0; i < headers.Count; i++) { MessageHeaderInfo header = headers[i]; MessageHeaderDescription headerDescription = messageInfo.HeaderDescriptionTable.Get(header.Name, header.Namespace); if (headerDescription != null) { if (header.MustUnderstand) headers.UnderstoodHeaders.Add(header); object item = null; XmlDictionaryReader headerReader = headers.GetReaderAtHeader(i); try { object dataValue = DeserializeHeaderContents(headerReader, messageDescription, headerDescription); if (headerDescription.TypedHeader) item = TypedHeaderManager.Create(headerDescription.Type, dataValue, headers[i].MustUnderstand, headers[i].Relay, headers[i].Actor); else item = dataValue; } finally { headerReader.Close(); } if (headerDescription.Multiple) { if (multipleHeaderValues == null) multipleHeaderValues = new KeyValuePair<Type, ArrayList>[parameters.Length]; if (multipleHeaderValues[headerDescription.Index].Key == null) { multipleHeaderValues[headerDescription.Index] = new KeyValuePair<System.Type, System.Collections.ArrayList>(headerDescription.TypedHeader ? TypedHeaderManager.GetMessageHeaderType(headerDescription.Type) : headerDescription.Type, new ArrayList()); } multipleHeaderValues[headerDescription.Index].Value.Add(item); } else parameters[headerDescription.Index] = item; } else if (messageInfo.UnknownHeaderDescription != null) { MessageHeaderDescription unknownHeaderDescription = messageInfo.UnknownHeaderDescription; XmlDictionaryReader headerReader = headers.GetReaderAtHeader(i); try { XmlDocument doc = new XmlDocument(); object dataValue = doc.ReadNode(headerReader); if (dataValue != null && unknownHeaderDescription.TypedHeader) dataValue = TypedHeaderManager.Create(unknownHeaderDescription.Type, dataValue, headers[i].MustUnderstand, headers[i].Relay, headers[i].Actor); elementList.Add(dataValue); } finally { headerReader.Close(); } } } if (multipleHeaderValues != null) { for (int i = 0; i < parameters.Length; i++) { if (multipleHeaderValues[i].Key != null) parameters[i] = multipleHeaderValues[i].Value.ToArray(multipleHeaderValues[i].Key); } } if (messageInfo.UnknownHeaderDescription != null) parameters[messageInfo.UnknownHeaderDescription.Index] = elementList.ToArray(messageInfo.UnknownHeaderDescription.TypedHeader ? typeof(MessageHeader<XmlElement>) : typeof(XmlElement)); } object DeserializeHeaderContents(XmlDictionaryReader reader, MessageDescription messageDescription, MessageHeaderDescription headerDescription) { bool isQueryable; Type dataContractType = DataContractSerializerOperationFormatter.GetSubstituteDataContractType(headerDescription.Type, out isQueryable); XmlObjectSerializer serializerLocal = serializerFactory.CreateSerializer(dataContractType, headerDescription.Name, headerDescription.Namespace, this.knownTypes); object val = serializerLocal.ReadObject(reader); if (isQueryable && val != null) { return Queryable.AsQueryable((IEnumerable)val); } return val; } protected override object DeserializeBody(XmlDictionaryReader reader, MessageVersion version, string action, MessageDescription messageDescription, object[] parameters, bool isRequest) { if (reader == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader")); if (parameters == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("parameters")); MessageInfo messageInfo; if (isRequest) messageInfo = requestMessageInfo; else messageInfo = replyMessageInfo; if (messageInfo.WrapperName != null) { if (!reader.IsStartElement(messageInfo.WrapperName, messageInfo.WrapperNamespace)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString(SR.SFxInvalidMessageBody, messageInfo.WrapperName, messageInfo.WrapperNamespace, reader.NodeType, reader.Name, reader.NamespaceURI))); bool isEmptyElement = reader.IsEmptyElement; reader.Read(); if (isEmptyElement) return null; } object returnValue = null; if (messageInfo.ReturnPart != null) { while (true) { PartInfo part = messageInfo.ReturnPart; if (part.Serializer.IsStartObject(reader)) { returnValue = DeserializeParameter(reader, part, isRequest); break; } if (!reader.IsStartElement()) break; OperationFormatter.TraceAndSkipElement(reader); } } DeserializeParameters(reader, messageInfo.BodyParts, parameters, isRequest); if (messageInfo.WrapperName != null) reader.ReadEndElement(); return returnValue; } void DeserializeParameters(XmlDictionaryReader reader, PartInfo[] parts, object[] parameters, bool isRequest) { int nextPartIndex = 0; while (reader.IsStartElement()) { for (int i = nextPartIndex; i < parts.Length; i++) { PartInfo part = parts[i]; if (part.Serializer.IsStartObject(reader)) { object parameterValue = DeserializeParameter(reader, part, isRequest); parameters[part.Description.Index] = parameterValue; nextPartIndex = i + 1; } else parameters[part.Description.Index] = null; } if (reader.IsStartElement()) OperationFormatter.TraceAndSkipElement(reader); } } object DeserializeParameter(XmlDictionaryReader reader, PartInfo part, bool isRequest) { if (part.Description.Multiple) { ArrayList items = new ArrayList(); while (part.Serializer.IsStartObject(reader)) items.Add(DeserializeParameterPart(reader, part, isRequest)); return items.ToArray(part.Description.Type); } return DeserializeParameterPart(reader, part, isRequest); } object DeserializeParameterPart(XmlDictionaryReader reader, PartInfo part, bool isRequest) { object val; try { val = part.ReadObject(reader); } catch (System.InvalidOperationException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.SFxInvalidMessageBodyErrorDeserializingParameter, part.Description.Namespace, part.Description.Name), e)); } catch (System.Runtime.Serialization.InvalidDataContractException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException( SR.GetString(SR.SFxInvalidMessageBodyErrorDeserializingParameter, part.Description.Namespace, part.Description.Name), e)); } catch (System.FormatException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( OperationFormatter.CreateDeserializationFailedFault( SR.GetString(SR.SFxInvalidMessageBodyErrorDeserializingParameterMore, part.Description.Namespace, part.Description.Name, e.Message), e)); } catch (System.Runtime.Serialization.SerializationException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( OperationFormatter.CreateDeserializationFailedFault( SR.GetString(SR.SFxInvalidMessageBodyErrorDeserializingParameterMore, part.Description.Namespace, part.Description.Name, e.Message), e)); } return val; } internal static Type GetSubstituteDataContractType(Type type, out bool isQueryable) { if (type == typeOfIQueryable) { isQueryable = true; return typeOfIEnumerable; } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeOfIQueryableGeneric) { isQueryable = true; return typeOfIEnumerableGeneric.MakeGenericType(type.GetGenericArguments()); } isQueryable = false; return type; } class DataContractSerializerMessageHeader : XmlObjectSerializerHeader { PartInfo headerPart; public DataContractSerializerMessageHeader(PartInfo headerPart, object headerValue, bool mustUnderstand, string actor, bool relay) : base(headerPart.DictionaryName.Value, headerPart.DictionaryNamespace.Value, headerValue, headerPart.Serializer, mustUnderstand, actor ?? string.Empty, relay) { this.headerPart = headerPart; } protected override void OnWriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion) { //Prefix needed since there may be xsi:type attribute at toplevel with qname value where ns = "" string prefix = (this.Namespace == null || this.Namespace.Length == 0) ? string.Empty : "h"; writer.WriteStartElement(prefix, headerPart.DictionaryName, headerPart.DictionaryNamespace); WriteHeaderAttributes(writer, messageVersion); } } protected class MessageInfo { internal PartInfo[] HeaderParts; internal XmlDictionaryString WrapperName; internal XmlDictionaryString WrapperNamespace; internal PartInfo[] BodyParts; internal PartInfo ReturnPart; internal MessageHeaderDescriptionTable HeaderDescriptionTable; internal MessageHeaderDescription UnknownHeaderDescription; internal bool AnyHeaders; } protected class PartInfo { XmlDictionaryString dictionaryName; XmlDictionaryString dictionaryNamespace; MessagePartDescription description; XmlObjectSerializer serializer; IList<Type> knownTypes; DataContractSerializerOperationBehavior serializerFactory; Type contractType; bool isQueryable; public PartInfo(MessagePartDescription description, XmlDictionaryString dictionaryName, XmlDictionaryString dictionaryNamespace, IList<Type> knownTypes, DataContractSerializerOperationBehavior behavior) { this.dictionaryName = dictionaryName; this.dictionaryNamespace = dictionaryNamespace; this.description = description; this.knownTypes = knownTypes; this.serializerFactory = behavior; this.contractType = DataContractSerializerOperationFormatter.GetSubstituteDataContractType(description.Type, out this.isQueryable); } public Type ContractType { get { return this.contractType; } } public MessagePartDescription Description { get { return description; } } public XmlDictionaryString DictionaryName { get { return dictionaryName; } } public XmlDictionaryString DictionaryNamespace { get { return dictionaryNamespace; } } public XmlObjectSerializer Serializer { get { if (serializer == null) { serializer = serializerFactory.CreateSerializer(contractType, DictionaryName, DictionaryNamespace, knownTypes); } return serializer; } } public object ReadObject(XmlDictionaryReader reader) { return this.ReadObject(reader, this.Serializer); } public object ReadObject(XmlDictionaryReader reader, XmlObjectSerializer serializer) { object val = this.serializer.ReadObject(reader, false /* verifyObjectName */); if (this.isQueryable && val != null) { return Queryable.AsQueryable((IEnumerable)val); } return val; } } } }
/* Copyright 2012 Michael Edwards Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //-CRE- using System; using System.Collections.Concurrent; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Web; using Glass.Mapper.Pipelines.ConfigurationResolver.Tasks.OnDemandResolver; using Glass.Mapper.Sc.Configuration; using Glass.Mapper.Sc.Fields; using Glass.Mapper.Sc.Pipelines.GetChromeData; using Glass.Mapper.Sc.RenderField; using Glass.Mapper.Sc.Web.Ui; using Sitecore.Collections; using Sitecore.Data; using Sitecore.Data.Events; using Sitecore.Data.Items; using Sitecore.Diagnostics; using Sitecore.Pipelines; using Sitecore.Pipelines.RenderField; using Sitecore.SecurityModel; using Sitecore.Text; using Sitecore.Web; namespace Glass.Mapper.Sc { /// <summary> /// This class contains a set of helpers that make converting items mapped in Glass.Sitecore.Mapper to HTML /// </summary> public class GlassHtml : IGlassHtml { private static readonly Type ImageType = typeof(Image); private static readonly Type LinkType = typeof(Link); private static ConcurrentDictionary<string, object> _compileCache = new ConcurrentDictionary<string, object>(); private readonly Context _context; static GlassHtml() { } public const string Parameters = "Parameters"; /// <summary> /// The image width /// </summary> public const string ImageWidth = "width"; /// <summary> /// The image height /// </summary> public const string ImageHeight = "height"; /// <summary> /// The image tag format /// </summary> public static string ImageTagFormat = "<img src={2}{0}{2} {1}/>"; public static string LinkTagFormat = "<a href={3}{0}{3} {1}>{2}"; public static string QuotationMark = "'"; protected Func<T, string> GetCompiled<T>(Expression<Func<T, string>> expression) { if (!SitecoreContext.Config.UseGlassHtmlLambdaCache) { return expression.Compile(); } var key = typeof(T).FullName + expression.Body; if (_compileCache.ContainsKey(key)) { return (Func<T, string>)_compileCache[key]; } var compiled = expression.Compile(); _compileCache.TryAdd(key, compiled); return compiled; } protected Func<T, object> GetCompiled<T>(Expression<Func<T, object>> expression) { if (SitecoreContext.Config == null || !SitecoreContext.Config.UseGlassHtmlLambdaCache) { return expression.Compile(); } var key = typeof(T).FullName + expression.Body; if (_compileCache.ContainsKey(key)) { return (Func<T, object>)_compileCache[key]; } var compiled = expression.Compile(); _compileCache.TryAdd(key, compiled); return compiled; } /// <summary> /// Gets the sitecore context. /// </summary> /// <value> /// The sitecore context. /// </value> public ISitecoreContext SitecoreContext { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="GlassHtml"/> class. /// </summary> /// <param name="sitecoreContext">The service that will be used to load and save data</param> public GlassHtml(ISitecoreContext sitecoreContext) { SitecoreContext = sitecoreContext; _context = sitecoreContext.GlassContext; } /// <summary> /// Edits the frame. /// </summary> /// <param name="buttons">The buttons.</param> /// <param name="path">The path.</param> /// <param name="output">The output text writer</param> /// <param name="title">The title for the edit frame</param> /// <returns> /// GlassEditFrame. /// </returns> public GlassEditFrame EditFrame(string title, string buttons, string path = null, TextWriter output = null) { if (output == null) { output = HttpContext.Current.Response.Output; } var frame = new GlassEditFrame(title, buttons, output, path); frame.RenderFirstPart(); return frame; } public GlassEditFrame EditFrame<T>(T model, string title = null, TextWriter output = null, params Expression<Func<T, object>>[] fields) where T : class { if (IsInEditingMode && Sitecore.Context.IsLoggedIn && model != null) { if (fields.Any()) { var fieldIdsOrNames = fields.Select(x => Mapper.Utilities.GetGlassProperty<T, SitecoreTypeConfiguration>(x, this.SitecoreContext.GlassContext, model)) .Cast<SitecoreFieldConfiguration>() .Where(x => x != null) .Select(x => x.FieldId != (ID)null ? x.FieldId.ToString() : x.FieldName); var buttonPath = "{0}{1}".Formatted( EditFrameBuilder.BuildToken, string.Join("|", fieldIdsOrNames)); if (title.IsNotNullOrEmpty()) { buttonPath += "<title>{0}<title>".Formatted(title); } var field = fields.FirstOrDefault(); var config = Mapper.Utilities.GetTypeConfig<T, SitecoreTypeConfiguration>(field, SitecoreContext.GlassContext, model); var pathConfig = config.Properties .OfType<SitecoreInfoConfiguration>() .FirstOrDefault(x => x.Type == SitecoreInfoType.Path); var path = string.Empty; if (pathConfig == null) { var id = config.GetId(model); if (id == ID.Null) { throw new MapperException( "Failed to find ID. Ensure that you have an ID property on your model."); } var item = SitecoreContext.Database.GetItem(id); path = item.Paths.Path; } else { path = pathConfig.PropertyGetter(model) as string; } return EditFrame(title, buttonPath, path, output); } } return new GlassNullEditFrame(); } /// <summary> /// Makes the field editable using the Sitecore Page Editor. Using the specifed service to write data. /// </summary> /// <typeparam name="T">A class loaded by Glass.Sitecore.Mapper</typeparam> /// <param name="target">The model object that contains the item to be edited</param> /// <param name="field">The field that should be made editable</param> /// <param name="parameters">Additional rendering parameters, e.g. ImageParameters</param> /// <returns>HTML output to either render the editable controls or normal HTML</returns> public virtual string Editable<T>(T target, Expression<Func<T, object>> field, object parameters = null) { return MakeEditable(field, null, target, parameters); } /// <summary> /// Makes the field editable using the Sitecore Page Editor. Using the specifed service to write data. /// </summary> /// <typeparam name="T">A class loaded by Glass.Sitecore.Mapper</typeparam> /// <param name="target">The model object that contains the item to be edited</param> /// <param name="field">The field that should be made editable</param> /// <param name="standardOutput">The output to display when the Sitecore Page Editor is not being used</param> /// <param name="parameters">Additional rendering parameters, e.g. ImageParameters</param> /// <returns>HTML output to either render the editable controls or normal HTML</returns> public virtual string Editable<T>(T target, Expression<Func<T, object>> field, Expression<Func<T, string>> standardOutput, object parameters = null) { return MakeEditable(field, standardOutput, target, parameters); } public virtual T GetRenderingParameters<T>(string parameters, ID renderParametersTemplateId) where T : class { var nameValueCollection = WebUtil.ParseUrlParameters(parameters); return GetRenderingParameters<T>(nameValueCollection, renderParametersTemplateId); } public T GetRenderingParameters<T>(NameValueCollection parameters, ID renderParametersTemplateId) where T : class { var item = Utilities.CreateFakeItem(null, renderParametersTemplateId, SitecoreContext.Database, "renderingParameters"); using (new SecurityDisabler()) { using (new EventDisabler()) { using (new VersionCountDisabler()) { item.Editing.BeginEdit(); foreach (var key in parameters.AllKeys) { item[key] = parameters[key]; } T obj = SitecoreContext.Cast<T>(item); item.Editing.EndEdit(); item.Delete(); //added for clean up return obj; } } } } /// <summary> /// Converts rendering parameters to a concrete type. Use this method if you have defined the template ID on the /// model configuration. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="parameters"></param> /// <returns></returns> public virtual T GetRenderingParameters<T>(string parameters) where T : class { if (String.IsNullOrEmpty(parameters)) { return default(T); } var nameValueCollection = WebUtil.ParseUrlParameters(parameters); return GetRenderingParameters<T>(nameValueCollection); } /// <summary> /// Converts rendering parameters to a concrete type. Use this method if you have defined the template ID on the /// model configuration. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="parameters"></param> /// <returns></returns> public virtual T GetRenderingParameters<T>(NameValueCollection parameters) where T : class { if (parameters == null) { return default(T); } var config = SitecoreContext.GlassContext[typeof(T)] as SitecoreTypeConfiguration; if (config == null) { SitecoreContext.GlassContext.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(T))); } config = SitecoreContext.GlassContext[typeof(T)] as SitecoreTypeConfiguration; return GetRenderingParameters<T>(parameters, config.TemplateId); } public virtual RenderingResult BeginRenderLink<T>(T model, Expression<Func<T, object>> field, TextWriter writer, object parameters = null, bool isEditable = false) { NameValueCollection attrs; if (parameters is NameValueCollection) { attrs = parameters as NameValueCollection; } else { attrs = Utilities.GetPropertiesCollection(parameters, true); } if (IsInEditingMode && isEditable) { if (attrs != null) { attrs.Add("haschildren", "true"); return MakeEditable(field, null, model, attrs, _context, SitecoreContext.Database, writer); } return MakeEditable(field, null, model, "haschildren=true", _context, SitecoreContext.Database, writer); } else { return BeginRenderLink(field.Compile().Invoke(model) as Link, attrs, string.Empty, writer); } } /// <summary> /// Checks if an attribute is part of the NameValueCollection and updates it with the /// default if it isn't. /// </summary> /// <param name="collection">The collection of parameters</param> /// <param name="name">The name of the attribute in the collection</param> /// <param name="defaultValue">The default value for the attribute</param> public static void AttributeCheck(SafeDictionary<string> collection, string name, string defaultValue) { if (collection[name].IsNullOrEmpty() && !defaultValue.IsNullOrEmpty()) collection[name] = defaultValue; } /// <summary> /// Checks if an attribute is part of the NameValueCollection and updates it with the /// default if it isn't. /// </summary> /// <param name="collection">The collection of parameters</param> /// <param name="name">The name of the attribute in the collection</param> /// <param name="defaultValue">The default value for the attribute</param> public static void AttributeCheck(NameValueCollection collection, string name, string defaultValue) { if (collection[name].IsNullOrEmpty() && !defaultValue.IsNullOrEmpty()) collection[name] = defaultValue; } /// <summary> /// Render HTML for a link /// </summary> /// <param name="model">The model containing the link</param> /// <param name="field">An expression that points to the link</param> /// <param name="attributes">A collection of parameters to added to the link</param> /// <param name="isEditable">Indicate if the link should be editable in the page editor</param> /// <param name="contents">Content to go in the link</param> /// <returns>An "a" HTML element</returns> public virtual string RenderLink<T>(T model, Expression<Func<T, object>> field, object attributes = null, bool isEditable = false, string contents = null) { NameValueCollection attrs; if (attributes is NameValueCollection) { attrs = attributes as NameValueCollection; } else { attrs = Utilities.GetPropertiesCollection(attributes, true); } var sb = new StringBuilder(); var writer = new StringWriter(sb); var linkField = field.Compile().Invoke(model) as Fields.Link; RenderingResult result; if (IsInEditingMode && isEditable) { if (contents.HasValue()) { attrs.Add("haschildren", "true"); attrs.Add("text",contents); } if (linkField != null) { AttributeCheck(attrs, "class", linkField.Class); AttributeCheck(attrs, "title", linkField.Title); } result = MakeEditable( field, null, model, attrs, _context, SitecoreContext.Database, writer); if (contents.IsNotNullOrEmpty()) { sb.Append(contents); } } else { result = BeginRenderLink( GetCompiled(field).Invoke(model) as Link, attrs, contents, writer ); } result.Dispose(); writer.Flush(); writer.Close(); return sb.ToString(); } /// <summary> /// Indicates if the site is in editing mode /// </summary> /// <value><c>true</c> if this instance is in editing mode; otherwise, <c>false</c>.</value> public static bool IsInEditingMode { get { return Utilities.IsPageEditorEditing; } } private string MakeEditable<T>(Expression<Func<T, object>> field, Expression<Func<T, string>> standardOutput, T target, object parameters) { StringBuilder sb = new StringBuilder(); var writer = new StringWriter(sb); var result = MakeEditable(field, standardOutput, target, parameters, _context, SitecoreContext.Database, writer); result.Dispose(); writer.Flush(); writer.Close(); return sb.ToString(); } #region Statics /// <summary> /// Render HTML for a link /// </summary> /// <param name="link">The link to render</param> /// <param name="attributes">Addtiional parameters to add. Do not include href or title</param> /// <param name="contents">Content to go in the link instead of the standard text</param> /// <returns>An "a" HTML element</returns> [Obsolete("Use the SafeDictionary Overload")] public static RenderingResult BeginRenderLink(Link link, NameValueCollection attributes, string contents, TextWriter writer) { return BeginRenderLink(link, attributes.ToSafeDictionary(), contents, writer); } /// <summary> /// Render HTML for a link /// </summary> /// <param name="link">The link to render</param> /// <param name="attributes">Addtiional parameters to add. Do not include href or title</param> /// <param name="contents">Content to go in the link instead of the standard text</param> /// <returns>An "a" HTML element</returns> public static RenderingResult BeginRenderLink(Link link, SafeDictionary<string> attributes, string contents, TextWriter writer) { if (link == null) return new RenderingResult(writer, string.Empty, string.Empty); if (attributes == null) attributes = new SafeDictionary<string>(); contents = contents == null ? link.Text ?? link.Title : contents; var url = link.BuildUrl(attributes); url = HttpUtility.HtmlEncode(url); //we decode and then encode the HTML to avoid a double encoding of HTML characters. //some versions of Sitecore save '&' as '&amp;' and others as '&'. contents = HttpUtility.HtmlEncode(HttpUtility.HtmlDecode(contents)); var title = HttpUtility.HtmlEncode(HttpUtility.HtmlDecode(link.Title)); AttributeCheck(attributes, "class", link.Class); AttributeCheck(attributes, "target", link.Target); AttributeCheck(attributes, "title", title); string firstPart = LinkTagFormat.Formatted(url, Utilities.ConvertAttributes(attributes, QuotationMark), contents, QuotationMark); string lastPart = "</a>"; return new RenderingResult(writer, firstPart, lastPart); } /// <summary> /// Makes the editable. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="field">The field.</param> /// <param name="standardOutput">The standard output.</param> /// <param name="model">The model.</param> /// <param name="parameters">The parameters.</param> /// <returns>System.String.</returns> /// <exception cref="Glass.Mapper.MapperException"> /// To many parameters in linq expression {0}.Formatted(field.Body) /// or /// Expression doesn't evaluate to a member {0}.Formatted(field.Body) /// or /// Page editting error. Could not find property {0} on type {1}.Formatted(memberExpression.Member.Name, config.Type.FullName) /// or /// Page editting error. Could not find data handler for property {2} {0}.{1}.Formatted( /// prop.DeclaringType, prop.Name, prop.MemberType) /// </exception> /// <exception cref="System.NullReferenceException">Context cannot be null</exception> private RenderingResult MakeEditable<T>( Expression<Func<T, object>> field, Expression<Func<T, string>> standardOutput, T model, object parameters, Context context, Database database, TextWriter writer) { string firstPart = string.Empty; string lastPart = string.Empty; try { if (field == null) throw new NullReferenceException("No field set"); if (model == null) throw new NullReferenceException("No model set"); string parametersStringTemp = string.Empty; SafeDictionary<string> dictionary = new SafeDictionary<string>(); if (parameters == null) { parametersStringTemp = string.Empty; } else if (parameters is string) { parametersStringTemp = parameters as string; dictionary = WebUtil.ParseQueryString(parametersStringTemp ?? string.Empty); } else if (parameters is NameValueCollection) { var collection = (NameValueCollection)parameters; foreach (var key in collection.AllKeys) { dictionary.Add(key, collection[key]); } } else { var collection = Utilities.GetPropertiesCollection(parameters, true); foreach (var key in collection.AllKeys) { dictionary.Add(key, collection[key]); } } if (IsInEditingMode) { MemberExpression memberExpression; var finalTarget = Mapper.Utilities.GetTargetObjectOfLamba(field, model, out memberExpression); var config = Mapper.Utilities.GetTypeConfig<T, SitecoreTypeConfiguration>(field, context, model); var dataHandler = Mapper.Utilities.GetGlassProperty<T, SitecoreTypeConfiguration>(field, context, model); var scClass = config.ResolveItem(finalTarget, database); using (new ContextItemSwitcher(scClass)) { RenderFieldArgs renderFieldArgs = new RenderFieldArgs(); renderFieldArgs.Item = scClass; var fieldConfig = (SitecoreFieldConfiguration)dataHandler; if (fieldConfig.FieldId != (ID)null && fieldConfig.FieldId != ID.Null) { renderFieldArgs.FieldName = fieldConfig.FieldId.ToString(); } else { renderFieldArgs.FieldName = fieldConfig.FieldName; } renderFieldArgs.Parameters = dictionary; renderFieldArgs.DisableWebEdit = false; CorePipeline.Run("renderField", (PipelineArgs)renderFieldArgs); firstPart = renderFieldArgs.Result.FirstPart; lastPart = renderFieldArgs.Result.LastPart; } } else { if (standardOutput != null) { firstPart = GetCompiled(standardOutput)(model).ToString(); } else { object target = (GetCompiled(field)(model) ?? string.Empty); if (ImageType.IsInstanceOfType(target)) { var image = target as Image; firstPart = RenderImage(image, dictionary); } else if (LinkType.IsInstanceOfType(target)) { var link = target as Link; var sb = new StringBuilder(); var linkWriter = new StringWriter(sb); var result = BeginRenderLink(link, dictionary, null, linkWriter); result.Dispose(); linkWriter.Flush(); linkWriter.Close(); firstPart = sb.ToString(); } else { firstPart = target.ToString(); } } } } catch (Exception ex) { firstPart = "<p>{0}</p><pre>{1}</pre>".Formatted(ex.Message, ex.StackTrace); Sitecore.Diagnostics.Log.Error("Failed to render field", ex, typeof(IGlassHtml)); } return new RenderingResult(writer, firstPart, lastPart); //return field.Compile().Invoke(model).ToString(); } #endregion /// <summary> /// Renders an image allowing simple page editor support /// </summary> /// <typeparam name="T">The model type</typeparam> /// <param name="model">The model that contains the image field</param> /// <param name="field">A lambda expression to the image field, should be of type Glass.Mapper.Sc.Fields.Image</param> /// <param name="parameters">Image parameters, e.g. width, height</param> /// <param name="isEditable">Indicates if the field should be editable</param> /// <param name="outputHeightWidth">Indicates if the height and width attributes should be output when rendering the image</param> /// <returns></returns> public virtual string RenderImage<T>(T model, Expression<Func<T, object>> field, object parameters = null, bool isEditable = false, bool outputHeightWidth = false) { var attrs = Utilities.GetPropertiesCollection(parameters, true).ToSafeDictionary(); if (IsInEditingMode && isEditable) { var url = new UrlString(); foreach (var pair in attrs) { url.Parameters.Add(pair.Key, pair.Value); } if (!outputHeightWidth) { url.Parameters.Add("width", "-1"); url.Parameters.Add("height", "-1"); } return Editable(model, field, url.Query); } else { return RenderImage(GetCompiled(field).Invoke(model) as Image, parameters == null ? null : attrs, outputHeightWidth); } } /// <summary> /// Renders HTML for an image /// </summary> /// <param name="image">The image to render</param> /// <param name="attributes">Additional parameters to add. Do not include alt or src</param> /// <param name="outputHeightWidth">Indicates if the height and width attributes should be output when rendering the image</param> /// <returns>An img HTML element</returns> public virtual string RenderImage( Image image, SafeDictionary<string> attributes, bool outputHeightWidth = false ) { if (image == null) { return string.Empty; } if (attributes == null) { attributes = new SafeDictionary<string>(); } var origionalKeys = attributes.Keys.ToList(); //should there be some warning about these removals? AttributeCheck(attributes, ImageParameterKeys.CLASS, image.Class); if (!attributes.ContainsKey(ImageParameterKeys.ALT)) { attributes[ImageParameterKeys.ALT] = image.Alt; } AttributeCheck(attributes, ImageParameterKeys.BORDER, image.Border); if (image.HSpace > 0) AttributeCheck(attributes, ImageParameterKeys.HSPACE, image.HSpace.ToString(CultureInfo.InvariantCulture)); if (image.VSpace > 0) AttributeCheck(attributes, ImageParameterKeys.VSPACE, image.VSpace.ToString(CultureInfo.InvariantCulture)); if (image.Width > 0) AttributeCheck(attributes, ImageParameterKeys.WIDTHHTML, image.Width.ToString(CultureInfo.InvariantCulture)); if (image.Height > 0) AttributeCheck(attributes, ImageParameterKeys.HEIGHTHTML, image.Height.ToString(CultureInfo.InvariantCulture)); var urlParams = new SafeDictionary<string>(); var htmlParams = new SafeDictionary<string>(); /* * ME - This method is used to render images rather than going back to the fieldrender * because it stops another call having to be passed to Sitecore. */ if (image == null || image.Src.IsNullOrWhiteSpace()) return String.Empty; if (attributes == null) attributes = new SafeDictionary<string>(); Action<string> remove = key => attributes.Remove(key); Action<string> url = key => { urlParams.Add(key, attributes[key]); remove(key); }; Action<string> html = key => { htmlParams.Add(key, attributes[key]); remove(key); }; Action<string> both = key => { htmlParams.Add(key, attributes[key]); urlParams.Add(key, attributes[key]); remove(key); }; var keys = attributes.Keys.ToList(); foreach (var key in keys) { //if we have not config we just add it to both if (SitecoreContext.Config == null) { both(key); } else { bool found = false; if (SitecoreContext.Config.ImageAttributes.Contains(key)) { html(key); found = true; } if (SitecoreContext.Config.ImageQueryString.Contains(key)) { url(key); found = true; } if (!found) { html(key); } } } //copy width and height across to url if (!urlParams.ContainsKey(ImageParameterKeys.WIDTH) && !urlParams.ContainsKey(ImageParameterKeys.HEIGHT)) { if (origionalKeys.Contains(ImageParameterKeys.WIDTHHTML)) { urlParams[ImageParameterKeys.WIDTH] = htmlParams[ImageParameterKeys.WIDTHHTML]; } if (origionalKeys.Contains(ImageParameterKeys.HEIGHTHTML)) { urlParams[ImageParameterKeys.HEIGHT] = htmlParams[ImageParameterKeys.HEIGHTHTML]; } } if (!urlParams.ContainsKey(ImageParameterKeys.LANGUAGE) && image.Language != null) { urlParams[ImageParameterKeys.LANGUAGE] = image.Language.Name; } //calculate size var finalSize = Utilities.ResizeImage( image.Width, image.Height, urlParams[ImageParameterKeys.SCALE].ToFlaot(), urlParams[ImageParameterKeys.WIDTH].ToInt(), urlParams[ImageParameterKeys.HEIGHT].ToInt(), urlParams[ImageParameterKeys.MAX_WIDTH].ToInt(), urlParams[ImageParameterKeys.MAX_HEIGHT].ToInt()); if (finalSize.Height > 0) { urlParams[ImageParameterKeys.HEIGHT] = finalSize.Height.ToString(); } if (finalSize.Width > 0) { urlParams[ImageParameterKeys.WIDTH] = finalSize.Width.ToString(); } Action<string, string> originalAttributeClean = (exists, missing) => { if (origionalKeys.Contains(exists) && !origionalKeys.Contains(missing)) { urlParams.Remove(missing); htmlParams.Remove(missing); } }; //we do some smart clean up originalAttributeClean(ImageParameterKeys.WIDTHHTML, ImageParameterKeys.HEIGHTHTML); originalAttributeClean(ImageParameterKeys.HEIGHTHTML, ImageParameterKeys.WIDTHHTML); if (!outputHeightWidth) { htmlParams.Remove(ImageParameterKeys.WIDTHHTML); htmlParams.Remove(ImageParameterKeys.HEIGHTHTML); } var builder = new UrlBuilder(image.Src); foreach (var key in urlParams.Keys) { builder.AddToQueryString(key, urlParams[key]); } string mediaUrl = builder.ToString(); #if (SC81 || SC80 || SC75 || SC82) mediaUrl = ProtectMediaUrl(mediaUrl); #endif mediaUrl = HttpUtility.HtmlEncode(mediaUrl); return ImageTagFormat.Formatted(mediaUrl, Utilities.ConvertAttributes(htmlParams, QuotationMark), QuotationMark); } #if (SC81 || SC80 || SC75 || SC82) public virtual string ProtectMediaUrl(string url) { return Sitecore.Resources.Media.HashingUtils.ProtectAssetUrl(url); } #endif } }
// 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; namespace System.Collections.Generic { // The SortedDictionary class implements a generic sorted list of keys // and values. Entries in a sorted list are sorted by their keys and // are accessible both by key and by index. The keys of a sorted dictionary // can be ordered either according to a specific IComparer // implementation given when the sorted dictionary is instantiated, or // according to the IComparable implementation provided by the keys // themselves. In either case, a sorted dictionary does not allow entries // with duplicate or null keys. // // A sorted list internally maintains two arrays that store the keys and // values of the entries. The capacity of a sorted list is the allocated // length of these internal arrays. As elements are added to a sorted list, the // capacity of the sorted list is automatically increased as required by // reallocating the internal arrays. The capacity is never automatically // decreased, but users can call either TrimExcess or // Capacity explicitly. // // The GetKeyList and GetValueList methods of a sorted list // provides access to the keys and values of the sorted list in the form of // List implementations. The List objects returned by these // methods are aliases for the underlying sorted list, so modifications // made to those lists are directly reflected in the sorted list, and vice // versa. // // The SortedList class provides a convenient way to create a sorted // copy of another dictionary, such as a Hashtable. For example: // // Hashtable h = new Hashtable(); // h.Add(...); // h.Add(...); // ... // SortedList s = new SortedList(h); // // The last line above creates a sorted list that contains a copy of the keys // and values stored in the hashtable. In this particular example, the keys // will be ordered according to the IComparable interface, which they // all must implement. To impose a different ordering, SortedList also // has a constructor that allows a specific IComparer implementation to // be specified. // [DebuggerTypeProxy(typeof(IDictionaryDebugView<,>))] [DebuggerDisplay("Count = {Count}")] public class SortedList<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue> { private TKey[] _keys; private TValue[] _values; private int _size; private int _version; private IComparer<TKey> _comparer; private KeyList _keyList; private ValueList _valueList; private object _syncRoot; private const int DefaultCapacity = 4; // Constructs a new sorted list. The sorted list is initially empty and has // a capacity of zero. Upon adding the first element to the sorted list the // capacity is increased to DefaultCapacity, and then increased in multiples of two as // required. The elements of the sorted list are ordered according to the // IComparable interface, which must be implemented by the keys of // all entries added to the sorted list. public SortedList() { _keys = Array.Empty<TKey>(); _values = Array.Empty<TValue>(); _size = 0; _comparer = Comparer<TKey>.Default; } // Constructs a new sorted list. The sorted list is initially empty and has // a capacity of zero. Upon adding the first element to the sorted list the // capacity is increased to 16, and then increased in multiples of two as // required. The elements of the sorted list are ordered according to the // IComparable interface, which must be implemented by the keys of // all entries added to the sorted list. // public SortedList(int capacity) { if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum); _keys = new TKey[capacity]; _values = new TValue[capacity]; _comparer = Comparer<TKey>.Default; } // Constructs a new sorted list with a given IComparer // implementation. The sorted list is initially empty and has a capacity of // zero. Upon adding the first element to the sorted list the capacity is // increased to 16, and then increased in multiples of two as required. The // elements of the sorted list are ordered according to the given // IComparer implementation. If comparer is null, the // elements are compared to each other using the IComparable // interface, which in that case must be implemented by the keys of all // entries added to the sorted list. // public SortedList(IComparer<TKey> comparer) : this() { if (comparer != null) { _comparer = comparer; } } // Constructs a new sorted dictionary with a given IComparer // implementation and a given initial capacity. The sorted list is // initially empty, but will have room for the given number of elements // before any reallocations are required. The elements of the sorted list // are ordered according to the given IComparer implementation. If // comparer is null, the elements are compared to each other using // the IComparable interface, which in that case must be implemented // by the keys of all entries added to the sorted list. // public SortedList(int capacity, IComparer<TKey> comparer) : this(comparer) { Capacity = capacity; } // Constructs a new sorted list containing a copy of the entries in the // given dictionary. The elements of the sorted list are ordered according // to the IComparable interface, which must be implemented by the // keys of all entries in the given dictionary as well as keys // subsequently added to the sorted list. // public SortedList(IDictionary<TKey, TValue> dictionary) : this(dictionary, null) { } // Constructs a new sorted list containing a copy of the entries in the // given dictionary. The elements of the sorted list are ordered according // to the given IComparer implementation. If comparer is // null, the elements are compared to each other using the // IComparable interface, which in that case must be implemented // by the keys of all entries in the given dictionary as well as keys // subsequently added to the sorted list. // public SortedList(IDictionary<TKey, TValue> dictionary, IComparer<TKey> comparer) : this((dictionary != null ? dictionary.Count : 0), comparer) { if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); int count = dictionary.Count; if (count != 0) { TKey[] keys = _keys; dictionary.Keys.CopyTo(keys, 0); dictionary.Values.CopyTo(_values, 0); Debug.Assert(count == _keys.Length); if (count > 1) { comparer = Comparer; // obtain default if this is null. Array.Sort<TKey, TValue>(keys, _values, comparer); for (int i = 1; i != keys.Length; ++i) { if (comparer.Compare(keys[i - 1], keys[i]) == 0) { throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, keys[i])); } } } } _size = count; } // Adds an entry with the given key and value to this sorted list. An // ArgumentException is thrown if the key is already present in the sorted list. // public void Add(TKey key, TValue value) { if (key == null) throw new ArgumentNullException(nameof(key)); int i = Array.BinarySearch<TKey>(_keys, 0, _size, key, _comparer); if (i >= 0) throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, key), nameof(key)); Insert(~i, key, value); } void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair) { Add(keyValuePair.Key, keyValuePair.Value); } bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair) { int index = IndexOfKey(keyValuePair.Key); if (index >= 0 && EqualityComparer<TValue>.Default.Equals(_values[index], keyValuePair.Value)) { return true; } return false; } bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair) { int index = IndexOfKey(keyValuePair.Key); if (index >= 0 && EqualityComparer<TValue>.Default.Equals(_values[index], keyValuePair.Value)) { RemoveAt(index); return true; } return false; } // Returns the capacity of this sorted list. The capacity of a sorted list // represents the allocated length of the internal arrays used to store the // keys and values of the list, and thus also indicates the maximum number // of entries the list can contain before a reallocation of the internal // arrays is required. // public int Capacity { get { return _keys.Length; } set { if (value != _keys.Length) { if (value < _size) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_SmallCapacity); } if (value > 0) { TKey[] newKeys = new TKey[value]; TValue[] newValues = new TValue[value]; if (_size > 0) { Array.Copy(_keys, 0, newKeys, 0, _size); Array.Copy(_values, 0, newValues, 0, _size); } _keys = newKeys; _values = newValues; } else { _keys = Array.Empty<TKey>(); _values = Array.Empty<TValue>(); } } } } public IComparer<TKey> Comparer { get { return _comparer; } } void IDictionary.Add(object key, object value) { if (key == null) throw new ArgumentNullException(nameof(key)); if (value == null && !(default(TValue) == null)) // null is an invalid value for Value types throw new ArgumentNullException(nameof(value)); if (!(key is TKey)) throw new ArgumentException(SR.Format(SR.Arg_WrongType, key, typeof(TKey)), nameof(key)); if (!(value is TValue) && value != null) // null is a valid value for Reference Types throw new ArgumentException(SR.Format(SR.Arg_WrongType, value, typeof(TValue)), nameof(value)); Add((TKey)key, (TValue)value); } // Returns the number of entries in this sorted list. public int Count { get { return _size; } } // Returns a collection representing the keys of this sorted list. This // method returns the same object as GetKeyList, but typed as an // ICollection instead of an IList. public IList<TKey> Keys { get { return GetKeyListHelper(); } } ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { return GetKeyListHelper(); } } ICollection IDictionary.Keys { get { return GetKeyListHelper(); } } IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys { get { return GetKeyListHelper(); } } // Returns a collection representing the values of this sorted list. This // method returns the same object as GetValueList, but typed as an // ICollection instead of an IList. // public IList<TValue> Values { get { return GetValueListHelper(); } } ICollection<TValue> IDictionary<TKey, TValue>.Values { get { return GetValueListHelper(); } } ICollection IDictionary.Values { get { return GetValueListHelper(); } } IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values { get { return GetValueListHelper(); } } private KeyList GetKeyListHelper() { if (_keyList == null) _keyList = new KeyList(this); return _keyList; } private ValueList GetValueListHelper() { if (_valueList == null) _valueList = new ValueList(this); return _valueList; } bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return false; } } bool IDictionary.IsReadOnly { get { return false; } } bool IDictionary.IsFixedSize { get { return false; } } bool ICollection.IsSynchronized { get { return false; } } // Synchronization root for this object. object ICollection.SyncRoot { get { if (_syncRoot == null) { Threading.Interlocked.CompareExchange(ref _syncRoot, new object(), null); } return _syncRoot; } } // Removes all entries from this sorted list. public void Clear() { // clear does not change the capacity _version++; // Don't need to doc this but we clear the elements so that the gc can reclaim the references. Array.Clear(_keys, 0, _size); Array.Clear(_values, 0, _size); _size = 0; } bool IDictionary.Contains(object key) { if (IsCompatibleKey(key)) { return ContainsKey((TKey)key); } return false; } // Checks if this sorted list contains an entry with the given key. public bool ContainsKey(TKey key) { return IndexOfKey(key) >= 0; } // Checks if this sorted list contains an entry with the given value. The // values of the entries of the sorted list are compared to the given value // using the Object.Equals method. This method performs a linear // search and is substantially slower than the Contains // method. public bool ContainsValue(TValue value) { return IndexOfValue(value) >= 0; } // Copies the values in this SortedList to an array. void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (arrayIndex < 0 || arrayIndex > array.Length) { throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index); } if (array.Length - arrayIndex < Count) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } for (int i = 0; i < Count; i++) { KeyValuePair<TKey, TValue> entry = new KeyValuePair<TKey, TValue>(_keys[i], _values[i]); array[arrayIndex + i] = entry; } } void ICollection.CopyTo(Array array, int index) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); } if (array.GetLowerBound(0) != 0) { throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array)); } if (index < 0 || index > array.Length) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); } if (array.Length - index < Count) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } KeyValuePair<TKey, TValue>[] keyValuePairArray = array as KeyValuePair<TKey, TValue>[]; if (keyValuePairArray != null) { for (int i = 0; i < Count; i++) { keyValuePairArray[i + index] = new KeyValuePair<TKey, TValue>(_keys[i], _values[i]); } } else { object[] objects = array as object[]; if (objects == null) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } try { for (int i = 0; i < Count; i++) { objects[i + index] = new KeyValuePair<TKey, TValue>(_keys[i], _values[i]); } } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } } } private const int MaxArrayLength = 0X7FEFFFFF; // Ensures that the capacity of this sorted list is at least the given // minimum value. If the current capacity of the list is less than // min, the capacity is increased to twice the current capacity or // to min, whichever is larger. private void EnsureCapacity(int min) { int newCapacity = _keys.Length == 0 ? DefaultCapacity : _keys.Length * 2; // Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow. // Note that this check works even when _items.Length overflowed thanks to the (uint) cast if ((uint)newCapacity > MaxArrayLength) newCapacity = MaxArrayLength; if (newCapacity < min) newCapacity = min; Capacity = newCapacity; } // Returns the value of the entry at the given index. private TValue GetByIndex(int index) { if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); return _values[index]; } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } IDictionaryEnumerator IDictionary.GetEnumerator() { return new Enumerator(this, Enumerator.DictEntry); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } // Returns the key of the entry at the given index. private TKey GetKey(int index) { if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); return _keys[index]; } // Returns the value associated with the given key. If an entry with the // given key is not found, the returned value is null. public TValue this[TKey key] { get { int i = IndexOfKey(key); if (i >= 0) return _values[i]; throw new KeyNotFoundException(); // return default(TValue); } set { if (((object)key) == null) throw new ArgumentNullException(nameof(key)); int i = Array.BinarySearch<TKey>(_keys, 0, _size, key, _comparer); if (i >= 0) { _values[i] = value; _version++; return; } Insert(~i, key, value); } } object IDictionary.this[object key] { get { if (IsCompatibleKey(key)) { int i = IndexOfKey((TKey)key); if (i >= 0) { return _values[i]; } } return null; } set { if (!IsCompatibleKey(key)) { throw new ArgumentException(SR.Argument_InvalidArgumentForComparison, nameof(key)); } if (value == null && !(default(TValue) == null)) throw new ArgumentNullException(nameof(value)); TKey tempKey = (TKey)key; try { this[tempKey] = (TValue)value; } catch (InvalidCastException) { throw new ArgumentException(SR.Format(SR.Arg_WrongType, value, typeof(TValue)), nameof(value)); } } } // Returns the index of the entry with a given key in this sorted list. The // key is located through a binary search, and thus the average execution // time of this method is proportional to Log2(size), where // size is the size of this sorted list. The returned value is -1 if // the given key does not occur in this sorted list. Null is an invalid // key value. public int IndexOfKey(TKey key) { if (key == null) throw new ArgumentNullException(nameof(key)); int ret = Array.BinarySearch<TKey>(_keys, 0, _size, key, _comparer); return ret >= 0 ? ret : -1; } // Returns the index of the first occurrence of an entry with a given value // in this sorted list. The entry is located through a linear search, and // thus the average execution time of this method is proportional to the // size of this sorted list. The elements of the list are compared to the // given value using the Object.Equals method. public int IndexOfValue(TValue value) { return Array.IndexOf(_values, value, 0, _size); } // Inserts an entry with a given key and value at a given index. private void Insert(int index, TKey key, TValue value) { if (_size == _keys.Length) EnsureCapacity(_size + 1); if (index < _size) { Array.Copy(_keys, index, _keys, index + 1, _size - index); Array.Copy(_values, index, _values, index + 1, _size - index); } _keys[index] = key; _values[index] = value; _size++; _version++; } public bool TryGetValue(TKey key, out TValue value) { int i = IndexOfKey(key); if (i >= 0) { value = _values[i]; return true; } value = default(TValue); return false; } // Removes the entry at the given index. The size of the sorted list is // decreased by one. public void RemoveAt(int index) { if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); _size--; if (index < _size) { Array.Copy(_keys, index + 1, _keys, index, _size - index); Array.Copy(_values, index + 1, _values, index, _size - index); } _keys[_size] = default(TKey); _values[_size] = default(TValue); _version++; } // Removes an entry from this sorted list. If an entry with the specified // key exists in the sorted list, it is removed. An ArgumentException is // thrown if the key is null. public bool Remove(TKey key) { int i = IndexOfKey(key); if (i >= 0) RemoveAt(i); return i >= 0; } void IDictionary.Remove(object key) { if (IsCompatibleKey(key)) { Remove((TKey)key); } } // Sets the capacity of this sorted list to the size of the sorted list. // This method can be used to minimize a sorted list's memory overhead once // it is known that no new elements will be added to the sorted list. To // completely clear a sorted list and release all memory referenced by the // sorted list, execute the following statements: // // SortedList.Clear(); // SortedList.TrimExcess(); public void TrimExcess() { int threshold = (int)(((double)_keys.Length) * 0.9); if (_size < threshold) { Capacity = _size; } } private static bool IsCompatibleKey(object key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } return (key is TKey); } /// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedListEnumerator"]/*' /> private struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDictionaryEnumerator { private SortedList<TKey, TValue> _sortedList; private TKey _key; private TValue _value; private int _index; private int _version; private int _getEnumeratorRetType; // What should Enumerator.Current return? internal const int KeyValuePair = 1; internal const int DictEntry = 2; internal Enumerator(SortedList<TKey, TValue> sortedList, int getEnumeratorRetType) { _sortedList = sortedList; _index = 0; _version = _sortedList._version; _getEnumeratorRetType = getEnumeratorRetType; _key = default(TKey); _value = default(TValue); } public void Dispose() { _index = 0; _key = default(TKey); _value = default(TValue); } object IDictionaryEnumerator.Key { get { if (_index == 0 || (_index == _sortedList.Count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return _key; } } public bool MoveNext() { if (_version != _sortedList._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); if ((uint)_index < (uint)_sortedList.Count) { _key = _sortedList._keys[_index]; _value = _sortedList._values[_index]; _index++; return true; } _index = _sortedList.Count + 1; _key = default(TKey); _value = default(TValue); return false; } DictionaryEntry IDictionaryEnumerator.Entry { get { if (_index == 0 || (_index == _sortedList.Count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return new DictionaryEntry(_key, _value); } } public KeyValuePair<TKey, TValue> Current { get { return new KeyValuePair<TKey, TValue>(_key, _value); } } object IEnumerator.Current { get { if (_index == 0 || (_index == _sortedList.Count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } if (_getEnumeratorRetType == DictEntry) { return new DictionaryEntry(_key, _value); } else { return new KeyValuePair<TKey, TValue>(_key, _value); } } } object IDictionaryEnumerator.Value { get { if (_index == 0 || (_index == _sortedList.Count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return _value; } } void IEnumerator.Reset() { if (_version != _sortedList._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } _index = 0; _key = default(TKey); _value = default(TValue); } } private sealed class SortedListKeyEnumerator : IEnumerator<TKey>, IEnumerator { private SortedList<TKey, TValue> _sortedList; private int _index; private int _version; private TKey _currentKey; internal SortedListKeyEnumerator(SortedList<TKey, TValue> sortedList) { _sortedList = sortedList; _version = sortedList._version; } public void Dispose() { _index = 0; _currentKey = default(TKey); } public bool MoveNext() { if (_version != _sortedList._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } if ((uint)_index < (uint)_sortedList.Count) { _currentKey = _sortedList._keys[_index]; _index++; return true; } _index = _sortedList.Count + 1; _currentKey = default(TKey); return false; } public TKey Current { get { return _currentKey; } } object IEnumerator.Current { get { if (_index == 0 || (_index == _sortedList.Count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return _currentKey; } } void IEnumerator.Reset() { if (_version != _sortedList._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } _index = 0; _currentKey = default(TKey); } } private sealed class SortedListValueEnumerator : IEnumerator<TValue>, IEnumerator { private SortedList<TKey, TValue> _sortedList; private int _index; private int _version; private TValue _currentValue; internal SortedListValueEnumerator(SortedList<TKey, TValue> sortedList) { _sortedList = sortedList; _version = sortedList._version; } public void Dispose() { _index = 0; _currentValue = default(TValue); } public bool MoveNext() { if (_version != _sortedList._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } if ((uint)_index < (uint)_sortedList.Count) { _currentValue = _sortedList._values[_index]; _index++; return true; } _index = _sortedList.Count + 1; _currentValue = default(TValue); return false; } public TValue Current { get { return _currentValue; } } object IEnumerator.Current { get { if (_index == 0 || (_index == _sortedList.Count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return _currentValue; } } void IEnumerator.Reset() { if (_version != _sortedList._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } _index = 0; _currentValue = default(TValue); } } [DebuggerTypeProxy(typeof(DictionaryKeyCollectionDebugView<,>))] [DebuggerDisplay("Count = {Count}")] private sealed class KeyList : IList<TKey>, ICollection { private SortedList<TKey, TValue> _dict; internal KeyList(SortedList<TKey, TValue> dictionary) { _dict = dictionary; } public int Count { get { return _dict._size; } } public bool IsReadOnly { get { return true; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return ((ICollection)_dict).SyncRoot; } } public void Add(TKey key) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public void Clear() { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public bool Contains(TKey key) { return _dict.ContainsKey(key); } public void CopyTo(TKey[] array, int arrayIndex) { // defer error checking to Array.Copy Array.Copy(_dict._keys, 0, array, arrayIndex, _dict.Count); } void ICollection.CopyTo(Array array, int arrayIndex) { if (array != null && array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); try { // defer error checking to Array.Copy Array.Copy(_dict._keys, 0, array, arrayIndex, _dict.Count); } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } } public void Insert(int index, TKey value) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public TKey this[int index] { get { return _dict.GetKey(index); } set { throw new NotSupportedException(SR.NotSupported_KeyCollectionSet); } } public IEnumerator<TKey> GetEnumerator() { return new SortedListKeyEnumerator(_dict); } IEnumerator IEnumerable.GetEnumerator() { return new SortedListKeyEnumerator(_dict); } public int IndexOf(TKey key) { if (((object)key) == null) throw new ArgumentNullException(nameof(key)); int i = Array.BinarySearch<TKey>(_dict._keys, 0, _dict.Count, key, _dict._comparer); if (i >= 0) return i; return -1; } public bool Remove(TKey key) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); // return false; } public void RemoveAt(int index) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } } [DebuggerTypeProxy(typeof(DictionaryValueCollectionDebugView<,>))] [DebuggerDisplay("Count = {Count}")] private sealed class ValueList : IList<TValue>, ICollection { private SortedList<TKey, TValue> _dict; internal ValueList(SortedList<TKey, TValue> dictionary) { _dict = dictionary; } public int Count { get { return _dict._size; } } public bool IsReadOnly { get { return true; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return ((ICollection)_dict).SyncRoot; } } public void Add(TValue key) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public void Clear() { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public bool Contains(TValue value) { return _dict.ContainsValue(value); } public void CopyTo(TValue[] array, int arrayIndex) { // defer error checking to Array.Copy Array.Copy(_dict._values, 0, array, arrayIndex, _dict.Count); } void ICollection.CopyTo(Array array, int index) { if (array != null && array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); try { // defer error checking to Array.Copy Array.Copy(_dict._values, 0, array, index, _dict.Count); } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } } public void Insert(int index, TValue value) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public TValue this[int index] { get { return _dict.GetByIndex(index); } set { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } } public IEnumerator<TValue> GetEnumerator() { return new SortedListValueEnumerator(_dict); } IEnumerator IEnumerable.GetEnumerator() { return new SortedListValueEnumerator(_dict); } public int IndexOf(TValue value) { return Array.IndexOf(_dict._values, value, 0, _dict.Count); } public bool Remove(TValue value) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); // return false; } public void RemoveAt(int index) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Memoria.Prime; using Memoria.Prime.CSV; using UnityEngine; using Object = System.Object; namespace Memoria.Assets { internal sealed class LanguageMap { private const String LanguageKey = "KEY"; private const String SymbolKey = "Symbol"; private readonly String[] _knownLanguages; private readonly Dictionary<String, SortedList<String, String>> _languages; private readonly SortedList<String, String> _failback; private readonly String _failbackLanguage; private String _currentLanguage; private String _currentSymbol; private SortedList<String, String> _current; public LanguageMap() { Byte[] tableData = ReadEmbadedTable(); ByteReader reader = new ByteReader(tableData); BetterList<String> cells = reader.ReadCSV(); if (cells.size < 2 || cells[0] != LanguageKey) throw new CsvParseException("Invalid localisation file."); Int32 languageCount = cells.size - 1; Dictionary<Int32, String> cellLanguages = new Dictionary<Int32, String>(languageCount); _languages = new Dictionary<String, SortedList<String, String>>(languageCount); _knownLanguages = new String[languageCount]; for (Int32 i = 1; i < cells.size; i++) { String language = cells[i]; cellLanguages.Add(i, language); _knownLanguages[i - 1] = language; SortedList<String, String> dic = new SortedList<String, String>(); dic.Add(LanguageKey, language); _languages.Add(language, dic); } ReadText(reader, cellLanguages); _failbackLanguage = cellLanguages[1]; _failback = _languages[_failbackLanguage]; _current = _failback; LoadExternalText(); } public String CurrentLanguage => _currentLanguage; public String CurrentSymbol => _currentSymbol; public ICollection<String> KnownLanguages => _knownLanguages; public SortedList<String, String> ProvideDictionary(String symbol) { if (symbol == _currentSymbol) return _current; return _languages.Values.FirstOrDefault(languageDic => languageDic[SymbolKey] == symbol); } public void Broadcast() { SelectLanguage(LanguagePrefs.Key); } public void SelectLanguage(String language) { if (_languages.TryGetValue(language, out var languageDic)) { _current = languageDic; _currentLanguage = language; LanguagePrefs.Key = language; } else { _current = _failback; _currentLanguage = _failbackLanguage; LanguagePrefs.Key = null; Log.Error($"[LocalizationDictionary] Cannot find localisation data for the language [{language}]."); } _currentSymbol = Get(SymbolKey); UIRoot.Broadcast("OnLocalize"); } private Boolean TryGetAlternativeKey(String key, out String alternativeKey) { switch (UICamera.currentScheme) { case UICamera.ControlScheme.Touch: alternativeKey = key + " Mobile"; return true; case UICamera.ControlScheme.Controller: alternativeKey = key + " Controller"; return true; } alternativeKey = null; return false; } public String Get(String key) { if (TryGetAlternativeKey(key, out var alternativeKey)) { if (TryGetValue(alternativeKey, out var alternativeValue)) return alternativeValue; } if (TryGetValue(key, out var value)) return value; return key; } private Boolean TryGetValue(String key, out String value) { if (_current.TryGetValue(key, out value)) return true; if (_failback.TryGetValue(key, out value)) return true; return false; } private void ReadText(ByteReader reader, Dictionary<Int32, String> cellLanguages) { while (reader.canRead) { BetterList<String> cells = reader.ReadCSV(); if (cells == null || cells.size < 2) continue; String key = cells[0]; if (String.IsNullOrEmpty(key)) continue; for (Int32 i = 1; i < cells.size; i++) { String value = cells[i]; String language = cellLanguages[i]; StoreValue(language, key, value); } } } private void LoadExternalText() { if (!Configuration.Import.Text) return; foreach (SortedList<String, String> languageDic in _languages.Values) { if (!languageDic.TryGetValue(SymbolKey, out String symbol)) continue; String importPath = ModTextResources.Import.GetSymbolPath(symbol, ModTextResources.SystemPath); if (!File.Exists(importPath)) { Log.Warning($"[LocalizationDictionary] Loading was skipped because a file does not exists: [{importPath}]..."); return; } Log.Message($"[LocalizationDictionary] Loading from [{importPath}]..."); TxtEntry[] entries = TxtReader.ReadStrings(importPath); foreach (TxtEntry entry in entries) { if (entry == null) continue; switch (entry.Prefix) { case "KEY": case "Symbol": case "Name": case "": continue; } languageDic[entry.Prefix] = entry.Value; } } Log.Message("[LocalizationDictionary] Loading completed successfully."); } private static Byte[] ReadEmbadedTable() { return AssetManager.LoadBytes("EmbeddedAsset/Manifest/Text/Localization.txt", out _); } private void StoreValue(String language, String key, String value) { SortedList<String, String> target = _languages[language]; try { target.Add(key, value); } catch (ArgumentException) { Debug.LogWarning("Localization key '" + key + "' is already present"); } catch (Exception ex) { Debug.LogError("Unable to add '" + key + "' to the Localization dictionary.\n" + ex.Message); } } private static class LanguagePrefs { private const String DefaultLanguage = "English(US)"; public static String Key { get => PlayerPrefs.GetString("Language", DefaultLanguage); set { if (value == null) PlayerPrefs.DeleteKey("Language"); else PlayerPrefs.SetString("Language", value); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: The boolean class serves as a wrapper for the primitive ** type boolean. ** ** ===========================================================*/ using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.Versioning; namespace System { [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct Boolean : IComparable, IConvertible, IComparable<Boolean>, IEquatable<Boolean> { // // Member Variables // private bool m_value; // Do not rename (binary serialization) // The true value. // internal const int True = 1; // The false value. // internal const int False = 0; // // Internal Constants are real consts for performance. // // The internal string representation of true. // internal const String TrueLiteral = "True"; // The internal string representation of false. // internal const String FalseLiteral = "False"; // // Public Constants // // The public string representation of true. // public static readonly String TrueString = TrueLiteral; // The public string representation of false. // public static readonly String FalseString = FalseLiteral; // // Overriden Instance Methods // /*=================================GetHashCode================================== **Args: None **Returns: 1 or 0 depending on whether this instance represents true or false. **Exceptions: None **Overriden From: Value ==============================================================================*/ // Provides a hash code for this instance. public override int GetHashCode() { return (m_value) ? True : False; } /*===================================ToString=================================== **Args: None **Returns: "True" or "False" depending on the state of the boolean. **Exceptions: None. ==============================================================================*/ // Converts the boolean value of this instance to a String. public override String ToString() { if (false == m_value) { return FalseLiteral; } return TrueLiteral; } public String ToString(IFormatProvider provider) { return ToString(); } // Determines whether two Boolean objects are equal. public override bool Equals(Object obj) { //If it's not a boolean, we're definitely not equal if (!(obj is Boolean)) { return false; } return (m_value == ((Boolean)obj).m_value); } [NonVersionable] public bool Equals(Boolean obj) { return m_value == obj; } // Compares this object to another object, returning an integer that // indicates the relationship. For booleans, false sorts before true. // null is considered to be less than any instance. // If object is not of type boolean, this method throws an ArgumentException. // // Returns a value less than zero if this object // public int CompareTo(Object obj) { if (obj == null) { return 1; } if (!(obj is Boolean)) { throw new ArgumentException(SR.Arg_MustBeBoolean); } if (m_value == ((Boolean)obj).m_value) { return 0; } else if (m_value == false) { return -1; } return 1; } public int CompareTo(Boolean value) { if (m_value == value) { return 0; } else if (m_value == false) { return -1; } return 1; } // // Static Methods // // Determines whether a String represents true or false. // public static Boolean Parse(String value) { if (value == null) throw new ArgumentNullException(nameof(value)); return Parse(value.AsSpan()); } public static bool Parse(ReadOnlySpan<char> value) => TryParse(value, out bool result) ? result : throw new FormatException(SR.Format_BadBoolean); // Determines whether a String represents true or false. // public static Boolean TryParse(String value, out Boolean result) { if (value == null) { result = false; return false; } return TryParse(value.AsSpan(), out result); } public static bool TryParse(ReadOnlySpan<char> value, out bool result) { ReadOnlySpan<char> trueSpan = TrueLiteral.AsSpan(); if (StringSpanHelpers.Equals(trueSpan, value, StringComparison.OrdinalIgnoreCase)) { result = true; return true; } ReadOnlySpan<char> falseSpan = FalseLiteral.AsSpan(); if (StringSpanHelpers.Equals(falseSpan, value, StringComparison.OrdinalIgnoreCase)) { result = false; return true; } // Special case: Trim whitespace as well as null characters. value = TrimWhiteSpaceAndNull(value); if (StringSpanHelpers.Equals(trueSpan, value, StringComparison.OrdinalIgnoreCase)) { result = true; return true; } if (StringSpanHelpers.Equals(falseSpan, value, StringComparison.OrdinalIgnoreCase)) { result = false; return true; } result = false; return false; } private static ReadOnlySpan<char> TrimWhiteSpaceAndNull(ReadOnlySpan<char> value) { const char nullChar = (char)0x0000; int start = 0; while (start < value.Length) { if (!Char.IsWhiteSpace(value[start]) && value[start] != nullChar) { break; } start++; } int end = value.Length - 1; while (end >= start) { if (!Char.IsWhiteSpace(value[end]) && value[end] != nullChar) { break; } end--; } return value.Slice(start, end - start + 1); } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Boolean; } bool IConvertible.ToBoolean(IFormatProvider provider) { return m_value; } char IConvertible.ToChar(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Boolean", "Char")); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Boolean", "DateTime")); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
using System; namespace Ionic.Zlib { sealed class Tree { private static readonly int HEAP_SIZE = (2 * InternalConstants.L_CODES + 1); // extra bits for each length code internal static readonly int[] ExtraLengthBits = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }; // extra bits for each distance code internal static readonly int[] ExtraDistanceBits = new int[] { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }; // extra bits for each bit length code internal static readonly int[] extra_blbits = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7}; internal static readonly sbyte[] bl_order = new sbyte[]{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; // The lengths of the bit length codes are sent in order of decreasing // probability, to avoid transmitting the lengths for unused bit // length codes. internal const int Buf_size = 8 * 2; // see definition of array dist_code below //internal const int DIST_CODE_LEN = 512; private static readonly sbyte[] _dist_code = new sbyte[] { 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 }; internal static readonly sbyte[] LengthCode = new sbyte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 }; internal static readonly int[] LengthBase = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 0 }; internal static readonly int[] DistanceBase = new int[] { 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 }; /// <summary> /// Map from a distance to a distance code. /// </summary> /// <remarks> /// No side effects. _dist_code[256] and _dist_code[257] are never used. /// </remarks> internal static int DistanceCode(int dist) { return (dist < 256) ? _dist_code[dist] : _dist_code[256 + SharedUtils.URShift(dist, 7)]; } internal short[] dyn_tree; // the dynamic tree internal int max_code; // largest code with non zero frequency internal StaticTree staticTree; // the corresponding static tree // Compute the optimal bit lengths for a tree and update the total bit length // for the current block. // IN assertion: the fields freq and dad are set, heap[heap_max] and // above are the tree nodes sorted by increasing frequency. // OUT assertions: the field len is set to the optimal bit length, the // array bl_count contains the frequencies for each bit length. // The length opt_len is updated; static_len is also updated if stree is // not null. internal void gen_bitlen(DeflateManager s) { short[] tree = dyn_tree; short[] stree = staticTree.treeCodes; int[] extra = staticTree.extraBits; int base_Renamed = staticTree.extraBase; int max_length = staticTree.maxLength; int h; // heap index int n, m; // iterate over the tree elements int bits; // bit length int xbits; // extra bits short f; // frequency int overflow = 0; // number of elements with bit length too large for (bits = 0; bits <= InternalConstants.MAX_BITS; bits++) s.bl_count[bits] = 0; // In a first pass, compute the optimal bit lengths (which may // overflow in the case of the bit length tree). tree[s.heap[s.heap_max] * 2 + 1] = 0; // root of the heap for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { n = s.heap[h]; bits = tree[tree[n * 2 + 1] * 2 + 1] + 1; if (bits > max_length) { bits = max_length; overflow++; } tree[n * 2 + 1] = (short) bits; // We overwrite tree[n*2+1] which is no longer needed if (n > max_code) continue; // not a leaf node s.bl_count[bits]++; xbits = 0; if (n >= base_Renamed) xbits = extra[n - base_Renamed]; f = tree[n * 2]; s.opt_len += f * (bits + xbits); if (stree != null) s.static_len += f * (stree[n * 2 + 1] + xbits); } if (overflow == 0) return ; // This happens for example on obj2 and pic of the Calgary corpus // Find the first bit length which could increase: do { bits = max_length - 1; while (s.bl_count[bits] == 0) bits--; s.bl_count[bits]--; // move one leaf down the tree s.bl_count[bits + 1] = (short) (s.bl_count[bits + 1] + 2); // move one overflow item as its brother s.bl_count[max_length]--; // The brother of the overflow item also moves one step up, // but this does not affect bl_count[max_length] overflow -= 2; } while (overflow > 0); for (bits = max_length; bits != 0; bits--) { n = s.bl_count[bits]; while (n != 0) { m = s.heap[--h]; if (m > max_code) continue; if (tree[m * 2 + 1] != bits) { s.opt_len = (int) (s.opt_len + ((long) bits - (long) tree[m * 2 + 1]) * (long) tree[m * 2]); tree[m * 2 + 1] = (short) bits; } n--; } } } // Construct one Huffman tree and assigns the code bit strings and lengths. // Update the total bit length for the current block. // IN assertion: the field freq is set for all tree elements. // OUT assertions: the fields len and code are set to the optimal bit length // and corresponding code. The length opt_len is updated; static_len is // also updated if stree is not null. The field max_code is set. internal void build_tree(DeflateManager s) { short[] tree = dyn_tree; short[] stree = staticTree.treeCodes; int elems = staticTree.elems; int n, m; // iterate over heap elements int max_code = -1; // largest code with non zero frequency int node; // new node being created // Construct the initial heap, with least frequent element in // heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. // heap[0] is not used. s.heap_len = 0; s.heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { if (tree[n * 2] != 0) { s.heap[++s.heap_len] = max_code = n; s.depth[n] = 0; } else { tree[n * 2 + 1] = 0; } } // The pkzip format requires that at least one distance code exists, // and that at least one bit should be sent even if there is only one // possible code. So to avoid special checks later on we force at least // two codes of non zero frequency. while (s.heap_len < 2) { node = s.heap[++s.heap_len] = (max_code < 2?++max_code:0); tree[node * 2] = 1; s.depth[node] = 0; s.opt_len--; if (stree != null) s.static_len -= stree[node * 2 + 1]; // node is 0 or 1 so it does not have extra bits } this.max_code = max_code; // The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, // establish sub-heaps of increasing lengths: for (n = s.heap_len / 2; n >= 1; n--) s.pqdownheap(tree, n); // Construct the Huffman tree by repeatedly combining the least two // frequent nodes. node = elems; // next internal node of the tree do { // n = node of least frequency n = s.heap[1]; s.heap[1] = s.heap[s.heap_len--]; s.pqdownheap(tree, 1); m = s.heap[1]; // m = node of next least frequency s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency s.heap[--s.heap_max] = m; // Create a new node father of n and m tree[node * 2] = unchecked((short) (tree[n * 2] + tree[m * 2])); s.depth[node] = (sbyte) (System.Math.Max((byte) s.depth[n], (byte) s.depth[m]) + 1); tree[n * 2 + 1] = tree[m * 2 + 1] = (short) node; // and insert the new node in the heap s.heap[1] = node++; s.pqdownheap(tree, 1); } while (s.heap_len >= 2); s.heap[--s.heap_max] = s.heap[1]; // At this point, the fields freq and dad are set. We can now // generate the bit lengths. gen_bitlen(s); // The field len is now set, we can generate the bit codes gen_codes(tree, max_code, s.bl_count); } // Generate the codes for a given tree and bit counts (which need not be // optimal). // IN assertion: the array bl_count contains the bit length statistics for // the given tree and the field len is set for all tree elements. // OUT assertion: the field code is set for all tree elements of non // zero code length. internal static void gen_codes(short[] tree, int max_code, short[] bl_count) { short[] next_code = new short[InternalConstants.MAX_BITS + 1]; // next code value for each bit length short code = 0; // running code value int bits; // bit index int n; // code index // The distribution counts are first used to generate the code values // without bit reversal. for (bits = 1; bits <= InternalConstants.MAX_BITS; bits++) unchecked { next_code[bits] = code = (short) ((code + bl_count[bits - 1]) << 1); } // Check that the bit counts in bl_count are consistent. The last code // must be all ones. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, // "inconsistent bit counts"); //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); for (n = 0; n <= max_code; n++) { int len = tree[n * 2 + 1]; if (len == 0) continue; // Now reverse the bits tree[n * 2] = unchecked((short) (bi_reverse(next_code[len]++, len))); } } // Reverse the first len bits of a code, using straightforward code (a faster // method would use a table) // IN assertion: 1 <= len <= 15 internal static int bi_reverse(int code, int len) { int res = 0; do { res |= code & 1; code >>= 1; //SharedUtils.URShift(code, 1); res <<= 1; } while (--len > 0); return res >> 1; } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.Serialization.Formatters; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Utilities; using System.Runtime.Serialization; using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; namespace Newtonsoft.Json { /// <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 { internal TypeNameHandling _typeNameHandling; internal FormatterAssemblyStyle _typeNameAssemblyFormat; internal PreserveReferencesHandling _preserveReferencesHandling; internal ReferenceLoopHandling _referenceLoopHandling; internal MissingMemberHandling _missingMemberHandling; internal ObjectCreationHandling _objectCreationHandling; internal NullValueHandling _nullValueHandling; internal DefaultValueHandling _defaultValueHandling; internal ConstructorHandling _constructorHandling; internal MetadataPropertyHandling _metadataPropertyHandling; internal JsonConverterCollection _converters; internal IContractResolver _contractResolver; internal ITraceWriter _traceWriter; internal IEqualityComparer _equalityComparer; internal SerializationBinder _binder; internal StreamingContext _context; private IReferenceResolver _referenceResolver; private Formatting? _formatting; private DateFormatHandling? _dateFormatHandling; private DateTimeZoneHandling? _dateTimeZoneHandling; private DateParseHandling? _dateParseHandling; private FloatFormatHandling? _floatFormatHandling; private FloatParseHandling? _floatParseHandling; private StringEscapeHandling? _stringEscapeHandling; private CultureInfo _culture; private int? _maxDepth; private bool _maxDepthSet; private bool? _checkAdditionalContent; private string _dateFormatString; private bool _dateFormatStringSet; /// <summary> /// Occurs when the <see cref="JsonSerializer"/> errors during serialization and deserialization. /// </summary> public virtual event EventHandler<ErrorEventArgs> Error; /// <summary> /// Gets or sets the <see cref="IReferenceResolver"/> used by the serializer when resolving references. /// </summary> public virtual IReferenceResolver ReferenceResolver { get { return GetReferenceResolver(); } set { if (value == null) { throw new ArgumentNullException(nameof(value), "Reference resolver cannot be null."); } _referenceResolver = value; } } /// <summary> /// Gets or sets the <see cref="SerializationBinder"/> used by the serializer when resolving type names. /// </summary> public virtual SerializationBinder Binder { get { return _binder; } set { if (value == null) { throw new ArgumentNullException(nameof(value), "Serialization binder cannot be null."); } _binder = value; } } /// <summary> /// Gets or sets the <see cref="ITraceWriter"/> used by the serializer when writing trace messages. /// </summary> /// <value>The trace writer.</value> public virtual ITraceWriter TraceWriter { get { return _traceWriter; } set { _traceWriter = value; } } /// <summary> /// Gets or sets the equality comparer used by the serializer when comparing references. /// </summary> /// <value>The equality comparer.</value> public virtual IEqualityComparer EqualityComparer { get { return _equalityComparer; } set { _equalityComparer = value; } } /// <summary> /// Gets or sets how type name writing and reading is handled by the serializer. /// </summary> /// <remarks> /// <see cref="TypeNameHandling"/> should be used with caution when your application deserializes JSON from an external source. /// Incoming types should be validated with a custom <see cref="T:System.Runtime.Serialization.SerializationBinder"/> /// when deserializing with a value other than <c>TypeNameHandling.None</c>. /// </remarks> public virtual TypeNameHandling TypeNameHandling { get { return _typeNameHandling; } set { if (value < TypeNameHandling.None || value > TypeNameHandling.Auto) { throw new ArgumentOutOfRangeException(nameof(value)); } _typeNameHandling = value; } } /// <summary> /// Gets or sets how a type name assembly is written and resolved by the serializer. /// </summary> /// <value>The type name assembly format.</value> public virtual FormatterAssemblyStyle TypeNameAssemblyFormat { get { return _typeNameAssemblyFormat; } set { if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full) { throw new ArgumentOutOfRangeException(nameof(value)); } _typeNameAssemblyFormat = value; } } /// <summary> /// Gets or sets how object references are preserved by the serializer. /// </summary> public virtual PreserveReferencesHandling PreserveReferencesHandling { get { return _preserveReferencesHandling; } set { if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All) { throw new ArgumentOutOfRangeException(nameof(value)); } _preserveReferencesHandling = value; } } /// <summary> /// Get or set how reference loops (e.g. a class referencing itself) is handled. /// </summary> public virtual ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling; } set { if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize) { throw new ArgumentOutOfRangeException(nameof(value)); } _referenceLoopHandling = value; } } /// <summary> /// Get or set how missing members (e.g. JSON contains a property that isn't a member on the object) are handled during deserialization. /// </summary> public virtual MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling; } set { if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error) { throw new ArgumentOutOfRangeException(nameof(value)); } _missingMemberHandling = value; } } /// <summary> /// Get or set how null values are handled during serialization and deserialization. /// </summary> public virtual NullValueHandling NullValueHandling { get { return _nullValueHandling; } set { if (value < NullValueHandling.Include || value > NullValueHandling.Ignore) { throw new ArgumentOutOfRangeException(nameof(value)); } _nullValueHandling = value; } } /// <summary> /// Get or set how null default are handled during serialization and deserialization. /// </summary> public virtual DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling; } set { if (value < DefaultValueHandling.Include || value > DefaultValueHandling.IgnoreAndPopulate) { throw new ArgumentOutOfRangeException(nameof(value)); } _defaultValueHandling = value; } } /// <summary> /// Gets or sets how objects are created during deserialization. /// </summary> /// <value>The object creation handling.</value> public virtual ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling; } set { if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace) { throw new ArgumentOutOfRangeException(nameof(value)); } _objectCreationHandling = value; } } /// <summary> /// Gets or sets how constructors are used during deserialization. /// </summary> /// <value>The constructor handling.</value> public virtual ConstructorHandling ConstructorHandling { get { return _constructorHandling; } set { if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor) { throw new ArgumentOutOfRangeException(nameof(value)); } _constructorHandling = value; } } /// <summary> /// Gets or sets how metadata properties are used during deserialization. /// </summary> /// <value>The metadata properties handling.</value> public virtual MetadataPropertyHandling MetadataPropertyHandling { get { return _metadataPropertyHandling; } set { if (value < MetadataPropertyHandling.Default || value > MetadataPropertyHandling.Ignore) { throw new ArgumentOutOfRangeException(nameof(value)); } _metadataPropertyHandling = value; } } /// <summary> /// Gets a collection <see cref="JsonConverter"/> that will be used during serialization. /// </summary> /// <value>Collection <see cref="JsonConverter"/> that will be used during serialization.</value> public virtual JsonConverterCollection Converters { get { if (_converters == null) { _converters = new JsonConverterCollection(); } return _converters; } } /// <summary> /// Gets or sets the contract resolver used by the serializer when /// serializing .NET objects to JSON and vice versa. /// </summary> public virtual IContractResolver ContractResolver { get { return _contractResolver; } set { _contractResolver = value ?? DefaultContractResolver.Instance; } } /// <summary> /// Gets or sets the <see cref="StreamingContext"/> used by the serializer when invoking serialization callback methods. /// </summary> /// <value>The context.</value> public virtual StreamingContext Context { get { return _context; } set { _context = value; } } /// <summary> /// Indicates how JSON text output is formatted. /// </summary> public virtual Formatting Formatting { get { return _formatting ?? JsonSerializerSettings.DefaultFormatting; } set { _formatting = value; } } /// <summary> /// Get or set how dates are written to JSON text. /// </summary> public virtual DateFormatHandling DateFormatHandling { get { return _dateFormatHandling ?? JsonSerializerSettings.DefaultDateFormatHandling; } set { _dateFormatHandling = value; } } /// <summary> /// Get or set how <see cref="DateTime"/> time zones are handling during serialization and deserialization. /// </summary> public virtual DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling ?? JsonSerializerSettings.DefaultDateTimeZoneHandling; } set { _dateTimeZoneHandling = value; } } /// <summary> /// Get or set how date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed when reading JSON. /// </summary> public virtual DateParseHandling DateParseHandling { get { return _dateParseHandling ?? JsonSerializerSettings.DefaultDateParseHandling; } set { _dateParseHandling = value; } } /// <summary> /// Get or set how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text. /// </summary> public virtual FloatParseHandling FloatParseHandling { get { return _floatParseHandling ?? JsonSerializerSettings.DefaultFloatParseHandling; } set { _floatParseHandling = value; } } /// <summary> /// Get or set how special floating point numbers, e.g. <see cref="F:System.Double.NaN"/>, /// <see cref="F:System.Double.PositiveInfinity"/> and <see cref="F:System.Double.NegativeInfinity"/>, /// are written as JSON text. /// </summary> public virtual FloatFormatHandling FloatFormatHandling { get { return _floatFormatHandling ?? JsonSerializerSettings.DefaultFloatFormatHandling; } set { _floatFormatHandling = value; } } /// <summary> /// Get or set how strings are escaped when writing JSON text. /// </summary> public virtual StringEscapeHandling StringEscapeHandling { get { return _stringEscapeHandling ?? JsonSerializerSettings.DefaultStringEscapeHandling; } set { _stringEscapeHandling = value; } } /// <summary> /// Get or set how <see cref="DateTime"/> and <see cref="DateTimeOffset"/> values are formatted when writing JSON text, and the expected date format when reading JSON text. /// </summary> public virtual string DateFormatString { get { return _dateFormatString ?? JsonSerializerSettings.DefaultDateFormatString; } set { _dateFormatString = value; _dateFormatStringSet = true; } } /// <summary> /// Gets or sets the culture used when reading JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>. /// </summary> public virtual CultureInfo Culture { get { return _culture ?? JsonSerializerSettings.DefaultCulture; } set { _culture = value; } } /// <summary> /// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a <see cref="JsonReaderException"/>. /// </summary> public virtual int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", nameof(value)); } _maxDepth = value; _maxDepthSet = true; } } /// <summary> /// Gets a value indicating whether there will be a check for additional JSON content after deserializing an object. /// </summary> /// <value> /// <c>true</c> if there will be a check for additional JSON content after deserializing an object; otherwise, <c>false</c>. /// </value> public virtual bool CheckAdditionalContent { get { return _checkAdditionalContent ?? JsonSerializerSettings.DefaultCheckAdditionalContent; } set { _checkAdditionalContent = value; } } internal bool IsCheckAdditionalContentSet() { return (_checkAdditionalContent != null); } /// <summary> /// Initializes a new instance of the <see cref="JsonSerializer"/> class. /// </summary> public JsonSerializer() { _referenceLoopHandling = JsonSerializerSettings.DefaultReferenceLoopHandling; _missingMemberHandling = JsonSerializerSettings.DefaultMissingMemberHandling; _nullValueHandling = JsonSerializerSettings.DefaultNullValueHandling; _defaultValueHandling = JsonSerializerSettings.DefaultDefaultValueHandling; _objectCreationHandling = JsonSerializerSettings.DefaultObjectCreationHandling; _preserveReferencesHandling = JsonSerializerSettings.DefaultPreserveReferencesHandling; _constructorHandling = JsonSerializerSettings.DefaultConstructorHandling; _typeNameHandling = JsonSerializerSettings.DefaultTypeNameHandling; _metadataPropertyHandling = JsonSerializerSettings.DefaultMetadataPropertyHandling; _context = JsonSerializerSettings.DefaultContext; _binder = DefaultSerializationBinder.Instance; _culture = JsonSerializerSettings.DefaultCulture; _contractResolver = DefaultContractResolver.Instance; } /// <summary> /// Creates a new <see cref="JsonSerializer"/> instance. /// The <see cref="JsonSerializer"/> will not use default settings /// from <see cref="JsonConvert.DefaultSettings"/>. /// </summary> /// <returns> /// A new <see cref="JsonSerializer"/> instance. /// The <see cref="JsonSerializer"/> will not use default settings /// from <see cref="JsonConvert.DefaultSettings"/>. /// </returns> public static JsonSerializer Create() { return new JsonSerializer(); } /// <summary> /// Creates a new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>. /// The <see cref="JsonSerializer"/> will not use default settings /// from <see cref="JsonConvert.DefaultSettings"/>. /// </summary> /// <param name="settings">The settings to be applied to the <see cref="JsonSerializer"/>.</param> /// <returns> /// A new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>. /// The <see cref="JsonSerializer"/> will not use default settings /// from <see cref="JsonConvert.DefaultSettings"/>. /// </returns> public static JsonSerializer Create(JsonSerializerSettings settings) { JsonSerializer serializer = Create(); if (settings != null) { ApplySerializerSettings(serializer, settings); } return serializer; } /// <summary> /// Creates a new <see cref="JsonSerializer"/> instance. /// The <see cref="JsonSerializer"/> will use default settings /// from <see cref="JsonConvert.DefaultSettings"/>. /// </summary> /// <returns> /// A new <see cref="JsonSerializer"/> instance. /// The <see cref="JsonSerializer"/> will use default settings /// from <see cref="JsonConvert.DefaultSettings"/>. /// </returns> public static JsonSerializer CreateDefault() { // copy static to local variable to avoid concurrency issues Func<JsonSerializerSettings> defaultSettingsCreator = JsonConvert.DefaultSettings; JsonSerializerSettings defaultSettings = (defaultSettingsCreator != null) ? defaultSettingsCreator() : null; return Create(defaultSettings); } /// <summary> /// Creates a new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>. /// The <see cref="JsonSerializer"/> will use default settings /// from <see cref="JsonConvert.DefaultSettings"/> as well as the specified <see cref="JsonSerializerSettings"/>. /// </summary> /// <param name="settings">The settings to be applied to the <see cref="JsonSerializer"/>.</param> /// <returns> /// A new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>. /// The <see cref="JsonSerializer"/> will use default settings /// from <see cref="JsonConvert.DefaultSettings"/> as well as the specified <see cref="JsonSerializerSettings"/>. /// </returns> public static JsonSerializer CreateDefault(JsonSerializerSettings settings) { JsonSerializer serializer = CreateDefault(); if (settings != null) { ApplySerializerSettings(serializer, settings); } return serializer; } private static void ApplySerializerSettings(JsonSerializer serializer, JsonSerializerSettings settings) { if (!CollectionUtils.IsNullOrEmpty(settings.Converters)) { // insert settings converters at the beginning so they take precedence // if user wants to remove one of the default converters they will have to do it manually for (int i = 0; i < settings.Converters.Count; i++) { serializer.Converters.Insert(i, settings.Converters[i]); } } // serializer specific if (settings._typeNameHandling != null) { serializer.TypeNameHandling = settings.TypeNameHandling; } if (settings._metadataPropertyHandling != null) { serializer.MetadataPropertyHandling = settings.MetadataPropertyHandling; } if (settings._typeNameAssemblyFormat != null) { serializer.TypeNameAssemblyFormat = settings.TypeNameAssemblyFormat; } if (settings._preserveReferencesHandling != null) { serializer.PreserveReferencesHandling = settings.PreserveReferencesHandling; } if (settings._referenceLoopHandling != null) { serializer.ReferenceLoopHandling = settings.ReferenceLoopHandling; } if (settings._missingMemberHandling != null) { serializer.MissingMemberHandling = settings.MissingMemberHandling; } if (settings._objectCreationHandling != null) { serializer.ObjectCreationHandling = settings.ObjectCreationHandling; } if (settings._nullValueHandling != null) { serializer.NullValueHandling = settings.NullValueHandling; } if (settings._defaultValueHandling != null) { serializer.DefaultValueHandling = settings.DefaultValueHandling; } if (settings._constructorHandling != null) { serializer.ConstructorHandling = settings.ConstructorHandling; } if (settings._context != null) { serializer.Context = settings.Context; } if (settings._checkAdditionalContent != null) { serializer._checkAdditionalContent = settings._checkAdditionalContent; } if (settings.Error != null) { serializer.Error += settings.Error; } if (settings.ContractResolver != null) { serializer.ContractResolver = settings.ContractResolver; } if (settings.ReferenceResolverProvider != null) { serializer.ReferenceResolver = settings.ReferenceResolverProvider(); } if (settings.TraceWriter != null) { serializer.TraceWriter = settings.TraceWriter; } if (settings.EqualityComparer != null) { serializer.EqualityComparer = settings.EqualityComparer; } if (settings.Binder != null) { serializer.Binder = settings.Binder; } // reader/writer specific // unset values won't override reader/writer set values if (settings._formatting != null) { serializer._formatting = settings._formatting; } if (settings._dateFormatHandling != null) { serializer._dateFormatHandling = settings._dateFormatHandling; } if (settings._dateTimeZoneHandling != null) { serializer._dateTimeZoneHandling = settings._dateTimeZoneHandling; } if (settings._dateParseHandling != null) { serializer._dateParseHandling = settings._dateParseHandling; } if (settings._dateFormatStringSet) { serializer._dateFormatString = settings._dateFormatString; serializer._dateFormatStringSet = settings._dateFormatStringSet; } if (settings._floatFormatHandling != null) { serializer._floatFormatHandling = settings._floatFormatHandling; } if (settings._floatParseHandling != null) { serializer._floatParseHandling = settings._floatParseHandling; } if (settings._stringEscapeHandling != null) { serializer._stringEscapeHandling = settings._stringEscapeHandling; } if (settings._culture != null) { serializer._culture = settings._culture; } if (settings._maxDepthSet) { serializer._maxDepth = settings._maxDepth; serializer._maxDepthSet = settings._maxDepthSet; } } /// <summary> /// Populates the JSON values onto the target object. /// </summary> /// <param name="reader">The <see cref="TextReader"/> that contains the JSON structure to reader values from.</param> /// <param name="target">The target object to populate values onto.</param> public void Populate(TextReader reader, object target) { Populate(new JsonTextReader(reader), target); } /// <summary> /// Populates the JSON values onto the target object. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> that contains the JSON structure to reader values from.</param> /// <param name="target">The target object to populate values onto.</param> public void Populate(JsonReader reader, object target) { PopulateInternal(reader, target); } internal virtual void PopulateInternal(JsonReader reader, object target) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); ValidationUtils.ArgumentNotNull(target, nameof(target)); // set serialization options onto reader CultureInfo previousCulture; DateTimeZoneHandling? previousDateTimeZoneHandling; DateParseHandling? previousDateParseHandling; FloatParseHandling? previousFloatParseHandling; int? previousMaxDepth; string previousDateFormatString; SetupReader(reader, out previousCulture, out previousDateTimeZoneHandling, out previousDateParseHandling, out previousFloatParseHandling, out previousMaxDepth, out previousDateFormatString); TraceJsonReader traceJsonReader = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonReader(reader) : null; JsonSerializerInternalReader serializerReader = new JsonSerializerInternalReader(this); serializerReader.Populate(traceJsonReader ?? reader, target); if (traceJsonReader != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); } /// <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="StringReader"/> /// into an instance of the specified type. /// </summary> /// <param name="reader">The <see cref="TextReader"/> containing the object.</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(TextReader reader, Type objectType) { return Deserialize(new JsonTextReader(reader), objectType); } /// <summary> /// Deserializes the JSON structure contained by the specified <see cref="JsonReader"/> /// into an instance of the specified type. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> containing the object.</param> /// <typeparam name="T">The type of the object to deserialize.</typeparam> /// <returns>The instance of <typeparamref name="T"/> being deserialized.</returns> public T Deserialize<T>(JsonReader reader) { return (T)Deserialize(reader, typeof(T)); } /// <summary> /// Deserializes the JSON structure contained by the specified <see cref="JsonReader"/> /// into an instance of the specified type. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> containing the object.</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) { return DeserializeInternal(reader, objectType); } internal virtual object DeserializeInternal(JsonReader reader, Type objectType) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); // set serialization options onto reader CultureInfo previousCulture; DateTimeZoneHandling? previousDateTimeZoneHandling; DateParseHandling? previousDateParseHandling; FloatParseHandling? previousFloatParseHandling; int? previousMaxDepth; string previousDateFormatString; SetupReader(reader, out previousCulture, out previousDateTimeZoneHandling, out previousDateParseHandling, out previousFloatParseHandling, out previousMaxDepth, out previousDateFormatString); TraceJsonReader traceJsonReader = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonReader(reader) : null; JsonSerializerInternalReader serializerReader = new JsonSerializerInternalReader(this); object value = serializerReader.Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent); if (traceJsonReader != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); return value; } private void SetupReader(JsonReader reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString) { if (_culture != null && !_culture.Equals(reader.Culture)) { previousCulture = reader.Culture; reader.Culture = _culture; } else { previousCulture = null; } if (_dateTimeZoneHandling != null && reader.DateTimeZoneHandling != _dateTimeZoneHandling) { previousDateTimeZoneHandling = reader.DateTimeZoneHandling; reader.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault(); } else { previousDateTimeZoneHandling = null; } if (_dateParseHandling != null && reader.DateParseHandling != _dateParseHandling) { previousDateParseHandling = reader.DateParseHandling; reader.DateParseHandling = _dateParseHandling.GetValueOrDefault(); } else { previousDateParseHandling = null; } if (_floatParseHandling != null && reader.FloatParseHandling != _floatParseHandling) { previousFloatParseHandling = reader.FloatParseHandling; reader.FloatParseHandling = _floatParseHandling.GetValueOrDefault(); } else { previousFloatParseHandling = null; } if (_maxDepthSet && reader.MaxDepth != _maxDepth) { previousMaxDepth = reader.MaxDepth; reader.MaxDepth = _maxDepth; } else { previousMaxDepth = null; } if (_dateFormatStringSet && reader.DateFormatString != _dateFormatString) { previousDateFormatString = reader.DateFormatString; reader.DateFormatString = _dateFormatString; } else { previousDateFormatString = null; } JsonTextReader textReader = reader as JsonTextReader; if (textReader != null) { DefaultContractResolver resolver = _contractResolver as DefaultContractResolver; if (resolver != null) { textReader.NameTable = resolver.GetState().NameTable; } } } private void ResetReader(JsonReader reader, CultureInfo previousCulture, DateTimeZoneHandling? previousDateTimeZoneHandling, DateParseHandling? previousDateParseHandling, FloatParseHandling? previousFloatParseHandling, int? previousMaxDepth, string previousDateFormatString) { // reset reader back to previous options if (previousCulture != null) { reader.Culture = previousCulture; } if (previousDateTimeZoneHandling != null) { reader.DateTimeZoneHandling = previousDateTimeZoneHandling.GetValueOrDefault(); } if (previousDateParseHandling != null) { reader.DateParseHandling = previousDateParseHandling.GetValueOrDefault(); } if (previousFloatParseHandling != null) { reader.FloatParseHandling = previousFloatParseHandling.GetValueOrDefault(); } if (_maxDepthSet) { reader.MaxDepth = previousMaxDepth; } if (_dateFormatStringSet) { reader.DateFormatString = previousDateFormatString; } JsonTextReader textReader = reader as JsonTextReader; if (textReader != null) { textReader.NameTable = null; } } /// <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 JsonTextWriter(textWriter), value); } /// <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="jsonWriter">The <see cref="JsonWriter"/> used to write the JSON structure.</param> /// <param name="value">The <see cref="Object"/> to serialize.</param> /// <param name="objectType"> /// The type of the value being serialized. /// This parameter is used when <see cref="TypeNameHandling"/> is Auto to write out the type name if the type of the value does not match. /// Specifing the type is optional. /// </param> public void Serialize(JsonWriter jsonWriter, object value, Type objectType) { SerializeInternal(jsonWriter, value, objectType); } /// <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> /// <param name="objectType"> /// The type of the value being serialized. /// This parameter is used when <see cref="TypeNameHandling"/> is Auto to write out the type name if the type of the value does not match. /// Specifing the type is optional. /// </param> public void Serialize(TextWriter textWriter, object value, Type objectType) { Serialize(new JsonTextWriter(textWriter), value, objectType); } /// <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) { SerializeInternal(jsonWriter, value, null); } internal virtual void SerializeInternal(JsonWriter jsonWriter, object value, Type objectType) { ValidationUtils.ArgumentNotNull(jsonWriter, nameof(jsonWriter)); // set serialization options onto writer Formatting? previousFormatting = null; if (_formatting != null && jsonWriter.Formatting != _formatting) { previousFormatting = jsonWriter.Formatting; jsonWriter.Formatting = _formatting.GetValueOrDefault(); } DateFormatHandling? previousDateFormatHandling = null; if (_dateFormatHandling != null && jsonWriter.DateFormatHandling != _dateFormatHandling) { previousDateFormatHandling = jsonWriter.DateFormatHandling; jsonWriter.DateFormatHandling = _dateFormatHandling.GetValueOrDefault(); } DateTimeZoneHandling? previousDateTimeZoneHandling = null; if (_dateTimeZoneHandling != null && jsonWriter.DateTimeZoneHandling != _dateTimeZoneHandling) { previousDateTimeZoneHandling = jsonWriter.DateTimeZoneHandling; jsonWriter.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault(); } FloatFormatHandling? previousFloatFormatHandling = null; if (_floatFormatHandling != null && jsonWriter.FloatFormatHandling != _floatFormatHandling) { previousFloatFormatHandling = jsonWriter.FloatFormatHandling; jsonWriter.FloatFormatHandling = _floatFormatHandling.GetValueOrDefault(); } StringEscapeHandling? previousStringEscapeHandling = null; if (_stringEscapeHandling != null && jsonWriter.StringEscapeHandling != _stringEscapeHandling) { previousStringEscapeHandling = jsonWriter.StringEscapeHandling; jsonWriter.StringEscapeHandling = _stringEscapeHandling.GetValueOrDefault(); } CultureInfo previousCulture = null; if (_culture != null && !_culture.Equals(jsonWriter.Culture)) { previousCulture = jsonWriter.Culture; jsonWriter.Culture = _culture; } string previousDateFormatString = null; if (_dateFormatStringSet && jsonWriter.DateFormatString != _dateFormatString) { previousDateFormatString = jsonWriter.DateFormatString; jsonWriter.DateFormatString = _dateFormatString; } TraceJsonWriter traceJsonWriter = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonWriter(jsonWriter) : null; JsonSerializerInternalWriter serializerWriter = new JsonSerializerInternalWriter(this); serializerWriter.Serialize(traceJsonWriter ?? jsonWriter, value, objectType); if (traceJsonWriter != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonWriter.GetSerializedJsonMessage(), null); } // reset writer back to previous options if (previousFormatting != null) { jsonWriter.Formatting = previousFormatting.GetValueOrDefault(); } if (previousDateFormatHandling != null) { jsonWriter.DateFormatHandling = previousDateFormatHandling.GetValueOrDefault(); } if (previousDateTimeZoneHandling != null) { jsonWriter.DateTimeZoneHandling = previousDateTimeZoneHandling.GetValueOrDefault(); } if (previousFloatFormatHandling != null) { jsonWriter.FloatFormatHandling = previousFloatFormatHandling.GetValueOrDefault(); } if (previousStringEscapeHandling != null) { jsonWriter.StringEscapeHandling = previousStringEscapeHandling.GetValueOrDefault(); } if (_dateFormatStringSet) { jsonWriter.DateFormatString = previousDateFormatString; } if (previousCulture != null) { jsonWriter.Culture = previousCulture; } } internal IReferenceResolver GetReferenceResolver() { if (_referenceResolver == null) { _referenceResolver = new DefaultReferenceResolver(); } return _referenceResolver; } internal JsonConverter GetMatchingConverter(Type type) { return GetMatchingConverter(_converters, type); } internal static JsonConverter GetMatchingConverter(IList<JsonConverter> converters, Type objectType) { #if DEBUG ValidationUtils.ArgumentNotNull(objectType, nameof(objectType)); #endif if (converters != null) { for (int i = 0; i < converters.Count; i++) { JsonConverter converter = converters[i]; if (converter.CanConvert(objectType)) { return converter; } } } return null; } internal void OnError(ErrorEventArgs e) { EventHandler<ErrorEventArgs> error = Error; if (error != null) { error(this, e); } } } }
// 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.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; namespace System { [Serializable] [CLSCompliant(false)] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct UInt16 : IComparable, IConvertible, IFormattable, IComparable<UInt16>, IEquatable<UInt16>, ISpanFormattable { private ushort m_value; // Do not rename (binary serialization) public const ushort MaxValue = (ushort)0xFFFF; public const ushort MinValue = 0; // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type UInt16, this method throws an ArgumentException. // public int CompareTo(Object value) { if (value == null) { return 1; } if (value is UInt16) { return ((int)m_value - (int)(((UInt16)value).m_value)); } throw new ArgumentException(SR.Arg_MustBeUInt16); } public int CompareTo(UInt16 value) { return ((int)m_value - (int)value); } public override bool Equals(Object obj) { if (!(obj is UInt16)) { return false; } return m_value == ((UInt16)obj).m_value; } [NonVersionable] public bool Equals(UInt16 obj) { return m_value == obj; } // Returns a HashCode for the UInt16 public override int GetHashCode() { return (int)m_value; } // Converts the current value to a String in base-10 with no extra padding. public override String ToString() { return Number.FormatUInt32(m_value, null, null); } public String ToString(IFormatProvider provider) { return Number.FormatUInt32(m_value, null, provider); } public String ToString(String format) { return Number.FormatUInt32(m_value, format, null); } public String ToString(String format, IFormatProvider provider) { return Number.FormatUInt32(m_value, format, provider); } public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null) { return Number.TryFormatUInt32(m_value, format, provider, destination, out charsWritten); } [CLSCompliant(false)] public static ushort Parse(String s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } [CLSCompliant(false)] public static ushort Parse(String s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, style, NumberFormatInfo.CurrentInfo); } [CLSCompliant(false)] public static ushort Parse(String s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } [CLSCompliant(false)] public static ushort Parse(String s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, style, NumberFormatInfo.GetInstance(provider)); } [CLSCompliant(false)] public static ushort Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Parse(s, style, NumberFormatInfo.GetInstance(provider)); } private static ushort Parse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info) { uint i = 0; try { i = Number.ParseUInt32(s, style, info); } catch (OverflowException e) { throw new OverflowException(SR.Overflow_UInt16, e); } if (i > MaxValue) throw new OverflowException(SR.Overflow_UInt16); return (ushort)i; } [CLSCompliant(false)] public static bool TryParse(String s, out UInt16 result) { if (s == null) { result = 0; return false; } return TryParse((ReadOnlySpan<char>)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } [CLSCompliant(false)] public static bool TryParse(ReadOnlySpan<char> s, out ushort result) { return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } [CLSCompliant(false)] public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out UInt16 result) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { result = 0; return false; } return TryParse((ReadOnlySpan<char>)s, style, NumberFormatInfo.GetInstance(provider), out result); } [CLSCompliant(false)] public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out ushort result) { NumberFormatInfo.ValidateParseStyleInteger(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out UInt16 result) { result = 0; UInt32 i; if (!Number.TryParseUInt32(s, style, info, out i)) { return false; } if (i > MaxValue) { return false; } result = (UInt16)i; return true; } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.UInt16; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(m_value); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return m_value; } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "UInt16", "DateTime")); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
/* * Copyright (c) Contributors * Copyright (c) Contributors, http://opensimulator.org/ * * 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. */ // to build without references to System.Drawing, comment this out #define SYSTEM_DRAWING using System; using System.Collections.Generic; using System.Text; using System.IO; #if SYSTEM_DRAWING using System.Drawing; using System.Drawing.Imaging; #endif namespace PrimMesher { public class SculptMesh { public List<Coord> coords; public List<Face> faces; public List<ViewerFace> viewerFaces; public List<Coord> normals; public List<UVCoord> uvs; public enum SculptType { sphere = 1, torus = 2, plane = 3, cylinder = 4 }; #if SYSTEM_DRAWING public SculptMesh SculptMeshFromFile(string fileName, SculptType sculptType, int lod, bool viewerMode) { Bitmap bitmap = (Bitmap)Bitmap.FromFile(fileName); SculptMesh sculptMesh = new SculptMesh(bitmap, sculptType, lod, viewerMode); bitmap.Dispose(); return sculptMesh; } public SculptMesh(string fileName, int sculptType, int lod, int viewerMode, int mirror, int invert) { Bitmap bitmap = (Bitmap)Bitmap.FromFile(fileName); _SculptMesh(bitmap, (SculptType)sculptType, lod, viewerMode != 0, mirror != 0, invert != 0); bitmap.Dispose(); } #endif /// <summary> /// ** Experimental ** May disappear from future versions ** not recommeneded for use in applications /// Construct a sculpt mesh from a 2D array of floats /// </summary> /// <param name="zMap"></param> /// <param name="xBegin"></param> /// <param name="xEnd"></param> /// <param name="yBegin"></param> /// <param name="yEnd"></param> /// <param name="viewerMode"></param> public SculptMesh(float[,] zMap, float xBegin, float xEnd, float yBegin, float yEnd, bool viewerMode) { float xStep, yStep; float uStep, vStep; int numYElements = zMap.GetLength(0); int numXElements = zMap.GetLength(1); try { xStep = (xEnd - xBegin) / (float)(numXElements - 1); yStep = (yEnd - yBegin) / (float)(numYElements - 1); uStep = 1.0f / (numXElements - 1); vStep = 1.0f / (numYElements - 1); } catch (DivideByZeroException) { return; } coords = new List<Coord>(); faces = new List<Face>(); normals = new List<Coord>(); uvs = new List<UVCoord>(); viewerFaces = new List<ViewerFace>(); int p1, p2, p3, p4; int x, y; int xStart = 0, yStart = 0; for (y = yStart; y < numYElements; y++) { int rowOffset = y * numXElements; for (x = xStart; x < numXElements; x++) { /* * p1-----p2 * | \ f2 | * | \ | * | f1 \| * p3-----p4 */ p4 = rowOffset + x; p3 = p4 - 1; p2 = p4 - numXElements; p1 = p3 - numXElements; Coord c = new Coord(xBegin + x * xStep, yBegin + y * yStep, zMap[y, x], false); this.coords.Add(c); if (viewerMode) { this.normals.Add(new Coord(false)); this.uvs.Add(new UVCoord(uStep * x, 1.0f - vStep * y)); } if (y > 0 && x > 0) { Face f1, f2; if (viewerMode) { f1 = new Face(p1, p4, p3, p1, p4, p3); f1.uv1 = p1; f1.uv2 = p4; f1.uv3 = p3; f2 = new Face(p1, p2, p4, p1, p2, p4); f2.uv1 = p1; f2.uv2 = p2; f2.uv3 = p4; } else { f1 = new Face(p1, p4, p3); f2 = new Face(p1, p2, p4); } this.faces.Add(f1); this.faces.Add(f2); } } } if (viewerMode) calcVertexNormals(SculptType.plane, numXElements, numYElements); } #if SYSTEM_DRAWING public SculptMesh(Bitmap sculptBitmap, SculptType sculptType, int lod, bool viewerMode) { _SculptMesh(sculptBitmap, sculptType, lod, viewerMode, false, false); } public SculptMesh(Bitmap sculptBitmap, SculptType sculptType, int lod, bool viewerMode, bool mirror, bool invert) { _SculptMesh(sculptBitmap, sculptType, lod, viewerMode, mirror, invert); } #endif public SculptMesh(List<List<Coord>> rows, SculptType sculptType, bool viewerMode, bool mirror, bool invert) { _SculptMesh(rows, sculptType, viewerMode, mirror, invert); } #if SYSTEM_DRAWING /// <summary> /// converts a bitmap to a list of lists of coords, while scaling the image. /// the scaling is done in floating point so as to allow for reduced vertex position /// quantization as the position will be averaged between pixel values. this routine will /// likely fail if the bitmap width and height are not powers of 2. /// </summary> /// <param name="bitmap"></param> /// <param name="scale"></param> /// <param name="mirror"></param> /// <returns></returns> private List<List<Coord>> bitmap2Coords(Bitmap bitmap, int scale, bool mirror) { int numRows = bitmap.Height / scale; int numCols = bitmap.Width / scale; List<List<Coord>> rows = new List<List<Coord>>(numRows); float pixScale = 1.0f / (scale * scale); pixScale /= 255; int imageX, imageY = 0; int rowNdx, colNdx; for (rowNdx = 0; rowNdx < numRows; rowNdx++) { List<Coord> row = new List<Coord>(numCols); for (colNdx = 0; colNdx < numCols; colNdx++) { imageX = colNdx * scale; int imageYStart = rowNdx * scale; int imageYEnd = imageYStart + scale; int imageXEnd = imageX + scale; float rSum = 0.0f; float gSum = 0.0f; float bSum = 0.0f; for (; imageX < imageXEnd; imageX++) { for (imageY = imageYStart; imageY < imageYEnd; imageY++) { Color c = bitmap.GetPixel(imageX, imageY); if (c.A != 255) { bitmap.SetPixel(imageX, imageY, Color.FromArgb(255, c.R, c.G, c.B)); c = bitmap.GetPixel(imageX, imageY); } rSum += c.R; gSum += c.G; bSum += c.B; } } if (mirror) row.Add(new Coord(-(rSum * pixScale - 0.5f), gSum * pixScale - 0.5f, bSum * pixScale - 0.5f, false)); else row.Add(new Coord(rSum * pixScale - 0.5f, gSum * pixScale - 0.5f, bSum * pixScale - 0.5f, false)); } rows.Add(row); } return rows; } private List<List<Coord>> bitmap2CoordsSampled(Bitmap bitmap, int scale, bool mirror) { int numRows = bitmap.Height / scale; int numCols = bitmap.Width / scale; List<List<Coord>> rows = new List<List<Coord>>(numRows); float pixScale = 1.0f / 256.0f; int imageX, imageY = 0; int rowNdx, colNdx; for (rowNdx = 0; rowNdx <= numRows; rowNdx++) { List<Coord> row = new List<Coord>(numCols); imageY = rowNdx * scale; if (rowNdx == numRows) imageY--; for (colNdx = 0; colNdx <= numCols; colNdx++) { imageX = colNdx * scale; if (colNdx == numCols) imageX--; Color c = bitmap.GetPixel(imageX, imageY); if (c.A != 255) { bitmap.SetPixel(imageX, imageY, Color.FromArgb(255, c.R, c.G, c.B)); c = bitmap.GetPixel(imageX, imageY); } if (mirror) row.Add(new Coord(-(c.R * pixScale - 0.5f), c.G * pixScale - 0.5f, c.B * pixScale - 0.5f, false)); else row.Add(new Coord(c.R * pixScale - 0.5f, c.G * pixScale - 0.5f, c.B * pixScale - 0.5f, false)); } rows.Add(row); } return rows; } void _SculptMesh(Bitmap sculptBitmap, SculptType sculptType, int lod, bool viewerMode, bool mirror, bool invert) { _SculptMesh(new SculptMap(sculptBitmap, lod).ToRows(mirror), sculptType, viewerMode, mirror, invert); } #endif void _SculptMesh(List<List<Coord>> rows, SculptType sculptType, bool viewerMode, bool mirror, bool invert) { coords = new List<Coord>(); faces = new List<Face>(); normals = new List<Coord>(); uvs = new List<UVCoord>(); sculptType = (SculptType)(((int)sculptType) & 0x07); if (mirror) invert = !invert; viewerFaces = new List<ViewerFace>(); int width = rows[0].Count; int p1, p2, p3, p4; int imageX, imageY; if (sculptType != SculptType.plane) { if (rows.Count % 2 == 0) { for (int rowNdx = 0; rowNdx < rows.Count; rowNdx++) rows[rowNdx].Add(rows[rowNdx][0]); } else { int lastIndex = rows[0].Count - 1; for (int i = 0; i < rows.Count; i++) rows[i][0] = rows[i][lastIndex]; } } Coord topPole = rows[0][width / 2]; Coord bottomPole = rows[rows.Count - 1][width / 2]; if (sculptType == SculptType.sphere) { if (rows.Count % 2 == 0) { int count = rows[0].Count; List<Coord> topPoleRow = new List<Coord>(count); List<Coord> bottomPoleRow = new List<Coord>(count); for (int i = 0; i < count; i++) { topPoleRow.Add(topPole); bottomPoleRow.Add(bottomPole); } rows.Insert(0, topPoleRow); rows.Add(bottomPoleRow); } else { int count = rows[0].Count; List<Coord> topPoleRow = rows[0]; List<Coord> bottomPoleRow = rows[rows.Count - 1]; for (int i = 0; i < count; i++) { topPoleRow[i] = topPole; bottomPoleRow[i] = bottomPole; } } } if (sculptType == SculptType.torus) rows.Add(rows[0]); int coordsDown = rows.Count; int coordsAcross = rows[0].Count; float widthUnit = 1.0f / (coordsAcross - 1); float heightUnit = 1.0f / (coordsDown - 1); for (imageY = 0; imageY < coordsDown; imageY++) { int rowOffset = imageY * coordsAcross; for (imageX = 0; imageX < coordsAcross; imageX++) { /* * p1-----p2 * | \ f2 | * | \ | * | f1 \| * p3-----p4 */ p4 = rowOffset + imageX; p3 = p4 - 1; p2 = p4 - coordsAcross; p1 = p3 - coordsAcross; this.coords.Add(rows[imageY][imageX]); if (viewerMode) { this.normals.Add(new Coord(false)); this.uvs.Add(new UVCoord(widthUnit * imageX, heightUnit * imageY)); } if (imageY > 0 && imageX > 0) { Face f1, f2; if (viewerMode) { if (invert) { f1 = new Face(p1, p4, p3, p1, p4, p3); f1.uv1 = p1; f1.uv2 = p4; f1.uv3 = p3; f2 = new Face(p1, p2, p4, p1, p2, p4); f2.uv1 = p1; f2.uv2 = p2; f2.uv3 = p4; } else { f1 = new Face(p1, p3, p4, p1, p3, p4); f1.uv1 = p1; f1.uv2 = p3; f1.uv3 = p4; f2 = new Face(p1, p4, p2, p1, p4, p2); f2.uv1 = p1; f2.uv2 = p4; f2.uv3 = p2; } } else { if (invert) { f1 = new Face(p1, p4, p3); f2 = new Face(p1, p2, p4); } else { f1 = new Face(p1, p3, p4); f2 = new Face(p1, p4, p2); } } this.faces.Add(f1); this.faces.Add(f2); } } } if (viewerMode) calcVertexNormals(sculptType, coordsAcross, coordsDown); } /// <summary> /// Duplicates a SculptMesh object. All object properties are copied by value, including lists. /// </summary> /// <returns></returns> public SculptMesh Copy() { return new SculptMesh(this); } public SculptMesh(SculptMesh sm) { coords = new List<Coord>(sm.coords); faces = new List<Face>(sm.faces); viewerFaces = new List<ViewerFace>(sm.viewerFaces); normals = new List<Coord>(sm.normals); uvs = new List<UVCoord>(sm.uvs); } private void calcVertexNormals(SculptType sculptType, int xSize, int ySize) { // compute vertex normals by summing all the surface normals of all the triangles sharing // each vertex and then normalizing int numFaces = this.faces.Count; for (int i = 0; i < numFaces; i++) { Face face = this.faces[i]; Coord surfaceNormal = face.SurfaceNormal(this.coords); this.normals[face.n1] += surfaceNormal; this.normals[face.n2] += surfaceNormal; this.normals[face.n3] += surfaceNormal; } int numNormals = this.normals.Count; for (int i = 0; i < numNormals; i++) this.normals[i] = this.normals[i].Normalize(); if (sculptType != SculptType.plane) { // blend the vertex normals at the cylinder seam for (int y = 0; y < ySize; y++) { int rowOffset = y * xSize; this.normals[rowOffset] = this.normals[rowOffset + xSize - 1] = (this.normals[rowOffset] + this.normals[rowOffset + xSize - 1]).Normalize(); } } foreach (Face face in this.faces) { ViewerFace vf = new ViewerFace(0); vf.v1 = this.coords[face.v1]; vf.v2 = this.coords[face.v2]; vf.v3 = this.coords[face.v3]; vf.coordIndex1 = face.v1; vf.coordIndex2 = face.v2; vf.coordIndex3 = face.v3; vf.n1 = this.normals[face.n1]; vf.n2 = this.normals[face.n2]; vf.n3 = this.normals[face.n3]; vf.uv1 = this.uvs[face.uv1]; vf.uv2 = this.uvs[face.uv2]; vf.uv3 = this.uvs[face.uv3]; this.viewerFaces.Add(vf); } } /// <summary> /// Adds a value to each XYZ vertex coordinate in the mesh /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="z"></param> public void AddPos(float x, float y, float z) { int i; int numVerts = this.coords.Count; Coord vert; for (i = 0; i < numVerts; i++) { vert = this.coords[i]; vert.X += x; vert.Y += y; vert.Z += z; this.coords[i] = vert; } if (this.viewerFaces != null) { int numViewerFaces = this.viewerFaces.Count; for (i = 0; i < numViewerFaces; i++) { ViewerFace v = this.viewerFaces[i]; v.AddPos(x, y, z); this.viewerFaces[i] = v; } } } /// <summary> /// Rotates the mesh /// </summary> /// <param name="q"></param> public void AddRot(Quat q) { int i; int numVerts = this.coords.Count; for (i = 0; i < numVerts; i++) this.coords[i] *= q; int numNormals = this.normals.Count; for (i = 0; i < numNormals; i++) this.normals[i] *= q; if (this.viewerFaces != null) { int numViewerFaces = this.viewerFaces.Count; for (i = 0; i < numViewerFaces; i++) { ViewerFace v = this.viewerFaces[i]; v.v1 *= q; v.v2 *= q; v.v3 *= q; v.n1 *= q; v.n2 *= q; v.n3 *= q; this.viewerFaces[i] = v; } } } public void Scale(float x, float y, float z) { int i; int numVerts = this.coords.Count; Coord m = new Coord(x, y, z, false); for (i = 0; i < numVerts; i++) this.coords[i] *= m; if (this.viewerFaces != null) { int numViewerFaces = this.viewerFaces.Count; for (i = 0; i < numViewerFaces; i++) { ViewerFace v = this.viewerFaces[i]; v.v1 *= m; v.v2 *= m; v.v3 *= m; this.viewerFaces[i] = v; } } } public void DumpRaw(String path, String name, String title) { if (path == null) return; String fileName = name + "_" + title + ".raw"; String completePath = System.IO.Path.Combine(path, fileName); StreamWriter sw = new StreamWriter(completePath); for (int i = 0; i < this.faces.Count; i++) { string s = this.coords[this.faces[i].v1].ToString(); s += " " + this.coords[this.faces[i].v2].ToString(); s += " " + this.coords[this.faces[i].v3].ToString(); sw.WriteLine(s); } sw.Close(); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using QuantConnect.Data; using QuantConnect.Brokerages; using QuantConnect.Orders.Fees; using QuantConnect.Orders; using QuantConnect.Interfaces; using QuantConnect.Securities; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// Regression test algorithm where custom a <see cref="FeeModel"/> does not use Account the Currency /// </summary> public class FeeModelNotUsingAccountCurrency : QCAlgorithm, IRegressionAlgorithmDefinition { private Security _security; // Adding this so we only trade once, so math is easier and clear private bool _alreadyTraded; private int _initialEurCash = 10000; private decimal _orderFeesInAccountCurrency; /// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> public override void Initialize() { SetStartDate(2018, 4, 4); // Set Start Date SetEndDate(2018, 4, 4); // Set End Date // Set Strategy Cash (USD) to 0. This is required for // SetHoldings(_security.Symbol, 1) not to fail SetCash(0); // EUR/USD conversion rate will be updated dynamically // Note: the conversion rates are required in backtesting (for now) because of this issue: // https://github.com/QuantConnect/Lean/issues/1859 SetCash("EUR", _initialEurCash, 1.23m); SetBrokerageModel(BrokerageName.GDAX, AccountType.Cash); _security = AddCrypto("BTCEUR"); // This is required because in our custom model, NonAccountCurrencyCustomFeeModel, // fees will be charged in ETH (not Base, nor Quote, not account currency). // Setting the cash allows the system to add a data subscription to fetch required conversion rates. SetCash("ETH", 0, 0m); _security.FeeModel = new NonAccountCurrencyCustomFeeModel(); } /// <summary> /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. /// </summary> /// <param name="data">Slice object keyed by symbol containing the stock data</param> public override void OnData(Slice data) { if (!Portfolio.Invested && !_alreadyTraded) { _alreadyTraded = true; SetHoldings(_security.Symbol, 1); Debug("Purchased Stock"); } else { Liquidate(_security.Symbol); } } public override void OnOrderEvent(OrderEvent orderEvent) { Debug(Time + " " + orderEvent); _orderFeesInAccountCurrency += Portfolio.CashBook.ConvertToAccountCurrency(orderEvent.OrderFee.Value).Amount; } public override void OnEndOfAlgorithm() { Log($"TotalPortfolioValue: {Portfolio.TotalPortfolioValue}"); Log($"CashBook: {Portfolio.CashBook}"); Log($"Holdings.TotalCloseProfit: {_security.Holdings.TotalCloseProfit()}"); // Fees will be applied to the corresponding Cash currency. 1 ETH * 2 trades if (Portfolio.CashBook["ETH"].Amount != -2) { throw new Exception("Unexpected ETH cash amount: " + $"{Portfolio.CashBook["ETH"].Amount}"); } if (Portfolio.CashBook["USD"].Amount != 0) { throw new Exception("Unexpected USD cash amount: " + $"{Portfolio.CashBook["USD"].Amount}"); } if (Portfolio.CashBook["BTC"].Amount != 0) { throw new Exception("Unexpected BTC cash amount: " + $"{Portfolio.CashBook["BTC"].Amount}"); } if (Portfolio.CashBook.ContainsKey(Currencies.NullCurrency)) { throw new Exception("Unexpected NullCurrency cash"); } var closedTrade = TradeBuilder.ClosedTrades[0]; var profitInQuoteCurrency = (closedTrade.ExitPrice - closedTrade.EntryPrice) * closedTrade.Quantity; if (Portfolio.CashBook["EUR"].Amount != _initialEurCash + profitInQuoteCurrency) { throw new Exception("Unexpected EUR cash amount: " + $"{Portfolio.CashBook["EUR"].Amount}"); } if (closedTrade.TotalFees != _orderFeesInAccountCurrency) { throw new Exception($"Unexpected closed trades total fees {closedTrade.TotalFees}"); } if (_security.Holdings.TotalFees != _orderFeesInAccountCurrency) { throw new Exception($"Unexpected closed trades total fees {closedTrade.TotalFees}"); } } internal class NonAccountCurrencyCustomFeeModel : FeeModel { public override OrderFee GetOrderFee(OrderFeeParameters parameters) { return new OrderFee(new CashAmount(1m, "ETH")); } } /// <summary> /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm. /// </summary> public bool CanRunLocally { get; } = true; /// <summary> /// This is used by the regression test system to indicate which languages this algorithm is written in. /// </summary> public Language[] Languages { get; } = { Language.CSharp }; /// <summary> /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm /// </summary> public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string> { {"Total Trades", "2"}, {"Average Win", "0%"}, {"Average Loss", "0%"}, {"Compounding Annual Return", "0%"}, {"Drawdown", "0%"}, {"Expectancy", "0"}, {"Net Profit", "0%"}, {"Sharpe Ratio", "0"}, {"Probabilistic Sharpe Ratio", "0%"}, {"Loss Rate", "0%"}, {"Win Rate", "0%"}, {"Profit-Loss Ratio", "0"}, {"Alpha", "0"}, {"Beta", "0"}, {"Annual Standard Deviation", "0"}, {"Annual Variance", "0"}, {"Information Ratio", "0"}, {"Tracking Error", "0"}, {"Treynor Ratio", "0"}, {"Total Fees", "$804.33"}, {"Estimated Strategy Capacity", "$11000.00"}, {"Lowest Capacity Asset", "BTCEUR XJ"}, {"Fitness Score", "0.504"}, {"Kelly Criterion Estimate", "0"}, {"Kelly Criterion Probability Value", "0"}, {"Sortino Ratio", "79228162514264337593543950335"}, {"Return Over Maximum Drawdown", "-15.574"}, {"Portfolio Turnover", "2.057"}, {"Total Insights Generated", "0"}, {"Total Insights Closed", "0"}, {"Total Insights Analysis Completed", "0"}, {"Long Insight Count", "0"}, {"Short Insight Count", "0"}, {"Long/Short Ratio", "100%"}, {"Estimated Monthly Alpha Value", "$0"}, {"Total Accumulated Estimated Alpha Value", "$0"}, {"Mean Population Estimated Insight Value", "$0"}, {"Mean Population Direction", "0%"}, {"Mean Population Magnitude", "0%"}, {"Rolling Averaged Population Direction", "0%"}, {"Rolling Averaged Population Magnitude", "0%"}, {"OrderListHash", "c84d1ceacb0da30c1c1c0314f9fc850c"} }; } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace CodeCave.Revit.Toolkit.Parameters.Shared { /// <summary> /// This class represents Revit shared parameter file. /// </summary> /// <inheritdoc cref="ICloneable" /> /// <inheritdoc cref="IEquatable{SharedParameterFile}" /> /// <seealso cref="ICloneable" /> /// <seealso cref="IEquatable{SharedParameterFile}" /> public sealed partial class SharedParameterFile { /// <summary> /// Represents the entries of the *PARAM section of a shared parameter file. /// </summary> /// <seealso cref="T:CodeCave.Revit.Toolkit.Parameters.IDefinition" /> /// <seealso cref="T:CodeCave.Revit.Toolkit.Parameters.IParameter" /> /// <inheritdoc cref="IDefinition" /> /// <inheritdoc cref="IParameter" /> /// <seealso cref="IEquatable{SharedParameterFile}" /> [DebuggerDisplay("Name = {Name} Guid = {Guid} Group = {Group?.Id} Type = {ParameterType}")] public class ParameterDefinition : IDefinition, IParameter, IEquatable<ParameterDefinition> { /// <summary> /// Initializes a new instance of the <see cref="ParameterDefinition"/> class. /// </summary> protected ParameterDefinition() {} /// <summary> /// Initializes a new instance of the <see cref="ParameterDefinition"/> class. /// </summary> /// <param name="guid">The unique identifier of the parameter.</param> /// <param name="name">The name of the parameter.</param> /// <param name="group">The group parameter belongs to.</param> /// <param name="type">The parameter type.</param> /// <param name="dataCategory">The data category.</param> /// <param name="description">The description.</param> /// <param name="isVisible">if set to <c>true</c> [is visible].</param> /// <param name="userModifiable">if set to <c>true</c> [is user modifiable].</param> /// <inheritdoc /> public ParameterDefinition( Guid guid, string name, Group group, ParameterType type, string dataCategory = "", string description = "", bool isVisible = true, bool userModifiable = true) : this() { Guid = guid; Name = name; Group = group; ParameterType = type; DataCategory = dataCategory; Description = description; IsVisible = isVisible; UserModifiable = userModifiable; } /// <inheritdoc /> /// <summary> /// Gets the unique identifier. /// </summary> /// <value> /// The unique identifier. /// </value> public Guid Guid { get; protected set; } = Guid.Empty; /// <inheritdoc /> /// <summary> /// Gets the name. /// </summary> /// <value> /// The name. /// </value> public string Name { get; protected set; } /// <inheritdoc /> /// <summary> /// Gets the type of the unit. /// </summary> /// <value> /// The type of the unit. /// </value> public UnitType UnitType => ParameterType.GetUnitType(); /// <inheritdoc /> /// <summary> /// Gets the parameter group. /// </summary> /// <value> /// The parameter group. /// </value> public BuiltInParameterGroup ParameterGroup => BuiltInParameterGroup.INVALID; /// <inheritdoc /> /// <summary> /// Gets the type of the parameter. /// </summary> /// <value> /// The type of the parameter. /// </value> public ParameterType ParameterType { get; protected set; } = ParameterType.Invalid; /// <inheritdoc /> /// <summary> /// Gets the display type of the unit. /// </summary> /// <value> /// The display type of the unit. /// </value> public DisplayUnitType DisplayUnitType => DisplayUnitType.DUT_UNDEFINED; /// <summary> /// Gets or sets the group. /// </summary> /// <value> /// The group object. /// </value> public Group Group { get; set; } /// <summary> /// Gets or sets the data category. /// https://knowledge.autodesk.com/support/revit-products/troubleshooting/caas/sfdcarticles/sfdcarticles/Why-the-DATACATEGORY-column-is-empty-in-shared-parameter-txt-file.html. /// </summary> /// <value> /// The data category. /// </value> public string DataCategory { get; protected set; } = ""; /// <inheritdoc /> /// <summary> /// Gets a value indicating whether parameter is shared. /// </summary> /// <value> /// <c>true</c> if this parameter is shared; otherwise, <c>false</c>. /// </value> public bool IsShared => true; /// <summary> /// Gets or sets a value indicating whether this instance is visible. /// </summary> /// <value> /// <c>true</c> if this instance is visible; otherwise, <c>false</c>. /// </value> public bool IsVisible { get; protected set; } = true; /// <summary> /// Gets or sets the description. /// </summary> /// <value> /// The description. /// </value> public string Description { get; protected set; } = ""; /// <summary> /// Gets or sets a value indicating whether [user modifiable]. /// </summary> /// <value> /// <c>true</c> if [user modifiable]; otherwise, <c>false</c>. /// </value> public bool UserModifiable { get; protected set; } = true; /// <summary> /// Determines whether the specified <see cref="object" />, is equal to this instance. /// </summary> /// <param name="obj">The <see cref="object" /> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="object" /> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return !(obj is null) && (ReferenceEquals(this, obj) || Equals(obj as ParameterDefinition)); } /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// true if the current object is equal to the <paramref name="other">other</paramref> parameter; otherwise, false. /// </returns> /// <inheritdoc /> public bool Equals(ParameterDefinition other) { return null != other && Equals(Guid, other.Guid) && Equals(Name, other.Name) && Equals(UnitType, other.UnitType) && Equals(ParameterGroup, other.ParameterGroup) && Equals(ParameterType, other.ParameterType) && Equals(DisplayUnitType, other.DisplayUnitType) && Equals(Group, other.Group) && Equals(DataCategory, other.DataCategory) && Equals(IsVisible, other.IsVisible) && Equals(Description, other.Description) && Equals(UserModifiable, other.UserModifiable); } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { unchecked { var hashCode = Guid.GetHashCode(); hashCode = (hashCode * 397) ^ (Name != null ? Name.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (int)UnitType; hashCode = (hashCode * 397) ^ (int)ParameterGroup; hashCode = (hashCode * 397) ^ (int)ParameterType; hashCode = (hashCode * 397) ^ (int)DisplayUnitType; hashCode = (hashCode * 397) ^ (Group != null ? Group.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (DataCategory != null ? DataCategory.GetHashCode() : 0); hashCode = (hashCode * 397) ^ IsVisible.GetHashCode(); hashCode = (hashCode * 397) ^ (Description != null ? Description.GetHashCode() : 0); hashCode = (hashCode * 397) ^ UserModifiable.GetHashCode(); return hashCode; } } } /// <summary> /// A collection of parameter entries tied to a specific <see cref="SharedParameterFile"/> parent. /// </summary> /// <seealso cref="T:System.Collections.Generic.List`1" /> /// <inheritdoc /> public class ParameterCollection : List<ParameterDefinition> { protected readonly SharedParameterFile parameterFile; /// <summary> /// Initializes a new instance of the <see cref="ParameterCollection" /> class. /// </summary> /// <param name="parameterFile">The parent parameter file.</param> /// <param name="parameters">The parameters.</param> /// <exception cref="T:System.ArgumentNullException">parameterFile.</exception> /// <inheritdoc /> public ParameterCollection(SharedParameterFile parameterFile, IEnumerable<ParameterDefinition> parameters) :base(parameters ?? new List<ParameterDefinition>()) { this.parameterFile = parameterFile ?? throw new ArgumentNullException(nameof(parameterFile)); } public new void Add(ParameterDefinition parameter) { if (parameter == null) throw new ArgumentNullException(nameof(parameter)); if (parameter.Group == null) throw new ArgumentNullException( nameof(parameter), $"Parameter you have provided has no {nameof(ParameterDefinition.Group)} assigned"); if (parameter.Guid == null) throw new ArgumentNullException( nameof(parameter), $"Parameter you have provided has no {nameof(ParameterDefinition.Guid)} assigned"); if (this.Any(p => Equals(parameter.Guid, p.Guid))) throw new ArgumentException( nameof(parameter), $"You are trying to add a parameter with {nameof(ParameterDefinition.Guid)}={parameter.Guid} value already used by another parameter in the collection"); if (this.Any(p => Equals(parameter.Name, p.Name))) throw new ArgumentException( nameof(parameter), $"You are trying to add a parameter with {nameof(ParameterDefinition.Guid)}={parameter.Guid} value already used by another parameter in the collection"); if (parameterFile.Groups.Any(g => Equals(g.Id, parameter.Group?.Id) && !Equals(g.Name, parameter.Group?.Name))) throw new ArgumentException( nameof(parameter), $"You are trying to add a parameter with {nameof(Group)}.{nameof(Group.Id)}={parameter.Group.Id} value already used by another group in {nameof(Groups)} collection"); if (parameterFile.Groups.Any(g => Equals(g.Name, parameter.Group?.Name) && !Equals(g.Id, parameter.Group?.Id))) throw new ArgumentException( nameof(parameter), $"You are trying to add a parameter with {nameof(Group)}.{nameof(Group.Name)}={parameter.Group.Name} value already used by another group in {nameof(Groups)} collection"); base.Add(parameter); } /// <summary> /// Adds the range of parameters. /// </summary> /// <param name="parameters">The parameters.</param> /// <exception cref="ArgumentNullException">parameters.</exception> public new void AddRange(IEnumerable<ParameterDefinition> parameters) { if (parameters == null) throw new ArgumentNullException(nameof(parameters)); foreach (var parameter in parameters) { Add(parameter); } } /// <summary> /// Adds the specified unique identifier. /// </summary> /// <param name="guid">The unique identifier.</param> /// <param name="name">The name.</param> /// <param name="groupName">Name of the group.</param> /// <param name="type">The type.</param> /// <param name="dataCategory">The data category.</param> /// <param name="description">The description.</param> /// <param name="isVisible">if set to <c>true</c> [is visible].</param> /// <param name="userModifiable">if set to <c>true</c> [user modifiable].</param> /// <exception cref="ArgumentNullException">groupName.</exception> public void Add( Guid guid, string name, string groupName, ParameterType type, string dataCategory = "", string description = "", bool isVisible = true, bool userModifiable = true) { if (string.IsNullOrWhiteSpace(groupName)) throw new ArgumentNullException(nameof(groupName)); var group = parameterFile.Groups.FirstOrDefault(g => Equals(groupName, g.Name)) ?? new Group(groupName, parameterFile.Groups.Count + 1); Add( guid, name, group, type, dataCategory, description, isVisible, userModifiable); } /// <summary> /// Adds the specified unique identifier. /// </summary> /// <param name="guid">The unique identifier.</param> /// <param name="name">The name.</param> /// <param name="group">The group.</param> /// <param name="type">The type.</param> /// <param name="dataCategory">The data category.</param> /// <param name="description">The description.</param> /// <param name="isVisible">if set to <c>true</c> [is visible].</param> /// <param name="userModifiable">if set to <c>true</c> [user modifiable].</param> /// <exception cref="ArgumentNullException"> /// name /// or /// group. /// </exception> public void Add( Guid guid, string name, Group group, ParameterType type, string dataCategory = "", string description = "", bool isVisible = true, bool userModifiable = true) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException(nameof(name)); if (@group == null) throw new ArgumentNullException(nameof(@group)); Add(new ParameterDefinition( guid, name, group, type, dataCategory, description, isVisible, userModifiable)); } } } }
using System; namespace MailChimpSharp.Core.Sections.Campaigns { public class CampaignCreateOptionsBuilder { private readonly CampaignCreateOptions _options; public CampaignCreateOptionsBuilder() { _options = new CampaignCreateOptions(); } protected CampaignCreateOptions Options { get { return _options; } } public static implicit operator CampaignCreateOptions(CampaignCreateOptionsBuilder builder) { return builder.Options; } public CampaignCreateOptionsBuilder Authenticate() { Options.Authenticate = true; return this; } public CampaignCreateOptionsBuilder AutoGenerateFooter() { Options.AutoFooter = true; return this; } public CampaignCreateOptionsBuilder AutoTweet() { Options.AutoTweet = true; return this; } public CampaignCreateOptionsBuilder DisableFacebookComments() { Options.FacebookComments = false; return this; } public CampaignCreateOptionsBuilder DisableHtmlClickTracking() { Options.Tracking.HtmlClicks = false; return this; } public CampaignCreateOptionsBuilder DisableOpenTracking() { Options.Tracking.Opens = false; return this; } public CampaignCreateOptionsBuilder EnableEcomm360() { Options.Ecomm360 = true; return this; } public CampaignCreateOptionsBuilder EnableTextClickTracking() { Options.Tracking.TextClicks = true; return this; } public CampaignCreateOptionsBuilder EnableTimewarp() { Options.Timewarp = true; return this; } public CampaignCreateOptionsBuilder GenerateText() { Options.GenerateText = true; return this; } public CampaignCreateOptionsBuilder InFolder(int folderId) { Options.FolderId = folderId; return this; } public CampaignCreateOptionsBuilder InlineCss() { Options.InlineCss = true; return this; } public CampaignCreateOptionsBuilder PostToFacebookPages(params string[] pageIds) { Options.AutoFacebookPost.AddRange(pageIds); return this; } public CampaignCreateOptionsBuilder PushCampaignToHighRise() { EnsureHighRiseOptionsInitialised(); Options.CrmTracking.Highrise.Campaign = true; return this; } public CampaignCreateOptionsBuilder PushCampaignToSalesForce() { EnsureSalesForceOptionsInitialised(); Options.CrmTracking.SalesForce.Campaign = true; return this; } public CampaignCreateOptionsBuilder PushNotesToCapsule() { EnsureCapsuleOptionsInitialised(); Options.CrmTracking.Capsule.Notes = true; return this; } public CampaignCreateOptionsBuilder PushNotesToHighRise() { EnsureHighRiseOptionsInitialised(); Options.CrmTracking.Highrise.Notes = true; return this; } public CampaignCreateOptionsBuilder PushNotesToSalesForce() { EnsureSalesForceOptionsInitialised(); Options.CrmTracking.SalesForce.Notes = true; return this; } public CampaignCreateOptionsBuilder SendToList(string listId) { if (string.IsNullOrWhiteSpace(listId)) { throw new ArgumentException("Invalid listId"); } Options.ListId = listId; return this; } public CampaignCreateOptionsBuilder UsingBaseTemplate(int baseTemplateId) { Options.BaseTemplateId = baseTemplateId; return this; } public CampaignCreateOptionsBuilder UsingGalleryTemplate(int galleryTemplateId) { Options.GalleryTemplateId = galleryTemplateId; return this; } public CampaignCreateOptionsBuilder UsingTemplate(int templateId) { Options.TemplateId = templateId; return this; } public CampaignCreateOptionsBuilder WithClickTaleTag(string tag) { EnsureAnalyticsOptionsInitialised(); Options.Analytics.ClickTale = tag; return this; } public CampaignCreateOptionsBuilder WithFromEmail(string fromEmail) { Options.FromEmail = fromEmail; return this; } public CampaignCreateOptionsBuilder WithFromName(string fromName) { Options.FromName = fromName; return this; } public CampaignCreateOptionsBuilder WithGoalTag(string tag) { EnsureAnalyticsOptionsInitialised(); Options.Analytics.Goal = tag; return this; } public CampaignCreateOptionsBuilder WithGoogleAnalyticsTag(string tag) { EnsureAnalyticsOptionsInitialised(); Options.Analytics.Google = tag; return this; } public CampaignCreateOptionsBuilder WithSubject(string subject) { Options.Subject = subject; return this; } public CampaignCreateOptionsBuilder WithTitle(string title) { Options.Title = title; return this; } public CampaignCreateOptionsBuilder WithToName(string toName) { Options.ToName = toName; return this; } private void EnsureAnalyticsOptionsInitialised() { if (Options.Analytics == null) { Options.Analytics = new CampaignCreateOptions.AnalyticsOptions(); } } private void EnsureCapsuleOptionsInitialised() { EnsureCrmTrackingOptionsInitialised(); if (Options.CrmTracking.Capsule == null) { Options.CrmTracking.Capsule = new CampaignCreateOptions.CrmTrackingOptions.CapsuleOptions(); } } private void EnsureCrmTrackingOptionsInitialised() { if (Options.CrmTracking == null) { Options.CrmTracking = new CampaignCreateOptions.CrmTrackingOptions(); } } private void EnsureHighRiseOptionsInitialised() { EnsureCrmTrackingOptionsInitialised(); if (Options.CrmTracking.Highrise == null) { Options.CrmTracking.Highrise = new CampaignCreateOptions.CrmTrackingOptions.HighriseOptions(); } } private void EnsureSalesForceOptionsInitialised() { EnsureCrmTrackingOptionsInitialised(); if (Options.CrmTracking.SalesForce == null) { Options.CrmTracking.SalesForce = new CampaignCreateOptions.CrmTrackingOptions.SalesForceOptions(); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using System; using System.Diagnostics; using System.Linq; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Microsoft.Build.Shared; using Xunit; namespace Microsoft.Build.UnitTests { #if FEATURE_CODETASKFACTORY using System.CodeDom.Compiler; public sealed class CodeTaskFactoryTests { /// <summary> /// Test the simple case where we have a string parameter and we want to log that. /// </summary> [Fact] public void BuildTaskSimpleCodeFactory() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactory` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactory Text=`Hello, World!` /> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("Hello, World!"); } /// <summary> /// Test the simple case where we have a string parameter and we want to log that. /// Specifically testing that even when the ToolsVersion is post-4.0, and thus /// Microsoft.Build.Tasks.v4.0.dll is expected to NOT be in MSBuildToolsPath, that /// we will redirect under the covers to use the current tasks instead. /// </summary> [Fact] public void BuildTaskSimpleCodeFactory_RedirectFrom4() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactory` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactory Text=`Hello, World!` /> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("Hello, World!"); mockLogger.AssertLogDoesntContain("Microsoft.Build.Tasks.v4.0.dll"); } /// <summary> /// Test the simple case where we have a string parameter and we want to log that. /// Specifically testing that even when the ToolsVersion is post-12.0, and thus /// Microsoft.Build.Tasks.v12.0.dll is expected to NOT be in MSBuildToolsPath, that /// we will redirect under the covers to use the current tasks instead. /// </summary> [Fact] public void BuildTaskSimpleCodeFactory_RedirectFrom12() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactory` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.v12.0.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactory Text=`Hello, World!` /> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("Hello, World!"); mockLogger.AssertLogDoesntContain("Microsoft.Build.Tasks.v12.0.dll"); } /// <summary> /// Test the simple case where we have a string parameter and we want to log that. /// Specifically testing that even when the ToolsVersion is post-4.0, and we have redirection /// logic in place for the AssemblyFile case to deal with Microsoft.Build.Tasks.v4.0.dll not /// being in MSBuildToolsPath anymore, that this does NOT affect full fusion AssemblyNames -- /// it's picked up from the GAC, where it is anyway, so there's no need to redirect. /// </summary> [Fact] public void BuildTaskSimpleCodeFactory_NoAssemblyNameRedirect() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactory` TaskFactory=`CodeTaskFactory` AssemblyName=`Microsoft.Build.Tasks.Core, Version=15.1.0.0` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactory Text=`Hello, World!` /> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("Hello, World!"); mockLogger.AssertLogContains("Microsoft.Build.Tasks.Core, Version=15.1.0.0"); } /// <summary> /// Test the simple case where we have a string parameter and we want to log that. /// </summary> [Fact] public void VerifyRequiredAttribute() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_VerifyRequiredAttribute` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text Required='true'/> </ParameterGroup> <Task> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_VerifyRequiredAttribute/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, false); mockLogger.AssertLogContains("MSB4044"); } /// <summary> /// Verify we get an error if a runtime exception is logged /// </summary> [Fact] public void RuntimeException() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_RuntimeException` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code> throw new InvalidOperationException(""MyCustomException""); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_RuntimeException/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, true); mockLogger.AssertLogContains("MSB4018"); mockLogger.AssertLogContains("MyCustomException"); } /// <summary> /// Verify we get an error if a the languages attribute is set but it is empty /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void EmptyLanguage() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_EmptyLanguage` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code Language=''> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_EmptyLanguage/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, false); string unformattedMessage = ResourceUtilities.GetResourceString("CodeTaskFactory.AttributeEmpty"); mockLogger.AssertLogContains(String.Format(unformattedMessage, "Language")); } /// <summary> /// Verify we get an error if a the Type attribute is set but it is empty /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void EmptyType() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_EmptyType` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code Type=''> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_EmptyType/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, false); string unformattedMessage = ResourceUtilities.GetResourceString("CodeTaskFactory.AttributeEmpty"); mockLogger.AssertLogContains(String.Format(unformattedMessage, "Type")); } /// <summary> /// Verify we get an error if a the source attribute is set but it is empty /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void EmptySource() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_EmptySource` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code Source=''> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_EmptySource/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, false); string unformattedMessage = ResourceUtilities.GetResourceString("CodeTaskFactory.AttributeEmpty"); mockLogger.AssertLogContains(String.Format(unformattedMessage, "Source")); } /// <summary> /// Verify we get an error if a reference is missing an include attribute is set but it is empty /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void EmptyReferenceInclude() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_EmptyReferenceInclude` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Reference/> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_EmptyReferenceInclude/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, false); string unformattedMessage = ResourceUtilities.GetResourceString("CodeTaskFactory.AttributeEmpty"); mockLogger.AssertLogContains(String.Format(unformattedMessage, "Include")); } /// <summary> /// Verify we get an error if a Using statement is missing an namespace attribute is set but it is empty /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void EmptyUsingNamespace() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_EmptyUsingNamespace` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Using/> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_EmptyUsingNamespace/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, false); string unformattedMessage = ResourceUtilities.GetResourceString("CodeTaskFactory.AttributeEmpty"); mockLogger.AssertLogContains(String.Format(unformattedMessage, "Namespace")); } /// <summary> /// Verify we get pass even if the reference is not a full path /// </summary> [Fact] public void ReferenceNotPath() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_ReferenceNotPath` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Reference Include='System'/> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_ReferenceNotPath Text=""Hello""/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("Hello"); } /// <summary> /// Verify we get an error a reference has strange chars /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void ReferenceInvalidChars() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_ReferenceInvalidChars` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Reference Include='@@#$@#'/> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_ReferenceInvalidChars/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, false); mockLogger.AssertLogContains("MSB3755"); mockLogger.AssertLogContains("@@#$@#"); } /// <summary> /// Verify we get an error if a using has invalid chars /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void UsingInvalidChars() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_UsingInvalidChars` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Using Namespace='@@#$@#'/> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_UsingInvalidChars/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, false); mockLogger.AssertLogContains("CS1646"); } /// <summary> /// Verify we get an error if the sources points to an invalid file /// </summary> [Fact] public void SourcesInvalidFile() { string tempFileName = "Moose_" + Guid.NewGuid().ToString() + ".cs"; string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_SourcesInvalidFile` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code Source='$(SystemDrive)\\" + tempFileName + @"'> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_SourcesInvalidFile/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, false); mockLogger.AssertLogContains(Environment.GetEnvironmentVariable("SystemDrive") + '\\' + tempFileName); } /// <summary> /// Verify we get an error if a the code element is missing /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void MissingCodeElement() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_MissingCodeElement` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_MissingCodeElement/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, false); mockLogger.AssertLogContains(String.Format(ResourceUtilities.GetResourceString("CodeTaskFactory.CodeElementIsMissing"), "CustomTaskFromCodeFactory_MissingCodeElement")); } /// <summary> /// Test the case where we have adding a using statement /// </summary> [Fact] public void BuildTaskSimpleCodeFactoryTestExtraUsing() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactoryTestExtraUsing` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Using Namespace='System.Linq.Expressions'/> <Code> string linqString = ExpressionType.Add.ToString(); Log.LogMessage(MessageImportance.High, linqString + Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactoryTestExtraUsing Text=`:Hello, World!` /> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); string linqString = System.Linq.Expressions.ExpressionType.Add.ToString(); mockLogger.AssertLogContains(linqString + ":Hello, World!"); } /// <summary> /// Verify setting the output tag on the parameter causes it to be an output from the perspective of the targets /// </summary> [Fact] public void BuildTaskDateCodeFactory() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`DateTaskFromCodeFactory_BuildTaskDateCodeFactory` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll`> <ParameterGroup> <CurrentDate ParameterType=`System.String` Output=`true` /> </ParameterGroup> <Task> <Code> CurrentDate = DateTime.Now.ToString(); </Code> </Task> </UsingTask> <Target Name=`Build`> <DateTaskFromCodeFactory_BuildTaskDateCodeFactory> <Output TaskParameter=`CurrentDate` PropertyName=`CurrentDate` /> </DateTaskFromCodeFactory_BuildTaskDateCodeFactory> <Message Text=`Current Date and Time: [[$(CurrentDate)]]` Importance=`High` /> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("Current Date and Time:"); mockLogger.AssertLogDoesntContain("[[]]"); } /// <summary> /// Verify that the vb language works and that creating the execute method also works /// </summary> [Fact] public void MethodImplmentationVB() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CodeMethod_MethodImplmentationVB` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll`> <ParameterGroup> <Text ParameterType='System.String' /> </ParameterGroup> <Task> <Code Type='Method' Language='vb'> <![CDATA[ Public Overrides Function Execute() As Boolean Log.LogMessage(MessageImportance.High, Text) Return True End Function ]]> </Code> </Task> </UsingTask> <Target Name=`Build`> <CodeMethod_MethodImplmentationVB Text='IAMVBTEXT'/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("IAMVBTEXT"); } /// <summary> /// Verify that System does not need to be passed in as a extra reference when targeting vb /// </summary> [Fact] public void BuildTaskSimpleCodeFactoryTestSystemVB() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactoryTestSystemVB` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code Language='vb'> Dim headerRequest As String headerRequest = System.Net.HttpRequestHeader.Accept.ToString() Log.LogMessage(MessageImportance.High, headerRequest + Text) </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactoryTestSystemVB Text=`:Hello, World!` /> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("Accept" + ":Hello, World!"); } /// <summary> /// Verify that System does not need to be passed in as a extra reference when targeting c# /// </summary> [Fact] public void BuildTaskSimpleCodeFactoryTestSystemCS() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactoryTestSystemCS` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code Language='cs'> string headerRequest = System.Net.HttpRequestHeader.Accept.ToString(); Log.LogMessage(MessageImportance.High, headerRequest + Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactoryTestSystemCS Text=`:Hello, World!` /> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("Accept" + ":Hello, World!"); } /// <summary> /// Make sure we can pass in extra references than the automatic ones. For example the c# compiler does not pass in /// system.dll. So lets test that case /// </summary> [Fact] public void BuildTaskSimpleCodeFactoryTestExtraReferenceCS() { string netFrameworkDirectory = ToolLocationHelper.GetPathToDotNetFrameworkReferenceAssemblies(TargetDotNetFrameworkVersion.Version45); if (netFrameworkDirectory == null) { // "CouldNotFindRequiredTestDirectory" return; } string systemNETLocation = Path.Combine(netFrameworkDirectory, "System.Net.dll"); if (!File.Exists(systemNETLocation)) { // "CouldNotFindRequiredTestFile" return; } string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactoryTestExtraReferenceCS` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Using Namespace='System.Net'/> <Reference Include='" + systemNETLocation + @"'/> <Code> string netString = System.Net.HttpStatusCode.OK.ToString(); Log.LogMessage(MessageImportance.High, netString + Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactoryTestExtraReferenceCS Text=`:Hello, World!` /> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("OK" + ":Hello, World!"); } /// <summary> /// jscript .net works /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void MethodImplementationJScriptNet() { if (!CodeDomProvider.IsDefinedLanguage("js")) { // "JScript .net Is not installed on the test machine this test cannot run" return; } string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CodeMethod_MethodImplementationJScriptNet` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll`> <ParameterGroup> <Text ParameterType='System.String' /> </ParameterGroup> <Task> <Code Type='Method' Language='js'> <![CDATA[ override function Execute() : System.Boolean { Log.LogMessage(MessageImportance.High, Text); return true; } ]]> </Code> </Task> </UsingTask> <Target Name=`Build`> <CodeMethod_MethodImplementationJScriptNet Text='IAMJSTEXT'/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("IAMJSTEXT"); } /// <summary> /// Verify we can set a code type of Method which expects us to override the execute method entirely. /// </summary> [Fact] public void MethodImplementation() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CodeMethod_MethodImplementation` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll`> <ParameterGroup> <Text ParameterType='System.String' /> </ParameterGroup> <Task> <Code Type='Method'> <![CDATA[ public override bool Execute() { Log.LogMessage(MessageImportance.High, Text); return true; } ]]> </Code> </Task> </UsingTask> <Target Name=`Build`> <CodeMethod_MethodImplementation Text='IAMTEXT'/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("IAMTEXT"); } /// <summary> /// Verify we can set the type to Class and this expects an entire class to be entered into the code tag /// </summary> [Fact] public void ClassImplementationTest() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`LogNameValue_ClassImplementationTest` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll`> <ParameterGroup> <Name ParameterType='System.String' /> <Value ParameterType='System.String' /> </ParameterGroup> <Task> <Code Type='Class'> <![CDATA[ using System; using System.Collections.Generic; using System.Text; using Microsoft.Build.Utilities; using Microsoft.Build.Framework; namespace Microsoft.Build.NonShippingTasks { public class LogNameValue_ClassImplementationTest : Task { private string variableName; private string variableValue; [Required] public string Name { get { return variableName; } set { variableName = value; } } public string Value { get { return variableValue; } set { variableValue = value; } } public override bool Execute() { // Set the process environment Log.LogMessage(""Setting {0}={1}"", this.variableName, this.variableValue); return true; } } } ]]> </Code> </Task> </UsingTask> <Target Name=`Build`> <LogNameValue_ClassImplementationTest Name='MyName' Value='MyValue'/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("MyName=MyValue"); } /// <summary> /// Verify we can set the type to Class and this expects an entire class to be entered into the code tag /// </summary> [Fact] public void ClassImplementationTestDoesNotInheritFromITask() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`ClassImplementationTestDoesNotInheritFromITask` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll`> <ParameterGroup> <Name ParameterType='System.String' /> <Value ParameterType='System.String' /> </ParameterGroup> <Task> <Code Type='Class'> <![CDATA[ using System; using System.Collections.Generic; using System.Text; using Microsoft.Build.Utilities; using Microsoft.Build.Framework; namespace Microsoft.Build.NonShippingTasks { public class ClassImplementationTestDoesNotInheritFromITask { private string variableName; [Required] public string Name { get { return variableName; } set { variableName = value; } } public bool Execute() { // Set the process environment Console.Out.WriteLine(variableName); return true; } } } ]]> </Code> </Task> </UsingTask> <Target Name=`Build`> <ClassImplementationTestDoesNotInheritFromITask Name='MyName' Value='MyValue'/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, false); string unformattedMessage = ResourceUtilities.GetResourceString("CodeTaskFactory.NeedsITaskInterface"); mockLogger.AssertLogContains(unformattedMessage); } /// <summary> /// Verify we get an error if a the Type attribute is set but it is empty /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void MultipleCodeElements() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_EmptyType` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_EmptyType/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, false); string unformattedMessage = ResourceUtilities.GetResourceString("CodeTaskFactory.MultipleCodeNodes"); mockLogger.AssertLogContains(unformattedMessage); } /// <summary> /// Verify we get an error if a the Type attribute is set but it is empty /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void ReferenceNestedInCode() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_EmptyType` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code> <Reference Include=""System.Xml""/> <Using Namespace=""Hello""/> <Task/> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_EmptyType/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, false); string unformattedMessage = ResourceUtilities.GetResourceString("CodeTaskFactory.InvalidElementLocation"); mockLogger.AssertLogContains(String.Format(unformattedMessage, "Reference", "Code")); mockLogger.AssertLogContains(String.Format(unformattedMessage, "Using", "Code")); mockLogger.AssertLogContains(String.Format(unformattedMessage, "Task", "Code")); } /// <summary> /// Verify we get an error if there is an unknown element in the task tag /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void UnknownElementInTask() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_EmptyType` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Unknown/> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_EmptyType Text=""HELLO""/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, false); string unformattedMessage = ResourceUtilities.GetResourceString("CodeTaskFactory.InvalidElementLocation"); mockLogger.AssertLogContains(String.Format(unformattedMessage, "Unknown", "Task")); } /// <summary> /// Verify we can set a source file location and this will be read in and used. /// </summary> [Fact] public void ClassSourcesTest() { string sourceFileContent = @" using System; using System.Collections.Generic; using System.Text; using Microsoft.Build.Utilities; using Microsoft.Build.Framework; namespace Microsoft.Build.NonShippingTasks { public class LogNameValue_ClassSourcesTest : Task { private string variableName; private string variableValue; [Required] public string Name { get { return variableName; } set { variableName = value; } } public string Value { get { return variableValue; } set { variableValue = value; } } public override bool Execute() { // Set the process environment Log.LogMessage(""Setting {0}={1}"", this.variableName, this.variableValue); return true; } } } "; string tempFileDirectory = Path.GetTempPath(); string tempFileName = Guid.NewGuid().ToString() + ".cs"; string tempSourceFile = Path.Combine(tempFileDirectory, tempFileName); File.WriteAllText(tempSourceFile, sourceFileContent); try { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`LogNameValue_ClassSourcesTest` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll`> <ParameterGroup> <Name ParameterType='System.String' /> <Value ParameterType='System.String' /> </ParameterGroup> <Task> <Code Source='" + tempSourceFile + @"'/> </Task> </UsingTask> <Target Name=`Build`> <LogNameValue_ClassSourcesTest Name='MyName' Value='MyValue'/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("MyName=MyValue"); } finally { if (File.Exists(tempSourceFile)) { File.Delete(tempSourceFile); } } } /// <summary> /// Code factory test where the TMP directory does not exist. /// See https://github.com/Microsoft/msbuild/issues/328 for details. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void BuildTaskSimpleCodeFactoryTempDirectoryDoesntExist() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactory` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactory Text=`Hello, World!` /> </Target> </Project>"; var oldTempPath = Environment.GetEnvironmentVariable("TMP"); var newTempPath = Path.Combine(Path.GetFullPath(oldTempPath), Path.GetRandomFileName()); try { // Ensure we're getting the right temp path (%TMP% == GetTempPath()) Assert.Equal( FileUtilities.EnsureTrailingSlash(Path.GetTempPath()), FileUtilities.EnsureTrailingSlash(Path.GetFullPath(oldTempPath))); Assert.False(Directory.Exists(newTempPath)); Environment.SetEnvironmentVariable("TMP", newTempPath); Assert.Equal( FileUtilities.EnsureTrailingSlash(newTempPath), FileUtilities.EnsureTrailingSlash(Path.GetTempPath())); MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("Hello, World!"); } finally { Environment.SetEnvironmentVariable("TMP", oldTempPath); FileUtilities.DeleteDirectoryNoThrow(newTempPath, true); } } } #else public sealed class CodeTaskFactoryTests { [Fact] public void CodeTaskFactoryNotSupported() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactory` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactory Text=`Hello, World!` /> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, allowTaskCrash: false); BuildErrorEventArgs error = mockLogger.Errors.FirstOrDefault(); Assert.NotNull(error); Assert.Equal("MSB4801: The task factory \"CodeTaskFactory\" is not supported on the .NET Core version of MSBuild.", error.Message); } } #endif }
namespace AngleSharp.Css.Parser { using AngleSharp.Css.Dom; using AngleSharp.Css.Values; using AngleSharp.Text; using System; using System.Collections.Generic; static class GradientParser { private static readonly Dictionary<String, Func<StringSource, ICssGradientFunctionValue>> GradientFunctions = new Dictionary<string, Func<StringSource, ICssGradientFunctionValue>> { { FunctionNames.LinearGradient, ParseLinearGradient }, { FunctionNames.RepeatingLinearGradient, ParseRepeatingLinearGradient }, { FunctionNames.RadialGradient, ParseRadialGradient }, { FunctionNames.RepeatingRadialGradient, ParseRepeatingRadialGradient }, }; public static ICssGradientFunctionValue ParseGradient(this StringSource source) { var pos = source.Index; var ident = source.ParseIdent(); if (ident != null && source.Current == Symbols.RoundBracketOpen && GradientFunctions.TryGetValue(ident, out var function)) { source.SkipCurrentAndSpaces(); return function.Invoke(source); } source.BackTo(pos); return null; } private static ICssGradientFunctionValue ParseLinearGradient(StringSource source) { return ParseLinearGradient(source, false); } private static ICssGradientFunctionValue ParseRepeatingLinearGradient(StringSource source) { return ParseLinearGradient(source, true); } /// <summary> /// Parses a linear gradient. /// https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient /// </summary> private static ICssGradientFunctionValue ParseLinearGradient(StringSource source, Boolean repeating) { var start = source.Index; var angle = ParseLinearAngle(source); if (angle != null) { var current = source.SkipSpacesAndComments(); if (current != Symbols.Comma) { return null; } source.SkipCurrentAndSpaces(); } else { source.BackTo(start); } var stops = ParseGradientStops(source); if (stops != null && source.Current == Symbols.RoundBracketClose) { source.SkipCurrentAndSpaces(); return new CssLinearGradientValue(angle, stops, repeating); } return null; } private static ICssGradientFunctionValue ParseRadialGradient(StringSource source) { return ParseRadialGradient(source, false); } private static ICssGradientFunctionValue ParseRepeatingRadialGradient(StringSource source) { return ParseRadialGradient(source, true); } /// <summary> /// Parses a radial gradient /// https://developer.mozilla.org/en-US/docs/Web/CSS/radial-gradient /// </summary> private static ICssGradientFunctionValue ParseRadialGradient(StringSource source, Boolean repeating) { var start = source.Index; var options = ParseRadialOptions(source); if (options.HasValue) { var current = source.SkipSpacesAndComments(); if (current != Symbols.Comma) { return null; } source.SkipCurrentAndSpaces(); } else { source.BackTo(start); } var stops = ParseGradientStops(source); if (stops != null && source.Current == Symbols.RoundBracketClose) { var circle = options?.Circle ?? false; var center = options?.Center ?? Point.Center; var width = options?.Width; var height = options?.Height; var sizeMode = options?.Size ?? CssRadialGradientValue.SizeMode.None; source.SkipCurrentAndSpaces(); return new CssRadialGradientValue(circle, center, width, height, sizeMode, stops, repeating); } return null; } private static CssGradientStopValue[] ParseGradientStops(StringSource source) { var stops = new List<CssGradientStopValue>(); var current = source.Current; while (!source.IsDone) { if (stops.Count > 0) { if (current != Symbols.Comma) break; source.SkipCurrentAndSpaces(); } var stop = ParseGradientStop(source); if (stop == null) break; stops.Add(stop); current = source.SkipSpacesAndComments(); } return stops.ToArray(); } private static CssGradientStopValue ParseGradientStop(StringSource source) { var color = source.ParseColor(); source.SkipSpacesAndComments(); var position = source.ParseDistanceOrCalc(); if (color.HasValue) { return new CssGradientStopValue(color.Value, position); } return null; } private static ICssValue ParseLinearAngle(StringSource source) { if (source.IsIdentifier(CssKeywords.To)) { source.SkipSpacesAndComments(); return ParseLinearAngleKeywords(source); } else { // This is for backwards compatibility. Usually only "to" syntax is supported. var pos = source.Index; var test = source.ParseIdent(); source.BackTo(pos); if (test != null && Map.GradientAngles.ContainsKey(test)) { return ParseLinearAngleKeywords(source); } } return source.ParseAngleOrCalc(); } private static ICssValue ParseLinearAngleKeywords(StringSource source) { var a = source.ParseIdent(); source.SkipSpacesAndComments(); var b = source.ParseIdent(); var keyword = default(String); if (a != null && b != null) { if (a.IsOneOf(CssKeywords.Top, CssKeywords.Bottom)) { var t = b; b = a; a = t; } keyword = String.Concat(a, " ", b); } else if (a != null) { keyword = a; } if (keyword != null && Map.GradientAngles.TryGetValue(keyword, out var angle)) { return angle; } return null; } private static RadialOptions? ParseRadialOptions(StringSource source) { var circle = false; var center = Point.Center; var width = default(ICssValue); var height = default(ICssValue); var size = CssRadialGradientValue.SizeMode.None; var redo = false; var ident = source.ParseIdent(); if (ident != null) { if (ident.Isi(CssKeywords.Circle)) { circle = true; source.SkipSpacesAndComments(); var radius = source.ParseLengthOrCalc(); if (radius != null) { width = height = radius; } else { size = ToSizeMode(source) ?? CssRadialGradientValue.SizeMode.None; } redo = true; } else if (ident.Isi(CssKeywords.Ellipse)) { circle = false; source.SkipSpacesAndComments(); var el = source.ParseDistanceOrCalc(); source.SkipSpacesAndComments(); var es = source.ParseDistanceOrCalc(); if (el != null && es != null) { width = el; height = es; } else if (el == null && es == null) { size = ToSizeMode(source) ?? CssRadialGradientValue.SizeMode.None; } else { return null; } redo = true; } else if (Map.RadialGradientSizeModes.ContainsKey(ident)) { size = Map.RadialGradientSizeModes[ident]; source.SkipSpacesAndComments(); ident = source.ParseIdent(); if (ident != null) { if (ident.Isi(CssKeywords.Circle)) { circle = true; redo = true; } else if (ident.Isi(CssKeywords.Ellipse)) { circle = false; redo = true; } } } } else { var el = source.ParseDistanceOrCalc(); source.SkipSpacesAndComments(); var es = source.ParseDistanceOrCalc(); if (el != null && es != null) { circle = false; width = el; height = es; } else if (el != null) { circle = true; width = el; } else { return null; } redo = true; } if (redo) { source.SkipSpacesAndComments(); ident = source.ParseIdent(); } if (ident != null) { if (!ident.Isi(CssKeywords.At)) { return null; } source.SkipSpacesAndComments(); var pt = source.ParsePoint(); if (!pt.HasValue) { return null; } center = pt.Value; } return new RadialOptions { Circle = circle, Center = center, Width = width, Height = height, Size = size }; } public struct RadialOptions { public Boolean Circle; public Point Center; public ICssValue Width; public ICssValue Height; public CssRadialGradientValue.SizeMode Size; } private static CssRadialGradientValue.SizeMode? ToSizeMode(StringSource source) { var pos = source.Index; var ident = source.ParseIdent(); var result = CssRadialGradientValue.SizeMode.None; if (ident != null && Map.RadialGradientSizeModes.TryGetValue(ident, out result)) { return result; } source.BackTo(pos); return null; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Versions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal partial class SolutionCrawlerRegistrationService { private partial class WorkCoordinator { private const int MinimumDelayInMS = 50; private readonly Registration _registration; private readonly LogAggregator _logAggregator; private readonly IAsynchronousOperationListener _listener; private readonly IOptionService _optionService; private readonly CancellationTokenSource _shutdownNotificationSource; private readonly CancellationToken _shutdownToken; private readonly SimpleTaskQueue _eventProcessingQueue; // points to processor task private readonly IncrementalAnalyzerProcessor _documentAndProjectWorkerProcessor; private readonly SemanticChangeProcessor _semanticChangeProcessor; public WorkCoordinator( IAsynchronousOperationListener listener, IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> analyzerProviders, Registration registration) { _logAggregator = new LogAggregator(); _registration = registration; _listener = listener; _optionService = _registration.GetService<IOptionService>(); _optionService.OptionChanged += OnOptionChanged; // event and worker queues _shutdownNotificationSource = new CancellationTokenSource(); _shutdownToken = _shutdownNotificationSource.Token; _eventProcessingQueue = new SimpleTaskQueue(TaskScheduler.Default); var activeFileBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.ActiveFileWorkerBackOffTimeSpanInMS); var allFilesWorkerBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.AllFilesWorkerBackOffTimeSpanInMS); var entireProjectWorkerBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.EntireProjectWorkerBackOffTimeSpanInMS); _documentAndProjectWorkerProcessor = new IncrementalAnalyzerProcessor( listener, analyzerProviders, _registration, activeFileBackOffTimeSpanInMS, allFilesWorkerBackOffTimeSpanInMS, entireProjectWorkerBackOffTimeSpanInMS, _shutdownToken); var semanticBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.SemanticChangeBackOffTimeSpanInMS); var projectBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.ProjectPropagationBackOffTimeSpanInMS); _semanticChangeProcessor = new SemanticChangeProcessor(listener, _registration, _documentAndProjectWorkerProcessor, semanticBackOffTimeSpanInMS, projectBackOffTimeSpanInMS, _shutdownToken); // if option is on if (_optionService.GetOption(InternalSolutionCrawlerOptions.SolutionCrawler)) { _registration.Workspace.WorkspaceChanged += OnWorkspaceChanged; _registration.Workspace.DocumentOpened += OnDocumentOpened; _registration.Workspace.DocumentClosed += OnDocumentClosed; } } public int CorrelationId { get { return _registration.CorrelationId; } } public void AddAnalyzer(IIncrementalAnalyzer analyzer, bool highPriorityForActiveFile) { // add analyzer _documentAndProjectWorkerProcessor.AddAnalyzer(analyzer, highPriorityForActiveFile); // and ask to re-analyze whole solution for the given analyzer var set = _registration.CurrentSolution.Projects.SelectMany(p => p.DocumentIds).ToSet(); Reanalyze(analyzer, set); } public void Shutdown(bool blockingShutdown) { _optionService.OptionChanged -= OnOptionChanged; // detach from the workspace _registration.Workspace.WorkspaceChanged -= OnWorkspaceChanged; _registration.Workspace.DocumentOpened -= OnDocumentOpened; _registration.Workspace.DocumentClosed -= OnDocumentClosed; // cancel any pending blocks _shutdownNotificationSource.Cancel(); _documentAndProjectWorkerProcessor.Shutdown(); SolutionCrawlerLogger.LogWorkCoordinatorShutdown(CorrelationId, _logAggregator); if (blockingShutdown) { var shutdownTask = Task.WhenAll( _eventProcessingQueue.LastScheduledTask, _documentAndProjectWorkerProcessor.AsyncProcessorTask, _semanticChangeProcessor.AsyncProcessorTask); shutdownTask.Wait(TimeSpan.FromSeconds(5)); if (!shutdownTask.IsCompleted) { SolutionCrawlerLogger.LogWorkCoordinatorShutdownTimeout(CorrelationId); } } } private void OnOptionChanged(object sender, OptionChangedEventArgs e) { // if solution crawler got turned off or on. if (e.Option == InternalSolutionCrawlerOptions.SolutionCrawler) { var value = (bool)e.Value; if (value) { _registration.Workspace.WorkspaceChanged += OnWorkspaceChanged; _registration.Workspace.DocumentOpened += OnDocumentOpened; _registration.Workspace.DocumentClosed += OnDocumentClosed; } else { _registration.Workspace.WorkspaceChanged -= OnWorkspaceChanged; _registration.Workspace.DocumentOpened -= OnDocumentOpened; _registration.Workspace.DocumentClosed -= OnDocumentClosed; } SolutionCrawlerLogger.LogOptionChanged(CorrelationId, value); return; } // Changing the UseV2Engine option is a no-op as we have a single engine now. if (e.Option == Diagnostics.InternalDiagnosticsOptions.UseDiagnosticEngineV2) { _documentAndProjectWorkerProcessor.ChangeDiagnosticsEngine((bool)e.Value); } ReanalyzeOnOptionChange(sender, e); } private void ReanalyzeOnOptionChange(object sender, OptionChangedEventArgs e) { // otherwise, let each analyzer decide what they want on option change ISet<DocumentId> set = null; foreach (var analyzer in _documentAndProjectWorkerProcessor.Analyzers) { if (analyzer.NeedsReanalysisOnOptionChanged(sender, e)) { set = set ?? _registration.CurrentSolution.Projects.SelectMany(p => p.DocumentIds).ToSet(); this.Reanalyze(analyzer, set); } } } public void Reanalyze(IIncrementalAnalyzer analyzer, IEnumerable<DocumentId> documentIds, bool highPriority = false) { var asyncToken = _listener.BeginAsyncOperation("Reanalyze"); _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemAsync(analyzer, documentIds, highPriority), _shutdownToken).CompletesAsyncOperation(asyncToken); SolutionCrawlerLogger.LogReanalyze(CorrelationId, analyzer, documentIds, highPriority); } private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs args) { // guard us from cancellation try { ProcessEvents(args, _listener.BeginAsyncOperation("OnWorkspaceChanged")); } catch (OperationCanceledException oce) { if (NotOurShutdownToken(oce)) { throw; } // it is our cancellation, ignore } catch (AggregateException ae) { ae = ae.Flatten(); // If we had a mix of exceptions, don't eat it if (ae.InnerExceptions.Any(e => !(e is OperationCanceledException)) || ae.InnerExceptions.Cast<OperationCanceledException>().Any(NotOurShutdownToken)) { // We had a cancellation with a different token, so don't eat it throw; } // it is our cancellation, ignore } } private bool NotOurShutdownToken(OperationCanceledException oce) { return oce.CancellationToken == _shutdownToken; } private void ProcessEvents(WorkspaceChangeEventArgs args, IAsyncToken asyncToken) { SolutionCrawlerLogger.LogWorkspaceEvent(_logAggregator, (int)args.Kind); // TODO: add telemetry that record how much it takes to process an event (max, min, average and etc) switch (args.Kind) { case WorkspaceChangeKind.SolutionAdded: case WorkspaceChangeKind.SolutionChanged: case WorkspaceChangeKind.SolutionReloaded: case WorkspaceChangeKind.SolutionRemoved: case WorkspaceChangeKind.SolutionCleared: ProcessSolutionEvent(args, asyncToken); break; case WorkspaceChangeKind.ProjectAdded: case WorkspaceChangeKind.ProjectChanged: case WorkspaceChangeKind.ProjectReloaded: case WorkspaceChangeKind.ProjectRemoved: ProcessProjectEvent(args, asyncToken); break; case WorkspaceChangeKind.DocumentAdded: case WorkspaceChangeKind.DocumentReloaded: case WorkspaceChangeKind.DocumentChanged: case WorkspaceChangeKind.DocumentRemoved: case WorkspaceChangeKind.AdditionalDocumentAdded: case WorkspaceChangeKind.AdditionalDocumentRemoved: case WorkspaceChangeKind.AdditionalDocumentChanged: case WorkspaceChangeKind.AdditionalDocumentReloaded: ProcessDocumentEvent(args, asyncToken); break; default: throw ExceptionUtilities.Unreachable; } } private void OnDocumentOpened(object sender, DocumentEventArgs e) { var asyncToken = _listener.BeginAsyncOperation("OnDocumentOpened"); _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemAsync(e.Document, InvocationReasons.DocumentOpened), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void OnDocumentClosed(object sender, DocumentEventArgs e) { var asyncToken = _listener.BeginAsyncOperation("OnDocumentClosed"); _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemAsync(e.Document, InvocationReasons.DocumentClosed), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void ProcessDocumentEvent(WorkspaceChangeEventArgs e, IAsyncToken asyncToken) { switch (e.Kind) { case WorkspaceChangeKind.DocumentAdded: EnqueueEvent(e.NewSolution, e.DocumentId, InvocationReasons.DocumentAdded, asyncToken); break; case WorkspaceChangeKind.DocumentRemoved: EnqueueEvent(e.OldSolution, e.DocumentId, InvocationReasons.DocumentRemoved, asyncToken); break; case WorkspaceChangeKind.DocumentReloaded: case WorkspaceChangeKind.DocumentChanged: EnqueueEvent(e.OldSolution, e.NewSolution, e.DocumentId, asyncToken); break; case WorkspaceChangeKind.AdditionalDocumentAdded: case WorkspaceChangeKind.AdditionalDocumentRemoved: case WorkspaceChangeKind.AdditionalDocumentChanged: case WorkspaceChangeKind.AdditionalDocumentReloaded: // If an additional file has changed we need to reanalyze the entire project. EnqueueEvent(e.NewSolution, e.ProjectId, InvocationReasons.AdditionalDocumentChanged, asyncToken); break; default: throw ExceptionUtilities.Unreachable; } } private void ProcessProjectEvent(WorkspaceChangeEventArgs e, IAsyncToken asyncToken) { switch (e.Kind) { case WorkspaceChangeKind.ProjectAdded: OnProjectAdded(e.NewSolution.GetProject(e.ProjectId)); EnqueueEvent(e.NewSolution, e.ProjectId, InvocationReasons.DocumentAdded, asyncToken); break; case WorkspaceChangeKind.ProjectRemoved: EnqueueEvent(e.OldSolution, e.ProjectId, InvocationReasons.DocumentRemoved, asyncToken); break; case WorkspaceChangeKind.ProjectChanged: case WorkspaceChangeKind.ProjectReloaded: EnqueueEvent(e.OldSolution, e.NewSolution, e.ProjectId, asyncToken); break; default: throw ExceptionUtilities.Unreachable; } } private void ProcessSolutionEvent(WorkspaceChangeEventArgs e, IAsyncToken asyncToken) { switch (e.Kind) { case WorkspaceChangeKind.SolutionAdded: OnSolutionAdded(e.NewSolution); EnqueueEvent(e.NewSolution, InvocationReasons.DocumentAdded, asyncToken); break; case WorkspaceChangeKind.SolutionRemoved: EnqueueEvent(e.OldSolution, InvocationReasons.SolutionRemoved, asyncToken); break; case WorkspaceChangeKind.SolutionCleared: EnqueueEvent(e.OldSolution, InvocationReasons.DocumentRemoved, asyncToken); break; case WorkspaceChangeKind.SolutionChanged: case WorkspaceChangeKind.SolutionReloaded: EnqueueEvent(e.OldSolution, e.NewSolution, asyncToken); break; default: throw ExceptionUtilities.Unreachable; } } private void OnSolutionAdded(Solution solution) { var asyncToken = _listener.BeginAsyncOperation("OnSolutionAdded"); _eventProcessingQueue.ScheduleTask(() => { var semanticVersionTrackingService = solution.Workspace.Services.GetService<ISemanticVersionTrackingService>(); if (semanticVersionTrackingService != null) { semanticVersionTrackingService.LoadInitialSemanticVersions(solution); } }, _shutdownToken).CompletesAsyncOperation(asyncToken); } private void OnProjectAdded(Project project) { var asyncToken = _listener.BeginAsyncOperation("OnProjectAdded"); _eventProcessingQueue.ScheduleTask(() => { var semanticVersionTrackingService = project.Solution.Workspace.Services.GetService<ISemanticVersionTrackingService>(); if (semanticVersionTrackingService != null) { semanticVersionTrackingService.LoadInitialSemanticVersions(project); } }, _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution oldSolution, Solution newSolution, IAsyncToken asyncToken) { _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemAsync(oldSolution, newSolution), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution solution, InvocationReasons invocationReasons, IAsyncToken asyncToken) { _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemForSolutionAsync(solution, invocationReasons), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution oldSolution, Solution newSolution, ProjectId projectId, IAsyncToken asyncToken) { _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemAfterDiffAsync(oldSolution, newSolution, projectId), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution solution, ProjectId projectId, InvocationReasons invocationReasons, IAsyncToken asyncToken) { _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemForProjectAsync(solution, projectId, invocationReasons), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution solution, DocumentId documentId, InvocationReasons invocationReasons, IAsyncToken asyncToken) { _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemForDocumentAsync(solution, documentId, invocationReasons), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution oldSolution, Solution newSolution, DocumentId documentId, IAsyncToken asyncToken) { // document changed event is the special one. _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemAfterDiffAsync(oldSolution, newSolution, documentId), _shutdownToken).CompletesAsyncOperation(asyncToken); } private async Task EnqueueWorkItemAsync(Document document, InvocationReasons invocationReasons, SyntaxNode changedMember = null) { // we are shutting down _shutdownToken.ThrowIfCancellationRequested(); var priorityService = document.GetLanguageService<IWorkCoordinatorPriorityService>(); var isLowPriority = priorityService != null && await priorityService.IsLowPriorityAsync(document, _shutdownToken).ConfigureAwait(false); var currentMember = GetSyntaxPath(changedMember); // call to this method is serialized. and only this method does the writing. _documentAndProjectWorkerProcessor.Enqueue( new WorkItem(document.Id, document.Project.Language, invocationReasons, isLowPriority, currentMember, _listener.BeginAsyncOperation("WorkItem"))); // enqueue semantic work planner if (invocationReasons.Contains(PredefinedInvocationReasons.SemanticChanged)) { // must use "Document" here so that the snapshot doesn't go away. we need the snapshot to calculate p2p dependency graph later. // due to this, we might hold onto solution (and things kept alive by it) little bit longer than usual. _semanticChangeProcessor.Enqueue(document, currentMember); } } private SyntaxPath GetSyntaxPath(SyntaxNode changedMember) { // using syntax path might be too expansive since it will be created on every keystroke. // but currently, we have no other way to track a node between two different tree (even for incrementally parsed one) if (changedMember == null) { return null; } return new SyntaxPath(changedMember); } private async Task EnqueueWorkItemAsync(Project project, InvocationReasons invocationReasons) { foreach (var documentId in project.DocumentIds) { var document = project.GetDocument(documentId); await EnqueueWorkItemAsync(document, invocationReasons).ConfigureAwait(false); } } private async Task EnqueueWorkItemAsync(IIncrementalAnalyzer analyzer, IEnumerable<DocumentId> documentIds, bool highPriority) { var solution = _registration.CurrentSolution; foreach (var documentId in documentIds) { var document = solution.GetDocument(documentId); if (document == null) { continue; } var priorityService = document.GetLanguageService<IWorkCoordinatorPriorityService>(); var isLowPriority = priorityService != null && await priorityService.IsLowPriorityAsync(document, _shutdownToken).ConfigureAwait(false); var invocationReasons = highPriority ? InvocationReasons.ReanalyzeHighPriority : InvocationReasons.Reanalyze; _documentAndProjectWorkerProcessor.Enqueue( new WorkItem(documentId, document.Project.Language, invocationReasons, isLowPriority, analyzer, _listener.BeginAsyncOperation("WorkItem"))); } } private async Task EnqueueWorkItemAsync(Solution oldSolution, Solution newSolution) { var solutionChanges = newSolution.GetChanges(oldSolution); // TODO: Async version for GetXXX methods? foreach (var addedProject in solutionChanges.GetAddedProjects()) { await EnqueueWorkItemAsync(addedProject, InvocationReasons.DocumentAdded).ConfigureAwait(false); } foreach (var projectChanges in solutionChanges.GetProjectChanges()) { await EnqueueWorkItemAsync(projectChanges).ConfigureAwait(continueOnCapturedContext: false); } foreach (var removedProject in solutionChanges.GetRemovedProjects()) { await EnqueueWorkItemAsync(removedProject, InvocationReasons.DocumentRemoved).ConfigureAwait(false); } } private async Task EnqueueWorkItemAsync(ProjectChanges projectChanges) { await EnqueueProjectConfigurationChangeWorkItemAsync(projectChanges).ConfigureAwait(false); foreach (var addedDocumentId in projectChanges.GetAddedDocuments()) { await EnqueueWorkItemAsync(projectChanges.NewProject.GetDocument(addedDocumentId), InvocationReasons.DocumentAdded).ConfigureAwait(false); } foreach (var changedDocumentId in projectChanges.GetChangedDocuments()) { await EnqueueWorkItemAsync(projectChanges.OldProject.GetDocument(changedDocumentId), projectChanges.NewProject.GetDocument(changedDocumentId)) .ConfigureAwait(continueOnCapturedContext: false); } foreach (var removedDocumentId in projectChanges.GetRemovedDocuments()) { await EnqueueWorkItemAsync(projectChanges.OldProject.GetDocument(removedDocumentId), InvocationReasons.DocumentRemoved).ConfigureAwait(false); } } private async Task EnqueueProjectConfigurationChangeWorkItemAsync(ProjectChanges projectChanges) { var oldProject = projectChanges.OldProject; var newProject = projectChanges.NewProject; // TODO: why solution changes return Project not ProjectId but ProjectChanges return DocumentId not Document? var projectConfigurationChange = InvocationReasons.Empty; if (!object.Equals(oldProject.ParseOptions, newProject.ParseOptions)) { projectConfigurationChange = projectConfigurationChange.With(InvocationReasons.ProjectParseOptionChanged); } if (projectChanges.GetAddedMetadataReferences().Any() || projectChanges.GetAddedProjectReferences().Any() || projectChanges.GetAddedAnalyzerReferences().Any() || projectChanges.GetRemovedMetadataReferences().Any() || projectChanges.GetRemovedProjectReferences().Any() || projectChanges.GetRemovedAnalyzerReferences().Any() || !object.Equals(oldProject.CompilationOptions, newProject.CompilationOptions) || !object.Equals(oldProject.AssemblyName, newProject.AssemblyName) || !object.Equals(oldProject.Name, newProject.Name) || !object.Equals(oldProject.AnalyzerOptions, newProject.AnalyzerOptions)) { projectConfigurationChange = projectConfigurationChange.With(InvocationReasons.ProjectConfigurationChanged); } if (!projectConfigurationChange.IsEmpty) { await EnqueueWorkItemAsync(projectChanges.NewProject, projectConfigurationChange).ConfigureAwait(false); } } private async Task EnqueueWorkItemAsync(Document oldDocument, Document newDocument) { var differenceService = newDocument.GetLanguageService<IDocumentDifferenceService>(); if (differenceService == null) { // For languages that don't use a Roslyn syntax tree, they don't export a document difference service. // The whole document should be considered as changed in that case. await EnqueueWorkItemAsync(newDocument, InvocationReasons.DocumentChanged).ConfigureAwait(false); } else { var differenceResult = await differenceService.GetDifferenceAsync(oldDocument, newDocument, _shutdownToken).ConfigureAwait(false); if (differenceResult != null) { await EnqueueWorkItemAsync(newDocument, differenceResult.ChangeType, differenceResult.ChangedMember).ConfigureAwait(false); } } } private Task EnqueueWorkItemForDocumentAsync(Solution solution, DocumentId documentId, InvocationReasons invocationReasons) { var document = solution.GetDocument(documentId); return EnqueueWorkItemAsync(document, invocationReasons); } private Task EnqueueWorkItemForProjectAsync(Solution solution, ProjectId projectId, InvocationReasons invocationReasons) { var project = solution.GetProject(projectId); return EnqueueWorkItemAsync(project, invocationReasons); } private async Task EnqueueWorkItemForSolutionAsync(Solution solution, InvocationReasons invocationReasons) { foreach (var projectId in solution.ProjectIds) { await EnqueueWorkItemForProjectAsync(solution, projectId, invocationReasons).ConfigureAwait(false); } } private async Task EnqueueWorkItemAfterDiffAsync(Solution oldSolution, Solution newSolution, ProjectId projectId) { var oldProject = oldSolution.GetProject(projectId); var newProject = newSolution.GetProject(projectId); await EnqueueWorkItemAsync(newProject.GetChanges(oldProject)).ConfigureAwait(continueOnCapturedContext: false); } private async Task EnqueueWorkItemAfterDiffAsync(Solution oldSolution, Solution newSolution, DocumentId documentId) { var oldProject = oldSolution.GetProject(documentId.ProjectId); var newProject = newSolution.GetProject(documentId.ProjectId); await EnqueueWorkItemAsync(oldProject.GetDocument(documentId), newProject.GetDocument(documentId)).ConfigureAwait(continueOnCapturedContext: false); } internal void WaitUntilCompletion_ForTestingPurposesOnly(ImmutableArray<IIncrementalAnalyzer> workers) { var solution = _registration.CurrentSolution; var list = new List<WorkItem>(); foreach (var project in solution.Projects) { foreach (var document in project.Documents) { list.Add(new WorkItem(document.Id, document.Project.Language, InvocationReasons.DocumentAdded, false, EmptyAsyncToken.Instance)); } } _documentAndProjectWorkerProcessor.WaitUntilCompletion_ForTestingPurposesOnly(workers, list); } internal void WaitUntilCompletion_ForTestingPurposesOnly() { _documentAndProjectWorkerProcessor.WaitUntilCompletion_ForTestingPurposesOnly(); } } } }
/* VRPhysicsBody * MiddleVR * (c) MiddleVR */ using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using MiddleVR_Unity3D; [AddComponentMenu("MiddleVR/Physics/Body")] [RequireComponent(typeof(VRClusterObject))] public class VRPhysicsBody : MonoBehaviour { #region Member Variables [SerializeField] private bool m_Static = false; [SerializeField] private float m_Mass = 0.0f; [SerializeField] private double m_Margin = 0.0; [SerializeField] private double m_RotationDamping = 0.0; [SerializeField] private double m_TranslationDamping = 0.0; private vrPhysicsGeometry m_Geometry = null; private vrPhysicsBody m_PhysicsBody = null; private string m_PhysicsBodyName = ""; private vrEventListener m_MVREventListener = null; #endregion #region Member Properties public float Mass { get { return m_Mass; } set { m_Mass = value; } } public vrPhysicsBody PhysicsBody { get { return m_PhysicsBody; } } public string PhysicsBodyName { get { return m_PhysicsBodyName; } } #endregion #region MonoBehaviour Member Functions protected void Start() { if (MiddleVR.VRClusterMgr.IsCluster() && !MiddleVR.VRClusterMgr.IsServer()) { enabled = false; return; } if (MiddleVR.VRPhysicsMgr == null) { MiddleVRTools.Log(0, "[X] PhysicsBody: No PhysicsManager found."); enabled = false; return; } vrPhysicsEngine physicsEngine = MiddleVR.VRPhysicsMgr.GetPhysicsEngine(); if (physicsEngine == null) { MiddleVRTools.Log(0, "[X] PhysicsBody: Failed to access a physics engine for body '" + name + "'."); enabled = false; return; } if (m_PhysicsBody == null) { m_PhysicsBody = physicsEngine.CreateBodyWithUniqueName(name); if (m_PhysicsBody == null) { MiddleVRTools.Log(0, "[X] PhysicsBody: Failed to create a physics body for '" + name + "'."); enabled = false; return; } else { GC.SuppressFinalize(m_PhysicsBody); m_MVREventListener = new vrEventListener(OnMVRNodeDestroy); m_PhysicsBody.AddEventListener(m_MVREventListener); var nodesMapper = MVRNodesMapper.Instance; nodesMapper.AddMapping( gameObject, m_PhysicsBody, MVRNodesMapper.ENodesSyncDirection.MiddleVRToUnity, MVRNodesMapper.ENodesInitValueOrigin.FromUnity); m_PhysicsBodyName = m_PhysicsBody.GetName(); string geometryName = m_PhysicsBodyName + ".Geometry"; MiddleVRTools.Log(4, "[>] PhysicsBody: Creation of the physics geometry '" + geometryName + "'."); m_Geometry = new vrPhysicsGeometry(geometryName); GC.SuppressFinalize(m_Geometry); Mesh mesh = null; MeshCollider meshCollider = GetComponent<MeshCollider>(); if (meshCollider != null) { mesh = meshCollider.sharedMesh; if (mesh != null) { MiddleVRTools.Log(2, "[ ] PhysicsBody: the physics geometry '" + geometryName + "' uses the mesh of its MeshCollider."); } } // No mesh from collider was found so let's try from the mesh filter. if (mesh == null) { mesh = GetComponent<MeshFilter>().sharedMesh; if (mesh != null) { MiddleVRTools.Log(2, "[ ] PhysicsBody: the physics geometry '" + geometryName + "' uses the mesh of its MeshFilter."); } } if (mesh != null) { ConvertGeometry(mesh); MiddleVRTools.Log(4, "[ ] PhysicsBody: Physics geometry created."); } else { MiddleVRTools.Log( 0, "[X] PhysicsBody: Failed to create the physics geometry '" + geometryName + "'."); } MiddleVRTools.Log(4, "[<] PhysicsBody: Creation of the physics geometry '" + geometryName + "' ended."); m_PhysicsBody.SetGeometry(m_Geometry); m_PhysicsBody.SetStatic(m_Static); m_PhysicsBody.SetMass(m_Mass); m_PhysicsBody.SetRotationDamping(m_RotationDamping); m_PhysicsBody.SetTranslationDamping(m_TranslationDamping); m_PhysicsBody.SetMargin(m_Margin); if (physicsEngine.AddBody(m_PhysicsBody)) { MiddleVRTools.Log(3, "[ ] PhysicsBody: The physics body '" + m_PhysicsBodyName + "' was added to the physics simulation."); } else { MiddleVRTools.Log(3, "[X] PhysicsBody: Failed to add the body '" + m_PhysicsBodyName + "' to the physics simulation."); } } } } protected void Update() { if (m_Geometry != null && m_PhysicsBody.IsInSimulation()) { // The geometry was used for creation so it can be deleted. // Clear now content to avoid a delayed memory deallocation. m_Geometry.Clear(); m_Geometry.Dispose(); m_Geometry = null; } } protected void OnDestroy() { if (m_PhysicsBody != null) { if (MVRNodesMapper.HasInstance()) { var nodesMapper = MVRNodesMapper.Instance; nodesMapper.RemoveMapping(gameObject); } if (MiddleVR.VRPhysicsMgr != null) { vrPhysicsEngine physicsEngine = MiddleVR.VRPhysicsMgr.GetPhysicsEngine(); if (physicsEngine != null) { physicsEngine.DestroyBody(m_PhysicsBodyName); } } m_PhysicsBody.Dispose(); m_PhysicsBody = null; } m_PhysicsBodyName = ""; if (m_MVREventListener != null) { m_MVREventListener.Dispose(); } } #endregion #region VRPhysicsBody Functions private bool OnMVRNodeDestroy(vrEvent iBaseEvt) { vrObjectEvent e = vrObjectEvent.Cast(iBaseEvt); if (e != null) { if (e.ComesFrom(m_PhysicsBody)) { if (e.eventType == (int)VRObjectEventEnum.VRObjectEvent_Destroy) { // Killed in MiddleVR so delete it in C#. m_PhysicsBody.Dispose(); } } } return true; } private void ConvertGeometry(Mesh mesh) { Vector3[] vertices = mesh.vertices; int[] triangles = mesh.triangles; MiddleVRTools.Log(3, "PhysicsBody: Number of vertices: " + vertices.Length); MiddleVRTools.Log(3, "PhysicsBody: Number of Triangles: " + triangles.Length); // We will reuse the same vectors to avoid many memory allocations. Vector3 vertexPos = new Vector3(); vrVec3 vPos = new vrVec3(); // We compute a matrix to scale vertices according to their world // coordinates, so this scale depends on the scales of the GameObject // parents. Matrices 4x4 are used because matrices 3x3 aren't available. vrMatrix worldMatrix = MVRTools.RawFromUnity(transform.localToWorldMatrix); worldMatrix.SetCol(3, new vrVec4(0.0f, 0.0f, 0.0f, 0.0f)); worldMatrix.SetRow(3, new vrVec4(0.0f, 0.0f, 0.0f, 0.0f)); vrQuat invRotWorlQ = worldMatrix.GetRotation(); invRotWorlQ = invRotWorlQ.Normalize().GetInverse(); vrMatrix invRotWorldMatrix = new vrMatrix(); invRotWorldMatrix.SetRotation(invRotWorlQ); invRotWorldMatrix.SetCol(3, new vrVec4(0.0f, 0.0f, 0.0f, 0.0f)); invRotWorldMatrix.SetRow(3, new vrVec4(0.0f, 0.0f, 0.0f, 0.0f)); vrMatrix scaleWorldMatrix = invRotWorldMatrix.Mult(worldMatrix); Matrix4x4 scaleWorldMatrixUnity = MiddleVRTools.RawToUnity(scaleWorldMatrix); foreach (Vector3 vertex in vertices) { vertexPos = scaleWorldMatrixUnity.MultiplyPoint3x4(vertex); MiddleVRTools.FromUnity(vertexPos, ref vPos); m_Geometry.AddVertex(vPos); MiddleVRTools.Log(6, "PhysicsBody: Adding a vertex at position (" + vPos.x() + ", " + vPos.y() + ", " + vPos.z() + ")."); } for (int i = 0, iEnd = triangles.Length; i < iEnd; i += 3) { uint index0 = (uint)triangles[i]; uint index1 = (uint)triangles[i + 1]; uint index2 = (uint)triangles[i + 2]; m_Geometry.AddTriangle(index0, index1, index2); MiddleVRTools.Log(6, "PhysicsBody: Adding a triangle with vertex indexes (" + index0 + ", " + index1 + ", " + index2 + ")."); } } #endregion }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Common; using System.Diagnostics; using System.Globalization; using System.Text; using System.Diagnostics.CodeAnalysis; namespace System.Data.Common { public class DbConnectionStringBuilder : System.Collections.IDictionary { // keyword->value currently listed in the connection string private Dictionary<string, object> _currentValues; // cached connectionstring to avoid constant rebuilding // and to return a user's connectionstring as is until editing occurs private string _connectionString = ""; public DbConnectionStringBuilder() { } private ICollection Collection { get { return (ICollection)CurrentValues; } } private IDictionary Dictionary { get { return (IDictionary)CurrentValues; } } private Dictionary<string, object> CurrentValues { get { Dictionary<string, object> values = _currentValues; if (null == values) { values = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); _currentValues = values; } return values; } } object System.Collections.IDictionary.this[object keyword] { // delegate to this[string keyword] get { return this[ObjectToString(keyword)]; } set { this[ObjectToString(keyword)] = value; } } public virtual object this[string keyword] { get { ADP.CheckArgumentNull(keyword, "keyword"); object value; if (CurrentValues.TryGetValue(keyword, out value)) { return value; } throw ADP.KeywordNotSupported(keyword); } set { ADP.CheckArgumentNull(keyword, "keyword"); if (null != value) { string keyvalue = DbConnectionStringBuilderUtil.ConvertToString(value); DbConnectionOptions.ValidateKeyValuePair(keyword, keyvalue); // store keyword/value pair CurrentValues[keyword] = keyvalue; } _connectionString = null; } } public string ConnectionString { get { string connectionString = _connectionString; if (null == connectionString) { StringBuilder builder = new StringBuilder(); foreach (string keyword in Keys) { object value; if (ShouldSerialize(keyword) && TryGetValue(keyword, out value)) { string keyvalue = (null != value) ? Convert.ToString(value, CultureInfo.InvariantCulture) : (string)null; AppendKeyValuePair(builder, keyword, keyvalue); } } connectionString = builder.ToString(); _connectionString = connectionString; } return connectionString; } set { DbConnectionOptions constr = new DbConnectionOptions(value, null); string originalValue = ConnectionString; Clear(); try { for (NameValuePair pair = constr.KeyChain; null != pair; pair = pair.Next) { if (null != pair.Value) { this[pair.Name] = pair.Value; } else { Remove(pair.Name); } } _connectionString = null; } catch (ArgumentException) { // restore original string ConnectionString = originalValue; _connectionString = originalValue; throw; } } } public virtual int Count { get { return CurrentValues.Count; } } public bool IsReadOnly { get { return false; } } public virtual bool IsFixedSize { get { return false; } } bool System.Collections.ICollection.IsSynchronized { get { return Collection.IsSynchronized; } } public virtual ICollection Keys { get { return Dictionary.Keys; } } object System.Collections.ICollection.SyncRoot { get { return Collection.SyncRoot; } } public virtual ICollection Values { get { System.Collections.Generic.ICollection<string> keys = (System.Collections.Generic.ICollection<string>)Keys; System.Collections.Generic.IEnumerator<string> keylist = keys.GetEnumerator(); object[] values = new object[keys.Count]; for (int i = 0; i < values.Length; ++i) { keylist.MoveNext(); values[i] = this[keylist.Current]; Debug.Assert(null != values[i], "null value " + keylist.Current); } return new System.Data.Common.ReadOnlyCollection<object>(values); } } void System.Collections.IDictionary.Add(object keyword, object value) { Add(ObjectToString(keyword), value); } public void Add(string keyword, object value) { this[keyword] = value; } public static void AppendKeyValuePair(StringBuilder builder, string keyword, string value) { DbConnectionOptions.AppendKeyValuePairBuilder(builder, keyword, value, false); } public virtual void Clear() { _connectionString = ""; CurrentValues.Clear(); } // does the keyword exist as a strongly typed keyword or as a stored value bool System.Collections.IDictionary.Contains(object keyword) { return ContainsKey(ObjectToString(keyword)); } public virtual bool ContainsKey(string keyword) { ADP.CheckArgumentNull(keyword, "keyword"); return CurrentValues.ContainsKey(keyword); } void ICollection.CopyTo(Array array, int index) { Collection.CopyTo(array, index); } public virtual bool EquivalentTo(DbConnectionStringBuilder connectionStringBuilder) { ADP.CheckArgumentNull(connectionStringBuilder, "connectionStringBuilder"); if ((GetType() != connectionStringBuilder.GetType()) || (CurrentValues.Count != connectionStringBuilder.CurrentValues.Count)) { return false; } object value; foreach (KeyValuePair<string, object> entry in CurrentValues) { if (!connectionStringBuilder.CurrentValues.TryGetValue(entry.Key, out value) || !entry.Value.Equals(value)) { return false; } } return true; } IEnumerator System.Collections.IEnumerable.GetEnumerator() { return Collection.GetEnumerator(); } IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { return Dictionary.GetEnumerator(); } private string ObjectToString(object keyword) { try { return (string)keyword; } catch (InvalidCastException) { throw new ArgumentException("keyword", "not a string"); } } void System.Collections.IDictionary.Remove(object keyword) { Remove(ObjectToString(keyword)); } public virtual bool Remove(string keyword) { ADP.CheckArgumentNull(keyword, "keyword"); if (CurrentValues.Remove(keyword)) { _connectionString = null; return true; } return false; } // does the keyword exist as a stored value or something that should always be persisted public virtual bool ShouldSerialize(string keyword) { ADP.CheckArgumentNull(keyword, "keyword"); return CurrentValues.ContainsKey(keyword); } public override string ToString() { return ConnectionString; } public virtual bool TryGetValue(string keyword, out object value) { ADP.CheckArgumentNull(keyword, "keyword"); return CurrentValues.TryGetValue(keyword, out value); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.MachineLearning.CommitmentPlans { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// CommitmentPlansOperations operations. /// </summary> internal partial class CommitmentPlansOperations : Microsoft.Rest.IServiceOperations<AzureMLCommitmentPlansManagementClient>, ICommitmentPlansOperations { /// <summary> /// Initializes a new instance of the CommitmentPlansOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal CommitmentPlansOperations(AzureMLCommitmentPlansManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AzureMLCommitmentPlansManagementClient /// </summary> public AzureMLCommitmentPlansManagementClient Client { get; private set; } /// <summary> /// Retrieve an Azure ML commitment plan by its subscription, resource group /// and name. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='commitmentPlanName'> /// The Azure ML commitment plan name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<CommitmentPlan>> GetWithHttpMessagesAsync(string resourceGroupName, string commitmentPlanName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (commitmentPlanName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "commitmentPlanName"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("commitmentPlanName", commitmentPlanName); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/commitmentPlans/{commitmentPlanName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{commitmentPlanName}", System.Uri.EscapeDataString(commitmentPlanName)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<CommitmentPlan>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CommitmentPlan>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates a new Azure ML commitment plan resource or updates an existing one. /// </summary> /// <param name='createOrUpdatePayload'> /// The payload to create or update the Azure ML commitment plan. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='commitmentPlanName'> /// The Azure ML commitment plan name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<CommitmentPlan>> CreateOrUpdateWithHttpMessagesAsync(CommitmentPlan createOrUpdatePayload, string resourceGroupName, string commitmentPlanName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (createOrUpdatePayload == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "createOrUpdatePayload"); } if (createOrUpdatePayload != null) { createOrUpdatePayload.Validate(); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (commitmentPlanName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "commitmentPlanName"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("createOrUpdatePayload", createOrUpdatePayload); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("commitmentPlanName", commitmentPlanName); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/commitmentPlans/{commitmentPlanName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{commitmentPlanName}", System.Uri.EscapeDataString(commitmentPlanName)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(createOrUpdatePayload != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(createOrUpdatePayload, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<CommitmentPlan>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CommitmentPlan>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CommitmentPlan>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Remove an existing Azure ML commitment plan. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='commitmentPlanName'> /// The Azure ML commitment plan name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> RemoveWithHttpMessagesAsync(string resourceGroupName, string commitmentPlanName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (commitmentPlanName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "commitmentPlanName"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("commitmentPlanName", commitmentPlanName); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Remove", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/commitmentPlans/{commitmentPlanName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{commitmentPlanName}", System.Uri.EscapeDataString(commitmentPlanName)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse(); _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) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Patch an existing Azure ML commitment plan resource. /// </summary> /// <param name='patchPayload'> /// The payload to patch the Azure ML commitment plan with. Only tags and SKU /// may be modified on an existing commitment plan. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='commitmentPlanName'> /// The Azure ML commitment plan name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<CommitmentPlan>> PatchWithHttpMessagesAsync(CommitmentPlanPatchPayload patchPayload, string resourceGroupName, string commitmentPlanName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (patchPayload == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "patchPayload"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (commitmentPlanName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "commitmentPlanName"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("patchPayload", patchPayload); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("commitmentPlanName", commitmentPlanName); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Patch", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/commitmentPlans/{commitmentPlanName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{commitmentPlanName}", System.Uri.EscapeDataString(commitmentPlanName)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(patchPayload != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(patchPayload, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<CommitmentPlan>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CommitmentPlan>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Retrieve all Azure ML commitment plans in a subscription. /// </summary> /// <param name='skipToken'> /// Continuation token for pagination. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CommitmentPlan>>> ListWithHttpMessagesAsync(string skipToken = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("skipToken", skipToken); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.MachineLearning/commitmentPlans").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (skipToken != null) { _queryParameters.Add(string.Format("$skipToken={0}", System.Uri.EscapeDataString(skipToken))); } if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CommitmentPlan>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<CommitmentPlan>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Retrieve all Azure ML commitment plans in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='skipToken'> /// Continuation token for pagination. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CommitmentPlan>>> ListInResourceGroupWithHttpMessagesAsync(string resourceGroupName, string skipToken = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("skipToken", skipToken); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListInResourceGroup", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/commitmentPlans").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (skipToken != null) { _queryParameters.Add(string.Format("$skipToken={0}", System.Uri.EscapeDataString(skipToken))); } if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CommitmentPlan>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<CommitmentPlan>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Retrieve all Azure ML commitment plans in a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CommitmentPlan>>> ListNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (nextPageLink == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CommitmentPlan>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<CommitmentPlan>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Retrieve all Azure ML commitment plans in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CommitmentPlan>>> ListInResourceGroupNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (nextPageLink == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListInResourceGroupNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CommitmentPlan>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<CommitmentPlan>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
/** * JsonParser * * Copyright (c) 2016 Osamu Takahashi * Copyright (c) 2016 Rusty Raven Inc. * * This software is released under the MIT License. * http://opensource.org/licenses/mit-license.php * * @author Osamu Takahashi */ using System; using System.Collections.Generic; using System.IO; namespace Codebook.Runtime { internal enum TokenType { INTEGER = 1001, DOUBLE = 1002, STRING = 1003, TRUE = 1004, FALSE = 1005, NULL = 1006 } public class InvalidJsonTokenException : Exception {} public class InvalidJsonFormatException : Exception {} internal class JsonLexer { private Stream _stream; private string _token = ""; private int _r = 0; private bool _woRead = false; private bool _clearToken = false; public string Token { get { return _token; } } enum State { INITIAL, NUMBER, NUMBER2, NUMBER3, NUMBER4, EXP, EXP2, EXP3, STRING, ESC, UNICODE, WORD } private State _state = State.INITIAL; public JsonLexer(Stream stream) { _stream = stream; } public int GetToken() { var wd = 0; while(true) { if (_clearToken) { _token = ""; _clearToken = false; } if (!_woRead) { _r = _stream.ReadByte(); if (_r < 0) wd += 1; if (wd > 1) throw new SystemException("Invalid Read(watch dog detected)"); } _woRead = false; switch(_state) { case State.INITIAL: if (_r == ' ' || _r == '\t' || _r == '\r' || _r== '\n') { continue; } else if (_r == '-') { _token += (char)_r; _state = State.NUMBER; } else if (_r == '0') { _token += (char)_r; _state = State.NUMBER2; } else if ('1' <= _r && _r <= '9') { _token += (char)_r; _state = State.NUMBER3; } else if (_r == '\"') { _state = State.STRING; } else if (_r == 't') { _token += (char)_r; _state = State.WORD; } else if (_r == 'f') { _token += (char)_r; _state = State.WORD; } else if (_r == 'n') { _token += (char)_r; _state = State.WORD; } else { _clearToken = true; _token += (char)_r; return _r; } break; // When first character is '-' case State.NUMBER: if (_r == '0') { _token += (char)_r; _state = State.NUMBER2; } else if ('1' <= _r && _r <= '9') { _token += (char)_r; _state = State.NUMBER3; } else { _woRead = true; _state = State.INITIAL; _clearToken = true; _token += (char)_r; return '-'; } break; // When first character is '0' case State.NUMBER2: if (_r == '.') { _token += (char)_r; _state = State.NUMBER4; } else if (_r == 'e' || _r == 'E') { _token += (char)_r; _state = State.EXP; } else { _woRead = true; _state = State.INITIAL; _clearToken = true; return (int)TokenType.INTEGER; } break; // When first digit is not '0' case State.NUMBER3: if ('0' <= _r && _r <= '9') { _token += (char)_r; } else if (_r == '.') { _token += (char)_r; _state = State.NUMBER4; } else if (_r == 'e' || _r == 'E') { _token += (char)_r; _state = State.EXP; } else { _woRead = true; _state = State.INITIAL; _clearToken = true; return (int)TokenType.INTEGER; } break; // frac part case State.NUMBER4: if ('0' <= _r && _r <= '9') { _token += (char)_r; } else if (_r == 'e' || _r == 'E') { _token += (char)_r; _state = State.EXP; } else { _woRead = true; _state = State.INITIAL; _clearToken = true; return (int)TokenType.DOUBLE; } break; case State.EXP: if (_r == '+') { _token += (char)_r; _state = State.EXP2; } else if (_r == '-') { _token += (char)_r; _state = State.EXP2; } else if ('0' <= _r && _r <= '9') { _token += (char)_r; _state = State.EXP3; } else { throw new InvalidJsonTokenException(); } break; case State.EXP2: if ('0' <= _r && _r <= '9') { _token += (char)_r; _state = State.EXP3; } else { throw new InvalidJsonTokenException(); } break; case State.EXP3: if ('0' <= _r && _r <= '9') { _token += (char)_r; } else { _woRead = true; _state = State.INITIAL; _clearToken = true; return (int)TokenType.DOUBLE; } break; case State.STRING: if (_r == '\"') { _token = System.Text.RegularExpressions.Regex.Unescape(_token); _state = State.INITIAL; _clearToken = true; return (int)TokenType.STRING; } if (_r == '\\') { _state = State.ESC; } else { _token += (char)_r; } break; case State.ESC: if (_r == '\\') { _token += (char)_r; } else if (_r == 'u') { _token += "\\u"; _state = State.STRING; } else if (_r == 'n') { _token += '\n'; _state = State.STRING; } else if (_r == 'r') { _token += '\r'; _state = State.STRING; } else if (_r == 't') { _token += '\t'; _state = State.STRING; } else if (_r == 'b') { _token += (char)0x08; _state = State.STRING; } else if (_r == 'f') { _token += (char)0x0c; _state = State.STRING; } else if (_r == '\"') { _token += '\"'; _state = State.STRING; } else if (_r == '/') { _token += (char)0x2f; _state = State.STRING; } else { throw new InvalidJsonTokenException(); } break; case State.WORD: if ('a' <= _r && _r <= 'z') { _token += (char)_r; } else { _woRead = true; _state = State.INITIAL; if (_token == "true") { _clearToken = true; return (int)TokenType.TRUE; } else if (_token == "false") { _clearToken = true; return (int)TokenType.FALSE; } else if (_token == "null") { _clearToken = true; return (int)TokenType.NULL; } throw new InvalidJsonTokenException(); } break; } } } } /** * The JSON parsing class * Reading from stream and parsing it to JValue(JObject) */ public class JsonParser { private JsonLexer _lexer; enum State { OBJECT, FIELDS, FIELDS2, VALUE, VALUE2, ARRAY, ARRAY2 } private State _state = State.OBJECT; public JsonParser(Stream stream) { _lexer = new JsonLexer(stream); } /** * A parsing funciton * Throw InvalidJsonTokenException or InvalidJsonFormatException when find a error * * @return if any object exists, return it * if not, return Option<JValue>.None */ public Option<JValue> Parse() { Stack<JValue> objStack = new Stack<JValue>(); Stack<string> fieldName = new Stack<string>(); while(true) { var token = _lexer.GetToken(); if (token < 0) return Option<JValue>.None; switch(_state) { case State.OBJECT: if (token == '{') { objStack.Push(new JObject()); _state = State.FIELDS; } else { throw new InvalidJsonFormatException(); } break; case State.FIELDS: if (token == '}') { var obj = objStack.Pop(); if (objStack.Count == 0) { return Option<JValue>.Some(obj); } else { var top = objStack.Peek(); if (top is JObject) { ((JObject)top).Fields.Add(new JField(fieldName.Pop(),obj)); _state = State.VALUE2; } else { ((JArray)top).Values.Add(obj); _state = State.ARRAY2; } } } else if (token == (int)TokenType.STRING) { fieldName.Push(_lexer.Token); _state = State.FIELDS2; } else { throw new InvalidJsonFormatException(); } break; case State.FIELDS2: if (token == ':') { _state = State.VALUE; } else { throw new InvalidJsonFormatException(); } break; case State.VALUE: if (token == (int)TokenType.STRING) { ((JObject)objStack.Peek()).Fields.Add(new JField(fieldName.Pop(),new JString(_lexer.Token))); _state = State.VALUE2; } else if (token == (int)TokenType.INTEGER) { ((JObject)objStack.Peek()).Fields.Add(new JField(fieldName.Pop(),new JInt(Int64.Parse(_lexer.Token)))); _state = State.VALUE2; } else if (token == (int)TokenType.DOUBLE) { ((JObject)objStack.Peek()).Fields.Add(new JField(fieldName.Pop(),new JDouble(Double.Parse(_lexer.Token)))); _state = State.VALUE2; } else if (token == (int)TokenType.TRUE) { ((JObject)objStack.Peek()).Fields.Add(new JField(fieldName.Pop(),new JBool(true))); _state = State.VALUE2; } else if (token == (int)TokenType.FALSE) { ((JObject)objStack.Peek()).Fields.Add(new JField(fieldName.Pop(),new JBool(false))); _state = State.VALUE2; } else if (token == (int)TokenType.NULL) { ((JObject)objStack.Peek()).Fields.Add(new JField(fieldName.Pop(),new JNull())); _state = State.VALUE2; } else if (token == '[') { objStack.Push(new JArray()); _state = State.ARRAY; } else if (token == '{') { objStack.Push(new JObject()); _state = State.FIELDS; } else { throw new InvalidJsonFormatException(); } break; case State.VALUE2: if (token == ',') { _state = State.FIELDS; } else if (token == '}') { var obj = objStack.Pop(); if (objStack.Count == 0) { return Option<JValue>.Some(obj); } else { var top = objStack.Peek(); if (top is JObject) { ((JObject)top).Fields.Add(new JField(fieldName.Pop(),obj)); _state = State.VALUE2; } else { ((JArray)top).Values.Add(obj); _state = State.ARRAY2; } } } else { throw new InvalidJsonFormatException(); } break; case State.ARRAY: if (token == ']') { var arr = objStack.Pop(); var top = objStack.Peek(); if (top is JObject) { ((JObject)top).Fields.Add(new JField(fieldName.Pop(),arr)); _state = State.VALUE2; } else { // JArray ((JArray)top).Values.Add(arr); _state = State.ARRAY2; } } else if (token == (int)TokenType.STRING) { ((JArray)objStack.Peek()).Values.Add(new JString(_lexer.Token)); _state = State.ARRAY2; } else if (token == (int)TokenType.INTEGER) { ((JArray)objStack.Peek()).Values.Add(new JInt(Int64.Parse(_lexer.Token))); _state = State.ARRAY2; } else if (token == (int)TokenType.DOUBLE) { ((JArray)objStack.Peek()).Values.Add(new JDouble(Double.Parse(_lexer.Token))); _state = State.ARRAY2; } else if (token == (int)TokenType.TRUE) { ((JArray)objStack.Peek()).Values.Add(new JBool(true)); _state = State.ARRAY2; } else if (token == (int)TokenType.FALSE) { ((JArray)objStack.Peek()).Values.Add(new JBool(false)); _state = State.ARRAY2; } else if (token == (int)TokenType.NULL) { ((JArray)objStack.Peek()).Values.Add(new JNull()); _state = State.ARRAY2; } else if (token == '[') { objStack.Push(new JArray()); } else if (token == '{') { objStack.Push(new JObject()); _state = State.FIELDS; } else { throw new InvalidJsonFormatException(); } break; case State.ARRAY2: if (token == ',') { _state = State.ARRAY; } else if (token == ']') { var arr = objStack.Pop(); var top = objStack.Peek(); if (top is JObject) { ((JObject)top).Fields.Add(new JField(fieldName.Pop(),arr)); _state = State.VALUE2; } else { // JArray ((JArray)top).Values.Add(arr); _state = State.ARRAY2; } } else { throw new InvalidJsonFormatException(); } break; } } } } }
//------------------------------------------------------------------------------ // <copyright file="FileUpload.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ // namespace System.Web.UI.WebControls { using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.IO; using System.Text; using System.Web.UI.HtmlControls; /// <devdoc> /// Displays a text box and browse button that allows the user to select a file for uploading. /// </devdoc> [ControlValueProperty("FileBytes")] [ValidationProperty("FileName")] [Designer("System.Web.UI.Design.WebControls.PreviewControlDesigner, " + AssemblyRef.SystemDesign)] public class FileUpload : WebControl { private static readonly IList<HttpPostedFile> _emptyFileCollection = new HttpPostedFile[0]; private IList<HttpPostedFile> _postedFiles; public FileUpload() : base(HtmlTextWriterTag.Input) { } [ Browsable(true), DefaultValue(false), WebCategory("Behavior"), WebSysDescription(SR.FileUpload_AllowMultiple) ] public virtual bool AllowMultiple { get { object o = ViewState["AllowMultiple"]; return (o != null) ? (bool)o : false; } set { ViewState["AllowMultiple"] = value; } } /// <devdoc> /// Gets the byte contents of the uploaded file. Needed for ControlParameters and templatized /// ImageFields. /// </devdoc> [ Bindable(true), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public byte[] FileBytes { get { Stream fileStream = FileContent; if (fileStream != null && fileStream != Stream.Null) { long fileStreamLength = fileStream.Length; BinaryReader reader = new BinaryReader(fileStream); Byte[] completeImage = null; if (fileStreamLength > Int32.MaxValue) { throw new HttpException(SR.GetString(SR.FileUpload_StreamTooLong)); } if (!fileStream.CanSeek) { throw new HttpException(SR.GetString(SR.FileUpload_StreamNotSeekable)); } int currentStreamPosition = (int)fileStream.Position; int fileStreamIntLength = (int)fileStreamLength; try { fileStream.Seek(0, SeekOrigin.Begin); completeImage = reader.ReadBytes(fileStreamIntLength); } finally { // Don't close or dispose of the BinaryReader because doing so would close the stream. // We want to put the stream back to the original position in case this getter is called again // and the stream supports seeking, the bytes will be returned again. fileStream.Seek(currentStreamPosition, SeekOrigin.Begin); } if (completeImage.Length != fileStreamIntLength) { throw new HttpException(SR.GetString(SR.FileUpload_StreamLengthNotReached)); } return completeImage; } return new byte[0]; } } /// <devdoc> /// Gets the contents of the uploaded file. /// </devdoc> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public Stream FileContent { get { HttpPostedFile f = PostedFile; if (f != null) { return PostedFile.InputStream; } return Stream.Null; } } /// <devdoc> /// The name of the file on the client's computer, not including the path. /// </devdoc> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public string FileName { get { HttpPostedFile postedFile = PostedFile; string fileName = string.Empty; if (postedFile != null) { string fullFileName = postedFile.FileName; try { // Some browsers (IE 6, Netscape 4) return the fully-qualified filename, // like "C:\temp\foo.txt". The application writer is probably not interested // in the client path, so we just return the filename part. fileName = Path.GetFileName(fullFileName); } catch { fileName = fullFileName; } } return fileName; } } /// <devdoc> /// Whether or not a file was uploaded. /// </devdoc> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public bool HasFile { get { // Unfortunately returns false if a 0-byte file was uploaded, since we see a 0-byte // file if the user entered nothing, an invalid filename, or a valid filename // of a 0-byte file. We feel this scenario is uncommon. HttpPostedFile f = PostedFile; return f != null && f.ContentLength > 0; } } /// <devdoc> /// Whether or not at least 1 non-0-length file was uploaded. /// </devdoc> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public bool HasFiles { get { // Unfortunately returns false if a 0-byte file was uploaded, since we see a 0-byte // file if the user entered nothing, an invalid filename, or a valid filename // of a 0-byte file. We feel this scenario is uncommon. return PostedFiles.Any(f => f.ContentLength > 0); } } /// <devdoc> /// Provides access to the underlying HttpPostedFile. /// </devdoc> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public HttpPostedFile PostedFile { get { if (Page != null && Page.IsPostBack) { return Context.Request.Files[UniqueID]; } return null; } } [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public IList<HttpPostedFile> PostedFiles { get { if (_postedFiles == null) { IList<HttpPostedFile> result = _emptyFileCollection; if (Page != null && Page.IsPostBack) { result = Context.Request.Files.GetMultiple(UniqueID); Debug.Assert(result != null); } _postedFiles = result; } return _postedFiles; } } protected override void AddAttributesToRender(HtmlTextWriter writer) { writer.AddAttribute(HtmlTextWriterAttribute.Type, "file"); if (AllowMultiple) { writer.AddAttribute(HtmlTextWriterAttribute.Multiple, "multiple"); } string uniqueID = UniqueID; if (uniqueID != null) { writer.AddAttribute(HtmlTextWriterAttribute.Name, uniqueID); } base.AddAttributesToRender(writer); } protected internal override void OnPreRender(EventArgs e) { base.OnPreRender(e); HtmlForm form = Page.Form; if (form != null && form.Enctype.Length == 0) { form.Enctype = "multipart/form-data"; } } protected internal override void Render(HtmlTextWriter writer) { // Make sure we are in a form tag with runat=server. if (Page != null) { Page.VerifyRenderingInServerForm(this); } base.Render(writer); } /// <devdoc> /// Initiates a utility method to save an uploaded file to disk. /// </devdoc> public void SaveAs(string filename) { HttpPostedFile f = PostedFile; if (f != null) { f.SaveAs(filename); } } } }
using System; using Xunit; namespace Prometheus.Client.Tests { public class LabelsHelperTests { [Theory] [InlineData(0, typeof(ValueTuple))] [InlineData(1, typeof(ValueTuple<string>))] [InlineData(2, typeof((string, string)))] [InlineData(7, typeof((string, string, string, string, string, string, string)))] [InlineData(8, typeof((string, string, string, string, string, string, string, string)))] [InlineData(16, typeof((string, string, string, string, string, string, string, string, string, string, string, string, string, string, string, string)))] public void MakeValueTupleTypeTests(int len, Type expected) { var type = LabelsHelper.MakeValueTupleType(len); Assert.Equal(expected, type); } [Fact] public void GetSize0Test() { var size = LabelsHelper.GetSize<ValueTuple>(); Assert.Equal(0, size); } [Fact] public void GetSize1Test() { var size = LabelsHelper.GetSize<ValueTuple<string>>(); Assert.Equal(1, size); } [Fact] public void GetSize2Test() { var size = LabelsHelper.GetSize<(string, string)>(); Assert.Equal(2, size); } [Fact] public void GetSize8Test() { var size = LabelsHelper.GetSize<(string, string, string, string, string, string, string, string)>(); Assert.Equal(8, size); } [Fact] public void GetSize16Test() { var size = LabelsHelper.GetSize<(string, string, string, string, string, string, string, string, string, string, string, string, string, string, string, string)>(); Assert.Equal(16, size); } [Fact] public void FormatTuple0() { var tuple = ValueTuple.Create(); var formatted = LabelsHelper.ToArray(tuple); Assert.Equal(new string[0], formatted); } [Fact] public void FormatTuple1() { var tuple = ValueTuple.Create("1"); var formatted = LabelsHelper.ToArray(tuple); Assert.Equal(new[] { "1" }, formatted); } [Fact] public void FormatTuple2() { var tuple = ("1", "2"); var formatted = LabelsHelper.ToArray(tuple); Assert.Equal(new[] { "1", "2" }, formatted); } [Fact] public void FormatTuple7() { var tuple = ("1", "2", "3", "4", "5", "6", "7"); var formatted = LabelsHelper.ToArray(tuple); Assert.Equal(new[] { "1", "2", "3", "4", "5", "6", "7" }, formatted); } [Fact] public void FormatTuple8() { var tuple = ("1", "2", "3", "4", "5", "6", "7", "8"); var formatted = LabelsHelper.ToArray(tuple); Assert.Equal(new[] { "1", "2", "3", "4", "5", "6", "7", "8" }, formatted); } [Fact] public void FormatTuple16() { var tuple = ("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"); var formatted = LabelsHelper.ToArray(tuple); Assert.Equal(new[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16" }, formatted); } [Fact] public void ParseTuple0() { var arr = new string[0]; var parsed = LabelsHelper.FromArray<ValueTuple>(arr); Assert.Equal(ValueTuple.Create(), parsed); } [Fact] public void ParseTuple1() { var arr = new[] { "1" }; var parsed = LabelsHelper.FromArray<ValueTuple<string>>(arr); Assert.Equal(ValueTuple.Create("1"), parsed); } [Fact] public void ParseTuple2() { var arr = new[] { "1", "2" }; var parsed = LabelsHelper.FromArray<(string, string)>(arr); Assert.Equal(("1", "2"), parsed); } [Fact] public void ParseTuple7() { var arr = new[] { "1", "2", "3", "4", "5", "6", "7" }; var parsed = LabelsHelper.FromArray<(string, string, string, string, string, string, string)>(arr); Assert.Equal(("1", "2", "3", "4", "5", "6", "7"), parsed); } [Fact] public void ParseTuple8() { var arr = new[] { "1", "2", "3", "4", "5", "6", "7", "8" }; var parsed = LabelsHelper.FromArray<(string, string, string, string, string, string, string, string)>(arr); Assert.Equal(("1", "2", "3", "4", "5", "6", "7", "8"), parsed); } [Fact] public void ParseTuple16() { var arr = new[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16" }; var parsed = LabelsHelper.FromArray<(string, string, string, string, string, string, string, string, string, string, string, string, string, string, string, string)>(arr); Assert.Equal(("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"), parsed); } [Fact] public void ThrowOnIntLabelName1() { var labels = ValueTuple.Create(1); Assert.Throws<NotSupportedException>(() => LabelsHelper.ToArray(labels)); } [Fact] public void ThrowOnIntLabelName8() { var labels = ("1", "2", "3", "4", "5", "6", "7", 8); Assert.Throws<NotSupportedException>(() => LabelsHelper.ToArray(labels)); } [Fact] public void ThrowOnIntLabelName16() { var labels = ("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", 16); Assert.Throws<NotSupportedException>(() => LabelsHelper.ToArray(labels)); } [Fact] public void ThrowOnEnumLabelName1() { var labels = ValueTuple.Create(MetricType.Untyped); Assert.Throws<NotSupportedException>(() => LabelsHelper.ToArray(labels)); } [Fact] public void ThrowOnEnumLabelName8() { var labels = ("1", "2", "3", "4", "5", "6", "7", MetricType.Untyped); Assert.Throws<NotSupportedException>(() => LabelsHelper.ToArray(labels)); } [Fact] public void ThrowOnEnumLabelName16() { var labels = ("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", MetricType.Untyped); Assert.Throws<NotSupportedException>(() => LabelsHelper.ToArray(labels)); } [Fact] public void GetHashCode0() { var tupleCode = LabelsHelper.GetHashCode(ValueTuple.Create()); var arrayCode = LabelsHelper.GetHashCode(new string[0]); Assert.Equal(tupleCode, arrayCode); } [Fact] public void GetHashCode1() { var tupleCode = LabelsHelper.GetHashCode(ValueTuple.Create("1")); var arrayCode = LabelsHelper.GetHashCode(new [] { "1" }); Assert.Equal(tupleCode, arrayCode); } [Fact] public void GetHashCode2() { var tupleCode = LabelsHelper.GetHashCode(ValueTuple.Create("1", "2")); var arrayCode = LabelsHelper.GetHashCode(new [] {"1", "2"}); Assert.Equal(tupleCode, arrayCode); } [Fact] public void GetHashCode8() { var tupleCode = LabelsHelper.GetHashCode(ValueTuple.Create("1", "2", "3", "4", "5", "6", "7", "8")); var arrayCode = LabelsHelper.GetHashCode(new [] {"1", "2", "3", "4", "5", "6", "7", "8"}); Assert.Equal(tupleCode, arrayCode); } } }
// 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 System.IO; using XmlCoreTest.Common; namespace System.Xml.Tests { //////////////////////////////////////////////////////////////// // TestFiles // //////////////////////////////////////////////////////////////// public class NameTable_TestFiles { //Data private static string s_allNodeTypeDTD = "AllNodeTypes.dtd"; private static string s_allNodeTypeENT = "AllNodeTypes.ent"; private static string s_genericXml = "Generic.xml"; private static string s_bigFileXml = "Big.xml"; public static void RemoveDataReader(EREADER_TYPE eReaderType) { switch (eReaderType) { case EREADER_TYPE.GENERIC: DeleteTestFile(s_allNodeTypeDTD); DeleteTestFile(s_allNodeTypeENT); DeleteTestFile(s_genericXml); break; case EREADER_TYPE.BIG_ELEMENT_SIZE: DeleteTestFile(s_bigFileXml); break; default: throw new Exception(); } } private static Dictionary<EREADER_TYPE, string> s_fileNameMap = null; public static string GetTestFileName(EREADER_TYPE eReaderType) { if (s_fileNameMap == null) InitFileNameMap(); return s_fileNameMap[eReaderType]; } private static void InitFileNameMap() { if (s_fileNameMap == null) { s_fileNameMap = new Dictionary<EREADER_TYPE, string>(); } s_fileNameMap.Add(EREADER_TYPE.GENERIC, s_genericXml); s_fileNameMap.Add(EREADER_TYPE.BIG_ELEMENT_SIZE, s_bigFileXml); } public static void CreateTestFile(ref string strFileName, EREADER_TYPE eReaderType) { strFileName = GetTestFileName(eReaderType); switch (eReaderType) { case EREADER_TYPE.GENERIC: CreateGenericTestFile(strFileName); break; case EREADER_TYPE.BIG_ELEMENT_SIZE: CreateBigElementTestFile(strFileName); break; default: throw new Exception(); } } protected static void DeleteTestFile(string strFileName) { } public static void CreateGenericTestFile(string strFileName) { MemoryStream ms = new MemoryStream(); TextWriter tw = new StreamWriter(ms); tw.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>"); tw.WriteLine("<!-- comment1 -->"); tw.WriteLine("<?PI1_First processing instruction?>"); tw.WriteLine("<?PI1a?>"); tw.WriteLine("<?PI1b?>"); tw.WriteLine("<?PI1c?>"); tw.WriteLine("<!DOCTYPE root SYSTEM \"AllNodeTypes.dtd\" ["); tw.WriteLine("<!NOTATION gif SYSTEM \"foo.exe\">"); tw.WriteLine("<!ELEMENT root ANY>"); tw.WriteLine("<!ELEMENT elem1 ANY>"); tw.WriteLine("<!ELEMENT ISDEFAULT ANY>"); tw.WriteLine("<!ENTITY % e SYSTEM \"AllNodeTypes.ent\">"); tw.WriteLine("%e;"); tw.WriteLine("<!ENTITY e1 \"e1foo\">"); tw.WriteLine("<!ENTITY e2 \"&ext3; e2bar\">"); tw.WriteLine("<!ENTITY e3 \"&e1; e3bzee \">"); tw.WriteLine("<!ENTITY e4 \"&e3; e4gee\">"); tw.WriteLine("<!ATTLIST elem1 child1 CDATA #IMPLIED child2 CDATA \"&e2;\" child3 CDATA #REQUIRED>"); tw.WriteLine("<!ATTLIST root xmlns:something CDATA #FIXED \"something\" xmlns:my CDATA #FIXED \"my\" xmlns:dt CDATA #FIXED \"urn:uuid:C2F41010-65B3-11d1-A29F-00AA00C14882/\">"); tw.WriteLine("<!ATTLIST ISDEFAULT d1 CDATA #FIXED \"d1value\">"); tw.WriteLine("<!ATTLIST MULTISPACES att IDREFS #IMPLIED>"); tw.WriteLine("<!ELEMENT CATMIXED (#PCDATA)>"); tw.WriteLine("]>"); tw.WriteLine("<PLAY>"); tw.WriteLine("<root xmlns:something=\"something\" xmlns:my=\"my\" xmlns:dt=\"urn:uuid:C2F41010-65B3-11d1-A29F-00AA00C14882/\">"); tw.WriteLine("<elem1 child1=\"\" child2=\"e1foo e3bzee e2bar\" child3=\"something\">"); tw.WriteLine("text node two e1foo text node three"); tw.WriteLine("</elem1>"); tw.WriteLine("e1foo e3bzee e2bar"); tw.WriteLine("<![CDATA[ This section contains characters that should not be interpreted as markup. For example, characters ', \","); tw.WriteLine("<, >, and & are all fine here.]]>"); tw.WriteLine("<elem2 att1=\"id1\" att2=\"up\" att3=\"attribute3\"> "); tw.WriteLine("<a />"); tw.WriteLine("</elem2>"); tw.WriteLine("<elem2> "); tw.WriteLine("elem2-text1"); tw.WriteLine("<a refs=\"id2\"> "); tw.WriteLine("this-is-a "); tw.WriteLine("</a> "); tw.WriteLine("elem2-text2"); tw.WriteLine("e1foo e3bzee "); tw.WriteLine("e1foo e3bzee e4gee"); tw.WriteLine("<!-- elem2-comment1-->"); tw.WriteLine("elem2-text3"); tw.WriteLine("<b> "); tw.WriteLine("this-is-b"); tw.WriteLine("</b>"); tw.WriteLine("elem2-text4"); tw.WriteLine("<?elem2_PI elem2-PI?>"); tw.WriteLine("elem2-text5"); tw.WriteLine("</elem2>"); tw.WriteLine("<elem2 att1=\"id2\"></elem2>"); tw.WriteLine("</root>"); tw.Write("<ENTITY1 att1='xxx&lt;xxx&#65;xxx&#x43;xxxe1fooxxx'>xxx&gt;xxx&#66;xxx&#x44;xxxe1fooxxx</ENTITY1>"); tw.WriteLine("<ENTITY2 att1='xxx&lt;xxx&#65;xxx&#x43;xxxe1fooxxx'>xxx&gt;xxx&#66;xxx&#x44;xxxe1fooxxx</ENTITY2>"); tw.WriteLine("<ENTITY3 att1='xxx&lt;xxx&#65;xxx&#x43;xxxe1fooxxx'>xxx&gt;xxx&#66;xxx&#x44;xxxe1fooxxx</ENTITY3>"); tw.WriteLine("<ENTITY4 att1='xxx&lt;xxx&#65;xxx&#x43;xxxe1fooxxx'>xxx&gt;xxx&#66;xxx&#x44;xxxe1fooxxx</ENTITY4>"); tw.WriteLine("<ENTITY5>e1foo e3bzee </ENTITY5>"); tw.WriteLine("<ATTRIBUTE1 />"); tw.WriteLine("<ATTRIBUTE2 a1='a1value' />"); tw.WriteLine("<ATTRIBUTE3 a1='a1value' a2='a2value' a3='a3value' />"); tw.WriteLine("<ATTRIBUTE4 a1='' />"); tw.WriteLine("<ATTRIBUTE5 CRLF='x\r\nx' CR='x\rx' LF='x\nx' MS='x x' TAB='x\tx' />"); tw.WriteLine("<ENDOFLINE1>x\r\nx</ENDOFLINE1>"); tw.WriteLine("<ENDOFLINE2>x\rx</ENDOFLINE2>"); tw.WriteLine("<ENDOFLINE3>x\nx</ENDOFLINE3>"); tw.WriteLine("<WHITESPACE1>\r\n<ELEM />\r\n</WHITESPACE1>"); tw.WriteLine("<WHITESPACE2> <ELEM /> </WHITESPACE2>"); tw.WriteLine("<WHITESPACE3>\t<ELEM />\t</WHITESPACE3>"); tw.WriteLine("<SKIP1 /><AFTERSKIP1 />"); tw.WriteLine("<SKIP2></SKIP2><AFTERSKIP2 />"); tw.WriteLine("<SKIP3><ELEM1 /><ELEM2>xxx yyy</ELEM2><ELEM3 /></SKIP3><AFTERSKIP3></AFTERSKIP3>"); tw.WriteLine("<SKIP4><ELEM1 /><ELEM2>xxx<ELEM3 /></ELEM2></SKIP4>"); tw.WriteLine("<CHARS1>0123456789</CHARS1>"); tw.WriteLine("<CHARS2>xxx<MARKUP />yyy</CHARS2>"); tw.WriteLine("<CHARS_ELEM1>xxx<MARKUP />yyy</CHARS_ELEM1>"); tw.WriteLine("<CHARS_ELEM2><MARKUP />yyy</CHARS_ELEM2>"); tw.WriteLine("<CHARS_ELEM3>xxx<MARKUP /></CHARS_ELEM3>"); tw.WriteLine("<CHARS_CDATA1>xxx<![CDATA[yyy]]>zzz</CHARS_CDATA1>"); tw.WriteLine("<CHARS_CDATA2><![CDATA[yyy]]>zzz</CHARS_CDATA2>"); tw.WriteLine("<CHARS_CDATA3>xxx<![CDATA[yyy]]></CHARS_CDATA3>"); tw.WriteLine("<CHARS_PI1>xxx<?PI_CHAR1 yyy?>zzz</CHARS_PI1>"); tw.WriteLine("<CHARS_PI2><?PI_CHAR2?>zzz</CHARS_PI2>"); tw.WriteLine("<CHARS_PI3>xxx<?PI_CHAR3 yyy?></CHARS_PI3>"); tw.WriteLine("<CHARS_COMMENT1>xxx<!-- comment1-->zzz</CHARS_COMMENT1>"); tw.WriteLine("<CHARS_COMMENT2><!-- comment1-->zzz</CHARS_COMMENT2>"); tw.WriteLine("<CHARS_COMMENT3>xxx<!-- comment1--></CHARS_COMMENT3>"); tw.Flush(); tw.WriteLine("<ISDEFAULT />"); tw.WriteLine("<ISDEFAULT a1='a1value' />"); tw.WriteLine("<BOOLEAN1>true</BOOLEAN1>"); tw.WriteLine("<BOOLEAN2>false</BOOLEAN2>"); tw.WriteLine("<BOOLEAN3>1</BOOLEAN3>"); tw.WriteLine("<BOOLEAN4>tRue</BOOLEAN4>"); tw.WriteLine("<DATETIME>1999-02-22T11:11:11</DATETIME>"); tw.WriteLine("<DATE>1999-02-22</DATE>"); tw.WriteLine("<TIME>11:11:11</TIME>"); tw.WriteLine("<INTEGER>9999</INTEGER>"); tw.WriteLine("<FLOAT>99.99</FLOAT>"); tw.WriteLine("<DECIMAL>.09</DECIMAL>"); tw.WriteLine("<CONTENT><e1 a1='a1value' a2='a2value'><e2 a1='a1value' a2='a2value'><e3 a1='a1value' a2='a2value'>leave</e3></e2></e1></CONTENT>"); tw.WriteLine("<TITLE><!-- this is a comment--></TITLE>"); tw.WriteLine("<PGROUP>"); tw.WriteLine("<ACT0 xmlns:foo=\"http://www.foo.com\" foo:Attr0=\"0\" foo:Attr1=\"1111111101\" foo:Attr2=\"222222202\" foo:Attr3=\"333333303\" foo:Attr4=\"444444404\" foo:Attr5=\"555555505\" foo:Attr6=\"666666606\" foo:Attr7=\"777777707\" foo:Attr8=\"888888808\" foo:Attr9=\"999999909\" />"); tw.WriteLine("<ACT1 Attr0=\'0\' Attr1=\'1111111101\' Attr2=\'222222202\' Attr3=\'333333303\' Attr4=\'444444404\' Attr5=\'555555505\' Attr6=\'666666606\' Attr7=\'777777707\' Attr8=\'888888808\' Attr9=\'999999909\' />"); tw.WriteLine("<QUOTE1 Attr0=\"0\" Attr1=\'1111111101\' Attr2=\"222222202\" Attr3=\'333333303\' />"); tw.WriteLine("<PERSONA>DROMIO OF EPHESUS</PERSONA>"); tw.WriteLine("<QUOTE2 Attr0=\"0\" Attr1=\"1111111101\" Attr2=\'222222202\' Attr3=\'333333303\' />"); tw.WriteLine("<QUOTE3 Attr0=\'0\' Attr1=\"1111111101\" Attr2=\'222222202\' Attr3=\"333333303\" />"); tw.WriteLine("<EMPTY1 />"); tw.WriteLine("<EMPTY2 val=\"abc\" />"); tw.WriteLine("<EMPTY3></EMPTY3>"); tw.WriteLine("<NONEMPTY0></NONEMPTY0>"); tw.WriteLine("<NONEMPTY1>ABCDE</NONEMPTY1>"); tw.WriteLine("<NONEMPTY2 val=\"abc\">1234</NONEMPTY2>"); tw.WriteLine("<ACT2 Attr0=\"10\" Attr1=\"1111111011\" Attr2=\"222222012\" Attr3=\"333333013\" Attr4=\"444444014\" Attr5=\"555555015\" Attr6=\"666666016\" Attr7=\"777777017\" Attr8=\"888888018\" Attr9=\"999999019\" />"); tw.WriteLine("<GRPDESCR>twin brothers, and sons to Aegeon and Aemilia.</GRPDESCR>"); tw.WriteLine("</PGROUP>"); tw.WriteLine("<PGROUP>"); tw.Flush(); tw.WriteLine("<XMLLANG0 xml:lang=\"en-US\">What color e1foo is it?</XMLLANG0>"); tw.Write("<XMLLANG1 xml:lang=\"en-GB\">What color is it?<a><b><c>Language Test</c><PERSONA>DROMIO OF EPHESUS</PERSONA></b></a></XMLLANG1>"); tw.WriteLine("<NOXMLLANG />"); tw.WriteLine("<EMPTY_XMLLANG Attr0=\"0\" xml:lang=\"en-US\" />"); tw.WriteLine("<XMLLANG2 xml:lang=\"en-US\">What color is it?<TITLE><!-- this is a comment--></TITLE><XMLLANG1 xml:lang=\"en-GB\">Testing language<XMLLANG0 xml:lang=\"en-US\">What color is it?</XMLLANG0>haha </XMLLANG1>hihihi</XMLLANG2>"); tw.WriteLine("<DONEXMLLANG />"); tw.WriteLine("<XMLSPACE1 xml:space=\'default\'>&lt; &gt;</XMLSPACE1>"); tw.Write("<XMLSPACE2 xml:space=\'preserve\'>&lt; &gt;<a><!-- comment--><b><?PI1a?><c>Space Test</c><PERSONA>DROMIO OF SYRACUSE</PERSONA></b></a></XMLSPACE2>"); tw.WriteLine("<NOSPACE />"); tw.WriteLine("<EMPTY_XMLSPACE Attr0=\"0\" xml:space=\'default\' />"); tw.WriteLine("<XMLSPACE2A xml:space=\'default\'>&lt; <XMLSPACE3 xml:space=\'preserve\'> &lt; &gt; <XMLSPACE4 xml:space=\'default\'> &lt; &gt; </XMLSPACE4> test </XMLSPACE3> &gt;</XMLSPACE2A>"); tw.WriteLine("<GRPDESCR>twin brothers, and attendants on the two Antipholuses.</GRPDESCR>"); tw.WriteLine("<DOCNAMESPACE>"); tw.WriteLine("<NAMESPACE0 xmlns:bar=\"1\"><bar:check>Namespace=1</bar:check></NAMESPACE0>"); tw.WriteLine("<NAMESPACE1 xmlns:bar=\"1\"><a><b><c><d><bar:check>Namespace=1</bar:check><bar:check2></bar:check2></d></c></b></a></NAMESPACE1>"); tw.WriteLine("<NONAMESPACE>Namespace=\"\"</NONAMESPACE>"); tw.WriteLine("<EMPTY_NAMESPACE bar:Attr0=\"0\" xmlns:bar=\"1\" />"); tw.WriteLine("<EMPTY_NAMESPACE1 Attr0=\"0\" xmlns=\"14\" />"); tw.WriteLine("<EMPTY_NAMESPACE2 Attr0=\"0\" xmlns=\"14\"></EMPTY_NAMESPACE2>"); tw.WriteLine("<NAMESPACE2 xmlns:bar=\"1\"><a><b><c xmlns:bar=\"2\"><d><bar:check>Namespace=2</bar:check></d></c></b></a></NAMESPACE2>"); tw.WriteLine("<NAMESPACE3 xmlns=\"1\"><a xmlns:a=\"2\" xmlns:b=\"3\" xmlns:c=\"4\"><b xmlns:d=\"5\" xmlns:e=\"6\" xmlns:f='7'><c xmlns:d=\"8\" xmlns:e=\"9\" xmlns:f=\"10\">"); tw.WriteLine("<d xmlns:g=\"11\" xmlns:h=\"12\"><check>Namespace=1</check><testns xmlns=\"100\"><empty100 /><check100>Namespace=100</check100></testns><check1>Namespace=1</check1><d:check8>Namespace=8</d:check8></d></c><d:check5>Namespace=5</d:check5></b></a>"); tw.WriteLine("<a13 a:check=\"Namespace=13\" xmlns:a=\"13\" /><check14 xmlns=\"14\">Namespace=14</check14></NAMESPACE3>"); tw.WriteLine("<NONAMESPACE>Namespace=\"\"</NONAMESPACE>"); tw.WriteLine("<NONAMESPACE1 Attr1=\"one\" xmlns=\"1000\">Namespace=\"\"</NONAMESPACE1>"); tw.WriteLine("</DOCNAMESPACE>"); tw.WriteLine("</PGROUP>"); tw.WriteLine("<GOTOCONTENT>some text<![CDATA[cdata info]]></GOTOCONTENT>"); tw.WriteLine("<SKIPCONTENT att1=\"\"> <!-- comment1--> \n <?PI_SkipContent instruction?></SKIPCONTENT>"); tw.WriteLine("<MIXCONTENT> <!-- comment1-->some text<?PI_SkipContent instruction?><![CDATA[cdata info]]></MIXCONTENT>"); tw.WriteLine("<A att=\"123\">1<B>2<C>3<D>4<E>5<F>6<G>7<H>8<I>9<J>10"); tw.WriteLine("<A1 att=\"456\">11<B1>12<C1>13<D1>14<E1>15<F1>16<G1>17<H1>18<I1>19<J1>20"); tw.WriteLine("<A2 att=\"789\">21<B2>22<C2>23<D2>24<E2>25<F2>26<G2>27<H2>28<I2>29<J2>30"); tw.WriteLine("<A3 att=\"123\">31<B3>32<C3>33<D3>34<E3>35<F3>36<G3>37<H3>38<I3>39<J3>40"); tw.WriteLine("<A4 att=\"456\">41<B4>42<C4>43<D4>44<E4>45<F4>46<G4>47<H4>48<I4>49<J4>50"); tw.WriteLine("<A5 att=\"789\">51<B5>52<C5>53<D5>54<E5>55<F5>56<G5>57<H5>58<I5>59<J5>60"); tw.WriteLine("<A6 att=\"123\">61<B6>62<C6>63<D6>64<E6>65<F6>66<G6>67<H6>68<I6>69<J6>70"); tw.WriteLine("<A7 att=\"456\">71<B7>72<C7>73<D7>74<E7>75<F7>76<G7>77<H7>78<I7>79<J7>80"); tw.WriteLine("<A8 att=\"789\">81<B8>82<C8>83<D8>84<E8>85<F8>86<G8>87<H8>88<I8>89<J8>90"); tw.WriteLine("<A9 att=\"123\">91<B9>92<C9>93<D9>94<E9>95<F9>96<G9>97<H9>98<I9>99<J9>100"); tw.WriteLine("<A10 att=\"123\">101<B10>102<C10>103<D10>104<E10>105<F10>106<G10>107<H10>108<I10>109<J10>110"); tw.WriteLine("</J10>109</I10>108</H10>107</G10>106</F10>105</E10>104</D10>103</C10>102</B10>101</A10>"); tw.WriteLine("</J9>99</I9>98</H9>97</G9>96</F9>95</E9>94</D9>93</C9>92</B9>91</A9>"); tw.WriteLine("</J8>89</I8>88</H8>87</G8>86</F8>85</E8>84</D8>83</C8>82</B8>81</A8>"); tw.WriteLine("</J7>79</I7>78</H7>77</G7>76</F7>75</E7>74</D7>73</C7>72</B7>71</A7>"); tw.WriteLine("</J6>69</I6>68</H6>67</G6>66</F6>65</E6>64</D6>63</C6>62</B6>61</A6>"); tw.WriteLine("</J5>59</I5>58</H5>57</G5>56</F5>55</E5>54</D5>53</C5>52</B5>51</A5>"); tw.WriteLine("</J4>49</I4>48</H4>47</G4>46</F4>45</E4>44</D4>43</C4>42</B4>41</A4>"); tw.WriteLine("</J3>39</I3>38</H3>37</G3>36</F3>35</E3>34</D3>33</C3>32</B3>31</A3>"); tw.WriteLine("</J2>29</I2>28</H2>27</G2>26</F2>25</E2>24</D2>23</C2>22</B2>21</A2>"); tw.WriteLine("</J1>19</I1>18</H1>17</G1>16</F1>15</E1>14</D1>13</C1>12</B1>11</A1>"); tw.Write("</J>9</I>8</H>7</G>6</F>5</E>4</D>3</C>2</B>1</A>"); tw.WriteLine("<EMPTY4 val=\"abc\"></EMPTY4>"); tw.WriteLine("<COMPLEX>Text<!-- comment --><![CDATA[cdata]]></COMPLEX>"); tw.WriteLine("<DUMMY />"); tw.WriteLine("<MULTISPACES att=' \r\n \t \r\r\n n1 \r\n \t \r\r\n n2 \r\n \t \r\r\n ' />"); tw.WriteLine("<CAT>AB<![CDATA[CD]]> </CAT>"); tw.WriteLine("<CATMIXED>AB<![CDATA[CD]]> </CATMIXED>"); tw.WriteLine("<VALIDXMLLANG0 xml:lang=\"a\" />"); tw.WriteLine("<VALIDXMLLANG1 xml:lang=\"\" />"); tw.WriteLine("<VALIDXMLLANG2 xml:lang=\"ab-cd-\" />"); tw.WriteLine("<VALIDXMLLANG3 xml:lang=\"a b-cd\" />"); tw.Write("</PLAY>"); tw.Flush(); FilePathUtil.addStream(strFileName, ms); } public static void CreateBigElementTestFile(string strFileName) { MemoryStream ms = new MemoryStream(); TextWriter tw = new StreamWriter(ms); string str = new String('Z', (1 << 20) - 1); tw.WriteLine("<Root>"); tw.Write("<"); tw.Write(str); tw.WriteLine("X />"); tw.Flush(); tw.Write("<"); tw.Write(str); tw.WriteLine("Y />"); tw.WriteLine("</Root>"); tw.Flush(); FilePathUtil.addStream(strFileName, ms); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Text; using System.Collections.Generic; using CodeUnderTest; namespace Tests { #region Tests [TestClass] public class RewrittenInheritanceTest : DisableAssertUI { [ClassCleanup] public static void ClassCleanup() { } [TestInitialize] public void TestInitialize() { } [TestCleanup] public void TestCleanup() { } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveOneLevelInheritanceInvariantTest() { new RewrittenInheritanceDerived().SetInheritedValueMustBeTrue(true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.InvariantException))] public void NegativeOneLevelInheritanceInvariantTest() { new RewrittenInheritanceDerived().SetInheritedValueMustBeTrue(false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveTwoLevelInheritanceInvariantTest() { new RewrittenInheritanceDerived().SetBaseValueMustBeTrue(true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.InvariantException))] public void NegativeTwoLevelInheritanceInvariantTest() { new RewrittenInheritanceDerived().SetBaseValueMustBeTrue(false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveBareInheritanceRequiresTest() { new RewrittenInheritanceDerived().BareRequires(true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PreconditionException))] public void NegativeBareInheritanceRequiresTest() { new RewrittenInheritanceDerived().BareRequires(false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveLegacyInheritanceRequiresTest() { new RewrittenInheritanceDerived().LegacyRequires(""); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(ArgumentNullException))] public void NegativeLegacyInheritanceRequiresTest() { new RewrittenInheritanceDerived().LegacyRequires(null); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveInheritanceRequiresWithExceptionTest() { new RewrittenInheritanceDerived().RequiresWithException(""); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(ArgumentNullException))] public void NegativeInheritanceRequiresWithExceptionTest() { new RewrittenInheritanceDerived().RequiresWithException(null); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveAdditiveInheritanceRequiresTest() { new RewrittenInheritanceDerived().AdditiveRequires(101); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PreconditionException))] public void NegativeAdditiveOneLevelInheritanceRequiresTest() { new RewrittenInheritanceDerived().AdditiveRequires(0); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PreconditionException))] public void NegativeAdditiveTwoLevelInheritanceRequiresTest() { new RewrittenInheritanceDerived().AdditiveRequires(0); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveSubtractiveInheritanceRequiresTest() { new RewrittenInheritanceDerived().SubtractiveRequires(101); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PreconditionException))] public void NegativeSubtractiveOneLevelInheritanceRequiresTest() { new RewrittenInheritanceDerived().SubtractiveRequires(0); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PreconditionException))] public void NegativeSubtractiveTwoLevelInheritanceRequiresTest() { new RewrittenInheritanceDerived().SubtractiveRequires(1); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveAdditiveInheritanceEnsuresTest() { new RewrittenInheritanceDerived().AdditiveEnsures(101); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeAdditiveOneLevelInheritanceEnsuresTest() { new RewrittenInheritanceDerived().AdditiveEnsures(1); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeAdditiveTwoLevelInheritanceEnsuresTest() { new RewrittenInheritanceDerived().AdditiveEnsures(0); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveSubtractiveInheritanceEnsuresTest() { new RewrittenInheritanceDerived().SubtractiveEnsures(101); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeSubtractiveOneLevelInheritanceEnsuresTest() { new RewrittenInheritanceDerived().SubtractiveEnsures(0); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeSubtractiveTwoLevelInheritanceEnsuresTest() { new RewrittenInheritanceDerived().SubtractiveEnsures(1); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveInheritedImplicitRequiresTest() { new RewrittenInheritanceDerived().InterfaceBaseRequires(true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveInheritedImplicitEnsuresTest() { new RewrittenInheritanceDerived().InterfaceBaseEnsures(true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PreconditionException))] public void NegativeInheritedImplicitRequiresTest() { new RewrittenInheritanceDerived().InterfaceBaseRequires(false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeInheritedImplicitEnsuresTest() { new RewrittenInheritanceDerived().InterfaceBaseEnsures(false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveImplicitlyOverriddenRequiresTest() { new RewrittenInheritanceDerived().ImplicitlyOverriddenInterfaceRequires(true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveImplicitlyOverriddenEnsuresTest() { new RewrittenInheritanceDerived().ImplicitlyOverriddenInterfaceEnsures(true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PreconditionException))] public void NegativeImplicitlyOverriddenRequiresTest() { new RewrittenInheritanceDerived().ImplicitlyOverriddenInterfaceRequires(false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeImplicitlyOverriddenEnsuresTest() { new RewrittenInheritanceDerived().ImplicitlyOverriddenInterfaceEnsures(false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveExplicitlyOverriddenRequiresTest() { new RewrittenInheritanceDerived().ExplicitlyOverriddenInterfaceRequires(true); new RewrittenInheritanceDerived().ExplicitlyOverriddenInterfaceRequires(false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveExplicitlyOverriddenEnsuresTest() { new RewrittenInheritanceDerived().ExplicitlyOverriddenInterfaceEnsures(true); new RewrittenInheritanceDerived().ExplicitlyOverriddenInterfaceEnsures(false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveMultiplyImplicitlyOverriddenRequiresTest() { new RewrittenInheritanceDerived().MultiplyImplicitlyOverriddenInterfaceRequires(true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveMultiplyImplicitlyOverriddenEnsuresTest() { new RewrittenInheritanceDerived().MultiplyImplicitlyOverriddenInterfaceEnsures(true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PreconditionException))] public void NegativeMultiplyImplicitlyOverriddenRequiresTest() { new RewrittenInheritanceDerived().MultiplyImplicitlyOverriddenInterfaceRequires(false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeMultiplyImplicitlyOverriddenEnsuresTest() { new RewrittenInheritanceDerived().MultiplyImplicitlyOverriddenInterfaceEnsures(false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveMultiplyExplicitlyOverriddenRequiresTest() { ((IRewrittenMultipleInheritanceInterface)new RewrittenInheritanceDerived()).MultiplyExplicitlyOverriddenInterfaceRequires(true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveMultiplyExplicitlyOverriddenEnsuresTest() { ((IRewrittenMultipleInheritanceInterface)new RewrittenInheritanceDerived()).MultiplyExplicitlyOverriddenInterfaceEnsures(true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PreconditionException))] public void NegativeMultiplyExplicitlyOverriddenRequiresTest() { ((IRewrittenMultipleInheritanceInterface)new RewrittenInheritanceDerived()).MultiplyExplicitlyOverriddenInterfaceRequires(false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeMultiplyExplicitlyOverriddenEnsuresTest() { ((IRewrittenMultipleInheritanceInterface)new RewrittenInheritanceDerived()).MultiplyExplicitlyOverriddenInterfaceEnsures(false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveMultiplyDifferentlyImplicitlyOverriddenRequiresTest() { new RewrittenInheritanceDerived().MultiplyDifferentlyOverriddenInterfaceRequires(true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveMultiplyDifferentlyExplicitlyOverriddenRequiresTest() { ((IRewrittenMultipleInheritanceInterface)new RewrittenInheritanceDerived()).MultiplyDifferentlyOverriddenInterfaceRequires(true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveMultiplyDifferentlyImplicitlyOverriddenEnsuresTest() { new RewrittenInheritanceDerived().MultiplyDifferentlyOverriddenInterfaceEnsures(true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveMultiplyDifferentlyExplicitlyOverriddenEnsuresTest() { ((IRewrittenMultipleInheritanceInterface)new RewrittenInheritanceDerived()).MultiplyDifferentlyOverriddenInterfaceEnsures(true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PreconditionException))] public void NegativeMultiplyDifferentlyImplicitlyOverriddenRequiresTest() { new RewrittenInheritanceDerived().MultiplyDifferentlyOverriddenInterfaceRequires(false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PreconditionException))] public void NegativeMultiplyDifferentlyExplicitlyOverriddenRequiresTest() { ((IRewrittenMultipleInheritanceInterface)new RewrittenInheritanceDerived()).MultiplyDifferentlyOverriddenInterfaceRequires(false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeMultiplyDifferentlyImplicitlyOverriddenEnsuresTest() { new RewrittenInheritanceDerived().MultiplyDifferentlyOverriddenInterfaceEnsures(false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeMultiplyDifferentlyExplicitlyOverriddenEnsuresTest() { ((IRewrittenMultipleInheritanceInterface)new RewrittenInheritanceDerived()).MultiplyDifferentlyOverriddenInterfaceEnsures(false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveImplicitRequiresTest() { new RewrittenInheritanceDerived().InterfaceRequiresMultipleOfTwo(2); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveImplicitEnsuresTest() { new RewrittenInheritanceDerived().InterfaceEnsuresMultipleOfTwo(2); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PreconditionException))] public void NegativeImplicitRequiresTest() { new RewrittenInheritanceDerived().InterfaceRequiresMultipleOfTwo(3); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeImplicitEnsuresTest() { new RewrittenInheritanceDerived().InterfaceEnsuresMultipleOfTwo(3); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveExplicitRequiresTest() { ((IRewrittenInheritanceInterfaceDerived2)new RewrittenInheritanceDerived()).InterfaceRequiresMultipleOfThree(3); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveExplicitEnsuresTest() { ((IRewrittenInheritanceInterfaceDerived2)new RewrittenInheritanceDerived()).InterfaceEnsuresMultipleOfThree(3); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PreconditionException))] public void NegativeExplicitRequiresTest() { ((IRewrittenInheritanceInterfaceDerived2)new RewrittenInheritanceDerived()).InterfaceRequiresMultipleOfThree(2); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeExplicitEnsuresTest() { ((IRewrittenInheritanceInterfaceDerived2)new RewrittenInheritanceDerived()).InterfaceEnsuresMultipleOfThree(2); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveNonExplicitRequiresTest() { new RewrittenInheritanceDerived().InterfaceRequiresMultipleOfThree(1); new RewrittenInheritanceDerived().InterfaceRequiresMultipleOfThree(2); new RewrittenInheritanceDerived().InterfaceRequiresMultipleOfThree(3); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveNonExplicitEnsuresTest() { new RewrittenInheritanceDerived().InterfaceEnsuresMultipleOfThree(1); new RewrittenInheritanceDerived().InterfaceEnsuresMultipleOfThree(2); new RewrittenInheritanceDerived().InterfaceEnsuresMultipleOfThree(3); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveDoubleRequiresTest() { new RewrittenInheritanceDerived().InterfaceRequires(6); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveDoubleEnsuresTest() { new RewrittenInheritanceDerived().InterfaceEnsures(6); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PreconditionException))] public void NegativeDoubleRequiresTest1() { new RewrittenInheritanceDerived().InterfaceRequires(1); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PreconditionException))] public void NegativeDoubleRequiresTest2() { new RewrittenInheritanceDerived().InterfaceRequires(2); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PreconditionException))] public void NegativeDoubleRequiresTest3() { new RewrittenInheritanceDerived().InterfaceRequires(3); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeDoubleEnsuresTest1() { new RewrittenInheritanceDerived().InterfaceEnsures(1); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeDoubleEnsuresTest2() { new RewrittenInheritanceDerived().InterfaceEnsures(2); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeDoubleEnsuresTest3() { new RewrittenInheritanceDerived().InterfaceEnsures(3); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveQuantifierTest1() { IQuantifierTest1 iq = new QuantifierTest1(); int[] A = new int[] { 3, 4, 5 }; iq.ModifyArray(A, 3, true); iq.CopyArray(A, true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeQuantifierTest1a() { IQuantifierTest1 iq = new QuantifierTest1(); int[] A = new int[] { 3, 4, 5 }; iq.ModifyArray(A, 3, false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeQuantifierTest1b() { IQuantifierTest1 iq = new QuantifierTest1(); int[] A = new int[] { 3, 4, 5 }; iq.CopyArray(A, false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveQuantifierTest2() { IQuantifierTest2 iq = new QuantifierTest2(); int[] A = new int[] { 3, 4, 5 }; iq.ModifyArray(A, 3, true); iq.CopyArray(A, true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeQuantifierTest2a() { IQuantifierTest2 iq = new QuantifierTest2(); int[] A = new int[] { 3, 4, 5 }; iq.ModifyArray(A, 3, false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeQuantifierTest2b() { IQuantifierTest2 iq = new QuantifierTest2(); int[] A = new int[] { 3, 4, 5 }; iq.CopyArray(A, false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveAbstractClass() { AbstractClassInterface a = new AbstractClassInterfaceImplementationSubType(); a.M(true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeAbstractClass() { AbstractClassInterface a = new AbstractClassInterfaceImplementationSubType(); a.M(false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveBaseClassWithMethodCallInContract() { DerivedClassForBaseClassWithMethodCallInContract o = new DerivedClassForBaseClassWithMethodCallInContract(); o.M(3); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PreconditionException))] public void NegativeBaseClassWithMethodCallInContract() { DerivedClassForBaseClassWithMethodCallInContract o = new DerivedClassForBaseClassWithMethodCallInContract(); o.M(0); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveInheritOld() { DerivedFromBaseClassWithOldAndResult o = new DerivedFromBaseClassWithOldAndResult(); int z = 3; o.InheritOld(ref z, true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeInheritOld() { DerivedFromBaseClassWithOldAndResult o = new DerivedFromBaseClassWithOldAndResult(); int z = 3; o.InheritOld(ref z, false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveInheritOldInQuantifier() { DerivedFromBaseClassWithOldAndResult o = new DerivedFromBaseClassWithOldAndResult(); int[] A = new int[] { 3, 4, 5 }; o.InheritOldInQuantifier(A, true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeInheritOldInQuantifier() { DerivedFromBaseClassWithOldAndResult o = new DerivedFromBaseClassWithOldAndResult(); int[] A = new int[] { 3, 4, 5 }; o.InheritOldInQuantifier(A, false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveInheritResultInContract() { DerivedFromBaseClassWithOldAndResult o = new DerivedFromBaseClassWithOldAndResult(); o.InheritResult(3, true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeInheritResultInContract() { DerivedFromBaseClassWithOldAndResult o = new DerivedFromBaseClassWithOldAndResult(); o.InheritResult(3, false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveInheritResultInQuantifier() { DerivedFromBaseClassWithOldAndResult o = new DerivedFromBaseClassWithOldAndResult(); int[] A = new int[] { 3, 4, 5 }; o.InheritResultInQuantifier(A, true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeInheritResultInQuantifier() { DerivedFromBaseClassWithOldAndResult o = new DerivedFromBaseClassWithOldAndResult(); int[] A = new int[] { 3, 4, 5 }; o.InheritResultInQuantifier(A, false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.InvariantException))] public void NegativeProperlyInstantiateInheritedInvariants() { NonGenericDerivedFromGenericWithInvariant ng = new NonGenericDerivedFromGenericWithInvariant(false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveProperlyInstantiateInheritedInvariants() { NonGenericDerivedFromGenericWithInvariant ng = new NonGenericDerivedFromGenericWithInvariant(true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveExplicitGenericInterfaceMethod() { IInterfaceWithGenericMethod i = new ExplicitGenericInterfaceMethodImplementation(0); foreach (var x in i.Bar<string>()) { } } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void NegativeExplicitGenericInterfaceMethod1() { try { IInterfaceWithGenericMethod i = new ExplicitGenericInterfaceMethodImplementation(1); foreach (var x in i.Bar<string>()) { } throw new Exception(); } catch (TestRewriterMethods.PostconditionException e) { Assert.AreEqual(": Contract.ForAll(Contract.Result<IEnumerable<T>>(), x => x != null)", e.Message); } } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void NegativeExplicitGenericInterfaceMethod2() { try { IInterfaceWithGenericMethod i = new ExplicitGenericInterfaceMethodImplementation(2); foreach (var x in i.Bar<string>()) { } throw new Exception(); } catch (TestRewriterMethods.PostconditionException e) { Assert.AreEqual(": Contract.Result<IEnumerable<T>>() != null", e.Message); } } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveImplicitGenericInterfaceMethod() { var i = new ImplicitGenericInterfaceMethodImplementation(0); foreach (var x in i.Bar<string>()) { } } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void NegativeImplicitGenericInterfaceMethod1() { try { var i = new ImplicitGenericInterfaceMethodImplementation(1); foreach (var x in i.Bar<string>()) { } throw new Exception(); } catch (TestRewriterMethods.PostconditionException e) { Assert.AreEqual(": Contract.ForAll(Contract.Result<IEnumerable<T>>(), x => x != null)", e.Message); } } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void NegativeImplicitGenericInterfaceMethod2() { try { var i = new ImplicitGenericInterfaceMethodImplementation(2); foreach (var x in i.Bar<string>()) { } throw new Exception(); } catch (TestRewriterMethods.PostconditionException e) { Assert.AreEqual(": Contract.Result<IEnumerable<T>>() != null", e.Message); } } #region Interface with method call in contract [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveIFaceWithMethodCalInContract() { IFaceWithMethodCallInContract o = new ImplForIFaceWithMethodCallInContract(); o.M(1); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PreconditionException))] public void NegativeIFaceWithMethodCalInContract1() { IFaceWithMethodCallInContract o = new ImplForIFaceWithMethodCallInContract(); o.M(3); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeIFaceWithMethodCalInContract2() { IFaceWithMethodCallInContract o = new ImplForIFaceWithMethodCallInContract(); o.M(5); } #endregion Interface with method call in contract #region ContractClass for abstract methods [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveAbstractMethodWithContract() { AbstractClass a = new ImplForAbstractMethod(); a.ReturnFirst(new int[] { 3, 4, 5 }, true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveAbstractMethodWithContract2() { AbstractClass a = new ImplForAbstractMethod(); a.Increment(3, true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PreconditionException))] public void NegativeAbstractMethodWithContract1() { AbstractClass a = new ImplForAbstractMethod(); a.ReturnFirst(null, true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PreconditionException))] public void NegativeAbstractMethodWithContract2() { AbstractClass a = new ImplForAbstractMethod(); a.ReturnFirst(new int[] { }, true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeAbstractMethodWithContract3() { AbstractClass a = new ImplForAbstractMethod(); a.ReturnFirst(new int[] { 3, 4, 5 }, false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PreconditionException))] public void NegativeAbstractMethodWithContract4() { AbstractClass a = new ImplForAbstractMethod(); a.Increment(-3, true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeAbstractMethodWithContract5() { AbstractClass a = new ImplForAbstractMethod(); a.Increment(3, false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveGenericAbstractClassWithContract() { GenericAbstractClass<string, string> a = new ImplForGenericAbstractClass(); a.ReturnFirst(new[] { "a", "B", "c" }, "B", true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveGenericAbstractClassWithContract2() { GenericAbstractClass<string, string> a = new ImplForGenericAbstractClass(); var result = a.Collection(2, 3); Assert.AreEqual(2, result.Length); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveGenericAbstractClassWithContract3() { GenericAbstractClass<string, string> a = new ImplForGenericAbstractClass(); var result = a.FirstNonNullMatch(new[] { null, null, "a", "b" }); Assert.AreEqual("a", result); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveGenericAbstractClassWithContract5() { GenericAbstractClass<string, string> a = new ImplForGenericAbstractClass(); var result = a.GenericMethod<float>(new[] { null, null, "a", "b" }); Assert.AreEqual(0, result.Length); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveGenericAbstractClassWithContract6() { GenericAbstractClass<string, string> a = new ImplForGenericAbstractClass(); var result = a.GenericMethod<string>(new[] { "a", "b" }); Assert.AreEqual(2, result.Length); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveGenericAbstractClassWithContract7() { GenericAbstractClass<string, string> a = new ImplForGenericAbstractClass(); var result = a.GenericMethod<object>(new[] { "a", "b" }); Assert.AreEqual(2, result.Length); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PreconditionException))] public void NegativeGenericAbstractClassWithContract1() { GenericAbstractClass<string, string> a = new ImplForGenericAbstractClass(); a.ReturnFirst(null, null, true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PreconditionException))] public void NegativeGenericAbstractClassWithContract2() { GenericAbstractClass<string, string> a = new ImplForGenericAbstractClass(); a.ReturnFirst(new string[] { }, null, true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeGenericAbstractClassWithContract3() { GenericAbstractClass<string, string> a = new ImplForGenericAbstractClass(); a.ReturnFirst(new[] { "3", "4", "5" }, "", false); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeGenericAbstractClassWithContract4() { GenericAbstractClass<string, string> a = new ImplForGenericAbstractClass(); a.Collection(5, 5); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeGenericAbstractClassWithContract5() { GenericAbstractClass<string, string> a = new ImplForGenericAbstractClass(); a.FirstNonNullMatch(new string[] { null, null, null }); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PreconditionException))] public void NegativeGenericAbstractClassWithContract6() { GenericAbstractClass<string, string> a = new ImplForGenericAbstractClass(); var result = a.GenericMethod<string>(null); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PostconditionException))] public void NegativeGenericAbstractClassWithContract7() { GenericAbstractClass<string, string> a = new ImplForGenericAbstractClass(); var result = a.GenericMethod<int>(new string[0]); } #endregion ContractClass for abstract methods #region Stelem specialization [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveStelemSpecialization1() { var st = new DerivedOfClosureWithStelem<string>(); st.M(new string[] { "a", "b", "c" }, 1); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void NegativeStelemSpecialization1() { var st = new DerivedOfClosureWithStelem<string>(); try { st.M(new string[] { "a", "b", "c" }, 2); throw new Exception(); } catch (TestRewriterMethods.PreconditionException e) { Assert.AreEqual(e.Message, ": i + 1 < ts.Length"); } } #endregion } #endregion [TestClass] public class PublicProperty : DisableAssertUI { #region Test Management [ClassCleanup] public static void ClassCleanup() { } [TestInitialize] public void TestInitialize() { } [TestCleanup] public void TestCleanup() { } #endregion Test Management #region Tests [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositivePublicProperty() { D d = new D(); d.foo(-3); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] [ExpectedException(typeof(TestRewriterMethods.PreconditionException))] public void NegativePublicProperty() { D d = new D(); d.foo(3); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositivePublicPropertyUsingVirtualProperty() { SubtypeOfUsingVirtualProperty d = new SubtypeOfUsingVirtualProperty(); // This will fail if the inherited precondition is checked by calling //get_P with a non-virtual call. d.foo(3); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveTestProperRetargettingOfImplicitInterfaceMethod() { var o = new Strilanc.C(true); o.S(); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void NegativeTestProperRetargettingOfImplicitInterfaceMethod() { var o = new Strilanc.C(false); try { o.S(); throw new Exception(); } catch (TestRewriterMethods.PreconditionException p) { Assert.AreEqual("this.P", p.Condition); } } #endregion Tests } [TestClass] public class ThomasPani : DisableAssertUI { [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void PositiveInheritedInv() { var u = new CodeUnderTest.ThomasPani.U(); u.SetToValidValue(true); } [TestMethod, TestCategory("Runtime"), TestCategory("V4.0"), TestCategory("CoreTest"), TestCategory("Short")] public void NegativeInheritedInv() { var u = new CodeUnderTest.ThomasPani.U(); try { u.SetToValidValue(false); throw new Exception(); } catch (TestRewriterMethods.InvariantException e) { Assert.AreEqual("i > 0", e.Condition); } } } }
// 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.Reflection.Metadata; using System.Reflection.PortableExecutable; namespace System.Diagnostics { public sealed partial class FileVersionInfo { private static readonly char[] s_versionSeparators = new char[] { '.' }; private FileVersionInfo(string fileName) { _fileName = fileName; // For managed assemblies, read the file version information from the assembly's metadata. // This isn't quite what's done on Windows, which uses the Win32 GetFileVersionInfo to read // the Win32 resource information from the file, and the managed compiler uses these attributes // to fill in that resource information when compiling the assembly. It's possible // that after compilation, someone could have modified the resource information such that it // no longer matches what was or wasn't in the assembly. But that's a rare enough case // that this should match for all intents and purposes. If this ever becomes a problem, // we can implement a full-fledged Win32 resource parser; that would also enable support // for native Win32 PE files on Unix, but that should also be an extremely rare case. if (!TryLoadManagedAssemblyMetadata()) { // We could try to parse Executable and Linkable Format (ELF) files, but at present // for executables they don't store version information, which is typically just // available in the filename itself. For now, we won't do anything special, but // we can add more cases here as we find need and opportunity. } } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- /// <summary>Attempt to load our fields from the metadata of the file, if it's a managed assembly.</summary> /// <returns>true if the file is a managed assembly; otherwise, false.</returns> private bool TryLoadManagedAssemblyMetadata() { // First make sure it's a file we can actually read from. Only regular files are relevant, // and attempting to open and read from a file such as a named pipe file could cause us to // hang (waiting for someone else to open and write to the file). Interop.Sys.FileStatus fileStatus; if (Interop.Sys.Stat(_fileName, out fileStatus) != 0 || (fileStatus.Mode & Interop.Sys.FileTypes.S_IFMT) != Interop.Sys.FileTypes.S_IFREG) { throw new FileNotFoundException(SR.Format(SR.IO_FileNotFound_FileName, _fileName), _fileName); } try { // Try to load the file using the managed metadata reader using (FileStream assemblyStream = new FileStream(_fileName, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 0x1000, useAsync: false)) using (PEReader peReader = new PEReader(assemblyStream)) { if (peReader.HasMetadata) { MetadataReader metadataReader = peReader.GetMetadataReader(); if (metadataReader.IsAssembly) { LoadManagedAssemblyMetadata(metadataReader); return true; } } } } catch (BadImageFormatException) { } return false; } /// <summary>Load our fields from the metadata of the file as represented by the provided metadata reader.</summary> /// <param name="metadataReader">The metadata reader for the CLI file this represents.</param> private void LoadManagedAssemblyMetadata(MetadataReader metadataReader) { AssemblyDefinition assemblyDefinition = metadataReader.GetAssemblyDefinition(); // Set the internal and original names based on the file name. _internalName = _originalFilename = Path.GetFileName(_fileName); // Set the product version based on the assembly's version (this may be overwritten // later in the method). Version productVersion = assemblyDefinition.Version; _productVersion = productVersion.ToString(); _productMajor = productVersion.Major; _productMinor = productVersion.Minor; _productBuild = productVersion.Build != -1 ? productVersion.Build : 0; _productPrivate = productVersion.Revision != -1 ? productVersion.Revision : 0; // "Language Neutral" is used on Win32 for unknown language identifiers. _language = "Language Neutral"; // Set other fields to default values in case they're not overwritten by attributes _companyName = string.Empty; _comments = string.Empty; _fileDescription = " "; // this is what the managed compiler outputs when value isn't set _fileVersion = string.Empty; _legalCopyright = " "; // this is what the managed compiler outputs when value isn't set _legalTrademarks = string.Empty; _productName = string.Empty; _privateBuild = string.Empty; _specialBuild = string.Empty; // Be explicit about initialization to suppress warning about fields not being set _isDebug = false; _isPatched = false; _isPreRelease = false; _isPrivateBuild = false; _isSpecialBuild = false; bool sawAssemblyInformationalVersionAttribute = false; // Everything else is parsed from assembly attributes MetadataStringComparer comparer = metadataReader.StringComparer; foreach (CustomAttributeHandle attrHandle in assemblyDefinition.GetCustomAttributes()) { CustomAttribute attr = metadataReader.GetCustomAttribute(attrHandle); StringHandle typeNamespaceHandle = default(StringHandle), typeNameHandle = default(StringHandle); if (TryGetAttributeName(metadataReader, attr, out typeNamespaceHandle, out typeNameHandle) && comparer.Equals(typeNamespaceHandle, "System.Reflection")) { if (comparer.Equals(typeNameHandle, "AssemblyCompanyAttribute")) { GetStringAttributeArgumentValue(metadataReader, attr, ref _companyName); } else if (comparer.Equals(typeNameHandle, "AssemblyCopyrightAttribute")) { GetStringAttributeArgumentValue(metadataReader, attr, ref _legalCopyright); } else if (comparer.Equals(typeNameHandle, "AssemblyDescriptionAttribute")) { GetStringAttributeArgumentValue(metadataReader, attr, ref _comments); } else if (comparer.Equals(typeNameHandle, "AssemblyFileVersionAttribute")) { GetStringAttributeArgumentValue(metadataReader, attr, ref _fileVersion); ParseVersion(_fileVersion, out _fileMajor, out _fileMinor, out _fileBuild, out _filePrivate); } else if (comparer.Equals(typeNameHandle, "AssemblyInformationalVersionAttribute")) { GetStringAttributeArgumentValue(metadataReader, attr, ref _productVersion); ParseVersion(_productVersion, out _productMajor, out _productMinor, out _productBuild, out _productPrivate); sawAssemblyInformationalVersionAttribute = true; } else if (comparer.Equals(typeNameHandle, "AssemblyProductAttribute")) { GetStringAttributeArgumentValue(metadataReader, attr, ref _productName); } else if (comparer.Equals(typeNameHandle, "AssemblyTrademarkAttribute")) { GetStringAttributeArgumentValue(metadataReader, attr, ref _legalTrademarks); } else if (comparer.Equals(typeNameHandle, "AssemblyTitleAttribute")) { GetStringAttributeArgumentValue(metadataReader, attr, ref _fileDescription); } } } // When the managed compiler sees an [AssemblyVersion(...)] attribute, it uses that to set // both the assembly version and the product version in the Win32 resources. If it doesn't // see an [AssemblyVersion(...)], then it sets the assembly version to 0.0.0.0, however it // sets the product version in the Win32 resources to whatever was defined in the // [AssemblyFileVersionAttribute(...)] if there was one (unless there is an AssemblyInformationalVersionAttribute, // in which case it always uses that for the product version). Without parsing the Win32 resources, // we can't differentiate these two cases, so given the rarity of explicitly setting an // assembly's version number to 0.0.0.0, we assume that if it is 0.0.0.0 then the attribute // wasn't specified and we use the file version. if (!sawAssemblyInformationalVersionAttribute && _productVersion == "0.0.0.0") { _productVersion = _fileVersion; _productMajor = _fileMajor; _productMinor = _fileMinor; _productBuild = _fileBuild; _productPrivate = _filePrivate; } } /// <summary>Parses the version into its constituent parts.</summary> private static void ParseVersion(string versionString, out int major, out int minor, out int build, out int priv) { // Relatively-forgiving parsing of a version: // - If there are more than four parts (separated by periods), all results are deemed 0 // - If any part fails to parse completely as an integer, no further parts are parsed and are left as 0. // - If any part partially parses as an integer, that value is used for that part. // - Whitespace is treated like any other non-digit character and thus isn't ignored. // - Each component is parsed as a ushort, allowing for overflow. string[] parts = versionString.Split(s_versionSeparators); major = minor = build = priv = 0; if (parts.Length <= 4) { bool endedEarly; if (parts.Length > 0) { major = ParseUInt16UntilNonDigit(parts[0], out endedEarly); if (!endedEarly && parts.Length > 1) { minor = ParseUInt16UntilNonDigit(parts[1], out endedEarly); if (!endedEarly && parts.Length > 2) { build = ParseUInt16UntilNonDigit(parts[2], out endedEarly); if (!endedEarly && parts.Length > 3) { priv = ParseUInt16UntilNonDigit(parts[3], out endedEarly); } } } } } } /// <summary>Parses a string as a UInt16 until it hits a non-digit.</summary> /// <param name="s">The string to parse.</param> /// <returns>The parsed value.</returns> private static ushort ParseUInt16UntilNonDigit(string s, out bool endedEarly) { endedEarly = false; ushort result = 0; for (int index = 0; index < s.Length; index++) { char c = s[index]; if (c < '0' || c > '9') { endedEarly = true; break; } result = (ushort)((result * 10) + (c - '0')); // explicitly allow for overflow, as this is the behavior employed on Windows } return result; } /// <summary>Gets the name of an attribute.</summary> /// <param name="reader">The metadata reader.</param> /// <param name="attr">The attribute.</param> /// <param name="typeNamespaceHandle">The namespace of the attribute.</param> /// <param name="typeNameHandle">The name of the attribute.</param> /// <returns>true if the name could be retrieved; otherwise, false.</returns> private static bool TryGetAttributeName(MetadataReader reader, CustomAttribute attr, out StringHandle typeNamespaceHandle, out StringHandle typeNameHandle) { EntityHandle ctorHandle = attr.Constructor; switch (ctorHandle.Kind) { case HandleKind.MemberReference: EntityHandle container = reader.GetMemberReference((MemberReferenceHandle)ctorHandle).Parent; if (container.Kind == HandleKind.TypeReference) { TypeReference tr = reader.GetTypeReference((TypeReferenceHandle)container); typeNamespaceHandle = tr.Namespace; typeNameHandle = tr.Name; return true; } break; case HandleKind.MethodDefinition: MethodDefinition md = reader.GetMethodDefinition((MethodDefinitionHandle)ctorHandle); TypeDefinition td = reader.GetTypeDefinition(md.GetDeclaringType()); typeNamespaceHandle = td.Namespace; typeNameHandle = td.Name; return true; } // Unusual case, potentially invalid IL typeNamespaceHandle = default(StringHandle); typeNameHandle = default(StringHandle); return false; } /// <summary>Gets the string argument value of an attribute with a single fixed string argument.</summary> /// <param name="reader">The metadata reader.</param> /// <param name="attr">The attribute.</param> /// <param name="value">The value parsed from the attribute, if it could be retrieved; otherwise, the value is left unmodified.</param> private static void GetStringAttributeArgumentValue(MetadataReader reader, CustomAttribute attr, ref string value) { EntityHandle ctorHandle = attr.Constructor; BlobHandle signature; switch (ctorHandle.Kind) { case HandleKind.MemberReference: signature = reader.GetMemberReference((MemberReferenceHandle)ctorHandle).Signature; break; case HandleKind.MethodDefinition: signature = reader.GetMethodDefinition((MethodDefinitionHandle)ctorHandle).Signature; break; default: // Unusual case, potentially invalid IL return; } BlobReader signatureReader = reader.GetBlobReader(signature); BlobReader valueReader = reader.GetBlobReader(attr.Value); const ushort Prolog = 1; // two-byte "prolog" defined by ECMA-335 (II.23.3) to be at the beginning of attribute value blobs if (valueReader.ReadUInt16() == Prolog) { SignatureHeader header = signatureReader.ReadSignatureHeader(); int parameterCount; if (header.Kind == SignatureKind.Method && // attr ctor must be a method !header.IsGeneric && // attr ctor must be non-generic signatureReader.TryReadCompressedInteger(out parameterCount) && // read parameter count parameterCount == 1 && // attr ctor must have 1 parameter signatureReader.ReadSignatureTypeCode() == SignatureTypeCode.Void && // attr ctor return type must be void signatureReader.ReadSignatureTypeCode() == SignatureTypeCode.String) // attr ctor first parameter must be string { value = valueReader.ReadSerializedString(); } } } } }
using BeardBrosTrivia.Models; namespace BeardBrosTrivia { public static class Constants { public static string[] AlexFancyNames = { "Alex \"Cool Man\" Faciane", "The Cool Man", "Professor Kleen", "Miyamoto", "The creator of Mario" }; public static string[] JirardFancyNames = { "Jirard \"Dragonrider\" Khalil", "The Dragonrider", "The Completionist", "Beardman" }; public static string[] QuoteIntroSuffixes = { "once said", "can be heard saying", "told us", "tells us" }; public static string[] QuoteIntroPrefixes = { "Here are some words of wisdom from", "Here's something inspiring from", "Words of wisdom by", "By", "From", " " }; public static Quote[] Quotes = { new Quote ( "Do you have any more Whale trivia for us Alex?", "Jirard" ), new Quote ( "You know what they say; You can never save enough", "Jirard" ), new Quote ( "Later man.", "Jirard" ), new Quote ( "I beat it.", "Jirard" ), new Quote ( "That ain't me, man!", "Jirard" ), new Quote ( "Dummy Jirard, always making dumb scrub moves.", "Jirard" ), new Quote ( "With that in mind guys, this game gets our completionist rating of... Complete it!", "Jirard" ), new Quote ( "NINTENDUR!", "Jirard" ), new Quote ( "Oh Mark Carr", "Jirard" ), new Quote ( "The Gooch is right there", "Jirard" ), new Quote ( "Got got by art", "Jirard" ), new Quote ( "Watch Lie to Me.", "Jirard" ), new Quote ( "I just pressed A.", "Jirard" ), new Quote ( "I AM the nail.", "Jirard" ), new Quote ( "Ladies and gentlemen... the bullet", "Jirard" ), new Quote ( "I SAVE-STATED", "Jirard" ), new Quote ( "The double jump", "Jirard" ), new Quote ( "Don't", "Jirard" ), new Quote ( "Boba drink!", "Jirard" ), new Quote ( "Boba Fett, Boba Fett, Boba DRINK", "Jirard" ), new Quote ( "That's Jirard Syndrome", "Jirard" ), new Quote ( "I'm so damn big!", "Jirard" ), new Quote ( "Tight boys take their time.", "Jirard" ), new Quote ( "Welcome back to Bryan's Wrap Shack! Today's special is the Pork You Later.", "Jirard" ), new Quote ( "Speed, Demon!", "Alex" ), new Quote ( "Headin' for the border!", "Alex" ), new Quote ( "I gotta drop a dook!", "Alex" ), new Quote ( "The Female Whale, the Fe-Whale, if you will... She rolls around, like, trying her best not to have sex with the dude.", "Alex" ), new Quote ( "The ween is like... is like prehensile, and it like moves around like a snake or a tentacle, and it tries it's best to get in.", "Alex" ), new Quote ( "Then it finally happens, and no ones happy the whole time. Then they leave and everybody's sad about it.", "Alex" ), new Quote ( "Honestly if you had a chance to look at it... It's mesmerizing... because of how much NOT like human sex it is.", "Alex" ), new Quote ( "It's part of being a raconteur.", "Alex" ), new Quote ( "It's all about the big biscuit risk.", "Alex" ), new Quote ( "Ladies and Gentlemen... the bullet.", "Alex" ), new Quote ( "Later man.", "Alex" ), new Quote ( "Yeah, kinda like, bop him and land right in that little Goochy.", "Alex" ), new Quote ( "The space between two munchers. The Goochy.", "Alex" ), new Quote ( "Tight boy.", "Alex" ), new Quote ( "Clean boy.", "Alex" ), new Quote ( "We're still cops.", "Alex" ), new Quote ( "#PerfectDicks", "Alex" ), new Quote ( "You can do it, You just got to jump over the Triceratops", "Alex" ), new Quote ( "My sacrifice.", "Alex" ), new Quote ( "Don't count your laters before they're men.", "Alex" ), new Quote ( "He's not gonna be in Rush Hour 3.", "Alex" ), new Quote ( "People will watch you to get entertained, because they like the stuff that you do, not because they like that you obey them", "Alex" ), new Quote ( "You don't wanna skateboard with a chili dog.", "Alex" ), new Quote ( "I like to get drunk and play Jenga.", "Alex" ), new Quote ( "Tight", "Alex" ), new Quote ( "That's tight", "Alex" ), new Quote ( "Boba Drink", "Alex" ), new Quote ( "Boba Fett, Boba Fett, Boba Drink", "Alex" ), new Quote ( "When you're right, you're right.", "Alex" ), new Quote ( "You won't believe your eyes, so pleasantly surprised, when you realize you are in a book", "Alex" ), new Quote ( "This game is like Dark Souls", "Alex" ), new Quote ( "I think we finally have to do the Dirty Business, Alex.", "Jirard" ), new Quote ( "I sit with you and play all these hard games, and all I do is encourage you the whole time for hours and hours and hours and hours! And I'm sitting here playing one hard game, and all that happens is 'oh, this dude sucks at this game! oh he sucks, I've been trying not to yell at him about how much he sucks! Thank God somebody finally told him he sucks!'... I wanna be the guy Jirard!", "Alex" ) }; } }
using System; using Orleans; using Orleans.Runtime; using Orleans.Serialization; using Orleans.Utilities; using TestExtensions; using Xunit; namespace UnitTests.Serialization { [TestCategory("BVT"), TestCategory("Serialization")] public class ILBasedExceptionSerializerTests { private readonly ILSerializerGenerator serializerGenerator = new ILSerializerGenerator(); private readonly SerializationTestEnvironment environment; public ILBasedExceptionSerializerTests() { #pragma warning disable CS0618 // Type or member is obsolete this.environment = SerializationTestEnvironment.Initialize(null, typeof(ILBasedSerializer)); #pragma warning restore CS0618 // Type or member is obsolete } /// <summary> /// Tests that <see cref="ILBasedExceptionSerializer"/> supports distinct field selection for serialization /// versus copy operations. /// </summary> [Fact] public void ExceptionSerializer_SimpleException() { // Throw an exception so that is has a stack trace. var expected = GetNewException(); this.TestExceptionSerialization(expected); } private ILExceptionSerializerTestException TestExceptionSerialization(ILExceptionSerializerTestException expected) { var writer = new BinaryTokenStreamWriter(); // Deep copies should be reference-equal. Assert.Equal( expected, SerializationManager.DeepCopyInner(expected, new SerializationContext(this.environment.SerializationManager)), ReferenceEqualsComparer.Instance); this.environment.SerializationManager.Serialize(expected, writer); var reader = new DeserializationContext(this.environment.SerializationManager) { StreamReader = new BinaryTokenStreamReader(writer.ToByteArray()) }; var actual = (ILExceptionSerializerTestException) this.environment.SerializationManager.Deserialize(null, reader.StreamReader); Assert.Equal(expected.BaseField.Value, actual.BaseField.Value, StringComparer.Ordinal); Assert.Equal(expected.SubClassField, actual.SubClassField, StringComparer.Ordinal); Assert.Equal(expected.OtherField.Value, actual.OtherField.Value, StringComparer.Ordinal); // Check for referential equality in the two fields which happened to be reference-equals. Assert.Equal(actual.BaseField, actual.OtherField, ReferenceEqualsComparer.Instance); return actual; } /// <summary> /// Tests that <see cref="ILBasedExceptionSerializer"/> supports reference cycles. /// </summary> [Fact] public void ExceptionSerializer_ReferenceCycle() { // Throw an exception so that is has a stack trace. var expected = GetNewException(); // Create a reference cycle at the top level. expected.SomeObject = expected; var actual = this.TestExceptionSerialization(expected); Assert.Equal(actual, actual.SomeObject); } /// <summary> /// Tests that <see cref="ILBasedExceptionSerializer"/> supports reference cycles. /// </summary> [Fact] public void ExceptionSerializer_NestedReferenceCycle() { // Throw an exception so that is has a stack trace. var exception = GetNewException(); var expected = new Outer { SomeFunObject = exception.OtherField, Object = exception, }; // Create a reference cycle. exception.SomeObject = expected; var writer = new BinaryTokenStreamWriter(); this.environment.SerializationManager.Serialize(expected, writer); var reader = new DeserializationContext(this.environment.SerializationManager) { StreamReader = new BinaryTokenStreamReader(writer.ToByteArray()) }; var actual = (Outer)this.environment.SerializationManager.Deserialize(null, reader.StreamReader); Assert.Equal(expected.Object.BaseField.Value, actual.Object.BaseField.Value, StringComparer.Ordinal); Assert.Equal(expected.Object.SubClassField, actual.Object.SubClassField, StringComparer.Ordinal); Assert.Equal(expected.Object.OtherField.Value, actual.Object.OtherField.Value, StringComparer.Ordinal); // Check for referential equality in the fields which happened to be reference-equals. Assert.Equal(actual.Object.BaseField, actual.Object.OtherField, ReferenceEqualsComparer.Instance); Assert.Equal(actual, actual.Object.SomeObject, ReferenceEqualsComparer.Instance); Assert.Equal(actual.SomeFunObject, actual.Object.OtherField, ReferenceEqualsComparer.Instance); } private static ILExceptionSerializerTestException GetNewException() { ILExceptionSerializerTestException expected; try { var baseField = new SomeFunObject { Value = Guid.NewGuid().ToString() }; var res = new ILExceptionSerializerTestException { BaseField = baseField, SubClassField = Guid.NewGuid().ToString(), OtherField = baseField, }; throw res; } catch (ILExceptionSerializerTestException exception) { expected = exception; } return expected; } /// <summary> /// Tests that <see cref="ILBasedExceptionSerializer"/> supports distinct field selection for serialization /// versus copy operations. /// </summary> [Fact] public void ExceptionSerializer_UnknownException() { var expected = GetNewException(); var knowsException = new ILBasedExceptionSerializer(this.serializerGenerator, new TypeSerializer(new CachedTypeResolver())); var writer = new BinaryTokenStreamWriter(); var context = new SerializationContext(this.environment.SerializationManager) { StreamWriter = writer }; knowsException.Serialize(expected, context, null); // Deep copies should be reference-equal. var copyContext = new SerializationContext(this.environment.SerializationManager); Assert.Equal(expected, knowsException.DeepCopy(expected, copyContext), ReferenceEqualsComparer.Instance); // Create a deserializer which doesn't know about the expected exception type. var reader = new DeserializationContext(this.environment.SerializationManager) { StreamReader = new BinaryTokenStreamReader(writer.ToByteArray()) }; // Ensure that the deserialized object has the fallback type. var doesNotKnowException = new ILBasedExceptionSerializer(this.serializerGenerator, new TestTypeSerializer(new CachedTypeResolver())); var untypedActual = doesNotKnowException.Deserialize(null, reader); Assert.IsType<RemoteNonDeserializableException>(untypedActual); // Ensure that the original type name is preserved correctly. var actualDeserialized = (RemoteNonDeserializableException) untypedActual; Assert.Equal(RuntimeTypeNameFormatter.Format(typeof(ILExceptionSerializerTestException)), actualDeserialized.OriginalTypeName); // Re-serialize the deserialized object using the serializer which does not have access to the original type. writer = new BinaryTokenStreamWriter(); context = new SerializationContext(this.environment.SerializationManager) { StreamWriter = writer }; doesNotKnowException.Serialize(untypedActual, context, null); reader = new DeserializationContext(this.environment.SerializationManager) { StreamReader = new BinaryTokenStreamReader(writer.ToByteArray()) }; // Deserialize the round-tripped object and verify that it has the original type and all properties are // correctly. untypedActual = knowsException.Deserialize(null, reader); Assert.IsType<ILExceptionSerializerTestException>(untypedActual); var actual = (ILExceptionSerializerTestException) untypedActual; Assert.Equal(expected.BaseField.Value, actual.BaseField.Value, StringComparer.Ordinal); Assert.Equal(expected.SubClassField, actual.SubClassField, StringComparer.Ordinal); Assert.Equal(expected.OtherField.Value, actual.OtherField.Value, StringComparer.Ordinal); // Check for referential equality in the two fields which happened to be reference-equals. Assert.Equal(actual.BaseField, actual.OtherField, ReferenceEqualsComparer.Instance); } private class Outer { public SomeFunObject SomeFunObject { get; set; } public ILExceptionSerializerTestException Object { get; set; } } private class SomeFunObject { public string Value { get; set; } } private class BaseException : Exception { public SomeFunObject BaseField { get; set; } } [Serializable] private class ILExceptionSerializerTestException : BaseException { public string SubClassField { get; set; } public SomeFunObject OtherField { get; set; } public object SomeObject { get; set; } } private class TestTypeSerializer : TypeSerializer { internal override Type GetTypeFromName(string assemblyQualifiedTypeName, bool throwOnError) { if (throwOnError) throw new TypeLoadException($"Type {assemblyQualifiedTypeName} could not be loaded"); return null; } public TestTypeSerializer(ITypeResolver typeResolver) : base(typeResolver) { } } } }
namespace asktomyself { partial class main { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(main)); this.contextMenuStripIcon = new System.Windows.Forms.ContextMenuStrip(this.components); this.addToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.categoriesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.stopAskToMyselfToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.invertToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.logOutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openWebAccountToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.buyMeABeerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.aboutAskToMyselfToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.buttonOK = new System.Windows.Forms.Button(); this.lblQuestion = new System.Windows.Forms.Label(); this.lblAnswer = new System.Windows.Forms.Label(); this.txtFrom = new System.Windows.Forms.TextBox(); this.txtTo = new System.Windows.Forms.TextBox(); this.contextMenuStripLogin = new System.Windows.Forms.ContextMenuStrip(this.components); this.signInToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripSeparator(); this.aboutAskToMyselfToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator(); this.exitToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.Thunbnail = new System.Windows.Forms.PictureBox(); this.labelCategory = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.btnSolution = new System.Windows.Forms.Button(); this.lblCountdown = new System.Windows.Forms.Label(); this.toolStripMenuItem5 = new System.Windows.Forms.ToolStripSeparator(); this.contextMenuStripIcon.SuspendLayout(); this.contextMenuStripLogin.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.Thunbnail)).BeginInit(); this.SuspendLayout(); // // contextMenuStripIcon // this.contextMenuStripIcon.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.addToolStripMenuItem, this.categoriesToolStripMenuItem, this.stopAskToMyselfToolStripMenuItem, this.invertToolStripMenuItem, this.logOutToolStripMenuItem, this.toolStripMenuItem5, this.openWebAccountToolStripMenuItem, this.buyMeABeerToolStripMenuItem, this.toolStripMenuItem1, this.aboutAskToMyselfToolStripMenuItem, this.toolStripMenuItem2, this.exitToolStripMenuItem}); this.contextMenuStripIcon.Name = "contextMenuStripIcon"; this.contextMenuStripIcon.Size = new System.Drawing.Size(185, 220); // // addToolStripMenuItem // this.addToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("addToolStripMenuItem.Image"))); this.addToolStripMenuItem.Name = "addToolStripMenuItem"; this.addToolStripMenuItem.Size = new System.Drawing.Size(184, 22); this.addToolStripMenuItem.Text = "Add"; this.addToolStripMenuItem.Click += new System.EventHandler(this.addToolStripMenuItem_Click); // // categoriesToolStripMenuItem // this.categoriesToolStripMenuItem.Image = global::asktomyself.Properties.Resources.category; this.categoriesToolStripMenuItem.Name = "categoriesToolStripMenuItem"; this.categoriesToolStripMenuItem.Size = new System.Drawing.Size(184, 22); this.categoriesToolStripMenuItem.Text = "Categories"; // // stopAskToMyselfToolStripMenuItem // this.stopAskToMyselfToolStripMenuItem.Name = "stopAskToMyselfToolStripMenuItem"; this.stopAskToMyselfToolStripMenuItem.Size = new System.Drawing.Size(184, 22); this.stopAskToMyselfToolStripMenuItem.Text = "Stop ask to myself"; this.stopAskToMyselfToolStripMenuItem.Click += new System.EventHandler(this.stopAskToMyselfToolStripMenuItem_Click); // // invertToolStripMenuItem // this.invertToolStripMenuItem.CheckOnClick = true; this.invertToolStripMenuItem.Image = global::asktomyself.Properties.Resources.invert; this.invertToolStripMenuItem.Name = "invertToolStripMenuItem"; this.invertToolStripMenuItem.Size = new System.Drawing.Size(184, 22); this.invertToolStripMenuItem.Text = "Invert"; this.invertToolStripMenuItem.Click += new System.EventHandler(this.invertToolStripMenuItem_Click); // // logOutToolStripMenuItem // this.logOutToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("logOutToolStripMenuItem.Image"))); this.logOutToolStripMenuItem.Name = "logOutToolStripMenuItem"; this.logOutToolStripMenuItem.Size = new System.Drawing.Size(184, 22); this.logOutToolStripMenuItem.Text = "Sign out"; this.logOutToolStripMenuItem.Click += new System.EventHandler(this.logOutToolStripMenuItem_Click); // // openWebAccountToolStripMenuItem // this.openWebAccountToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("openWebAccountToolStripMenuItem.Image"))); this.openWebAccountToolStripMenuItem.Name = "openWebAccountToolStripMenuItem"; this.openWebAccountToolStripMenuItem.Size = new System.Drawing.Size(184, 22); this.openWebAccountToolStripMenuItem.Text = "Open web account"; this.openWebAccountToolStripMenuItem.Click += new System.EventHandler(this.openWebAccountToolStripMenuItem_Click); // // buyMeABeerToolStripMenuItem // this.buyMeABeerToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("buyMeABeerToolStripMenuItem.Image"))); this.buyMeABeerToolStripMenuItem.Name = "buyMeABeerToolStripMenuItem"; this.buyMeABeerToolStripMenuItem.Size = new System.Drawing.Size(184, 22); this.buyMeABeerToolStripMenuItem.Text = "Buy me a beer"; this.buyMeABeerToolStripMenuItem.Click += new System.EventHandler(this.buyMeABeerToolStripMenuItem_Click); // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(181, 6); // // aboutAskToMyselfToolStripMenuItem // this.aboutAskToMyselfToolStripMenuItem.Image = global::asktomyself.Properties.Resources.messagebox_info; this.aboutAskToMyselfToolStripMenuItem.Name = "aboutAskToMyselfToolStripMenuItem"; this.aboutAskToMyselfToolStripMenuItem.Size = new System.Drawing.Size(184, 22); this.aboutAskToMyselfToolStripMenuItem.Text = "About Ask To Myself"; // // toolStripMenuItem2 // this.toolStripMenuItem2.Name = "toolStripMenuItem2"; this.toolStripMenuItem2.Size = new System.Drawing.Size(181, 6); // // exitToolStripMenuItem // this.exitToolStripMenuItem.Image = global::asktomyself.Properties.Resources.exit; this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; this.exitToolStripMenuItem.Size = new System.Drawing.Size(184, 22); this.exitToolStripMenuItem.Text = "Exit"; // // buttonOK // this.buttonOK.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.buttonOK.Location = new System.Drawing.Point(77, 164); this.buttonOK.Name = "buttonOK"; this.buttonOK.Size = new System.Drawing.Size(75, 23); this.buttonOK.TabIndex = 1; this.buttonOK.Text = "Ok"; this.buttonOK.UseVisualStyleBackColor = true; this.buttonOK.Click += new System.EventHandler(this.buttonOK_Click); // // lblQuestion // this.lblQuestion.AutoSize = true; this.lblQuestion.BackColor = System.Drawing.Color.Transparent; this.lblQuestion.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblQuestion.Location = new System.Drawing.Point(13, 51); this.lblQuestion.Name = "lblQuestion"; this.lblQuestion.Size = new System.Drawing.Size(64, 16); this.lblQuestion.TabIndex = 2; this.lblQuestion.Text = "Question:"; // // lblAnswer // this.lblAnswer.AutoSize = true; this.lblAnswer.BackColor = System.Drawing.Color.Transparent; this.lblAnswer.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblAnswer.Location = new System.Drawing.Point(13, 100); this.lblAnswer.Name = "lblAnswer"; this.lblAnswer.Size = new System.Drawing.Size(55, 16); this.lblAnswer.TabIndex = 3; this.lblAnswer.Text = "Answer:"; // // txtFrom // this.txtFrom.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtFrom.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtFrom.Location = new System.Drawing.Point(16, 70); this.txtFrom.Name = "txtFrom"; this.txtFrom.Size = new System.Drawing.Size(229, 22); this.txtFrom.TabIndex = 4; // // txtTo // this.txtTo.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtTo.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtTo.Location = new System.Drawing.Point(16, 119); this.txtTo.Name = "txtTo"; this.txtTo.Size = new System.Drawing.Size(229, 22); this.txtTo.TabIndex = 5; this.txtTo.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtTo_KeyDown); // // contextMenuStripLogin // this.contextMenuStripLogin.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.signInToolStripMenuItem, this.toolStripMenuItem4, this.aboutAskToMyselfToolStripMenuItem1, this.toolStripMenuItem3, this.exitToolStripMenuItem1}); this.contextMenuStripLogin.Name = "contextMenuStripLogin"; this.contextMenuStripLogin.Size = new System.Drawing.Size(185, 82); // // signInToolStripMenuItem // this.signInToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("signInToolStripMenuItem.Image"))); this.signInToolStripMenuItem.Name = "signInToolStripMenuItem"; this.signInToolStripMenuItem.Size = new System.Drawing.Size(184, 22); this.signInToolStripMenuItem.Text = "Sign In"; this.signInToolStripMenuItem.Click += new System.EventHandler(this.signInToolStripMenuItem_Click); // // toolStripMenuItem4 // this.toolStripMenuItem4.Name = "toolStripMenuItem4"; this.toolStripMenuItem4.Size = new System.Drawing.Size(181, 6); // // aboutAskToMyselfToolStripMenuItem1 // this.aboutAskToMyselfToolStripMenuItem1.Image = global::asktomyself.Properties.Resources.messagebox_info; this.aboutAskToMyselfToolStripMenuItem1.Name = "aboutAskToMyselfToolStripMenuItem1"; this.aboutAskToMyselfToolStripMenuItem1.Size = new System.Drawing.Size(184, 22); this.aboutAskToMyselfToolStripMenuItem1.Text = "About Ask To Myself"; // // toolStripMenuItem3 // this.toolStripMenuItem3.Name = "toolStripMenuItem3"; this.toolStripMenuItem3.Size = new System.Drawing.Size(181, 6); // // exitToolStripMenuItem1 // this.exitToolStripMenuItem1.Image = global::asktomyself.Properties.Resources.exit; this.exitToolStripMenuItem1.Name = "exitToolStripMenuItem1"; this.exitToolStripMenuItem1.Size = new System.Drawing.Size(184, 22); this.exitToolStripMenuItem1.Text = "Exit"; // // Thunbnail // this.Thunbnail.BackColor = System.Drawing.Color.Transparent; this.Thunbnail.Location = new System.Drawing.Point(269, 42); this.Thunbnail.Name = "Thunbnail"; this.Thunbnail.Size = new System.Drawing.Size(152, 145); this.Thunbnail.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.Thunbnail.TabIndex = 6; this.Thunbnail.TabStop = false; // // labelCategory // this.labelCategory.AutoSize = true; this.labelCategory.BackColor = System.Drawing.Color.Transparent; this.labelCategory.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelCategory.Location = new System.Drawing.Point(90, 11); this.labelCategory.Name = "labelCategory"; this.labelCategory.Size = new System.Drawing.Size(226, 20); this.labelCategory.TabIndex = 7; this.labelCategory.Text = "No category selected right now"; // // label3 // this.label3.AutoSize = true; this.label3.BackColor = System.Drawing.Color.Transparent; this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(12, 11); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(81, 18); this.label3.TabIndex = 8; this.label3.Text = "Category:"; // // btnSolution // this.btnSolution.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnSolution.Location = new System.Drawing.Point(170, 164); this.btnSolution.Name = "btnSolution"; this.btnSolution.Size = new System.Drawing.Size(75, 23); this.btnSolution.TabIndex = 9; this.btnSolution.Text = "Solution"; this.btnSolution.UseVisualStyleBackColor = true; this.btnSolution.Click += new System.EventHandler(this.btnSolution_Click); // // lblCountdown // this.lblCountdown.AutoSize = true; this.lblCountdown.BackColor = System.Drawing.Color.Transparent; this.lblCountdown.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblCountdown.Location = new System.Drawing.Point(12, 167); this.lblCountdown.Name = "lblCountdown"; this.lblCountdown.Size = new System.Drawing.Size(29, 20); this.lblCountdown.TabIndex = 10; this.lblCountdown.Text = "15"; // // toolStripMenuItem5 // this.toolStripMenuItem5.Name = "toolStripMenuItem5"; this.toolStripMenuItem5.Size = new System.Drawing.Size(181, 6); // // main // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage"))); this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.ClientSize = new System.Drawing.Size(436, 201); this.Controls.Add(this.lblCountdown); this.Controls.Add(this.btnSolution); this.Controls.Add(this.labelCategory); this.Controls.Add(this.buttonOK); this.Controls.Add(this.txtTo); this.Controls.Add(this.label3); this.Controls.Add(this.Thunbnail); this.Controls.Add(this.txtFrom); this.Controls.Add(this.lblAnswer); this.Controls.Add(this.lblQuestion); this.DoubleBuffered = true; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Location = new System.Drawing.Point(10, 10); this.MaximizeBox = false; this.Name = "main"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Ask To Myself"; this.Load += new System.EventHandler(this.main_Load); this.Shown += new System.EventHandler(this.main_Shown); this.contextMenuStripIcon.ResumeLayout(false); this.contextMenuStripLogin.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.Thunbnail)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ContextMenuStrip contextMenuStripIcon; private System.Windows.Forms.ToolStripMenuItem addToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; private System.Windows.Forms.Button buttonOK; private System.Windows.Forms.Label lblQuestion; private System.Windows.Forms.Label lblAnswer; private System.Windows.Forms.TextBox txtFrom; private System.Windows.Forms.TextBox txtTo; private System.Windows.Forms.ToolStripMenuItem categoriesToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem invertToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem stopAskToMyselfToolStripMenuItem; private System.Windows.Forms.PictureBox Thunbnail; private System.Windows.Forms.ToolStripMenuItem logOutToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem aboutAskToMyselfToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2; private System.Windows.Forms.ContextMenuStrip contextMenuStripLogin; private System.Windows.Forms.ToolStripMenuItem signInToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem4; private System.Windows.Forms.ToolStripMenuItem aboutAskToMyselfToolStripMenuItem1; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem3; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem1; private System.Windows.Forms.Label labelCategory; private System.Windows.Forms.Label label3; private System.Windows.Forms.ToolStripMenuItem openWebAccountToolStripMenuItem; private System.Windows.Forms.Button btnSolution; private System.Windows.Forms.Label lblCountdown; private System.Windows.Forms.ToolStripMenuItem buyMeABeerToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem5; } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using COM = System.Runtime.InteropServices.ComTypes; // Disable obsolete warnings about VarEnum and COM-marshaling APIs in CoreCLR #pragma warning disable 618 namespace System.Management.Automation { internal static class ComInvoker { // DISP HRESULTS - may be returned by IDispatch.Invoke private const int DISP_E_EXCEPTION = unchecked((int)0x80020009); // LCID for en-US culture private const int LCID_DEFAULT = 0x0409; // The dispatch identifier for a parameter that receives the value of an assignment in a PROPERTYPUT. // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms221242(v=vs.85).aspx for details. private const int DISPID_PROPERTYPUT = -3; // Alias of GUID_NULL. It's a GUID set to all zero private static readonly Guid s_IID_NULL = new Guid(); // Size of the Variant struct private static readonly int s_variantSize = ClrFacade.SizeOf<Variant>(); /// <summary> /// Make a by-Ref VARIANT value based on the passed-in VARIANT argument /// </summary> /// <param name="srcVariantPtr">The source Variant pointer</param> /// <param name="destVariantPtr">The destination Variant pointer</param> private static unsafe void MakeByRefVariant(IntPtr srcVariantPtr, IntPtr destVariantPtr) { var srcVariant = (Variant*)srcVariantPtr; var destVariant = (Variant*)destVariantPtr; switch ((VarEnum)srcVariant->_typeUnion._vt) { case VarEnum.VT_EMPTY: case VarEnum.VT_NULL: // These cannot combine with VT_BYREF. Should try passing as a variant reference // We follow the code in ComBinder to handle 'VT_EMPTY' and 'VT_NULL' destVariant->_typeUnion._unionTypes._byref = new IntPtr(srcVariant); destVariant->_typeUnion._vt = (ushort)VarEnum.VT_VARIANT | (ushort)VarEnum.VT_BYREF; return; case VarEnum.VT_RECORD: // Representation of record is the same with or without byref destVariant->_typeUnion._unionTypes._record._record = srcVariant->_typeUnion._unionTypes._record._record; destVariant->_typeUnion._unionTypes._record._recordInfo = srcVariant->_typeUnion._unionTypes._record._recordInfo; break; case VarEnum.VT_VARIANT: destVariant->_typeUnion._unionTypes._byref = new IntPtr(srcVariant); break; case VarEnum.VT_DECIMAL: destVariant->_typeUnion._unionTypes._byref = new IntPtr(&(srcVariant->_decimal)); break; default: // All the other cases start at the same offset (it's a Union) so using &_i4 should work. // This is the same code as in CLR implementation. It could be &_i1, &_i2 and etc. CLR implementation just prefer using &_i4. destVariant->_typeUnion._unionTypes._byref = new IntPtr(&(srcVariant->_typeUnion._unionTypes._i4)); break; } destVariant->_typeUnion._vt = (ushort)(srcVariant->_typeUnion._vt | (ushort)VarEnum.VT_BYREF); } /// <summary> /// Alloc memory for a VARIANT array with the specified length. /// Also initialize the VARIANT elements to be the type 'VT_EMPTY'. /// </summary> /// <param name="length">Array length</param> /// <returns>Pointer to the array</returns> private static unsafe IntPtr NewVariantArray(int length) { IntPtr variantArray = Marshal.AllocCoTaskMem(s_variantSize * length); for (int i = 0; i < length; i++) { IntPtr currentVarPtr = variantArray + s_variantSize * i; var currentVar = (Variant*)currentVarPtr; currentVar->_typeUnion._vt = (ushort)VarEnum.VT_EMPTY; } return variantArray; } /// <summary> /// Generate the ByRef array indicating whether the corresponding argument is by-reference. /// </summary> /// <param name="parameters">Parameters retrieved from metadata</param> /// <param name="argumentCount">Count of arguments to pass in IDispatch.Invoke</param> /// <param name="isPropertySet">Indicate if we are handling arguments for PropertyPut/PropertyPutRef</param> /// <returns></returns> internal static bool[] GetByRefArray(ParameterInformation[] parameters, int argumentCount, bool isPropertySet) { if (parameters.Length == 0) { return null; } var byRef = new bool[argumentCount]; int argsToProcess = argumentCount; if (isPropertySet) { // If it's PropertySet, then the last value in arguments is the right-hand side value. // There is no corresponding parameter for that value, so it's for sure not by-ref. // Hence, set the last item of byRef array to be false. argsToProcess = argumentCount - 1; byRef[argsToProcess] = false; } Diagnostics.Assert(parameters.Length >= argsToProcess, "There might be more parameters than argsToProcess due unspecified optional arguments"); for (int i = 0; i < argsToProcess; i++) { byRef[i] = parameters[i].isByRef; } return byRef; } /// <summary> /// Invoke the COM member /// </summary> /// <param name="target">IDispatch object</param> /// <param name="dispId">Dispatch identifier that identifies the member</param> /// <param name="args">Arguments passed in</param> /// <param name="byRef">Boolean array that indicates by-Ref parameters</param> /// <param name="invokeKind">Invocation kind</param> /// <returns></returns> internal static object Invoke(IDispatch target, int dispId, object[] args, bool[] byRef, COM.INVOKEKIND invokeKind) { Diagnostics.Assert(target != null, "Caller makes sure an IDispatch object passed in."); Diagnostics.Assert(args == null || byRef == null || args.Length == byRef.Length, "If 'args' and 'byRef' are not null, then they should be one-on-one mapping."); int argCount = args != null ? args.Length : 0; int refCount = byRef != null ? byRef.Count(c => c) : 0; IntPtr variantArgArray = IntPtr.Zero, dispIdArray = IntPtr.Zero, tmpVariants = IntPtr.Zero; try { // Package arguments if (argCount > 0) { variantArgArray = NewVariantArray(argCount); int refIndex = 0; for (int i = 0; i < argCount; i++) { // !! The arguments should be in REVERSED order!! int actualIndex = argCount - i - 1; IntPtr varArgPtr = variantArgArray + s_variantSize * actualIndex; // If need to pass by ref, create a by-ref variant if (byRef != null && byRef[i]) { // Allocate memory for temporary VARIANTs used in by-ref marshalling if (tmpVariants == IntPtr.Zero) { tmpVariants = NewVariantArray(refCount); } // Create a VARIANT that the by-ref VARIANT points to IntPtr tmpVarPtr = tmpVariants + s_variantSize * refIndex; Marshal.GetNativeVariantForObject(args[i], tmpVarPtr); // Create the by-ref VARIANT MakeByRefVariant(tmpVarPtr, varArgPtr); refIndex++; } else { Marshal.GetNativeVariantForObject(args[i], varArgPtr); } } } var paramArray = new COM.DISPPARAMS[1]; paramArray[0].rgvarg = variantArgArray; paramArray[0].cArgs = argCount; if (invokeKind == COM.INVOKEKIND.INVOKE_PROPERTYPUT || invokeKind == COM.INVOKEKIND.INVOKE_PROPERTYPUTREF) { // For property putters, the first DISPID argument needs to be DISPID_PROPERTYPUT dispIdArray = Marshal.AllocCoTaskMem(4); // Allocate 4 bytes to hold a 32-bit signed integer Marshal.WriteInt32(dispIdArray, DISPID_PROPERTYPUT); paramArray[0].cNamedArgs = 1; paramArray[0].rgdispidNamedArgs = dispIdArray; } else { // Otherwise, no named parameters are necessary since powershell parser doesn't support named parameter paramArray[0].cNamedArgs = 0; paramArray[0].rgdispidNamedArgs = IntPtr.Zero; } // Make the call EXCEPINFO info = default(EXCEPINFO); object result = null; try { // 'puArgErr' is set when IDispatch.Invoke fails with error code 'DISP_E_PARAMNOTFOUND' and 'DISP_E_TYPEMISMATCH'. // Appropriate exceptions will be thrown in such cases, but FullCLR doesn't use 'puArgErr' in the exception handling, so we also ignore it. uint puArgErrNotUsed = 0; target.Invoke(dispId, s_IID_NULL, LCID_DEFAULT, invokeKind, paramArray, out result, out info, out puArgErrNotUsed); } catch (Exception innerException) { // When 'IDispatch.Invoke' returns error code, CLR will raise exception based on internal HR-to-Exception mapping. // Description of the return code can be found at https://msdn.microsoft.com/en-us/library/windows/desktop/ms221479(v=vs.85).aspx // According to CoreCLR team (yzha), the exception needs to be wrapped as an inner exception of TargetInvocationException. string exceptionMsg = null; if (innerException.HResult == DISP_E_EXCEPTION) { // Invoke was successful but the actual underlying method failed. // In this case, we use EXCEPINFO to get additional error info. // Use EXCEPINFO.scode or EXCEPINFO.wCode as HR to construct the correct exception. int code = info.scode != 0 ? info.scode : info.wCode; innerException = Marshal.GetExceptionForHR(code, IntPtr.Zero) ?? innerException; // Get the richer error description if it's available. if (info.bstrDescription != IntPtr.Zero) { exceptionMsg = Marshal.PtrToStringBSTR(info.bstrDescription); Marshal.FreeBSTR(info.bstrDescription); } // Free the BSTRs if (info.bstrSource != IntPtr.Zero) { Marshal.FreeBSTR(info.bstrSource); } if (info.bstrHelpFile != IntPtr.Zero) { Marshal.FreeBSTR(info.bstrHelpFile); } } var outerException = exceptionMsg == null ? new TargetInvocationException(innerException) : new TargetInvocationException(exceptionMsg, innerException); throw outerException; } // Now back propagate the by-ref arguments if (refCount > 0) { for (int i = 0; i < argCount; i++) { // !! The arguments should be in REVERSED order!! int actualIndex = argCount - i - 1; // If need to pass by ref, back propagate if (byRef != null && byRef[i]) { args[i] = Marshal.GetObjectForNativeVariant(variantArgArray + s_variantSize * actualIndex); } } } return result; } finally { // Free the variant argument array if (variantArgArray != IntPtr.Zero) { for (int i = 0; i < argCount; i++) { VariantClear(variantArgArray + s_variantSize * i); } Marshal.FreeCoTaskMem(variantArgArray); } // Free the dispId array if (dispIdArray != IntPtr.Zero) { Marshal.FreeCoTaskMem(dispIdArray); } // Free the temporary variants created when handling by-Ref arguments if (tmpVariants != IntPtr.Zero) { for (int i = 0; i < refCount; i++) { VariantClear(tmpVariants + s_variantSize * i); } Marshal.FreeCoTaskMem(tmpVariants); } } } /// <summary> /// Clear variables of type VARIANTARG (or VARIANT) before the memory containing the VARIANTARG is freed. /// </summary> /// <param name="pVariant"></param> [DllImport("oleaut32.dll")] internal static extern void VariantClear(IntPtr pVariant); /// <summary> /// We have to declare 'bstrSource', 'bstrDescription' and 'bstrHelpFile' as pointers because /// CLR marshalling layer would try to free those BSTRs by default and that is not correct. /// Therefore, manually marshalling might be needed to extract 'bstrDescription'. /// </summary> [StructLayout(LayoutKind.Sequential)] internal struct EXCEPINFO { public short wCode; public short wReserved; public IntPtr bstrSource; public IntPtr bstrDescription; public IntPtr bstrHelpFile; public int dwHelpContext; public IntPtr pvReserved; public IntPtr pfnDeferredFillIn; public int scode; } /// <summary> /// VARIANT type used for passing arguments in COM interop /// </summary> [StructLayout(LayoutKind.Explicit)] internal struct Variant { // Most of the data types in the Variant are carried in _typeUnion [FieldOffset(0)] internal TypeUnion _typeUnion; // Decimal is the largest data type and it needs to use the space that is normally unused in TypeUnion._wReserved1, etc. // Hence, it is declared to completely overlap with TypeUnion. A Decimal does not use the first two bytes, and so // TypeUnion._vt can still be used to encode the type. [FieldOffset(0)] internal Decimal _decimal; [StructLayout(LayoutKind.Explicit)] internal struct TypeUnion { [FieldOffset(0)] internal ushort _vt; [FieldOffset(2)] internal ushort _wReserved1; [FieldOffset(4)] internal ushort _wReserved2; [FieldOffset(6)] internal ushort _wReserved3; [FieldOffset(8)] internal UnionTypes _unionTypes; } [StructLayout(LayoutKind.Sequential)] internal struct Record { internal IntPtr _record; internal IntPtr _recordInfo; } [StructLayout(LayoutKind.Explicit)] internal struct UnionTypes { [FieldOffset(0)] internal SByte _i1; [FieldOffset(0)] internal Int16 _i2; [FieldOffset(0)] internal Int32 _i4; [FieldOffset(0)] internal Int64 _i8; [FieldOffset(0)] internal Byte _ui1; [FieldOffset(0)] internal UInt16 _ui2; [FieldOffset(0)] internal UInt32 _ui4; [FieldOffset(0)] internal UInt64 _ui8; [FieldOffset(0)] internal Int32 _int; [FieldOffset(0)] internal UInt32 _uint; [FieldOffset(0)] internal Int16 _bool; [FieldOffset(0)] internal Int32 _error; [FieldOffset(0)] internal Single _r4; [FieldOffset(0)] internal Double _r8; [FieldOffset(0)] internal Int64 _cy; [FieldOffset(0)] internal double _date; [FieldOffset(0)] internal IntPtr _bstr; [FieldOffset(0)] internal IntPtr _unknown; [FieldOffset(0)] internal IntPtr _dispatch; [FieldOffset(0)] internal IntPtr _pvarVal; [FieldOffset(0)] internal IntPtr _byref; [FieldOffset(0)] internal Record _record; } } } }
using System; using System.Collections.Generic; using System.Data; using System.Xml; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using VaultAtlas.DataModel; using System.Runtime.Serialization; namespace VaultAtlas.UI { public class EditShow : UserControl, IPlugInFunctionProvider { private System.Windows.Forms.ImageList imageList1; private TabControl baseTabControl1; private TabPage tabPage2; private System.Windows.Forms.Panel panel4; private System.ComponentModel.IContainer components; protected EditShow( SerializationInfo info, StreamingContext context ) : this() { this.InternalConstruct(); } public EditShow() { this.InternalConstruct(); } public Show GetShow(int index) { return VaultAtlasApplication.Model.ShowView.GetShow(index); } public void InternalConstruct() { InitializeComponent(); this.baseTabControl1.TabPages.Add(this.tabPage2); } public Show EditedShow { get; private set; } public int ShowIndex { get; private set; } public void Bind( int showIndex, Show show) { this.ShowIndex = showIndex; this.EditedShow = show; this.LoadPlugIns(); Text = EditedShow.Display; foreach (var showEdit in this._plugInShowEditors) { showEdit.OnBind(this, showIndex, show); } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(EditShow)); this.imageList1 = new System.Windows.Forms.ImageList(this.components); this.baseTabControl1 = new System.Windows.Forms.TabControl(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.panel4 = new System.Windows.Forms.Panel(); this.tabPage2.SuspendLayout(); this.SuspendLayout(); // // imageList1 // this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream"))); this.imageList1.TransparentColor = System.Drawing.Color.Transparent; this.imageList1.Images.SetKeyName(0, ""); this.imageList1.Images.SetKeyName(1, ""); this.imageList1.Images.SetKeyName(2, ""); // // baseTabControl1 // this.baseTabControl1.Alignment = System.Windows.Forms.TabAlignment.Bottom; this.baseTabControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.baseTabControl1.ImageList = this.imageList1; this.baseTabControl1.Location = new System.Drawing.Point(0, 0); this.baseTabControl1.Name = "baseTabControl1"; this.baseTabControl1.SelectedIndex = 0; this.baseTabControl1.Size = new System.Drawing.Size(482, 310); this.baseTabControl1.TabIndex = 0; // // tabPage2 // this.tabPage2.Controls.Add(this.panel4); this.tabPage2.ImageIndex = 0; this.tabPage2.Location = new System.Drawing.Point(0, 0); this.tabPage2.Name = "tabPage2"; this.tabPage2.Size = new System.Drawing.Size(448, 163); this.tabPage2.TabIndex = 4; this.tabPage2.Text = "Summary"; // // panel4 // this.panel4.Dock = System.Windows.Forms.DockStyle.Fill; this.panel4.Location = new System.Drawing.Point(0, 0); this.panel4.Name = "panel4"; this.panel4.Size = new System.Drawing.Size(448, 163); this.panel4.TabIndex = 3; // // EditShow // this.Controls.Add(this.baseTabControl1); this.Name = "EditShow"; this.Size = new System.Drawing.Size(482, 310); this.tabPage2.ResumeLayout(false); this.ResumeLayout(false); } #endregion private readonly IList<IShowEditPlugIn> _plugInShowEditors = new List<IShowEditPlugIn>(); private void AddTabPage( ITabPage tabPage, int index ) { var newTabPage = new TabPage(tabPage.Title); newTabPage.Controls.Add(tabPage.Control); newTabPage.ImageIndex = tabPage.ImageIndex; newTabPage.BorderStyle = BorderStyle.FixedSingle; this.baseTabControl1.TabPages.Insert( index, newTabPage); } private void LoadPlugIns() { this.baseTabControl1.TabPages.Clear(); this._plugInShowEditors.Clear(); foreach( var showEdit in VaultAtlasApplication.Model.PlugInManager.CreateShowEditorPlugIns()) { this._plugInShowEditors.Add( showEdit ); var tabPages = showEdit.CreateTabPages( this.imageList1 ); if ( tabPages != null ) { foreach( ITabPage tabPage in tabPages ) { this.AddTabPage( tabPage, ( showEdit is ShowEditData ) ? 0 : this.baseTabControl1.TabPages.Count); } } } this.baseTabControl1.SelectedTab = this.baseTabControl1.TabPages[0]; } private void FireRejectChanges() { EditedShow.Row.RejectChanges(); foreach( var plugIn in _plugInShowEditors ) plugIn.OnShowRejectChanges(); } public void SetTabVisible( ITabPage tabPage, bool visible ) { foreach( TabPage tab in baseTabControl1.TabPages ) { if ( tab.Controls[0] == tabPage.Control ) { if ( !visible) this.baseTabControl1.TabPages.Remove( tab ); return; } } if ( visible ) this.AddTabPage( tabPage, this.baseTabControl1.TabPages.Count ); } #region IPlugInFunctionProvider Member public void RequestClose() { if (EditedShow.Row.RowState != DataRowState.Deleted) ValidateChildren(); VaultAtlasApplication.MainForm.RequestCloseTab(this); var navi = VaultAtlasApplication.Model.ModelNavigator; if (navi != null) navi.NavigateTo(this.ShowIndex); } public void UndoChanges(Show show) { FireRejectChanges(); } public void DeleteShow(Show show) { if (MessageBox.Show(resources.DeleteThisShow, "", MessageBoxButtons.YesNo) == DialogResult.No) return; RequestClose(); EditedShow.Row.Delete(); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using Microsoft.Win32; using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Threading; namespace Microsoft.Win32.RegistryTests { public class RegistryKey_GetValue_str_obj_b : IDisposable { // Variables needed private RegistryKey _rk1, _rk2; private String _strTest = "This is a test string"; private String _testKeyName2 = "BCL_TEST_5"; private static int s_keyCount = 0; public void TestInitialize() { var counter = Interlocked.Increment(ref s_keyCount); _testKeyName2 += counter.ToString(); _rk1 = Microsoft.Win32.Registry.CurrentUser; //Make sure we don't have registry key that we create and test here CleanRegistryKeys(); } public RegistryKey_GetValue_str_obj_b() { TestInitialize(); } [Fact] public void Test01() { // [] Null arguments should be ignored try { #pragma warning disable 0618 Object obj = _rk1.GetValue(null, null, RegistryValueOptions.DoNotExpandEnvironmentNames); #pragma warning restore 0618 if (obj != null) { Assert.False(true, "Error Key value is incorrect..."); } } catch (Exception e) { Assert.False(true, "Error Unexpected exception occured , got exc==" + e.ToString()); } } [Fact] public void Test02() { // [] Passing in null object not throw. You should be able to specify null as default object to return try { #pragma warning disable 0618 if (_rk1.GetValue("tt", null, RegistryValueOptions.DoNotExpandEnvironmentNames) != null) #pragma warning restore 0618 { Assert.False(true, "Error null return expected"); } } catch (Exception e) { Assert.False(true, "Error Unexpected exception occured.... exception message...:" + e.ToString()); } } [Fact] public void Test03() { // [] Pass name=string.Empty try { #pragma warning disable 0618 Object obj1 = _rk1.GetValue(String.Empty, _strTest, RegistryValueOptions.DoNotExpandEnvironmentNames); #pragma warning restore 0618 if (obj1.ToString() != _strTest) { Assert.False(true, "Error null return expected"); } } catch (Exception e) { Assert.False(true, "Error Unexpected exception occured.... exception message...:" + e.ToString()); } } [Fact] public void Test04() { // [] Pass name=Existing key, default value = null _rk2 = _rk1.CreateSubKey(_testKeyName2); try { string strKey = "MyTestKey"; _rk2.SetValue(strKey, _strTest, RegistryValueKind.ExpandString); #pragma warning disable 0618 Object obj1 = _rk2.GetValue(strKey, null, RegistryValueOptions.DoNotExpandEnvironmentNames); #pragma warning restore 0618 if (obj1.ToString() != _strTest) { Assert.False(true, "Error null return expected"); } } catch (Exception e) { Assert.False(true, "Error Unexpected exception occured.... exception message...:" + e.ToString()); } } [Fact] public void Test05() { // [] Pass name=null, default value = some value _rk2 = _rk1.CreateSubKey(_testKeyName2); string strKey = "MyTestKey"; try { _rk2.SetValue(strKey, _strTest, RegistryValueKind.ExpandString); #pragma warning disable 0618 Object obj1 = _rk2.GetValue(null, _strTest, RegistryValueOptions.DoNotExpandEnvironmentNames); #pragma warning restore 0618 if (obj1.ToString() != _strTest) { Assert.False(true, "Error null return expected"); } } catch (Exception e) { Assert.False(true, "Error Unexpected exception occured.... exception message...:" + e.ToString()); } } [Fact] public void Test06() { // [] Make sure NoExpand = false works with some valid values. string[] strTestValues = new string[] { @"%Systemroot%\mydrive\mydriectory\myfile.xxx", @"%tmp%\gfdhghdfgk\fsdfds\dsd.yyy", @"%path%\rwerew.zzz", @"%Systemroot%\mydrive\%path%\myfile.xxx" }; string[] strExpectedTestValues = new string[] { Environment.ExpandEnvironmentVariables("%Systemroot%") + @"\mydrive\mydriectory\myfile.xxx", Environment.ExpandEnvironmentVariables("%tmp%") + @"\gfdhghdfgk\fsdfds\dsd.yyy", Environment.ExpandEnvironmentVariables("%path%") + @"\rwerew.zzz", Environment.ExpandEnvironmentVariables("%Systemroot%") + @"\mydrive\" + Environment.ExpandEnvironmentVariables("%path%") + @"\myfile.xxx" }; _rk2 = _rk1.CreateSubKey(_testKeyName2); try { for (int iLoop = 0; iLoop < strTestValues.Length; iLoop++) { string strKey = "MyTestKey" + iLoop.ToString(); _rk2.SetValue(strKey, strTestValues[iLoop], RegistryValueKind.ExpandString); #pragma warning disable 0618 Object obj1 = _rk2.GetValue(strKey, strTestValues[iLoop], RegistryValueOptions.None); #pragma warning restore 0618 if (obj1.ToString() != strExpectedTestValues[iLoop]) { Assert.False(true, string.Format("Error GetValue retried unexpected value.... Expected...:{0}, Actual...:{1}", strExpectedTestValues[iLoop], obj1.ToString())); } } } catch (Exception e) { Assert.False(true, "Error Unexpected exception occured.... exception message...:" + e.ToString()); } } [Fact] public void Test07() { _rk2 = _rk1.CreateSubKey(_testKeyName2); //Set some new environment variables and make sure the string[] strMyNewEnvVariables = new string[] { "MyEnv", "PathPath", "Name", "blah", "TestKEyyyyyyyyyyyyyy" }; try { for (int iLoop = 0; iLoop < strMyNewEnvVariables.Length; iLoop++) { SetEnvironmentVariable(strMyNewEnvVariables[iLoop], @"C:\UsedToBeCurrentDirectoryButAnythingWorks"); string strKey = "MyNewKey" + iLoop.ToString(); string strValue = "%" + strMyNewEnvVariables[iLoop] + "%" + @"\subdirectory\myfile.txt"; _rk2.SetValue(strKey, strValue, RegistryValueKind.ExpandString); #pragma warning disable 0618 Object obj1 = _rk2.GetValue(strKey, string.Empty, RegistryValueOptions.DoNotExpandEnvironmentNames); #pragma warning restore 0618 if (obj1.ToString() != strValue) { Assert.False(true, string.Format("Error GetValue retried unexpected value.... Expected...:{0}, Actual...:{1}", strValue, obj1.ToString())); } } } catch (Exception e) { Assert.False(true, "Error Unexpected exception occured.... exception message...:" + e.ToString()); } } [DllImport("api-ms-win-core-processenvironment-l1-1-0.dll", CharSet = CharSet.Unicode, SetLastError = true)] private static extern bool SetEnvironmentVariable(string lpName, string lpValue); [Fact] public void Test08() { // [] Vanilla case , add a bunch of different objects (sampling all value types) Random rand = new Random(-55); List<object> al = new List<object>(); al.Add((Byte)rand.Next(Byte.MinValue, Byte.MaxValue)); al.Add((SByte)rand.Next(SByte.MinValue, SByte.MaxValue)); al.Add((Int16)rand.Next(Int16.MinValue, Int16.MaxValue)); al.Add((UInt16)rand.Next(UInt16.MinValue, UInt16.MaxValue)); al.Add(rand.Next(Int32.MinValue, Int32.MaxValue)); al.Add((UInt32)rand.Next((int)UInt32.MinValue, Int32.MaxValue)); al.Add((Int64)rand.Next(Int32.MinValue, Int32.MaxValue)); al.Add(new Decimal(((Double)Decimal.MaxValue) * rand.NextDouble())); al.Add(new Decimal(((Double)Decimal.MinValue) * rand.NextDouble())); al.Add(new Decimal(((Double)Decimal.MinValue) * rand.NextDouble())); al.Add(new Decimal(((Double)Decimal.MaxValue) * rand.NextDouble())); al.Add((Double)Int32.MaxValue * rand.NextDouble()); al.Add((Double)Int32.MinValue * rand.NextDouble()); al.Add((float)Int32.MaxValue * (float)rand.NextDouble()); al.Add((float)Int32.MinValue * (float)rand.NextDouble()); al.Add(((UInt64)(UInt64)rand.Next((int)UInt64.MinValue, Int32.MaxValue))); al.Add(@"%Systemroot%\mydrive\mydriectory\myfile.xxx"); al.Add(@"%tmp%\mydrive\mydriectory\myfile.xxx"); al.Add(@"%path%\mydrive\mydriectory\myfile.xxx"); al.Add(@"%Systemroot\myblah\%useranme%%\mydrive\mydriectory\myfile.xxx"); al.Add(@"%path%\mydrive\%tmp%\myfile.xxx"); _rk2 = _rk1.CreateSubKey(_testKeyName2); try { IDictionary strEnvVariables = Environment.GetEnvironmentVariables(); IEnumerator e = (IEnumerator)strEnvVariables.GetEnumerator(); while (e.MoveNext()) { al.Add(((DictionaryEntry)e.Current).Value); } foreach (Object obj in al) _rk2.SetValue("Test_" + obj.ToString(), obj.ToString(), RegistryValueKind.ExpandString); // [] Get the objects back and check them foreach (Object obj in al) { #pragma warning disable 0618 Object v = _rk2.GetValue("Test_" + obj.ToString(), 13, RegistryValueOptions.DoNotExpandEnvironmentNames); #pragma warning restore 0618 if (!v.ToString().Equals(obj.ToString(), StringComparison.OrdinalIgnoreCase)) { Assert.False(true, "Error Expected==" + obj.ToString() + " , got value==" + v.ToString()); } } } catch (Exception e) { Assert.False(true, "Error Unexpected exception occured.... exception message...:" + e.ToString()); } } private void CleanRegistryKeys() { try { _rk1 = Microsoft.Win32.Registry.CurrentUser; if (_rk1.OpenSubKey(_testKeyName2) != null) _rk1.DeleteSubKeyTree(_testKeyName2); if (_rk1.GetValue(_testKeyName2) != null) _rk1.DeleteValue(_testKeyName2); } catch (Exception e) { Assert.False(true, "Unexpected exception occured in CleanRegistryKeys method... exception message...:" + e.Message); } } public void Dispose() { CleanRegistryKeys(); } } }
/**************************************************************************** Software: Midi Class Version: 1.5 Date: 2005/04/25 Author: Valentin Schmidt Contact: [email protected] License: Freeware You may use and modify this software as you wish. Translated to C# by Zeugma 440 TODO : http://www.musicxml.com/for-developers/ ? ****************************************************************************/ /* ==== SOME NOTES CONCERNING LENGTH CALCULATION - Z440 ==== - The calculated length is not "intelligent", i.e. the whole MIDI file is taken as musical material, even if there is only one note followed by three minutes of TimeSig's and tempo changes. It may be a choice of policy, but it appears that Winamp uses "intelligent" parsing, which ends the song whith the last _note_ event. */ using System; using System.IO; using ATL.Logging; using System.Collections.Generic; using System.Text; using static ATL.AudioData.AudioDataManager; using Commons; using static ATL.ChannelsArrangements; namespace ATL.AudioData.IO { /// <summary> /// Class for Musical Instruments Digital Interface files manipulation (extension : .MID, .MIDI) /// </summary> public class Midi : MetaDataIO, IAudioDataIO { //Private properties private IList<MidiTrack> tracks; // Tracks of the song private int timebase; // timebase = ticks per frame (quarter note) a.k.a. PPQN (Pulses Per Quarter Note) private int tempoMsgNum; // position of tempo event in track 0 private long tempo; // tempo (0 for unknown) // NB : there is no such thing as an uniform "song tempo" since tempo can change over time within each track ! private byte type; // MIDI STRUCTURE TYPE // 0 - single-track // 1 - multiple tracks, synchronous // 2 - multiple tracks, asynchronous private static class MidiEvents { // Standard events public const int EVT_PROGRAM_CHANGE = 0x0C; public const int EVT_NOTE_ON = 0x09; public const int EVT_NOTE_OFF = 0x08; public const int EVT_POLY_PRESSURE = 0x0A; public const int EVT_CONTROLLER_CHANGE = 0x0B; public const int EVT_CHANNEL_PRESSURE = 0x0D; public const int EVT_PITCH_BEND = 0x0E; public const int EVT_META = 0xFF; public const int EVT_SYSEX = 0xF0; // Meta events public const int META_SEQUENCE_NUM = 0x00; public const int META_TEXT = 0x01; public const int META_COPYRIGHT = 0x02; public const int META_TRACK_NAME = 0x03; public const int META_INSTRUMENT_NAME = 0x04; public const int META_LYRICS = 0x05; public const int META_MARKER = 0x06; public const int META_CUE = 0x07; public const int META_CHANNEL_PREFIX = 0x20; public const int META_CHANNEL_PREFIX_PORT = 0x21; public const int META_TRACK_END = 0x2F; public const int META_TEMPO = 0x51; public const int META_SMPTE_OFFSET = 0x54; public const int META_TIME_SIGNATURE = 0x58; public const int META_KEY_SIGNATURE = 0x59; public const int META_SEQUENCER_DATA = 0x7F; // Sequencer specific data } private class MidiEvent { public long TickOffset = 0; public int Type = 0; public bool isMetaEvent = false; public int Channel = 0; public int Param0 = 0; public int Param1 = 0; public String Description; public MidiEvent(long tickOffset, int type, int channel, int param0, int param1 = 0) { TickOffset = tickOffset; Type = type; Channel = channel; Param0 = param0; Param1 = param1; } } private class MidiTrack { public long Duration = 0; public long Ticks = 0; public long LastSignificantEventTicks = -1; public MidiEvent LastEvent = null; public IList<MidiEvent> events = new List<MidiEvent>(); public void Add(MidiEvent evt) { events.Add(evt); LastEvent = evt; if (MidiEvents.EVT_NOTE_ON == evt.Type || MidiEvents.EVT_NOTE_OFF == evt.Type || MidiEvents.EVT_CONTROLLER_CHANGE == evt.Type || MidiEvents.EVT_CHANNEL_PRESSURE == evt.Type || MidiEvents.EVT_POLY_PRESSURE == evt.Type || MidiEvents.EVT_PITCH_BEND == evt.Type || MidiEvents.META_TRACK_END == evt.Type ) { LastSignificantEventTicks = evt.TickOffset; } } } #region instruments private static readonly string[] instrumentList = new string[128] { "Piano", "Bright Piano", "Electric Grand", "Honky Tonk Piano", "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel", "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bell", "Dulcimer", "Hammond Organ", "Perc Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica", "Tango Accordion", "Nylon Str Guitar", "Steel String Guitar", "Jazz Electric Gtr", "Clean Guitar", "Muted Guitar", "Overdrive Guitar", "Distortion Guitar", "Guitar Harmonics", "Acoustic Bass", "Fingered Bass", "Picked Bass", "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Syn Bass 1", "Syn Bass 2", "Violin", "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp", "Timpani", "Ensemble Strings", "Slow Strings", "Synth Strings 1", "Synth Strings 2", "Choir Aahs", "Voice Oohs", "Syn Choir", "Orchestra Hit", "Trumpet", "Trombone", "Tuba", "Muted Trumpet", "French Horn", "Brass Ensemble", "Syn Brass 1", "Syn Brass 2", "Soprano Sax", "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet", "Piccolo", "Flute", "Recorder", "Pan Flute", "Bottle Blow", "Shakuhachi", "Whistle", "Ocarina", "Syn Square Wave", "Syn Saw Wave", "Syn Calliope", "Syn Chiff", "Syn Charang", "Syn Voice", "Syn Fifths Saw", "Syn Brass and Lead", "Fantasia", "Warm Pad", "Polysynth", "Space Vox", "Bowed Glass", "Metal Pad", "Halo Pad", "Sweep Pad", "Ice Rain", "Soundtrack", "Crystal", "Atmosphere", "Brightness", "Goblins", "Echo Drops", "Sci Fi", "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag Pipe", "Fiddle", "Shanai", "Tinkle Bell", "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Syn Drum", "Reverse Cymbal", "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird", "Telephone", "Helicopter", "Applause", "Gunshot"}; #endregion private const String MIDI_FILE_HEADER = "MThd"; private const String MIDI_TRACK_HEADER = "MTrk"; private const int DEFAULT_TEMPO = 500; // Default MIDI tempo is 120bpm, 500ms per beat public StringBuilder comment; private double duration; private double bitrate; private SizeInfo sizeInfo; private readonly string filePath; // ---------- INFORMATIVE INTERFACE IMPLEMENTATIONS & MANDATORY OVERRIDES // IAudioDataIO public int SampleRate { get { return 0; } } public bool IsVBR { get { return false; } } public int CodecFamily { get { return AudioDataIOFactory.CF_SEQ; } } public string FileName { get { return filePath; } } public double BitRate { get { return bitrate; } } public double Duration { get { return duration; } } public ChannelsArrangement ChannelsArrangement { get { return ChannelsArrangements.STEREO; } } public bool IsMetaSupported(int metaDataType) { return (metaDataType == MetaDataIOFactory.TAG_NATIVE); // Only for comments } // IMetaDataIO protected override int getDefaultTagOffset() { return TO_BUILTIN; } protected override int getImplementedTagType() { return MetaDataIOFactory.TAG_NATIVE; } protected override byte getFrameMapping(string zone, string ID, byte tagVersion) { throw new NotImplementedException(); } // ---------- CONSTRUCTORS & INITIALIZERS protected void resetData() { duration = 0; bitrate = 0; ResetData(); } public Midi(string filePath) { this.filePath = filePath; resetData(); } // === PRIVATE STRUCTURES/SUBCLASSES === private double getDuration() { long maxTicks = 0; double maxDuration = 0; // Longest duration among all tracks if (tracks.Count > 0) { // Look for the position of the latest "significant event" of the entire song (including TrackEnd) foreach (MidiTrack aTrack in tracks) { maxTicks = Math.Max(maxTicks, aTrack.LastSignificantEventTicks); } long currentDuration = 0; long lastTempoTicks = 0; int currentTempo = DEFAULT_TEMPO; // Build "duration chunks" using the "master tempo map" provided in track 0 foreach (MidiEvent evt in tracks[0].events) { if (MidiEvents.META_TEMPO == evt.Type) { currentDuration += (evt.TickOffset - lastTempoTicks) * currentTempo; currentTempo = evt.Param0; lastTempoTicks = evt.TickOffset; } } // Make sure the song lasts until the latest event if (maxTicks > lastTempoTicks) currentDuration += (maxTicks - lastTempoTicks) * currentTempo; maxDuration = currentDuration; } // For an obscure reason, this algorithm constantly calculates // a duration equals to (actual duration calculated by BASSMIDI - 1 second), hence this ugly " + 1000" return (maxDuration / timebase / 1000.00) + 1000; } /**************************************************************************** * * * Public methods * * * ****************************************************************************/ //--------------------------------------------------------------- // Imports Standard MIDI File (type 0 or 1) (and RMID) // (if optional parameter $tn set, only track $tn is imported) //--------------------------------------------------------------- public bool Read(BinaryReader source, AudioDataManager.SizeInfo sizeInfo, MetaDataIO.ReadTagParams readTagParams) { this.sizeInfo = sizeInfo; return read(source, readTagParams); } protected override bool read(BinaryReader source, MetaDataIO.ReadTagParams readTagParams) { byte[] header; string trigger; IList<string> trackStrings = new List<string>(); IList<MidiTrack> tracks = new List<MidiTrack>(); resetData(); // Ignores everything (comments) written before the MIDI header /* * trigger = ""; while (trigger != MIDI_FILE_HEADER) { trigger += new String(StreamUtils.ReadOneByteChars(source, 1)); if (trigger.Length > 4) trigger = trigger.Remove(0, 1); } */ StreamUtils.FindSequence(source.BaseStream, Utils.Latin1Encoding.GetBytes(MIDI_FILE_HEADER)); // Ready to read header data... header = source.ReadBytes(10); if ((header[0] != 0) || (header[1] != 0) || (header[2] != 0) || (header[3] != 6) ) { Logging.LogDelegator.GetLogDelegate()(Log.LV_ERROR,"Wrong MIDI header"); return false; } type = header[5]; // MIDI STRUCTURE TYPE // 0 - single-track // 1 - multiple tracks, synchronous // 2 - multiple tracks, asynchronous if (type > 1) { Logging.LogDelegator.GetLogDelegate()(Log.LV_WARNING, "SMF type 2 MIDI files are partially supported; results may be approximate"); } tagExists = true; timebase = (header[8] << 8) + header[9]; tempo = 0; // maybe (hopefully!) overwritten by parseTrack int trackSize = 0; int nbTrack = 0; comment = new StringBuilder(""); // Ready to read track data... while (source.BaseStream.Position < sizeInfo.FileSize - 4) { trigger = Utils.Latin1Encoding.GetString(source.ReadBytes(4)); if (trigger != MIDI_TRACK_HEADER) { source.BaseStream.Seek(-3, SeekOrigin.Current); if (!StreamUtils.FindSequence(source.BaseStream, Utils.Latin1Encoding.GetBytes(MIDI_TRACK_HEADER))) break; } // trackSize is stored in big endian -> needs inverting trackSize = StreamUtils.ReverseInt32(source.ReadInt32()); tracks.Add(parseTrack(source.ReadBytes(trackSize), nbTrack)); nbTrack++; } this.tracks = tracks; if (comment.Length > 0) comment.Remove(comment.Length - 1, 1); tagData.IntegrateValue(TagData.TAG_FIELD_COMMENT, comment.ToString()); duration = getDuration(); bitrate = (double) sizeInfo.FileSize / duration; return true; } #region Legacy Utilities //*************************************************************** // PUBLIC UTILITIES //*************************************************************** //--------------------------------------------------------------- // returns list of drumset instrument names //--------------------------------------------------------------- /* ## TO DO function getDrumset(){ return array( 35=>'Acoustic Bass Drum', 36=>'Bass Drum 1', 37=>'Side Stick', 38=>'Acoustic Snare', 39=>'Hand Clap', 40=>'Electric Snare', 41=>'Low Floor Tom', 42=>'Closed Hi-Hat', 43=>'High Floor Tom', 44=>'Pedal Hi-Hat', 45=>'Low Tom', 46=>'Open Hi-Hat', 47=>'Low Mid Tom', 48=>'High Mid Tom', 49=>'Crash Cymbal 1', 50=>'High Tom', 51=>'Ride Cymbal 1', 52=>'Chinese Cymbal', 53=>'Ride Bell', 54=>'Tambourine', 55=>'Splash Cymbal', 56=>'Cowbell', 57=>'Crash Cymbal 2', 58=>'Vibraslap', 59=>'Ride Cymbal 2', 60=>'High Bongo', 61=>'Low Bongo', 62=>'Mute High Conga', 63=>'Open High Conga', 64=>'Low Conga', 65=>'High Timbale', 66=>'Low Timbale', //35..66 67=>'High Agogo', 68=>'Low Agogo', 69=>'Cabase', 70=>'Maracas', 71=>'Short Whistle', 72=>'Long Whistle', 73=>'Short Guiro', 74=>'Long Guiro', 75=>'Claves', 76=>'High Wood Block', 77=>'Low Wood Block', 78=>'Mute Cuica', 79=>'Open Cuica', 80=>'Mute Triangle', 81=>'Open Triangle'); } */ //--------------------------------------------------------------- // returns list of standard drum kit names //--------------------------------------------------------------- /* ## TO DO function getDrumkitList(){ return array( 1 => 'Dry', 9 => 'Room', 19 => 'Power', 25 => 'Electronic', 33 => 'Jazz', 41 => 'Brush', 57 => 'SFX', 128 => 'Default' ); } */ //--------------------------------------------------------------- // returns list of note names //--------------------------------------------------------------- /* function getNoteList(){ //note 69 (A6) = A440 //note 60 (C6) = Middle C return array( //Do Re Mi Fa So La Ti 'C0', 'Cs0', 'D0', 'Ds0', 'E0', 'F0', 'Fs0', 'G0', 'Gs0', 'A0', 'As0', 'B0', 'C1', 'Cs1', 'D1', 'Ds1', 'E1', 'F1', 'Fs1', 'G1', 'Gs1', 'A1', 'As1', 'B1', 'C2', 'Cs2', 'D2', 'Ds2', 'E2', 'F2', 'Fs2', 'G2', 'Gs2', 'A2', 'As2', 'B2', 'C3', 'Cs3', 'D3', 'Ds3', 'E3', 'F3', 'Fs3', 'G3', 'Gs3', 'A3', 'As3', 'B3', 'C4', 'Cs4', 'D4', 'Ds4', 'E4', 'F4', 'Fs4', 'G4', 'Gs4', 'A4', 'As4', 'B4', 'C5', 'Cs5', 'D5', 'Ds5', 'E5', 'F5', 'Fs5', 'G5', 'Gs5', 'A5', 'As5', 'B5', 'C6', 'Cs6', 'D6', 'Ds6', 'E6', 'F6', 'Fs6', 'G6', 'Gs6', 'A6', 'As6', 'B6', 'C7', 'Cs7', 'D7', 'Ds7', 'E7', 'F7', 'Fs7', 'G7', 'Gs7', 'A7', 'As7', 'B7', 'C8', 'Cs8', 'D8', 'Ds8', 'E8', 'F8', 'Fs8', 'G8', 'Gs8', 'A8', 'As8', 'B8', 'C9', 'Cs9', 'D9', 'Ds9', 'E9', 'F9', 'Fs9', 'G9', 'Gs9', 'A9', 'As9', 'B9', 'C10','Cs10','D10','Ds10','E10','F10','Fs10','G10'); } */ #endregion private MidiTrack parseTrack(byte[] data, int trackNumber) { MidiTrack track = new MidiTrack(); int trackLen = data.Length; int position = 0; long currentTicks = 0; int currentDelta; byte eventType; int eventTypeHigh; int eventTypeLow; byte meta; int num; int len; byte tmp; byte c; String txt; MidiEvent evt; int currentTempo = 0; long lastTempoTicks = -1; while (position < trackLen) { // timedelta currentDelta = readVarLen(ref data, ref position); currentTicks += currentDelta; eventType = data[position]; eventTypeHigh = (eventType >> 4); eventTypeLow = (eventType - eventTypeHigh * 16); switch (eventTypeHigh) { case MidiEvents.EVT_PROGRAM_CHANGE: //PrCh = ProgramChange evt = new MidiEvent(currentTicks, eventTypeHigh, eventTypeLow + 1, data[position + 1]); evt.Description = " PrCh ch=" + evt.Channel + " p=" + evt.Param0; track.Add(evt); position += 2; break; case MidiEvents.EVT_NOTE_ON: //On evt = new MidiEvent(currentTicks, eventTypeHigh, eventTypeLow + 1, data[position + 1], data[position + 2]); evt.Description = " On ch=" + evt.Channel + " n=" + evt.Param0 + " v=" + evt.Param1; track.Add(evt); position += 3; break; case MidiEvents.EVT_NOTE_OFF: //Off evt = new MidiEvent(currentTicks, eventTypeHigh, eventTypeLow + 1, data[position + 1], data[position + 2]); evt.Description = " Off ch=" + evt.Channel + " n=" + evt.Param0 + " v=" + evt.Param1; track.Add(evt); position += 3; break; case MidiEvents.EVT_POLY_PRESSURE: //PoPr = PolyPressure evt = new MidiEvent(currentTicks, eventTypeHigh, eventTypeLow + 1, data[position + 1], data[position + 2]); evt.Description = " PoPr ch=" + evt.Channel + " n=" + evt.Param0 + " v=" + evt.Param1; track.Add(evt); position += 3; break; case MidiEvents.EVT_CONTROLLER_CHANGE: //Par = ControllerChange evt = new MidiEvent(currentTicks, eventTypeHigh, eventTypeLow + 1, data[position + 1], data[position + 2]); evt.Description = " Par ch=" + evt.Channel + " c=" + evt.Param0 + " v=" + evt.Param1; track.Add(evt); position += 3; break; case MidiEvents.EVT_CHANNEL_PRESSURE: //ChPr = ChannelPressure evt = new MidiEvent(currentTicks, eventTypeHigh, eventTypeLow + 1, data[position + 1]); evt.Description = " ChPr ch=" + evt.Channel + " v=" + evt.Param0; track.Add(evt); position += 2; break; case MidiEvents.EVT_PITCH_BEND: //Pb = PitchBend evt = new MidiEvent(currentTicks, eventTypeHigh, eventTypeLow + 1, (data[position + 1] & 0x7F) | ((data[position + 2] & 0x7F) << 7)); evt.Description = " Pb ch=" + evt.Channel + " v=" + evt.Param0; track.Add(evt); position += 3; break; default: switch (eventType) { case 0xFF: // Meta meta = data[position + 1]; switch (meta) { case MidiEvents.META_SEQUENCE_NUM: // sequence_number tmp = data[position + 2]; if (tmp == 0x00) { num = trackNumber; position += 3; } else { num = 1; position += 5; } evt = new MidiEvent(currentTicks, meta, -1, num); evt.isMetaEvent = true; evt.Description = " Seqnr " + evt.Param0; track.Add(evt); break; case MidiEvents.META_TEXT: // Meta Text case MidiEvents.META_COPYRIGHT: // Meta Copyright case MidiEvents.META_TRACK_NAME: // Meta TrackName ???sequence_name??? case MidiEvents.META_INSTRUMENT_NAME: // Meta InstrumentName case MidiEvents.META_LYRICS: // Meta Lyrics case MidiEvents.META_MARKER: // Meta Marker case MidiEvents.META_CUE: // Meta Cue String[] texttypes = new String[7] { "Text", "Copyright", "TrkName", "InstrName", "Lyric", "Marker", "Cue" }; String type = texttypes[meta - 1]; position += 2; len = readVarLen(ref data, ref position); if ((len + position) > trackLen) throw new Exception("Meta " + type + " has corrupt variable length field (" + len + ") [track: " + trackNumber + " dt: " + currentDelta + "]"); txt = Encoding.ASCII.GetString(data, position, len); if (MidiEvents.META_TEXT == meta || MidiEvents.META_TRACK_NAME == meta || MidiEvents.META_MARKER == meta) comment.Append(txt).Append(Settings.InternalValueSeparator); else if (MidiEvents.META_COPYRIGHT == meta) tagData.IntegrateValue(TagData.TAG_FIELD_COPYRIGHT, txt); evt = new MidiEvent(currentTicks, meta, -1, meta - 1); evt.isMetaEvent = true; evt.Description = " Meta " + type + " \"" + txt + "\""; track.Add(evt); position += len; break; case MidiEvents.META_CHANNEL_PREFIX: // ChannelPrefix evt = new MidiEvent(currentTicks, meta, -1, data[position + 3]); evt.isMetaEvent = true; evt.Description = " Meta ChannelPrefix " + evt.Param0; track.Add(evt); position += 4; break; case MidiEvents.META_CHANNEL_PREFIX_PORT: // ChannelPrefixOrPort evt = new MidiEvent(currentTicks, meta, -1, data[position + 3]); evt.isMetaEvent = true; evt.Description = " Meta ChannelPrefixOrPort " + evt.Param0; track.Add(evt); position += 4; break; case MidiEvents.META_TRACK_END: // Meta TrkEnd evt = new MidiEvent(currentTicks, meta, -1, -1); evt.isMetaEvent = true; evt.Description = " Meta TrkEnd"; track.Add(evt); track.Ticks = currentTicks; if (lastTempoTicks > -1) // there has been at least one tempo change in the track { track.Duration += (currentTicks - lastTempoTicks) * currentTempo; } else { track.Duration = currentTicks * this.tempo; } return track;//ignore rest //break; case MidiEvents.META_TEMPO: // Tempo // Adds (ticks since last tempo event)*current tempo to track duration if (lastTempoTicks > -1) { track.Duration += (currentTicks - lastTempoTicks) * currentTempo; } lastTempoTicks = currentTicks; currentTempo = data[position + 3] * 0x010000 + data[position + 4] * 0x0100 + data[position + 5]; if (0 == currentTempo) currentTempo = DEFAULT_TEMPO; evt = new MidiEvent(currentTicks, meta, -1, currentTempo); evt.isMetaEvent = true; evt.Description = " Meta Tempo " + evt.Param0 + " (duration :" + track.Duration + ")"; track.Add(evt); // Sets song tempo as last tempo event of 1st track // according to some MIDI files convention if (0 == trackNumber/* && 0 == this.tempo*/) { this.tempo = currentTempo; this.tempoMsgNum = track.events.Count - 1; } position += 6; break; case MidiEvents.META_SMPTE_OFFSET: // SMPTE offset byte h = data[position + 3]; byte m = data[position + 4]; byte s = data[position + 5]; byte f = data[position + 6]; byte fh = data[position + 7]; // TODO : store the arguments in a solid structure within MidiEvent evt = new MidiEvent(currentTicks, meta, -1, -1); evt.isMetaEvent = true; evt.Description = " Meta SMPTE " + h + " " + m + " " + s + " " + f + " " + fh; track.Add(evt); position += 8; break; case MidiEvents.META_TIME_SIGNATURE: // TimeSig byte z = data[position + 3]; int t = 2 ^ data[position + 4]; byte mc = data[position + 5]; c = data[position + 6]; // TODO : store the arguments in a solid structure within MidiEvent evt = new MidiEvent(currentTicks, meta, -1, -1); evt.isMetaEvent = true; evt.Description = " Meta TimeSig " + z + "/" + t + " " + mc + " " + c; track.Add(evt); position += 7; break; case MidiEvents.META_KEY_SIGNATURE: // KeySig evt = new MidiEvent(currentTicks, meta, -1, data[position + 3], data[position + 4]); evt.isMetaEvent = true; evt.Description = " Meta KeySig vz=" + evt.Param0 + " " + (evt.Param1 == 0 ? "major" : "minor"); track.Add(evt); position += 5; break; case MidiEvents.META_SEQUENCER_DATA: // Sequencer specific data position += 2; len = readVarLen(ref data, ref position); if ((len + position) > trackLen) throw new Exception("SeqSpec has corrupt variable length field (" + len + ") [track: " + trackNumber + " dt: " + currentDelta + "]"); position -= 3; { //String str = Encoding.ASCII.GetString(data, position + 3, len); //data.=' '.sprintf("%02x",(byte)($data[$p+3+$i])); evt = new MidiEvent(currentTicks, meta, -1, currentTempo); evt.isMetaEvent = true; evt.Description = " Meta SeqSpec"; track.Add(evt); } position += len + 3; break; default: // "unknown" Meta-Events byte metacode = data[position + 1]; position += 2; len = readVarLen(ref data, ref position); if ((len + position) > trackLen) throw new Exception("Meta " + metacode + " has corrupt variable length field (" + len + ") [track: " + trackNumber + " dt: " + currentDelta + "]"); position -= 3; { String str = Encoding.ASCII.GetString(data, position + 3, len); //sprintf("%02x",(byte)($data[$p+3+$i])); evt = new MidiEvent(currentTicks, meta, -1, currentTempo); evt.isMetaEvent = true; evt.Description = " Meta 0x" + metacode + " " + str; track.Add(evt); } position += len + 3; break; } // switch meta break; // End Meta case MidiEvents.EVT_SYSEX: // SysEx position += 1; len = readVarLen(ref data, ref position); if ((len + position) > trackLen) throw new Exception("SysEx has corrupt variable length field (" + len + ") [track: " + trackNumber + " dt: " + currentDelta + " p: " + position + "]"); { //String str = "f0" + Encoding.ASCII.GetString(data, position + 2, len); //str+=' '.sprintf("%02x",(byte)(data[p+2+i])); evt = new MidiEvent(currentTicks, eventTypeHigh, -1, currentTempo); evt.isMetaEvent = true; evt.Description = " SysEx"; track.Add(evt); } position += len; break; default: // Repetition of last event? if ((track.LastEvent.Type == MidiEvents.EVT_NOTE_ON) || (track.LastEvent.Type == MidiEvents.EVT_NOTE_OFF)) { evt = new MidiEvent(currentTicks, track.LastEvent.Type, track.LastEvent.Channel, data[position], data[position + 1]); evt.Description = " " + (track.LastEvent.Type == MidiEvents.EVT_NOTE_ON ? "On" : "Off") + " ch=" + evt.Channel + " n=" + evt.Param0 + " v=" + evt.Param1; track.Add(evt); position += 2; } else if (track.LastEvent.Type == MidiEvents.EVT_PROGRAM_CHANGE) { evt = new MidiEvent(currentTicks, track.LastEvent.Type, track.LastEvent.Channel, data[position]); evt.Description = " PrCh ch=" + evt.Channel + " p=" + evt.Param0; track.Add(evt); position += 1; } else if (track.LastEvent.Type == MidiEvents.EVT_POLY_PRESSURE) { evt = new MidiEvent(currentTicks, track.LastEvent.Type, track.LastEvent.Channel, data[position + 1], data[position + 2]); evt.Description = " PoPr ch=" + evt.Channel + " n=" + evt.Param0 + " v=" + evt.Param1; track.Add(evt); position += 2; } else if (track.LastEvent.Type == MidiEvents.EVT_CHANNEL_PRESSURE) { evt = new MidiEvent(currentTicks, track.LastEvent.Type, track.LastEvent.Channel, data[position]); evt.Description = " ChPr ch=" + evt.Channel + " v=" + evt.Param0; track.Add(evt); position += 1; } else if (track.LastEvent.Type == MidiEvents.EVT_CONTROLLER_CHANGE) { evt = new MidiEvent(currentTicks, track.LastEvent.Type, track.LastEvent.Channel, data[position], data[position + 1]); evt.Description = " Par ch=" + evt.Channel + " c=" + evt.Param0 + " v=" + evt.Param1; track.Add(evt); position += 2; } else if (track.LastEvent.Type == MidiEvents.EVT_PITCH_BEND) { evt = new MidiEvent(currentTicks, track.LastEvent.Type, track.LastEvent.Channel, (data[position] & 0x7F) | ((data[position + 1] & 0x7F) << 7)); evt.Description = " Pb ch=" + evt.Channel + " v=" + evt.Param0; track.Add(evt); position += 2; } //default: // MM: ToDo: Repetition of SysEx and META-events? with <last>?? \n"; // _err("unknown repetition: $last"); break; } // switch (eventType) break; } // switch ($high) } // while ( p < trackLen ) track.Ticks = currentTicks; if (lastTempoTicks > -1) { track.Duration += (currentTicks - lastTempoTicks) * currentTempo; } else { track.Duration = currentTicks * this.tempo; } return track; } //--------------------------------------------------------------- // variable length string to int (+repositioning) //--------------------------------------------------------------- //# TO LOOK AFTER CAREFULLY <.< private int readVarLen(ref byte[] data, ref int pos) { int value; int c; value = data[pos++]; if ((value & 0x80) != 0) { value &= 0x7F; do { c = data[pos++]; value = (value << 7) + (c & 0x7F); } while ((c & 0x80) != 0); } return (value); } protected override int write(TagData tag, BinaryWriter w, string zone) { // Not implemented, as it would require a whole new set of metadata related to tracks and their names return 0; } } }
#region License /* ********************************************************************************** * Copyright (c) Roman Ivantsov * This source code is subject to terms and conditions of the MIT License * for Irony. A copy of the license can be found in the License.txt file * at the root of this distribution. * By using this source code in any fashion, you are agreeing to be bound by the terms of the * MIT License. * You must not remove this notice from this software. * **********************************************************************************/ #endregion using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Reflection; namespace Irony.Parsing { [Flags] public enum TermFlags { None = 0, IsOperator = 0x01, IsOpenBrace = 0x02, IsCloseBrace = 0x04, IsBrace = IsOpenBrace | IsCloseBrace, IsLiteral = 0x08, IsConstant = 0x10, IsPunctuation = 0x20, IsDelimiter = 0x40, IsReservedWord = 0x080, IsMemberSelect = 0x100, IsNonScanner = 0x01000, // indicates that tokens for this terminal are NOT produced by scanner IsNonGrammar = 0x02000, // if set, parser would eliminate the token from the input stream; terms in Grammar.NonGrammarTerminals have this flag set IsTransient = 0x04000, // Transient non-terminal - should be replaced by it's child in the AST tree. IsNotReported = 0x08000, // Exclude from expected terminals list on syntax error //calculated flags IsNullable = 0x010000, IsVisible = 0x020000, IsKeyword = 0x040000, IsMultiline = 0x100000, //internal flags IsList = 0x200000, IsListContainer = 0x400000, //Indicates not to create AST node; mainly to suppress warning message on some special nodes that AST node type is not specified //Automatically set by MarkTransient method NoAstNode = 0x800000, } public delegate void AstNodeCreator(ParsingContext context, ParseTreeNode parseNode); //Basic Backus-Naur Form element. Base class for Terminal, NonTerminal, BnfExpression, GrammarHint public abstract class BnfTerm { #region consructors public BnfTerm(string name) : this(name, name) { } public BnfTerm(string name, string errorAlias) { Name = name; ErrorAlias = errorAlias; } public BnfTerm(string name, string errorAlias, Type nodeType) : this(name, errorAlias) { AstNodeType = nodeType; } public BnfTerm(string name, string errorAlias, AstNodeCreator nodeCreator) : this(name, errorAlias) { AstNodeCreator = nodeCreator; } #endregion #region virtuals and overrides public virtual void Init(GrammarData grammarData) { GrammarData = grammarData; } public virtual string GetParseNodeCaption(ParseTreeNode node) { if (GrammarData != null) return GrammarData.Grammar.GetParseNodeCaption(node); else return Name; } public override string ToString() { return Name; } public override int GetHashCode() { if (Name == null) return 0; return Name.GetHashCode(); } #endregion public const int NoPrecedence = 0; #region properties: Name, DisplayName, Key, Options public string Name; //ErrorAlias is used in error reporting, e.g. "Syntax error, expected <list-of-display-names>". public string ErrorAlias; public TermFlags Flags; protected GrammarData GrammarData; public int Precedence = NoPrecedence; public Associativity Associativity = Associativity.Neutral; public Grammar Grammar { get { return GrammarData.Grammar; } } public void SetFlag(TermFlags flag) { SetFlag(flag, true); } public void SetFlag(TermFlags flag, bool value) { if (value) Flags |= flag; else Flags &= ~flag; } #endregion #region AST node creations: AstNodeType, AstNodeCreator, AstNodeCreated /* -- new stuff public Ast.AstNodeConfig AstConfig { get { if (_astConfig == null) _astConfig = new Ast.AstNodeConfig(); return _astConfig; } set {_astConfig = value; } } Ast.AstNodeConfig _astConfig; */ public Type AstNodeType; public object AstData; //config data passed to AstNode public AstNodeCreator AstNodeCreator; // a custom method for creating AST nodes public event EventHandler<AstNodeEventArgs> AstNodeCreated; //an event signalling that AST node is created. // An optional map (selector, filter) of child AST nodes. This facility provides a way to adjust the "map" of child nodes in various languages to // the structure of a standard AST nodes (that can be shared betweeen languages). // ParseTreeNode object has two properties containing list nodes: ChildNodes and MappedChildNodes. // If term.AstPartsMap is null, these two child node lists are identical and contain all child nodes. // If AstParts is not null, then MappedChildNodes will contain child nodes identified by indexes in the map. // For example, if we set // term.AstPartsMap = new int[] {1, 4, 2}; // then MappedChildNodes will contain 3 child nodes, which are under indexes 1, 4, 2 in ChildNodes list. // The mapping is performed in CoreParser.cs, method CheckCreateMappedChildNodeList. public int[] AstPartsMap; public virtual void CreateAstNode(ParsingContext context, ParseTreeNode parseTreeNode) { //First check the custom creator delegate if (AstNodeCreator != null) { AstNodeCreator(context, parseTreeNode); // We assume that Node creator method creates node and initializes it, so parser does not need to call // IAstNodeInit.Init() method on node object. return; } Type nodeType = GetAstNodeType(context, parseTreeNode); if (nodeType == null) return; //we give a warning on grammar validation about this situation parseTreeNode.AstNode = Activator.CreateInstance(nodeType); //Initialize node var iInit = parseTreeNode.AstNode as IAstNodeInit; if (iInit != null) iInit.Init(context, parseTreeNode); } //method may be overriden to provide node type different from this.AstNodeType. StringLiteral is overriding this method // to use different node type for template strings protected virtual Type GetAstNodeType(ParsingContext context, ParseTreeNode nodeInfo) { return AstNodeType ?? Grammar.DefaultNodeType; } protected internal void OnAstNodeCreated(ParseTreeNode parseNode) { if (this.AstNodeCreated == null || parseNode.AstNode == null) return; AstNodeEventArgs args = new AstNodeEventArgs(parseNode); AstNodeCreated(this, args); } #endregion #region Kleene operators: Q(), Plus(), Star() NonTerminal _q, _plus, _star; //cash them public BnfExpression Q() { if (_q != null) return _q; _q = new NonTerminal(this.Name + "?"); _q.Rule = this | Grammar.CurrentGrammar.Empty; return _q; } [Obsolete("This method is obsolete, use Grammar.MakePlusRule or MakeStarRule instead.")] public NonTerminal Plus() { if (_plus != null) return _plus; _plus = new NonTerminal(this.Name + "+"); _plus.Rule = Grammar.MakePlusRule(_plus, this); return _plus; } [Obsolete("This method is obsolete, use Grammar.MakePlusRule or MakeStarRule instead.")] public NonTerminal Star() { if (_star != null) return _star; _star = new NonTerminal(this.Name + "*"); _star.Rule = Grammar.MakeStarRule(_star, this); return _star; } #endregion #region Operators: +, |, implicit public static BnfExpression operator +(BnfTerm term1, BnfTerm term2) { return Op_Plus(term1, term2); } public static BnfExpression operator +(BnfTerm term1, string symbol2) { return Op_Plus(term1, Grammar.CurrentGrammar.ToTerm(symbol2)); } public static BnfExpression operator +( string symbol1, BnfTerm term2) { return Op_Plus(Grammar.CurrentGrammar.ToTerm(symbol1), term2); } //Alternative public static BnfExpression operator |(BnfTerm term1, BnfTerm term2) { return Op_Pipe(term1, term2); } public static BnfExpression operator |(BnfTerm term1, string symbol2) { return Op_Pipe(term1, Grammar.CurrentGrammar.ToTerm(symbol2)); } public static BnfExpression operator |(string symbol1, BnfTerm term2) { return Op_Pipe(Grammar.CurrentGrammar.ToTerm(symbol1), term2); } //BNF operations implementation ----------------------- // Plus/sequence internal static BnfExpression Op_Plus(BnfTerm term1, BnfTerm term2) { //Check term1 and see if we can use it as result, simply adding term2 as operand BnfExpression expr1 = term1 as BnfExpression; if (expr1 == null || expr1.Data.Count > 1) //either not expression at all, or Pipe-type expression (count > 1) expr1 = new BnfExpression(term1); expr1.Data[expr1.Data.Count - 1].Add(term2); return expr1; } //Pipe/Alternative //New version proposed by the codeplex user bdaugherty internal static BnfExpression Op_Pipe(BnfTerm term1, BnfTerm term2) { BnfExpression expr1 = term1 as BnfExpression; if (expr1 == null) expr1 = new BnfExpression(term1); BnfExpression expr2 = term2 as BnfExpression; if (expr2 == null) expr2 = new BnfExpression(term2); expr1.Data.AddRange(expr2.Data); return expr1; } #endregion }//class public class BnfTermList : List<BnfTerm> { } public class BnfTermSet : HashSet<BnfTerm> { } public class AstNodeEventArgs : EventArgs { public AstNodeEventArgs(ParseTreeNode parseTreeNode) { ParseTreeNode = parseTreeNode; } public readonly ParseTreeNode ParseTreeNode; public object AstNode { get { return ParseTreeNode.AstNode; } } } }//namespace
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Text; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Services.Interfaces; namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver { /// <summary> /// Utility methods for inventory archiving /// </summary> public static class InventoryArchiveUtils { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // Character used for escaping the path delimter ("\/") and itself ("\\") in human escaped strings public static readonly char ESCAPE_CHARACTER = '\\'; // The character used to separate inventory path components (different folders and items) public static readonly char PATH_DELIMITER = '/'; /// <summary> /// Find a folder given a PATH_DELIMITER delimited path starting from a user's root folder /// </summary> /// /// This method does not handle paths that contain multiple delimitors /// /// FIXME: We have no way of distinguishing folders with the same path /// /// FIXME: Delimitors which occur in names themselves are not currently escapable. /// /// <param name="inventoryService"> /// Inventory service to query /// </param> /// <param name="userId"> /// User id to search /// </param> /// <param name="path"> /// The path to the required folder. /// It this is empty or consists only of the PATH_DELIMTER then this folder itself is returned. /// </param> /// <returns>An empty list if the folder is not found, otherwise a list of all folders that match the name</returns> public static List<InventoryFolderBase> FindFolderByPath( IInventoryService inventoryService, UUID userId, string path) { InventoryFolderBase rootFolder = inventoryService.GetRootFolder(userId); if (null == rootFolder) return new List<InventoryFolderBase>(); return FindFolderByPath(inventoryService, rootFolder, path); } /// <summary> /// Find a folder given a PATH_DELIMITER delimited path starting from this folder /// </summary> /// /// This method does not handle paths that contain multiple delimitors /// /// FIXME: We have no way of distinguishing folders with the same path. /// /// FIXME: Delimitors which occur in names themselves are not currently escapable. /// /// <param name="inventoryService"> /// Inventory service to query /// </param> /// <param name="startFolder"> /// The folder from which the path starts /// </param> /// <param name="path"> /// The path to the required folder. /// It this is empty or consists only of the PATH_DELIMTER then this folder itself is returned. /// </param> /// <returns>An empty list if the folder is not found, otherwise a list of all folders that match the name</returns> public static List<InventoryFolderBase> FindFolderByPath( IInventoryService inventoryService, InventoryFolderBase startFolder, string path) { List<InventoryFolderBase> foundFolders = new List<InventoryFolderBase>(); if (path == string.Empty) { foundFolders.Add(startFolder); return foundFolders; } path = path.Trim(); if (path == PATH_DELIMITER.ToString()) { foundFolders.Add(startFolder); return foundFolders; } // If the path isn't just / then trim any starting extraneous slashes path = path.TrimStart(new char[] { PATH_DELIMITER }); // m_log.DebugFormat("[INVENTORY ARCHIVE UTILS]: Adjusted path in FindFolderByPath() is [{0}]", path); string[] components = SplitEscapedPath(path); components[0] = UnescapePath(components[0]); //string[] components = path.Split(new string[] { PATH_DELIMITER.ToString() }, 2, StringSplitOptions.None); InventoryCollection contents = inventoryService.GetFolderContent(startFolder.Owner, startFolder.ID); foreach (InventoryFolderBase folder in contents.Folders) { if (folder.Name == components[0]) { if (components.Length > 1) foundFolders.AddRange(FindFolderByPath(inventoryService, folder, components[1])); else foundFolders.Add(folder); } } return foundFolders; } /// <summary> /// Find an item given a PATH_DELIMITOR delimited path starting from the user's root folder. /// /// This method does not handle paths that contain multiple delimitors /// /// FIXME: We do not yet handle situations where folders or items have the same name. We could handle this by some /// XPath like expression /// /// FIXME: Delimitors which occur in names themselves are not currently escapable. /// </summary> /// /// <param name="inventoryService"> /// Inventory service to query /// </param> /// <param name="userId"> /// The user to search /// </param> /// <param name="path"> /// The path to the required item. /// </param> /// <returns>null if the item is not found</returns> public static InventoryItemBase FindItemByPath( IInventoryService inventoryService, UUID userId, string path) { InventoryFolderBase rootFolder = inventoryService.GetRootFolder(userId); if (null == rootFolder) return null; return FindItemByPath(inventoryService, rootFolder, path); } /// <summary> /// Find an item given a PATH_DELIMITOR delimited path starting from this folder. /// /// This method does not handle paths that contain multiple delimitors /// /// FIXME: We do not yet handle situations where folders or items have the same name. We could handle this by some /// XPath like expression /// /// FIXME: Delimitors which occur in names themselves are not currently escapable. /// </summary> /// /// <param name="inventoryService"> /// Inventory service to query /// </param> /// <param name="startFolder"> /// The folder from which the path starts /// </param> /// <param name="path"> /// <param name="path"> /// The path to the required item. /// </param> /// <returns>null if the item is not found</returns> public static InventoryItemBase FindItemByPath( IInventoryService inventoryService, InventoryFolderBase startFolder, string path) { // If the path isn't just / then trim any starting extraneous slashes path = path.TrimStart(new char[] { PATH_DELIMITER }); string[] components = SplitEscapedPath(path); components[0] = UnescapePath(components[0]); //string[] components = path.Split(new string[] { PATH_DELIMITER }, 2, StringSplitOptions.None); if (components.Length == 1) { // m_log.DebugFormat( // "FOUND SINGLE COMPONENT [{0}]. Looking for this in [{1}] {2}", // components[0], startFolder.Name, startFolder.ID); List<InventoryItemBase> items = inventoryService.GetFolderItems(startFolder.Owner, startFolder.ID); // m_log.DebugFormat("[INVENTORY ARCHIVE UTILS]: Found {0} items in FindItemByPath()", items.Count); foreach (InventoryItemBase item in items) { // m_log.DebugFormat("[INVENTORY ARCHIVE UTILS]: Inspecting item {0} {1}", item.Name, item.ID); if (item.Name == components[0]) return item; } } else { // m_log.DebugFormat("FOUND COMPONENTS [{0}] and [{1}]", components[0], components[1]); InventoryCollection contents = inventoryService.GetFolderContent(startFolder.Owner, startFolder.ID); foreach (InventoryFolderBase folder in contents.Folders) { if (folder.Name == components[0]) return FindItemByPath(inventoryService, folder, components[1]); } } // We didn't find an item or intermediate folder with the given name return null; } /// <summary> /// Split a human escaped path into two components if it contains an unescaped path delimiter, or one component /// if no delimiter is present /// </summary> /// <param name="path"></param> /// <returns> /// The split path. We leave the components in their originally unescaped state (though we remove the delimiter /// which originally split them if applicable). /// </returns> public static string[] SplitEscapedPath(string path) { // m_log.DebugFormat("SPLITTING PATH {0}", path); bool singleEscapeChar = false; for (int i = 0; i < path.Length; i++) { if (path[i] == ESCAPE_CHARACTER && !singleEscapeChar) { singleEscapeChar = true; } else { if (PATH_DELIMITER == path[i] && !singleEscapeChar) return new string[2] { path.Remove(i), path.Substring(i + 1) }; else singleEscapeChar = false; } } // We didn't find a delimiter return new string[1] { path }; } /// <summary> /// Unescapes a human escaped path. This means that "\\" goes to "\", and "\/" goes to "/" /// </summary> /// <param name="path"></param> /// <returns></returns> public static string UnescapePath(string path) { // m_log.DebugFormat("ESCAPING PATH {0}", path); StringBuilder sb = new StringBuilder(); bool singleEscapeChar = false; for (int i = 0; i < path.Length; i++) { if (path[i] == ESCAPE_CHARACTER && !singleEscapeChar) singleEscapeChar = true; else singleEscapeChar = false; if (singleEscapeChar) { if (PATH_DELIMITER == path[i]) sb.Append(PATH_DELIMITER); } else { sb.Append(path[i]); } } // m_log.DebugFormat("ESCAPED PATH TO {0}", sb); return sb.ToString(); } /// <summary> /// Escape an archive path. /// </summary> /// This has to be done differently from human paths because we can't leave in any "/" characters (due to /// problems if the archive is built from or extracted to a filesystem /// <param name="path"></param> /// <returns></returns> public static string EscapeArchivePath(string path) { // Only encode ampersands (for escaping anything) and / (since this is used as general dir separator). return path.Replace("&", "&amp;").Replace("/", "&#47;"); } /// <summary> /// Unescape an archive path. /// </summary> /// <param name="path"></param> /// <returns></returns> public static string UnescapeArchivePath(string path) { return path.Replace("&#47;", "/").Replace("&amp;", "&"); } } }
using System; using System.IO; using System.Text; using System.Collections.Generic; using KaoriStudio.Core.Text.Parsing; namespace KaoriStudio.Core.Text.Serializers { public partial class UDMFSerializer { /// <summary> /// The UDMF lexer /// </summary> /// <param name="source">The source stream</param> /// <param name="inpos">The token position</param> /// <returns>A stream of tokens</returns> public static IEnumerable<Token<UDMFToken>> Lexer(TextReader source, TokenPosition inpos) { int state = 0; StringBuilder buffer = new StringBuilder(); TokenPosition pos = default(TokenPosition); int code = 0; int input; do { input = source.Read(); if (input == '\n') { inpos.Column = 1; inpos.Line++; } switch (state) { #region "/(0)" case 0: switch (input) { case -1: case '\t': case '\n': case '\r': case ' ': break; case '/': state = 14; break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': pos = inpos; buffer.Clear(); buffer.Append((char)input); state = 1; break; case '0': pos = inpos; buffer.Clear(); buffer.Append('0'); state = 2; break; case '+': case '-': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': pos = inpos; buffer.Clear(); buffer.Append((char)input); state = 4; break; case ';': yield return new Token<UDMFToken>(UDMFToken.Terminator, ";", inpos); break; case '=': yield return new Token<UDMFToken>(UDMFToken.Assignment, "=", inpos); break; case '{': yield return new Token<UDMFToken>(UDMFToken.OpenBlock, "{", inpos); break; case '}': yield return new Token<UDMFToken>(UDMFToken.CloseBlock, "}", inpos); break; case '"': pos = inpos; buffer.Clear(); state = 6; break; default: throw new TextDeserializationException(UnexpectedCharacter(state, input), source, inpos); } break; #endregion #region "/Identifier(1)" case 1: switch (input) { case -1: case '\t': case '\n': case '\r': case ' ': yield return new Token<UDMFToken>(UDMFToken.Identifier, buffer.ToString(), pos); state = 0; break; case '/': yield return new Token<UDMFToken>(UDMFToken.Identifier, buffer.ToString(), pos); state = 14; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': buffer.Append((char)input); break; case '+': case '-': yield return new Token<UDMFToken>(UDMFToken.Identifier, buffer.ToString(), pos); pos = inpos; buffer.Clear(); buffer.Append((char)input); state = 4; break; case ';': yield return new Token<UDMFToken>(UDMFToken.Identifier, buffer.ToString(), pos); yield return new Token<UDMFToken>(UDMFToken.Terminator, ";", inpos); state = 0; break; case '=': yield return new Token<UDMFToken>(UDMFToken.Identifier, buffer.ToString(), pos); yield return new Token<UDMFToken>(UDMFToken.Assignment, "=", inpos); state = 0; break; case '{': yield return new Token<UDMFToken>(UDMFToken.Identifier, buffer.ToString(), pos); yield return new Token<UDMFToken>(UDMFToken.OpenBlock, "{", inpos); state = 0; break; case '}': yield return new Token<UDMFToken>(UDMFToken.Identifier, buffer.ToString(), pos); yield return new Token<UDMFToken>(UDMFToken.CloseBlock, "}", inpos); state = 0; break; case '"': yield return new Token<UDMFToken>(UDMFToken.Identifier, buffer.ToString(), pos); pos = inpos; buffer.Clear(); state = 6; break; default: throw new TextDeserializationException(UnexpectedCharacter(state, input), source, inpos); } break; #endregion #region "/Zero(2)" case 2: switch (input) { case -1: case '\t': case '\n': case '\r': case ' ': yield return new Token<UDMFToken>(UDMFToken.Integer, buffer.ToString(), pos); state = 0; break; case '/': yield return new Token<UDMFToken>(UDMFToken.Integer, buffer.ToString(), pos); state = 14; break; case 'x': buffer.Append('x'); state = 3; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': buffer.Append((char)input); break; case '+': case '-': yield return new Token<UDMFToken>(UDMFToken.Integer, buffer.ToString(), pos); pos = inpos; buffer.Clear(); buffer.Append((char)input); state = 4; break; case ';': yield return new Token<UDMFToken>(UDMFToken.Integer, buffer.ToString(), pos); yield return new Token<UDMFToken>(UDMFToken.Terminator, ";", inpos); state = 0; break; case '=': yield return new Token<UDMFToken>(UDMFToken.Integer, buffer.ToString(), pos); yield return new Token<UDMFToken>(UDMFToken.Assignment, "=", inpos); state = 0; break; case '{': yield return new Token<UDMFToken>(UDMFToken.Integer, buffer.ToString(), pos); yield return new Token<UDMFToken>(UDMFToken.OpenBlock, "{", inpos); state = 0; break; case '}': yield return new Token<UDMFToken>(UDMFToken.Integer, buffer.ToString(), pos); yield return new Token<UDMFToken>(UDMFToken.CloseBlock, "}", inpos); state = 0; break; case '"': yield return new Token<UDMFToken>(UDMFToken.Integer, buffer.ToString(), pos); pos = inpos; buffer.Clear(); state = 6; break; case '.': buffer.Append('.'); state = 5; break; default: throw new TextDeserializationException(UnexpectedCharacter(state, input), source, inpos); } break; #endregion #region "/Hexadecimal(3)" case 3: switch (input) { case -1: case '\t': case '\n': case '\r': case ' ': yield return new Token<UDMFToken>(UDMFToken.Integer, buffer.ToString(), pos); state = 0; break; case '/': yield return new Token<UDMFToken>(UDMFToken.Integer, buffer.ToString(), pos); state = 0; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': buffer.Append((char)input); break; case '+': case '-': yield return new Token<UDMFToken>(UDMFToken.Identifier, buffer.ToString(), pos); pos = inpos; buffer.Clear(); buffer.Append((char)input); state = 4; break; case ';': yield return new Token<UDMFToken>(UDMFToken.Integer, buffer.ToString(), pos); yield return new Token<UDMFToken>(UDMFToken.Terminator, ";", inpos); state = 0; break; case '=': yield return new Token<UDMFToken>(UDMFToken.Integer, buffer.ToString(), pos); yield return new Token<UDMFToken>(UDMFToken.Assignment, "=", inpos); state = 0; break; case '{': yield return new Token<UDMFToken>(UDMFToken.Integer, buffer.ToString(), pos); yield return new Token<UDMFToken>(UDMFToken.OpenBlock, "{", inpos); state = 0; break; case '}': yield return new Token<UDMFToken>(UDMFToken.Integer, buffer.ToString(), pos); yield return new Token<UDMFToken>(UDMFToken.CloseBlock, "}", inpos); state = 0; break; case '"': yield return new Token<UDMFToken>(UDMFToken.Integer, buffer.ToString(), pos); pos = inpos; buffer.Clear(); state = 6; break; default: throw new TextDeserializationException(UnexpectedCharacter(state, input), source, inpos); } break; #endregion #region "/Integer(4)" case 4: switch (input) { case -1: case '\t': case '\n': case '\r': case ' ': yield return new Token<UDMFToken>(UDMFToken.Integer, buffer.ToString(), pos); state = 0; break; case '/': yield return new Token<UDMFToken>(UDMFToken.Integer, buffer.ToString(), pos); state = 14; break; case '.': case 'E': case 'e': buffer.Append((char)input); state = 5; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': buffer.Append((char)input); break; case ';': yield return new Token<UDMFToken>(UDMFToken.Integer, buffer.ToString(), pos); yield return new Token<UDMFToken>(UDMFToken.Terminator, ";", inpos); state = 0; break; case '=': yield return new Token<UDMFToken>(UDMFToken.Integer, buffer.ToString(), pos); yield return new Token<UDMFToken>(UDMFToken.Assignment, "=", inpos); state = 0; break; case '{': yield return new Token<UDMFToken>(UDMFToken.Integer, buffer.ToString(), pos); yield return new Token<UDMFToken>(UDMFToken.OpenBlock, "{", inpos); state = 0; break; case '}': yield return new Token<UDMFToken>(UDMFToken.Integer, buffer.ToString(), pos); yield return new Token<UDMFToken>(UDMFToken.CloseBlock, "}", inpos); state = 0; break; case '"': yield return new Token<UDMFToken>(UDMFToken.Integer, buffer.ToString(), pos); pos = inpos; buffer.Clear(); state = 6; break; default: throw new TextDeserializationException(UnexpectedCharacter(state, input), source, inpos); } break; #endregion #region "/Decimal(5)" case 5: switch (input) { case -1: case '\t': case '\n': case '\r': case ' ': yield return new Token<UDMFToken>(UDMFToken.Decimal, buffer.ToString(), pos); state = 0; break; case '/': yield return new Token<UDMFToken>(UDMFToken.Decimal, buffer.ToString(), pos); state = 14; break; case '+': case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'E': case 'e': buffer.Append((char)input); break; case ';': yield return new Token<UDMFToken>(UDMFToken.Decimal, buffer.ToString(), pos); yield return new Token<UDMFToken>(UDMFToken.Terminator, ";", inpos); state = 0; break; case '=': yield return new Token<UDMFToken>(UDMFToken.Decimal, buffer.ToString(), pos); yield return new Token<UDMFToken>(UDMFToken.Assignment, "=", inpos); state = 0; break; case '{': yield return new Token<UDMFToken>(UDMFToken.Decimal, buffer.ToString(), pos); yield return new Token<UDMFToken>(UDMFToken.OpenBlock, "{", inpos); state = 0; break; case '}': yield return new Token<UDMFToken>(UDMFToken.Decimal, buffer.ToString(), pos); yield return new Token<UDMFToken>(UDMFToken.CloseBlock, "}", inpos); state = 0; break; case '"': yield return new Token<UDMFToken>(UDMFToken.Decimal, buffer.ToString(), pos); pos = inpos; buffer.Clear(); state = 6; break; default: throw new TextDeserializationException(UnexpectedCharacter(state, input), source, inpos); } break; #endregion #region "/Literal(6)" case 6: switch (input) { case '"': yield return new Token<UDMFToken>(UDMFToken.Literal, buffer.ToString(), pos); state = 0; break; case '\\': state = 7; break; default: buffer.Append((char)input); break; } break; #endregion #region "/Literal/Escape(7)" case 7: switch (input) { case '0': code = 0; state = 8; break; case '1': code = 1; state = 8; break; case '2': code = 2; state = 8; break; case '3': code = 3; state = 8; break; case '4': code = 4; state = 8; break; case '5': code = 5; state = 8; break; case '6': code = 6; state = 8; break; case '7': code = 7; state = 8; break; case 'x': code = 0; state = 12; break; case 'r': buffer.Append('\r'); state = 6; break; case 'n': buffer.Append('\n'); state = 6; break; case 't': buffer.Append('\t'); state = 6; break; case 'b': buffer.Append((char)8); state = 6; break; case 'f': buffer.Append((char)12); state = 6; break; case 'u': code = 0; state = 10; break; case '"': case '\\': buffer.Append((char)input); state = 6; break; default: throw new TextDeserializationException(UnexpectedCharacter(state, input), source, inpos); } break; #endregion #region "/Literal/Octal1(8)" case 8: switch (input) { case '"': buffer.Append((char)code); yield return new Token<UDMFToken>(UDMFToken.Literal, buffer.ToString(), pos); state = 0; break; case '0': code = (code << 3) | 0; state = 9; break; case '1': code = (code << 3) | 1; state = 9; break; case '2': code = (code << 3) | 2; state = 9; break; case '3': code = (code << 3) | 3; state = 9; break; case '4': code = (code << 3) | 4; state = 9; break; case '5': code = (code << 3) | 5; state = 9; break; case '6': code = (code << 3) | 6; state = 9; break; case '7': code = (code << 3) | 7; state = 9; break; default: buffer.Append((char)code); buffer.Append((char)input); state = 6; break; } break; #endregion #region "/Literal/Octal2(9)" case 9: switch (input) { case '"': buffer.Append((char)code); yield return new Token<UDMFToken>(UDMFToken.Literal, buffer.ToString(), pos); state = 0; break; case '0': code = (code << 3) | 0; buffer.Append((char)code); state = 6; break; case '1': code = (code << 3) | 1; buffer.Append((char)code); state = 6; break; case '2': code = (code << 3) | 2; buffer.Append((char)code); state = 6; break; case '3': code = (code << 3) | 3; buffer.Append((char)code); state = 6; break; case '4': code = (code << 3) | 4; buffer.Append((char)code); state = 6; break; case '5': code = (code << 3) | 5; buffer.Append((char)code); state = 6; break; case '6': code = (code << 3) | 6; buffer.Append((char)code); state = 6; break; case '7': code = (code << 3) | 7; buffer.Append((char)code); state = 6; break; default: buffer.Append((char)code); buffer.Append((char)input); state = 6; break; } break; #endregion #region "/Literal/Unicode0(10)" case 10: switch (input) { case '"': buffer.Append((char)code); yield return new Token<UDMFToken>(UDMFToken.Literal, buffer.ToString(), pos); state = 0; break; case '0': code = (code << 4) | 0; state = 11; break; case '1': code = (code << 4) | 1; state = 11; break; case '2': code = (code << 4) | 2; state = 11; break; case '3': code = (code << 4) | 3; state = 11; break; case '4': code = (code << 4) | 4; state = 11; break; case '5': code = (code << 4) | 5; state = 11; break; case '6': code = (code << 4) | 6; state = 11; break; case '7': code = (code << 4) | 7; state = 11; break; case '8': code = (code << 4) | 8; state = 11; break; case '9': code = (code << 4) | 9; state = 11; break; case 'A': case 'a': code = (code << 4) | 10; state = 11; break; case 'B': case 'b': code = (code << 4) | 11; state = 11; break; case 'C': case 'c': code = (code << 4) | 12; state = 11; break; case 'D': case 'd': code = (code << 4) | 13; state = 11; break; case 'E': case 'e': code = (code << 4) | 14; state = 11; break; case 'F': case 'f': code = (code << 4) | 15; state = 11; break; default: buffer.Append((char)code); buffer.Append((char)input); state = 6; break; } break; #endregion #region "/Literal/Unicode1(11)" case 11: switch (input) { case '"': buffer.Append((char)code); yield return new Token<UDMFToken>(UDMFToken.Literal, buffer.ToString(), pos); state = 0; break; case '0': code = (code << 4) | 0; state = 12; break; case '1': code = (code << 4) | 1; state = 12; break; case '2': code = (code << 4) | 2; state = 12; break; case '3': code = (code << 4) | 3; state = 12; break; case '4': code = (code << 4) | 4; state = 12; break; case '5': code = (code << 4) | 5; state = 12; break; case '6': code = (code << 4) | 6; state = 12; break; case '7': code = (code << 4) | 7; state = 12; break; case '8': code = (code << 4) | 8; state = 12; break; case '9': code = (code << 4) | 9; state = 12; break; case 'A': case 'a': code = (code << 4) | 10; state = 12; break; case 'B': case 'b': code = (code << 4) | 11; state = 12; break; case 'C': case 'c': code = (code << 4) | 12; state = 12; break; case 'D': case 'd': code = (code << 4) | 13; state = 12; break; case 'E': case 'e': code = (code << 4) | 14; state = 12; break; case 'F': case 'f': code = (code << 4) | 15; state = 12; break; default: buffer.Append((char)code); buffer.Append((char)input); state = 6; break; } break; #endregion #region "/Literal/Unicode2(12)" case 12: switch (input) { case '"': buffer.Append((char)code); yield return new Token<UDMFToken>(UDMFToken.Literal, buffer.ToString(), pos); state = 0; break; case '0': code = (code << 4) | 0; state = 13; break; case '1': code = (code << 4) | 1; state = 13; break; case '2': code = (code << 4) | 2; state = 13; break; case '3': code = (code << 4) | 3; state = 13; break; case '4': code = (code << 4) | 4; state = 13; break; case '5': code = (code << 4) | 5; state = 13; break; case '6': code = (code << 4) | 6; state = 13; break; case '7': code = (code << 4) | 7; state = 13; break; case '8': code = (code << 4) | 8; state = 13; break; case '9': code = (code << 4) | 9; state = 13; break; case 'A': case 'a': code = (code << 4) | 10; state = 13; break; case 'B': case 'b': code = (code << 4) | 11; state = 13; break; case 'C': case 'c': code = (code << 4) | 12; state = 13; break; case 'D': case 'd': code = (code << 4) | 13; state = 13; break; case 'E': case 'e': code = (code << 4) | 14; state = 13; break; case 'F': case 'f': code = (code << 4) | 15; state = 13; break; default: buffer.Append((char)code); buffer.Append((char)input); state = 6; break; } break; #endregion #region "/Literal/Unicode3(13)" case 13: switch (input) { case '"': buffer.Append((char)code); yield return new Token<UDMFToken>(UDMFToken.Literal, buffer.ToString(), pos); state = 0; break; case '0': code = (code << 4) | 0; buffer.Append((char)code); state = 6; break; case '1': code = (code << 4) | 1; buffer.Append((char)code); state = 6; break; case '2': code = (code << 4) | 2; buffer.Append((char)code); state = 6; break; case '3': code = (code << 4) | 3; buffer.Append((char)code); state = 6; break; case '4': code = (code << 4) | 4; buffer.Append((char)code); state = 6; break; case '5': code = (code << 4) | 5; buffer.Append((char)code); state = 6; break; case '6': code = (code << 4) | 6; buffer.Append((char)code); state = 6; break; case '7': code = (code << 4) | 7; buffer.Append((char)code); state = 6; break; case '8': code = (code << 4) | 8; buffer.Append((char)code); state = 6; break; case '9': code = (code << 4) | 9; buffer.Append((char)code); state = 6; break; case 'A': case 'a': code = (code << 4) | 10; buffer.Append((char)code); state = 6; break; case 'B': case 'b': code = (code << 4) | 11; buffer.Append((char)code); state = 6; break; case 'C': case 'c': code = (code << 4) | 12; buffer.Append((char)code); state = 6; break; case 'D': case 'd': code = (code << 4) | 13; buffer.Append((char)code); state = 6; break; case 'E': case 'e': code = (code << 4) | 14; buffer.Append((char)code); state = 6; break; case 'F': case 'f': code = (code << 4) | 15; buffer.Append((char)code); state = 6; break; default: buffer.Append((char)code); buffer.Append((char)input); state = 6; break; } break; #endregion #region "/Comment(14)" case 14: switch (input) { case '*': state = 15; break; case '/': state = 17; break; default: throw new TextDeserializationException(UnexpectedCharacter(state, input), source, inpos); } break; #endregion #region "/Comment/Multi(15)" case 15: switch (input) { case '*': state = 16; break; } break; #endregion #region "/Comment/Multi/Leave(16)" case 16: switch (input) { case '*': break; case '/': state = 0; break; default: state = 15; break; } break; #endregion #region "/Comment/Line(17)" case 17: switch (input) { case '\n': state = 0; break; } break; #endregion default: throw new TextDeserializationException(string.Format("Unknown state number {0}", state), source, inpos); } inpos.Index++; inpos.Column++; } while (input != -1); } /// <summary> /// Lexer for UDMF /// </summary> /// <param name="source">The source reader</param> /// <returns>A stream of tokens</returns> public static IEnumerable<Token<UDMFToken>> Lexer(TextReader source) { return Lexer(source, new TokenPosition(0, 1, 1)); } private static string UnexpectedCharacter(int state, int input) { string[] states = { "/", "/Identifier", "/Zero", "/Hexadecimal", "/Integer", "/Decimal", "/Literal", "/Literal/Escape", "/Literal/Octal1", "/Literal/Octal2", "/Literal/Unicode0", "/Literal/Unicode1", "/Literal/Unicode2", "/Literal/Unicode3", "/Comment", "/Comment/Multi", "/Comment/Multi/Leave", "/Comment/Argument" }; if (input == -1) { return string.Format("Unexpected EOF in {0}({1})", states[state], state); } else { try { return string.Format("Unexpected character {0} ({1}) in {2}({3})", (char)input, input, states[state], state); } catch (InvalidCastException) { return string.Format("Unexpected character {0} in {1}({2})", input, states[state], state); } } } } }
//--------------------------------------------------------------------------- // <copyright file="DocumentSequenceTextContainer.cs" company="Microsoft"> // Copyright (C) 2004 by Microsoft Corporation. All rights reserved. // </copyright> // // Description: // DocumentSequenceTextContainer is a TextContainer that aggregates // 0 or more TextContainer and expose them as single TextContainer. // // History: // 07/14/2004 - Zhenbin Xu (ZhenbinX) - Created. // //--------------------------------------------------------------------------- #pragma warning disable 1634, 1691 // To enable presharp warning disables (#pragma suppress) below. namespace System.Windows.Documents { using MS.Internal; using MS.Internal.Documents; using System; using System.Collections; using System.Collections.Specialized; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Windows; // DependencyID etc. using System.Text; using System.Windows.Threading; // Dispatcher //===================================================================== /// <summary> /// DocumentSequenceTextContainer is a TextContainer that aggregates /// 0 or more TextContainer and expose them as single TextContainer. /// </summary> internal sealed class DocumentSequenceTextContainer : ITextContainer { //-------------------------------------------------------------------- // // Connstructors // //--------------------------------------------------------------------- #region Constructors internal DocumentSequenceTextContainer(DependencyObject parent) { Debug.Assert(parent != null); Debug.Assert(parent is FixedDocumentSequence); _parent = (FixedDocumentSequence)parent; _Initialize(); } #endregion Constructors //-------------------------------------------------------------------- // // Public Methods // //--------------------------------------------------------------------- #region Public Methods /// <summary> /// </summary> void ITextContainer.BeginChange() { _changeBlockLevel++; // We'll raise the Changing event when/if we get an actual // change added, inside AddChangeSegment. } /// <summary> /// <see cref="System.Windows.Documents.ITextContainer.BeginChangeNoUndo"/> /// </summary> void ITextContainer.BeginChangeNoUndo() { // We don't support undo, so follow the BeginChange codepath. ((ITextContainer)this).BeginChange(); } void ITextContainer.EndChange() { ((ITextContainer)this).EndChange(false /* skipEvents */); } /// <summary> /// </summary> void ITextContainer.EndChange(bool skipEvents) { TextContainerChangedEventArgs changes; Invariant.Assert(_changeBlockLevel > 0, "Unmatched EndChange call!"); _changeBlockLevel--; if (_changeBlockLevel == 0 && _changes != null) { changes = _changes; _changes = null; if (this.Changed != null && !skipEvents) { Changed(this, changes); } } } // Allocate a new ITextPointer at the specified offset. // Equivalent to this.Start.CreatePointer(offset), but does not // necessarily allocate this.Start. ITextPointer ITextContainer.CreatePointerAtOffset(int offset, LogicalDirection direction) { return ((ITextContainer)this).Start.CreatePointer(offset, direction); } // Not Implemented. ITextPointer ITextContainer.CreatePointerAtCharOffset(int charOffset, LogicalDirection direction) { throw new NotImplementedException(); } ITextPointer ITextContainer.CreateDynamicTextPointer(StaticTextPointer position, LogicalDirection direction) { return ((ITextPointer)position.Handle0).CreatePointer(direction); } StaticTextPointer ITextContainer.CreateStaticPointerAtOffset(int offset) { return new StaticTextPointer(this, ((ITextContainer)this).CreatePointerAtOffset(offset, LogicalDirection.Forward)); } TextPointerContext ITextContainer.GetPointerContext(StaticTextPointer pointer, LogicalDirection direction) { return ((ITextPointer)pointer.Handle0).GetPointerContext(direction); } int ITextContainer.GetOffsetToPosition(StaticTextPointer position1, StaticTextPointer position2) { return ((ITextPointer)position1.Handle0).GetOffsetToPosition((ITextPointer)position2.Handle0); } int ITextContainer.GetTextInRun(StaticTextPointer position, LogicalDirection direction, char[] textBuffer, int startIndex, int count) { return ((ITextPointer)position.Handle0).GetTextInRun(direction, textBuffer, startIndex, count); } object ITextContainer.GetAdjacentElement(StaticTextPointer position, LogicalDirection direction) { return ((ITextPointer)position.Handle0).GetAdjacentElement(direction); } DependencyObject ITextContainer.GetParent(StaticTextPointer position) { return null; } StaticTextPointer ITextContainer.CreatePointer(StaticTextPointer position, int offset) { return new StaticTextPointer(this, ((ITextPointer)position.Handle0).CreatePointer(offset)); } StaticTextPointer ITextContainer.GetNextContextPosition(StaticTextPointer position, LogicalDirection direction) { return new StaticTextPointer(this, ((ITextPointer)position.Handle0).GetNextContextPosition(direction)); } int ITextContainer.CompareTo(StaticTextPointer position1, StaticTextPointer position2) { return ((ITextPointer)position1.Handle0).CompareTo((ITextPointer)position2.Handle0); } int ITextContainer.CompareTo(StaticTextPointer position1, ITextPointer position2) { return ((ITextPointer)position1.Handle0).CompareTo(position2); } object ITextContainer.GetValue(StaticTextPointer position, DependencyProperty formattingProperty) { return ((ITextPointer)position.Handle0).GetValue(formattingProperty); } #if DEBUG /// <summary> /// Debug only ToString override. /// </summary> public override string ToString() { int blocks = 0; ChildDocumentBlock cdb = this._doclistHead; while (cdb != null) { blocks++; cdb = cdb.NextBlock; } return "DSTC Id=" + DebugId + " Blocks= " + blocks; } #endif // DEBUG #endregion Public Methods //-------------------------------------------------------------------- // // Public Properties // //--------------------------------------------------------------------- #region Public Properties /// <summary> /// Specifies whether or not the content of this TextContainer may be /// modified. /// </summary> /// <value> /// True if content may be modified, false otherwise. /// </value> /// <remarks> /// This TextContainer implementation always returns true. /// </remarks> bool ITextContainer.IsReadOnly { get { return true; } } /// <summary> /// <see cref="TextContainer.Start"/> /// </summary> ITextPointer ITextContainer.Start { get { Debug.Assert(_start != null); return _start; } } /// <summary> /// <see cref="TextContainer.End"/> /// </summary> ITextPointer ITextContainer.End { get { Debug.Assert(_end != null); return _end; } } /// <summary> /// Autoincremented counter of content changes in this TextContainer /// </summary> uint ITextContainer.Generation { get { // For read-only content, return some constant value. return 0; } } /// <summary> /// Collection of highlights applied to TextContainer content. /// </summary> Highlights ITextContainer.Highlights { get { return this.Highlights; } } /// <summary> /// <see cref="TextContainer.Parent"/> /// </summary> DependencyObject ITextContainer.Parent { get { return _parent; } } // TextEditor owns setting and clearing this property inside its // ctor/OnDetach methods. ITextSelection ITextContainer.TextSelection { get { return this.TextSelection; } set { _textSelection = value; } } // Optional undo manager, always null for this ITextContainer. UndoManager ITextContainer.UndoManager { get { return null; } } // <see cref="System.Windows.Documents.ITextContainer/> ITextView ITextContainer.TextView { get { return _textview; } set { _textview = value; } } // Count of symbols in this tree, equivalent to this.Start.GetOffsetToPosition(this.End), // but doesn't necessarily allocate anything. int ITextContainer.SymbolCount { get { return ((ITextContainer)this).Start.GetOffsetToPosition(((ITextContainer)this).End); } } // Not implemented. int ITextContainer.IMECharCount { get { #pragma warning suppress 56503 throw new NotImplementedException(); } } #endregion Public Properties //-------------------------------------------------------------------- // // Public Events // //--------------------------------------------------------------------- #region Public Events public event EventHandler Changing; public event TextContainerChangeEventHandler Change; public event TextContainerChangedEventHandler Changed; #endregion Public Events //-------------------------------------------------------------------- // // Internal Methods // //--------------------------------------------------------------------- #region Internal Methods //-------------------------------------------------------------------- // Utility Method //--------------------------------------------------------------------- // Verify parameter. Throw Exception if necessary. internal DocumentSequenceTextPointer VerifyPosition(ITextPointer position) { if (position == null) { throw new ArgumentNullException("position"); } if (position.TextContainer != this) { throw new ArgumentException(SR.Get(SRID.NotInAssociatedContainer, "position")); } DocumentSequenceTextPointer tp = position as DocumentSequenceTextPointer; if (tp == null) { throw new ArgumentException(SR.Get(SRID.BadFixedTextPosition, "position")); } return tp; } // Given an ITextPointer in a child TextContainer, create a position in parent's // address space to represent it. internal DocumentSequenceTextPointer MapChildPositionToParent(ITextPointer tp) { ChildDocumentBlock cdb = this._doclistHead; while (cdb != null) { if (cdb.ChildContainer == tp.TextContainer) { return new DocumentSequenceTextPointer(cdb, tp); } cdb = cdb.NextBlock; } return null; } // Find a ChildBlock in the list that corresponds to the given DocumentReference // Return null if cannot find internal ChildDocumentBlock FindChildBlock(DocumentReference docRef) { Debug.Assert(docRef != null); ChildDocumentBlock cdb = _doclistHead.NextBlock; while (cdb != null) { if (cdb.DocRef == docRef) { return cdb; } cdb = cdb.NextBlock; } return null; } // Return distance between two child TextContainer // 0 means the same container // n means block1 is n steps before block2 in the link list // -n means block1 is n steps after block2 in the link list internal int GetChildBlockDistance(ChildDocumentBlock block1, ChildDocumentBlock block2) { // Note: we can improve perf of this function by using generation // mark + caching index, if this function turns out to be costly. // However, I would expect it to not happen very often. if ((object)block1 == (object)block2) { return 0; } // Assuming block1 is before block2 int count = 0; ChildDocumentBlock cdb = block1; while (cdb != null) { if (cdb == block2) { return count; } count++; cdb = cdb.NextBlock; } // Now block2 has to be before block1 count = 0; cdb = block1; while (cdb != null) { if (cdb == block2) { return count; } count--; cdb = cdb.PreviousBlock; } Debug.Assert(false, "should never be here"); return 0; } #endregion Internal Methods //-------------------------------------------------------------------- // // Internal Properties // //--------------------------------------------------------------------- #region Internal Properties /// <summary> /// Collection of highlights applied to TextContainer content. /// </summary> internal Highlights Highlights { get { if (_highlights == null) { _highlights = new DocumentSequenceHighlights(this); } return _highlights; } } // TextSelection associated with this container. internal ITextSelection TextSelection { get { return _textSelection; } } #if DEBUG internal uint DebugId { get { return _debugId; } } #endif #endregion Internal Properties //-------------------------------------------------------------------- // // Private Methods // //--------------------------------------------------------------------- #region Private Methods //-------------------------------------------------------------------- // Initilization //--------------------------------------------------------------------- private void _Initialize() { Debug.Assert(_parent != null); // Create Start Block/Container/Position _doclistHead = new ChildDocumentBlock(this, new NullTextContainer()); // Create End Block/Container/Position _doclistTail = new ChildDocumentBlock(this, new NullTextContainer()); // Link Start and End container together _doclistHead.InsertNextBlock(_doclistTail); // Now initialize the child doc block list ChildDocumentBlock currentBlock = _doclistHead; foreach (DocumentReference docRef in _parent.References) { currentBlock.InsertNextBlock(new ChildDocumentBlock(this, docRef)); currentBlock = currentBlock.NextBlock; } //if we have at least one document, start and end pointers should be set to valid child blocks not to the placeholders if (_parent.References.Count != 0) { _start = new DocumentSequenceTextPointer(_doclistHead.NextBlock, _doclistHead.NextBlock.ChildContainer.Start); _end = new DocumentSequenceTextPointer(_doclistTail.PreviousBlock, _doclistTail.PreviousBlock.ChildContainer.End); } else { _start = new DocumentSequenceTextPointer(_doclistHead, _doclistHead.ChildContainer.Start); _end = new DocumentSequenceTextPointer(_doclistTail, _doclistTail.ChildContainer.End); } // Listen to collection changes _parent.References.CollectionChanged += new NotifyCollectionChangedEventHandler(_OnContentChanged); // Listen to Highlights changes so that it can notify sub-TextContainer this.Highlights.Changed += new HighlightChangedEventHandler(_OnHighlightChanged); } private void AddChange(ITextPointer startPosition, int symbolCount, PrecursorTextChangeType precursorTextChange) { Invariant.Assert(!_isReadOnly, "Illegal to modify DocumentSequenceTextContainer inside Change event scope!"); ITextContainer textContainer = (ITextContainer)this; textContainer.BeginChange(); try { // Contact any listeners. if (this.Changing != null) { Changing(this, EventArgs.Empty); } // Fire the ChangingEvent now if we haven't already. if (_changes == null) { _changes = new TextContainerChangedEventArgs(); } _changes.AddChange(precursorTextChange, DocumentSequenceTextPointer.GetOffsetToPosition(_start, startPosition), symbolCount, false /* collectTextChanges */); if (this.Change != null) { Invariant.Assert(precursorTextChange == PrecursorTextChangeType.ContentAdded || precursorTextChange == PrecursorTextChangeType.ContentRemoved); TextChangeType textChange = (precursorTextChange == PrecursorTextChangeType.ContentAdded) ? TextChangeType.ContentAdded : TextChangeType.ContentRemoved; _isReadOnly = true; try { // Pass in a -1 for charCount parameter. DocumentSequenceTextContainer // doesn't support this feature because it is only consumed by IMEs // which never run on read-only documents. Change(this, new TextContainerChangeEventArgs(startPosition, symbolCount, -1, textChange)); } finally { _isReadOnly = false; } } } finally { textContainer.EndChange(); } } //-------------------------------------------------------------------- // ContentChange //--------------------------------------------------------------------- private void _OnContentChanged(object sender, NotifyCollectionChangedEventArgs args) { #if DEBUG this._generation++; #endif if (args.Action == NotifyCollectionChangedAction.Add) { if (args.NewItems.Count != 1) { throw new NotSupportedException(SR.Get(SRID.RangeActionsNotSupported)); } else { object item = args.NewItems[0]; int startingIndex = args.NewStartingIndex; if (startingIndex != _parent.References.Count - 1) { throw new NotSupportedException(SR.Get(SRID.UnexpectedCollectionChangeAction, args.Action)); } ChildDocumentBlock newBlock = new ChildDocumentBlock(this, (DocumentReference)item); ChildDocumentBlock insertAfter = _doclistTail.PreviousBlock; insertAfter.InsertNextBlock(newBlock); DocumentSequenceTextPointer changeStart = new DocumentSequenceTextPointer(insertAfter, insertAfter.End); //Update end pointer _end = new DocumentSequenceTextPointer(newBlock, newBlock.ChildContainer.End); if (newBlock.NextBlock == _doclistTail && newBlock.PreviousBlock == _doclistHead) { //Update start pointer for the first block _start = new DocumentSequenceTextPointer(newBlock, newBlock.ChildContainer.Start); } // Record Change Notifications ITextContainer container = newBlock.ChildContainer; int symbolCount = 1; // takes too long to calculate for large documents, and no one will use this info // this does not affect state, only fires event handlers AddChange(changeStart, symbolCount, PrecursorTextChangeType.ContentAdded); } } else { throw new NotSupportedException(SR.Get(SRID.UnexpectedCollectionChangeAction, args.Action)); } } //-------------------------------------------------------------------- // Highlight compositing //--------------------------------------------------------------------- private void _OnHighlightChanged(object sender, HighlightChangedEventArgs args) { Debug.Assert(sender != null); Debug.Assert(args != null); Debug.Assert(args.Ranges != null); #if DEBUG { Highlights highlights = this.Highlights; StaticTextPointer highlightTransitionPosition; StaticTextPointer highlightRangeStart; object selected; DocumentsTrace.FixedDocumentSequence.Highlights.Trace("===BeginNewHighlightRange==="); highlightTransitionPosition = ((ITextContainer)this).CreateStaticPointerAtOffset(0); while (true) { // Move to the next highlight start. if (!highlights.IsContentHighlighted(highlightTransitionPosition, LogicalDirection.Forward)) { highlightTransitionPosition = highlights.GetNextHighlightChangePosition(highlightTransitionPosition, LogicalDirection.Forward); // No more highlights? if (highlightTransitionPosition.IsNull) break; } // highlightTransitionPosition is at the start of a new highlight run. selected = highlights.GetHighlightValue(highlightTransitionPosition, LogicalDirection.Forward, typeof(TextSelection)); // Save the start position and find the end. highlightRangeStart = highlightTransitionPosition; highlightTransitionPosition = highlights.GetNextHighlightChangePosition(highlightTransitionPosition, LogicalDirection.Forward); Invariant.Assert(!highlightTransitionPosition.IsNull, "Highlight start not followed by highlight end!"); // Store the highlight. if (selected != DependencyProperty.UnsetValue) { DocumentsTrace.FixedDocumentSequence.Highlights.Trace(string.Format("HightlightRange {0}-{1}", highlightRangeStart.ToString(), highlightTransitionPosition.ToString())); if (highlightRangeStart.GetPointerContext(LogicalDirection.Forward) != TextPointerContext.Text) { DocumentsTrace.FixedDocumentSequence.Highlights.Trace("<HighlightNotOnText>"); } else { char[] sb = new char[256]; TextPointerBase.GetTextWithLimit(highlightRangeStart.CreateDynamicTextPointer(LogicalDirection.Forward), LogicalDirection.Forward, sb, 0, 256, highlightTransitionPosition.CreateDynamicTextPointer(LogicalDirection.Forward)); DocumentsTrace.FixedDocumentSequence.TextOM.Trace(string.Format("HightlightContent [{0}]", new String(sb))); } } } DocumentsTrace.FixedDocumentSequence.TextOM.Trace("===EndNewHighlightRange==="); } #endif Debug.Assert(args.Ranges.Count > 0 && ((TextSegment)args.Ranges[0]).Start.CompareTo(((TextSegment)args.Ranges[0]).End) < 0); // For each change range we received, we need to figure out // affected child TextContainer, and notify it with appropriate // ranges that are in the child's address space. // // We only fire one highlight change notification for any child // TextContainer even if there is multiple change ranges fall // into the same child TextContainer. // // We scan the ranges and the child TextContainer in the same loop, // moving forward two scanning pointers and at boundary of each // TextContainer, we fire a change notification. // int idxScan = 0; DocumentSequenceTextPointer tsScan = null; ChildDocumentBlock cdbScan = null; List<TextSegment> rangeArray = new List<TextSegment>(4); while (idxScan < args.Ranges.Count) { TextSegment ts = (TextSegment)args.Ranges[idxScan]; DocumentSequenceTextPointer tsEnd = (DocumentSequenceTextPointer)ts.End; ITextPointer tpChildStart, tpChildEnd; ChildDocumentBlock lastBlock; // If tsScan == null, we were done with previous range, // so we are going to set tsScan to begining of this range. // Otherwise the previous range was split so we will simply // start from what was left over from previous loop. if (tsScan == null) { tsScan = (DocumentSequenceTextPointer)ts.Start; } lastBlock = cdbScan; cdbScan = tsScan.ChildBlock; if (lastBlock != null && cdbScan != lastBlock && !(lastBlock.ChildContainer is NullTextContainer) && rangeArray.Count != 0) { // This range is in a different block, so take care of old blocks first lastBlock.ChildHighlightLayer.RaiseHighlightChangedEvent(new ReadOnlyCollection<TextSegment>(rangeArray)); rangeArray.Clear(); } tpChildStart = tsScan.ChildPointer; if (tsEnd.ChildBlock != cdbScan) { // If this range crosses blocks, we are done with current block tpChildEnd = tsScan.ChildPointer.TextContainer.End; if (tpChildStart.CompareTo(tpChildEnd) != 0) { rangeArray.Add(new TextSegment(tpChildStart, tpChildEnd)); } // Notify child container if (!(cdbScan.ChildContainer is NullTextContainer) && rangeArray.Count != 0) { cdbScan.ChildHighlightLayer.RaiseHighlightChangedEvent(new ReadOnlyCollection<TextSegment>(rangeArray)); } // Move on to next block; cdbScan = cdbScan.NextBlock; tsScan = new DocumentSequenceTextPointer(cdbScan, cdbScan.ChildContainer.Start); rangeArray.Clear(); } else { // Otherwise we need to go on to see if there is more ranges // fall withing the same block. Simply add this change range tpChildEnd = tsEnd.ChildPointer; if (tpChildStart.CompareTo(tpChildEnd) != 0) { rangeArray.Add(new TextSegment(tpChildStart, tpChildEnd)); } // Move on to next range idxScan++; tsScan = null; } } // Fire change notification for the last child block. if (rangeArray.Count > 0 && (!(cdbScan == null || cdbScan.ChildContainer is NullTextContainer))) { cdbScan.ChildHighlightLayer.RaiseHighlightChangedEvent(new ReadOnlyCollection<TextSegment>(rangeArray)); } } #endregion Private Methods //-------------------------------------------------------------------- // // Private Fields // //--------------------------------------------------------------------- #region Private Fields private readonly FixedDocumentSequence _parent; // The content aggregator, supplied in ctor private DocumentSequenceTextPointer _start; // Start of the aggregated TextContainer private DocumentSequenceTextPointer _end; // End of the aggregated TextContainer private ChildDocumentBlock _doclistHead; // Head of the doubly linked list of child TextContainer entries private ChildDocumentBlock _doclistTail; // Tail of the doubly linked list of child TextContainer entries private ITextSelection _textSelection; // Collection of highlights applied to TextContainer content. private Highlights _highlights; // BeginChange ref count. When non-zero, we are inside a change block. private int _changeBlockLevel; // Array of pending changes in the current change block. // Null outside of a change block. private TextContainerChangedEventArgs _changes; // TextView associated with this TextContainer. private ITextView _textview; // Set true during Change event callback. // When true, modifying the TextContainer is disallowed. private bool _isReadOnly; #if DEBUG // The container generation, increamented whenever container content changes. private uint _generation; private uint _debugId = (DocumentSequenceTextContainer._debugIdCounter++); private static uint _debugIdCounter = 0; #endif #endregion Private Fields //-------------------------------------------------------------------- // // Private Classes // //--------------------------------------------------------------------- #region Private Classes /// <summary> /// DocumentSequence specific Highlights subclass accepts text pointers from /// either the DocSequence or any of its child FixedDocuments. This allows /// the highlights to be set on the DocSequence but the FixedDocuments continue /// to handle the rendering (FixedDocs look for their parent's Highlights if /// the parent is a DocSequence). /// </summary> private sealed class DocumentSequenceHighlights : Highlights { internal DocumentSequenceHighlights(DocumentSequenceTextContainer textContainer) : base(textContainer) { } /// <summary> /// Returns the value of a property stored on scoping highlight, if any. /// </summary> /// <param name="textPosition"> /// Position to query. /// </param> /// <param name="direction"> /// Direction of content to query. /// </param> /// <param name="highlightLayerOwnerType"> /// Type of the matching highlight layer owner. /// </param> /// <returns> /// The highlight value if set on any scoping highlight. If no property /// value is set, returns DependencyProperty.UnsetValue. /// </returns> internal override object GetHighlightValue(StaticTextPointer textPosition, LogicalDirection direction, Type highlightLayerOwnerType) { StaticTextPointer parentPosition; if (EnsureParentPosition(textPosition, direction, out parentPosition)) { return base.GetHighlightValue(parentPosition, direction, highlightLayerOwnerType); } return DependencyProperty.UnsetValue; } /// <summary> /// Returns true iff the indicated content has scoping highlights. /// </summary> /// <param name="textPosition"> /// Position to query. /// </param> /// <param name="direction"> /// Direction of content to query. /// </param> internal override bool IsContentHighlighted(StaticTextPointer textPosition, LogicalDirection direction) { StaticTextPointer parentPosition; if (EnsureParentPosition(textPosition, direction, out parentPosition)) { return base.IsContentHighlighted(parentPosition, direction); } return false; } /// <summary> /// Returns the position of the next highlight start or end in an /// indicated direction, or null if there is no such position. /// </summary> /// <param name="textPosition"> /// Position to query. /// </param> /// <param name="direction"> /// Direction of content to query. /// </param> internal override StaticTextPointer GetNextHighlightChangePosition(StaticTextPointer textPosition, LogicalDirection direction) { StaticTextPointer parentPosition; StaticTextPointer returnPointer = StaticTextPointer.Null; if (EnsureParentPosition(textPosition, direction, out parentPosition)) { returnPointer = base.GetNextHighlightChangePosition(parentPosition, direction); // If we were passed a child position, we need to convert the result back to a child position if (textPosition.TextContainer.Highlights != this) { returnPointer = GetStaticPositionInChildContainer(returnPointer, direction, textPosition); } } return returnPointer; } /// <summary> /// Returns the closest neighboring TextPointer in an indicated /// direction where a property value calculated from an embedded /// object, scoping text element, or scoping highlight could /// change. /// </summary> /// <param name="textPosition"> /// Position to query. /// </param> /// <param name="direction"> /// Direction of content to query. /// </param> /// <returns> /// If the following symbol is TextPointerContext.EmbeddedElement, /// TextPointerContext.ElementBegin, or TextPointerContext.ElementEnd, returns /// a TextPointer exactly one symbol distant. /// /// If the following symbol is TextPointerContext.Text, the distance /// of the returned TextPointer is the minimum of the value returned /// by textPosition.GetTextLength and the distance to any highlight /// start or end edge. /// /// If the following symbol is TextPointerContext.None, returns null. /// </returns> internal override StaticTextPointer GetNextPropertyChangePosition(StaticTextPointer textPosition, LogicalDirection direction) { StaticTextPointer parentPosition; StaticTextPointer returnPointer = StaticTextPointer.Null; if (EnsureParentPosition(textPosition, direction, out parentPosition)) { returnPointer = base.GetNextPropertyChangePosition(parentPosition, direction); // If we were passed a child position, we need to convert the result back to a child position if (textPosition.TextContainer.Highlights != this) { returnPointer = GetStaticPositionInChildContainer(returnPointer, direction, textPosition); } } return returnPointer; } /// <summary> /// Sets parentPosition to be a valid TextPointer in the parent document. This could either /// be the textPosition passed in (if its already on the parent document) or a conversion /// of the textPosition passed in. /// </summary> /// <returns>whether or not parentPosition is valid and should be used</returns> private bool EnsureParentPosition(StaticTextPointer textPosition, LogicalDirection direction, out StaticTextPointer parentPosition) { // Simple case - textPosition is already in the parent TextContainer parentPosition = textPosition; // If textPosition is on a child TextContainer, we convert it if (textPosition.TextContainer.Highlights != this) { // This case can't be converted so return false, out parameter should not be used if (textPosition.GetPointerContext(direction) == TextPointerContext.None) return false; // Turn the textPosition (which should be in the scope of a FixedDocument) // into a position in the scope of the DocumentSequence. ITextPointer dynamicTextPointer = textPosition.CreateDynamicTextPointer(LogicalDirection.Forward); ITextPointer parentTextPointer = ((DocumentSequenceTextContainer)this.TextContainer).MapChildPositionToParent(dynamicTextPointer); Debug.Assert(parentTextPointer != null); parentPosition = parentTextPointer.CreateStaticPointer(); } // Returning true - either we started with a parent position or we converted to one return true; } /// <summary> /// Conversion from a StaticTextPointer on a DocumentSequence into a StaticTextPointer /// on a specified FixedDocument. If the conversion results in a pointer on a different /// FixedDocument then we return one end of the FixedDocument (based on direction). /// </summary> /// <param name="textPosition">position in a DocumentSequence to convert</param> /// <param name="direction">direction of the desired conversion</param> /// <param name="originalPosition">original pointer from FixedDocument</param> private StaticTextPointer GetStaticPositionInChildContainer(StaticTextPointer textPosition, LogicalDirection direction, StaticTextPointer originalPosition) { StaticTextPointer parentTextPointer = StaticTextPointer.Null; if (!textPosition.IsNull) { DocumentSequenceTextPointer parentChangePosition = textPosition.CreateDynamicTextPointer(LogicalDirection.Forward) as DocumentSequenceTextPointer; Debug.Assert(parentChangePosition != null); // If the DocSequence position translates into a position in a different FixedDocument than // the original request, we return an end of the original FixedDocument (which end depends on direction) ITextPointer childTp = parentChangePosition.ChildPointer; if (childTp.TextContainer != originalPosition.TextContainer) { // If the position we started searching from is highlighted, cut the highlight // at the end of the text container. Otherwise return null (the highlight must // start in the next document). if (IsContentHighlighted(originalPosition, direction)) { childTp = direction == LogicalDirection.Forward ? originalPosition.TextContainer.End : originalPosition.TextContainer.Start; parentTextPointer = childTp.CreateStaticPointer(); } else { parentTextPointer = StaticTextPointer.Null; } } else { parentTextPointer = childTp.CreateStaticPointer(); } } return parentTextPointer; } } #endregion Private Classes } }
using System; using System.Data; using System.Data.OleDb; using System.Collections; using System.Configuration; using PCSComUtils.DataAccess; using PCSComUtils.PCSExc; using PCSComUtils.Common; namespace PCSComProduction.WorkOrder.DS { public class PRO_IssueMaterialDetailDS { public PRO_IssueMaterialDetailDS() { } private const string THIS = "PCSComProduction.WorkOrder.DS.PRO_IssueMaterialDetailDS"; /// <summary> /// This method uses to add data to PRO_IssueMaterialDetail /// </summary> /// <Inputs> /// PRO_IssueMaterialDetailVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Tuesday, June 14, 2005 /// </History> public void Add(object pobjObjectVO) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS =null; OleDbCommand ocmdPCS =null; try { PRO_IssueMaterialDetailVO objObject = (PRO_IssueMaterialDetailVO) pobjObjectVO; string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); strSql= "INSERT INTO PRO_IssueMaterialDetail(" + PRO_IssueMaterialDetailTable.LINE_FLD + "," + PRO_IssueMaterialDetailTable.COMMITQUANTITY_FLD + "," + PRO_IssueMaterialDetailTable.PRODUCTID_FLD + "," + PRO_IssueMaterialDetailTable.ISSUEMATERIALMASTERID_FLD + "," + PRO_IssueMaterialDetailTable.LOCATIONID_FLD + "," + PRO_IssueMaterialDetailTable.BINID_FLD + "," + PRO_IssueMaterialDetailTable.LOT_FLD + "," + PRO_IssueMaterialDetailTable.SERIAL_FLD + "," + PRO_IssueMaterialDetailTable.MASTERLOCATIONID_FLD + "," + PRO_IssueMaterialDetailTable.STOCKUMID_FLD + "," + PRO_IssueMaterialDetailTable.QASTATUS_FLD + "," + PRO_IssueMaterialDetailTable.WORKORDERMASTERID_FLD + "," + PRO_IssueMaterialDetailTable.WORKORDERDETAILID_FLD + "," + PRO_IssueMaterialDetailTable.BOMQUANTITY_FLD + ")" + "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)"; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.LINE_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.LINE_FLD].Value = objObject.Line; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.COMMITQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.COMMITQUANTITY_FLD].Value = objObject.CommitQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.PRODUCTID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.PRODUCTID_FLD].Value = objObject.ProductID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.ISSUEMATERIALMASTERID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.ISSUEMATERIALMASTERID_FLD].Value = objObject.IssueMaterialMasterID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.LOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.LOCATIONID_FLD].Value = objObject.LocationID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.BINID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.BINID_FLD].Value = objObject.BinID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.LOT_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.LOT_FLD].Value = objObject.Lot; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.SERIAL_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.SERIAL_FLD].Value = objObject.Serial; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.MASTERLOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.STOCKUMID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.STOCKUMID_FLD].Value = objObject.StockUMID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.QASTATUS_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.QASTATUS_FLD].Value = objObject.QAStatus; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.WORKORDERMASTERID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.WORKORDERMASTERID_FLD].Value = objObject.WorkOrderMasterID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.WORKORDERDETAILID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.WORKORDERDETAILID_FLD].Value = objObject.WorkOrderDetailID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.BOMQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.BOMQUANTITY_FLD].Value = objObject.BomQuantity; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to PRO_IssueMaterialDetail /// </summary> /// <Inputs> /// PRO_IssueMaterialDetailVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Tuesday, June 14, 2005 /// </History> public void Delete(int pintID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = String.Empty; strSql= "DELETE " + PRO_IssueMaterialDetailTable.TABLE_NAME + " WHERE " + "IssueMaterialDetailID" + "=" + pintID.ToString(); OleDbConnection oconPCS=null; OleDbCommand ocmdPCS =null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// Delete detail by master id /// </summary> /// <param name="pintID"></param> public void DeleteByMaster(int pintID) { const string METHOD_NAME = THIS + ".DeleteByMaster()"; OleDbConnection oconPCS=null; OleDbCommand ocmdPCS =null; try { string strSql= "DELETE " + PRO_IssueMaterialDetailTable.TABLE_NAME + " WHERE " + PRO_IssueMaterialDetailTable.ISSUEMATERIALMASTERID_FLD + "=" + pintID.ToString(); Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch(OleDbException ex) { if (ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); else throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } else throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to PRO_IssueMaterialDetail /// </summary> /// <Inputs> /// PRO_IssueMaterialDetailVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Tuesday, June 14, 2005 /// </History> public object GetObjectVO(int pintID) { const string METHOD_NAME = THIS + ".GetObjectVO()"; DataSet dstPCS = new DataSet(); OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + PRO_IssueMaterialDetailTable.ISSUEMATERIALDETAILID_FLD + "," + PRO_IssueMaterialDetailTable.LINE_FLD + "," + PRO_IssueMaterialDetailTable.COMMITQUANTITY_FLD + "," + PRO_IssueMaterialDetailTable.PRODUCTID_FLD + "," + PRO_IssueMaterialDetailTable.ISSUEMATERIALMASTERID_FLD + "," + PRO_IssueMaterialDetailTable.LOCATIONID_FLD + "," + PRO_IssueMaterialDetailTable.BINID_FLD + "," + PRO_IssueMaterialDetailTable.LOT_FLD + "," + PRO_IssueMaterialDetailTable.SERIAL_FLD + "," + PRO_IssueMaterialDetailTable.MASTERLOCATIONID_FLD + "," + PRO_IssueMaterialDetailTable.STOCKUMID_FLD + "," + PRO_IssueMaterialDetailTable.QASTATUS_FLD + "," + PRO_IssueMaterialDetailTable.WORKORDERMASTERID_FLD + "," + PRO_IssueMaterialDetailTable.WORKORDERDETAILID_FLD + "," + PRO_IssueMaterialDetailTable.BOMQUANTITY_FLD + " FROM " + PRO_IssueMaterialDetailTable.TABLE_NAME +" WHERE " + PRO_IssueMaterialDetailTable.ISSUEMATERIALDETAILID_FLD + "=" + pintID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); PRO_IssueMaterialDetailVO objObject = new PRO_IssueMaterialDetailVO(); while (odrPCS.Read()) { objObject.IssueMaterialDetailID = int.Parse(odrPCS[PRO_IssueMaterialDetailTable.ISSUEMATERIALDETAILID_FLD].ToString().Trim()); objObject.Line = int.Parse(odrPCS[PRO_IssueMaterialDetailTable.LINE_FLD].ToString().Trim()); objObject.CommitQuantity = Decimal.Parse(odrPCS[PRO_IssueMaterialDetailTable.COMMITQUANTITY_FLD].ToString().Trim()); objObject.ProductID = int.Parse(odrPCS[PRO_IssueMaterialDetailTable.PRODUCTID_FLD].ToString().Trim()); objObject.IssueMaterialMasterID = int.Parse(odrPCS[PRO_IssueMaterialDetailTable.ISSUEMATERIALMASTERID_FLD].ToString().Trim()); objObject.LocationID = int.Parse(odrPCS[PRO_IssueMaterialDetailTable.LOCATIONID_FLD].ToString().Trim()); objObject.BinID = int.Parse(odrPCS[PRO_IssueMaterialDetailTable.BINID_FLD].ToString().Trim()); objObject.Lot = odrPCS[PRO_IssueMaterialDetailTable.LOT_FLD].ToString().Trim(); objObject.Serial = odrPCS[PRO_IssueMaterialDetailTable.SERIAL_FLD].ToString().Trim(); objObject.MasterLocationID = int.Parse(odrPCS[PRO_IssueMaterialDetailTable.MASTERLOCATIONID_FLD].ToString().Trim()); objObject.StockUMID = int.Parse(odrPCS[PRO_IssueMaterialDetailTable.STOCKUMID_FLD].ToString().Trim()); objObject.QAStatus = int.Parse(odrPCS[PRO_IssueMaterialDetailTable.QASTATUS_FLD].ToString().Trim()); objObject.WorkOrderMasterID = int.Parse(odrPCS[PRO_IssueMaterialDetailTable.WORKORDERMASTERID_FLD].ToString().Trim()); objObject.WorkOrderDetailID = int.Parse(odrPCS[PRO_IssueMaterialDetailTable.WORKORDERDETAILID_FLD].ToString().Trim()); objObject.BomQuantity = int.Parse(odrPCS[PRO_IssueMaterialDetailTable.BOMQUANTITY_FLD].ToString().Trim()); } return objObject; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// Get Cached QA Status /// </summary> /// <param name="pintMasterLocationID"></param> /// <returns></returns> /// <author> Tuan TQ. 8 Mar, 2006</author> public DataTable GetCachedQAStatus(int pintCCNID, int pintMasterLocationID) { DataTable dtbResult = new DataTable(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; string strSql= "SELECT ISNULL(" + IV_BinCacheTable.INSPSTATUS_FLD + ",0) as " + IV_BinCacheTable.INSPSTATUS_FLD + ", " + IV_BinCacheTable.LOCATIONID_FLD + ", " + IV_BinCacheTable.BINID_FLD + ", " + IV_BinCacheTable.PRODUCTID_FLD + " FROM " + IV_BinCacheTable.TABLE_NAME + " WHERE " + IV_BinCacheTable.CCNID_FLD + "=" + pintCCNID + " AND " + IV_BinCacheTable.MASTERLOCATIONID_FLD + "=" + pintMasterLocationID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dtbResult); return dtbResult; } /// <summary> /// Get Available Quantity By Post Date /// </summary> /// <param name="pintMasterLocationID"></param> /// <returns></returns> /// <author> Tuan TQ. 8 Mar, 2006</author> public DataTable GetAvailableQuantityByPostDate(DateTime pdtmPostDate, int pintCCNID, int pintMasLocID, string pstrProductIDs) { const string SQL_DATETIME_FORMAT = "yyyy-MM-dd HH:mm"; DataTable dtbResult = new DataTable(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; string strSql = "SELECT ("; strSql += " ISNULL(SUM(ISNULL(bc.OHQuantity, 0) - ISNULL(bc.CommitQuantity, 0)), 0)"; strSql += " - ISNULL((SELECT ISNULL(SUM(ISNULL(TH.Quantity,0)),0)"; strSql += " FROM MST_TransactionHistory TH"; strSql += " INNER JOIN dbo.MST_TranType TT ON TT.TranTypeID = TH.TranTypeID"; strSql += " WHERE TT.Type = " + (int)TransactionHistoryType.In; strSql += " AND TH.PostDate > '" + pdtmPostDate.ToString(SQL_DATETIME_FORMAT) + "'"; strSql += " AND TH.CCNID = bc.CCNID"; strSql += " AND TH.MasterLocationID = bc.MasterLocationID"; strSql += " AND TH.LocationID = bc.LocationID"; strSql += " AND TH.BinID = bc.BinID"; strSql += " AND TH.ProductID = bc.ProductID"; strSql += " )"; strSql += " ,0)"; strSql += " - ISNULL((SELECT ISNULL(SUM(ISNULL(TH.Quantity,0)),0)"; strSql += " FROM MST_TransactionHistory TH"; strSql += " INNER JOIN dbo.MST_TranType TT ON TT.TranTypeID = TH.TranTypeID"; strSql += " WHERE TT.Type = 2"; strSql += " AND TH.PostDate > '" + pdtmPostDate.ToString(SQL_DATETIME_FORMAT) + "'"; strSql += " AND TH.CCNID = bc.CCNID"; strSql += " AND TH.MasterLocationID = bc.MasterLocationID"; strSql += " AND TH.LocationID = bc.LocationID"; strSql += " AND TH.BinID = bc.BinID"; strSql += " AND TH.ProductID = bc.ProductID"; strSql += " )"; strSql += " ,0)"; strSql += " + ISNULL((SELECT ISNULL(SUM(ISNULL(TH.Quantity,0)),0)"; strSql += " FROM MST_TransactionHistory TH"; strSql += " INNER JOIN dbo.MST_TranType TT ON TT.TranTypeID = TH.TranTypeID"; strSql += " WHERE TT.Type = 0"; strSql += " AND TH.PostDate > '" + pdtmPostDate.ToString(SQL_DATETIME_FORMAT) + "'"; strSql += " AND TH.CCNID = bc.CCNID"; strSql += " AND TH.MasterLocationID = bc.MasterLocationID"; strSql += " AND TH.LocationID = bc.LocationID"; strSql += " AND TH.BinID = bc.BinID"; strSql += " AND TH.ProductID = bc.ProductID"; strSql += " )"; strSql += " ,0)"; strSql += " )"; strSql += " as " + Constants.AVAILABLE_QTY_COL; strSql += " , bc.ProductID"; strSql += " , bc.BinID"; strSql += " , bc.LocationID"; strSql += " FROM IV_BinCache bc"; strSql += " WHERE bc.CCNID = " + pintCCNID; strSql += " AND bc.MasterLocationID = " + pintMasLocID; strSql += " AND bc.ProductID IN " + pstrProductIDs; strSql += " GROUP BY bc.ProductID, bc.BinID, bc.LocationID, bc.MasterLocationID, bc.CCNID"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dtbResult); return dtbResult; } /// <summary> /// Get Needed Quantity /// </summary> /// <param name="pintMasLocID"></param> /// <returns></returns> /// <author> Tuan TQ. 8 Mar, 2006</author> public DataTable GetNeededQuantity(int pintMasLocID) { const string VIEW_NEEDED_QUANTITY = "v_RemainComponentForWOIssueWithParentInfo"; DataTable dtbResult = new DataTable(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; string strSql= "SELECT RequiredQuantity as " + Constants.NEEDED_QTY_COL + ", "; strSql += PRO_WorkOrderDetailTable.WORKORDERDETAILID_FLD + ", "; strSql += PRO_WorkOrderBomDetailTable.COMPONENTID_FLD; strSql += " FROM " + VIEW_NEEDED_QUANTITY; strSql += " WHERE " + PRO_WorkOrderMasterTable.MASTERLOCATIONID_FLD + "=" + pintMasLocID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dtbResult); return dtbResult; } /// <summary> /// Get Commited Quantity /// </summary> /// <param name="pintMasterLocationID"></param> /// <returns></returns> /// <author> Tuan TQ. 8 Mar, 2006</author> public DataTable GetCommitedQuantity(int pintMasterLocationID) { DataTable dtbResult = new DataTable(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; string strSql = "SELECT SUM(" + PRO_IssueMaterialDetailTable.COMMITQUANTITY_FLD + ") as " + PRO_IssueMaterialDetailTable.COMMITQUANTITY_FLD + ", " + PRO_IssueMaterialDetailTable.WORKORDERDETAILID_FLD + ", " + PRO_IssueMaterialDetailTable.PRODUCTID_FLD + " FROM " + PRO_IssueMaterialDetailTable.TABLE_NAME + " WHERE " + PRO_IssueMaterialDetailTable.MASTERLOCATIONID_FLD + "=" + pintMasterLocationID + " GROUP BY " + PRO_IssueMaterialDetailTable.WORKORDERDETAILID_FLD + ", " + PRO_IssueMaterialDetailTable.PRODUCTID_FLD; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dtbResult); return dtbResult; } /// <summary> /// This method is used to calculate the commited quantity for this work order /// </summary> /// <param name="pintWorkOrderDetailID"></param> /// <param name="pintProductID"></param> /// <returns></returns> public decimal CalculateCommitedQty(int pintWorkOrderDetailID, int pintProductID) { const string METHOD_NAME = THIS + ".CalculateCommitedQty()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT sum(" + PRO_IssueMaterialDetailTable.COMMITQUANTITY_FLD + ")" + " FROM " + PRO_IssueMaterialDetailTable.TABLE_NAME + " WHERE " + PRO_IssueMaterialDetailTable.WORKORDERDETAILID_FLD + "=" + pintWorkOrderDetailID + " AND " + PRO_IssueMaterialDetailTable.PRODUCTID_FLD + "=" + pintProductID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); object objResult = ocmdPCS.ExecuteScalar(); if (objResult == DBNull.Value) { return 0; } else { return decimal.Parse(objResult.ToString()); } } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to PRO_IssueMaterialDetail /// </summary> /// <Inputs> /// PRO_IssueMaterialDetailVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Tuesday, June 14, 2005 /// </History> public void Update(object pobjObjecVO) { const string METHOD_NAME = THIS + ".Update()"; PRO_IssueMaterialDetailVO objObject = (PRO_IssueMaterialDetailVO) pobjObjecVO; //prepare value for parameters OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); strSql= "UPDATE PRO_IssueMaterialDetail SET " + PRO_IssueMaterialDetailTable.LINE_FLD + "= ?" + "," + PRO_IssueMaterialDetailTable.COMMITQUANTITY_FLD + "= ?" + "," + PRO_IssueMaterialDetailTable.PRODUCTID_FLD + "= ?" + "," + PRO_IssueMaterialDetailTable.ISSUEMATERIALMASTERID_FLD + "= ?" + "," + PRO_IssueMaterialDetailTable.LOCATIONID_FLD + "= ?" + "," + PRO_IssueMaterialDetailTable.BINID_FLD + "= ?" + "," + PRO_IssueMaterialDetailTable.LOT_FLD + "= ?" + "," + PRO_IssueMaterialDetailTable.SERIAL_FLD + "= ?" + "," + PRO_IssueMaterialDetailTable.MASTERLOCATIONID_FLD + "= ?" + "," + PRO_IssueMaterialDetailTable.STOCKUMID_FLD + "= ?" + "," + PRO_IssueMaterialDetailTable.QASTATUS_FLD + "= ?" + "," + PRO_IssueMaterialDetailTable.WORKORDERMASTERID_FLD + "= ?" + "," + PRO_IssueMaterialDetailTable.WORKORDERDETAILID_FLD + "= ?" + PRO_IssueMaterialDetailTable.BOMQUANTITY_FLD + "= ?" +" WHERE " + PRO_IssueMaterialDetailTable.ISSUEMATERIALDETAILID_FLD + "= ?"; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.LINE_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.LINE_FLD].Value = objObject.Line; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.COMMITQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.COMMITQUANTITY_FLD].Value = objObject.CommitQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.PRODUCTID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.PRODUCTID_FLD].Value = objObject.ProductID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.ISSUEMATERIALMASTERID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.ISSUEMATERIALMASTERID_FLD].Value = objObject.IssueMaterialMasterID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.LOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.LOCATIONID_FLD].Value = objObject.LocationID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.BINID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.BINID_FLD].Value = objObject.BinID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.LOT_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.LOT_FLD].Value = objObject.Lot; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.SERIAL_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.SERIAL_FLD].Value = objObject.Serial; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.MASTERLOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.STOCKUMID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.STOCKUMID_FLD].Value = objObject.StockUMID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.QASTATUS_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.QASTATUS_FLD].Value = objObject.QAStatus; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.WORKORDERMASTERID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.WORKORDERMASTERID_FLD].Value = objObject.WorkOrderMasterID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.WORKORDERDETAILID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.WORKORDERDETAILID_FLD].Value = objObject.WorkOrderDetailID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.ISSUEMATERIALDETAILID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.ISSUEMATERIALDETAILID_FLD].Value = objObject.IssueMaterialDetailID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.BOMQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.BOMQUANTITY_FLD].Value = objObject.BomQuantity; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to PRO_IssueMaterialDetail /// </summary> /// <Inputs> /// PRO_IssueMaterialDetailVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Tuesday, June 14, 2005 /// </History> public DataSet List() { const string METHOD_NAME = THIS + ".List()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + PRO_IssueMaterialDetailTable.ISSUEMATERIALDETAILID_FLD + "," + PRO_IssueMaterialDetailTable.LINE_FLD + "," + PRO_IssueMaterialDetailTable.COMMITQUANTITY_FLD + "," + PRO_IssueMaterialDetailTable.PRODUCTID_FLD + "," + PRO_IssueMaterialDetailTable.ISSUEMATERIALMASTERID_FLD + "," + PRO_IssueMaterialDetailTable.LOCATIONID_FLD + "," + PRO_IssueMaterialDetailTable.BINID_FLD + "," + PRO_IssueMaterialDetailTable.LOT_FLD + "," + PRO_IssueMaterialDetailTable.SERIAL_FLD + "," + PRO_IssueMaterialDetailTable.MASTERLOCATIONID_FLD + "," + PRO_IssueMaterialDetailTable.STOCKUMID_FLD + "," + PRO_IssueMaterialDetailTable.QASTATUS_FLD + "," + PRO_IssueMaterialDetailTable.WORKORDERMASTERID_FLD + "," + PRO_IssueMaterialDetailTable.WORKORDERDETAILID_FLD + "," + PRO_IssueMaterialDetailTable.BOMQUANTITY_FLD + " FROM " + PRO_IssueMaterialDetailTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS,PRO_IssueMaterialDetailTable.TABLE_NAME); return dstPCS; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to PRO_IssueMaterialDetail /// </summary> /// <Inputs> /// PRO_IssueMaterialDetailVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Tuesday, June 14, 2005 /// </History> public DataSet GetDetailData(int pintMasterID) { const string METHOD_NAME = THIS + ".GetDetailData()"; const string VIEW_PRO_ISSUEMATERIAL_DETAIL = "v_PRO_IssueMaterialDetail"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT * " + " FROM " + VIEW_PRO_ISSUEMATERIAL_DETAIL + " WHERE " + PRO_IssueMaterialDetailTable.ISSUEMATERIALMASTERID_FLD + "=" + pintMasterID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS,PRO_IssueMaterialDetailTable.TABLE_NAME); return dstPCS; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to PRO_IssueMaterialDetail /// </summary> /// <Inputs> /// PRO_IssueMaterialDetailVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Tuesday, June 14, 2005 /// </History> public void UpdateDataSet(DataSet pData) { const string METHOD_NAME = THIS + ".UpdateDataSet()"; string strSql; OleDbConnection oconPCS =null; OleDbCommandBuilder odcbPCS ; OleDbDataAdapter odadPCS = new OleDbDataAdapter(); try { strSql= "SELECT " + PRO_IssueMaterialDetailTable.ISSUEMATERIALDETAILID_FLD + "," + PRO_IssueMaterialDetailTable.LINE_FLD + "," + PRO_IssueMaterialDetailTable.COMMITQUANTITY_FLD + "," + PRO_IssueMaterialDetailTable.PRODUCTID_FLD + "," + PRO_IssueMaterialDetailTable.ISSUEMATERIALMASTERID_FLD + "," + PRO_IssueMaterialDetailTable.LOCATIONID_FLD + "," + PRO_IssueMaterialDetailTable.BINID_FLD + "," + PRO_IssueMaterialDetailTable.LOT_FLD + "," + PRO_IssueMaterialDetailTable.SERIAL_FLD + "," + PRO_IssueMaterialDetailTable.MASTERLOCATIONID_FLD + "," + PRO_IssueMaterialDetailTable.STOCKUMID_FLD + "," + PRO_IssueMaterialDetailTable.QASTATUS_FLD + "," + PRO_IssueMaterialDetailTable.WORKORDERMASTERID_FLD + "," + PRO_IssueMaterialDetailTable.AVAILABLEQUANTITY_FLD + "," + PRO_IssueMaterialDetailTable.WORKORDERDETAILID_FLD + "," + PRO_IssueMaterialDetailTable.BOMQUANTITY_FLD + " FROM " + PRO_IssueMaterialDetailTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pData.EnforceConstraints = false; odadPCS.Update(pData,PRO_IssueMaterialDetailTable.TABLE_NAME); } catch(OleDbException ex) { if(ex.Errors.Count >= 2) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// GetAvailableQuantity /// </summary> /// <param name="pintProductID"></param> /// <param name="pintWODetailID"></param> /// <returns></returns> /// <author>Trada</author> /// <date>Wednesday, June 29 2005</date> public decimal GetAvailableQuantity(int pintProductID, int pintWODetailID) { const string METHOD_NAME = THIS + ".GetAvailableQuantity()"; const string AVAILABLE_QUANTITY = "AvailableQuantity"; const string V_COMPONENTSCRAP = "V_ComponentScrap"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = " SELECT " + AVAILABLE_QUANTITY + " FROM " + V_COMPONENTSCRAP + " WHERE " + PRO_WorkOrderDetailTable.WORKORDERDETAILID_FLD + " = " + pintWODetailID.ToString() + " AND " + PRO_ComponentScrapDetailTable.COMPONENTID_FLD + " = " + pintProductID.ToString(); Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); object objResult = ocmdPCS.ExecuteScalar(); if (objResult == DBNull.Value) { return 0; } else { return decimal.Parse(objResult.ToString()); } } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// Get committed quantity of a product /// </summary> /// <param name="pintWorkOderMasterID">Work Order Master</param> /// <param name="pintWorkOrderDetailID">Work Order Detail</param> /// <param name="pintProductID">Product</param> /// <param name="pintMasterLocationID">Master Location</param> /// <param name="pintLocationID">Location</param> /// <param name="pintBinID">Bin</param> /// <param name="pstrLot">Lot</param> /// <param name="pstrSerial">Serial</param> /// <returns>Committed Quantity</returns> public decimal GetCommittedQuatity(int pintWorkOderMasterID, int pintWorkOrderDetailID, int pintProductID, int pintMasterLocationID, int pintLocationID, int pintBinID, string pstrLot, string pstrSerial) { const string METHOD_NAME = THIS + ".GetCommittedQuatity()"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = "SELECT ISNULL(SUM(ISNULL(CommitQuantity,0)), 0) FROM PRO_IssueMaterialDetail" + " WHERE WorkOrderMasterID = " + pintWorkOderMasterID + " AND WorkOrderDetailID = " + pintWorkOrderDetailID + " AND ProductID = " + pintProductID + " AND MasterLocationID = " + pintMasterLocationID + " AND LocationID = " + pintLocationID; if (pintBinID > 0) strSql += " AND BinID = " + pintBinID; if (pstrLot != null && pstrLot != string.Empty) strSql += " AND Lot = ?"; if (pstrSerial != null && pstrSerial != string.Empty) strSql += " AND Serial = ?"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); if (pstrLot != null && pstrLot != string.Empty) { ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.LOT_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.LOT_FLD].Value = pstrLot; } if (pstrSerial != null && pstrSerial != string.Empty) { ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.SERIAL_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.SERIAL_FLD].Value = pstrSerial; } ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); try { return decimal.Parse(ocmdPCS.ExecuteScalar().ToString()); } catch { return decimal.Zero; } } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// Recalculate remainquantity after complete WOLine /// </summary> /// <param name="pintWOIssueID"></param> /// <param name="pdecSubtractQty"></param> /// <returns></returns> public void UpdateRemainQuantity(int pintWOIssueID, decimal pdecSubtractQty) { const string METHOD_NAME = THIS + ".UpdateRemainQuantity()"; //prepare value for parameters OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); strSql= "UPDATE PRO_IssueMaterialDetail SET " + "CompletedQuantity" + "= isnull(CompletedQuantity,0) + ?" + "" +" WHERE " + PRO_IssueMaterialDetailTable.ISSUEMATERIALDETAILID_FLD + "= ?"; ocmdPCS.Parameters.Add(new OleDbParameter("CompletedQuantity", OleDbType.Decimal)); ocmdPCS.Parameters["CompletedQuantity"].Value = pdecSubtractQty; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssueMaterialDetailTable.ISSUEMATERIALDETAILID_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[PRO_IssueMaterialDetailTable.ISSUEMATERIALDETAILID_FLD].Value = pintWOIssueID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } } }
/* ------------------------------------------------------------------- Author: Cameron T. Owen Contact: cameron.t.owen at gmail dot com Copyright (c) 2011, Wayward Logic, www.waywardlogic.com Cameron T. Owen 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 Wayward Logic nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using UnityEngine; using System.Collections; using System.Collections.Generic; public enum XMLTokenType {None,Declaration,EntityElement,StartElement,EndElement,Attribute,Text,Entity} public enum XMLParserAttrbuteMode {Name,Assignment,Value} public enum XMLNodeType {Text,Element} /// <summary> /// XML Attribute Type /// </summary> [System.Serializable] public struct XMLAttribute { /// <summary> /// Name of the attribute /// </summary> public string name; /// <summary> /// Value of the attribute /// </summary> public string value; /// <summary> /// Initializes a new instance of the <see cref="XMLAttribute"/> struct. /// </summary> /// <param name='name'> /// Name of the attribute. /// </param> /// <param name='value'> /// Value of the attribute. /// </param> public XMLAttribute (string name, string value) { this.name = name; this.value = value; } /// <summary> /// Initializes a new instance of the <see cref="XMLAttribute"/> struct. /// </summary> /// <param name='name'> /// Name of the attribute. /// </param> public XMLAttribute (string name) { this.name = name; this.value = ""; } /// <summary> /// Returns a <see cref="System.String"/> that represents the current <see cref="XMLAttribute"/>. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents the current <see cref="XMLAttribute"/>. /// </returns> public override string ToString () { return value; } } /// <summary> /// Interface that all XML datatypes impliment. /// </summary> public interface IXMLNode { /// <summary> /// Gets or sets the value of the node. /// </summary> /// <value> /// The value. /// </value> string value { get; set; } /// <summary> /// Gets the type. /// </summary> /// <value> /// The type. /// </value> XMLNodeType type { get; } /// <summary> /// Gets the parent. /// </summary> /// <value> /// The parent IXMLNode in the hierarchy. /// </value> IXMLNode Parent { get; } /// <summary> /// Gets or sets the children. /// </summary> /// <value> /// The children IXMLNodes of this node. /// </value> List<IXMLNode> Children { get; set; } List<XMLAttribute> Attributes { get; set; } } /// <summary> /// XMLText node is used to represent text content in an XML document. /// </summary> [System.Serializable] public class XMLText : IXMLNode { protected string valueString; protected IXMLNode parentNode; /// <summary> /// Gets or sets the value. /// </summary> /// <value> /// The value string contains the text content of this node. /// </value> public string value { get { return valueString; } set { valueString = value; } } /// <summary> /// Gets the type. /// </summary> /// <value> /// Will always return XMLNodeType.Text /// </value> public XMLNodeType type { get { return XMLNodeType.Text; } } /// <summary> /// Gets the parent IXMLNode. /// </summary> /// <value> /// The parent node object. /// </value> public IXMLNode Parent { get { return parentNode; } } /// <summary> /// Gets or sets the child list. /// </summary> /// <value> /// The list of child nodes. Will always be an empty list. Settig the list will have no effect. /// </value> public List<IXMLNode> Children { get { return new List<IXMLNode> (); } set { } } /// <summary> /// Gets or sets the attribute list. /// </summary> /// <value> /// The list of this node's attributes. Will always be an empty list. /// </value> public List<XMLAttribute> Attributes { get { return new List<XMLAttribute> (); } set { } } /// <summary> /// Initializes a new instance of the <see cref="XMLText"/> class. /// </summary> /// <param name='text'> /// The text of the node. /// </param> /// <param name='parent'> /// This node's parent node. Should not be null for text nodes. /// </param> public XMLText (string text, IXMLNode parent) { valueString = text; parentNode = parent; if (parent != null) { parent.Children.Add (this); } } /// <summary> /// Returns a <see cref="System.String"/> that represents the current <see cref="XMLText"/>. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents the current <see cref="XMLText"/>. /// </returns> public override string ToString () { return valueString; } } /// <summary> /// XMLElement class is a container class for other XMLElements, XMLText nodes and XMLAttributes. /// </summary> [System.Serializable] public class XMLElement : IXMLNode { protected string valueString; protected IXMLNode parentNode; protected List<IXMLNode> childList; protected List<XMLAttribute> attributeList; /// <summary> /// Gets or sets the name value. /// </summary> /// <value> /// The name value of this XML Tag. /// </value> public string value { get { return valueString; } set { valueString = value; } } /// <summary> /// Gets the type. /// </summary> /// <value> /// Will always return XMLNodeType.Element /// </value> public XMLNodeType type { get { return XMLNodeType.Element; } } /// <summary> /// Gets the parent node. /// </summary> /// <value> /// The parent XMLElement of this node or null if this is the root node. /// </value> public IXMLNode Parent { get { return parentNode; } } /// <summary> /// Gets or sets the child list. /// </summary> /// <value> /// The list of child nodes. Will always be an empty list. /// </value> public List<IXMLNode> Children { get { return childList; } set { childList = value; } } /// <summary> /// Gets or sets the attribute list. /// </summary> /// <value> /// The list of this node's attributes. /// </value> public List<XMLAttribute> Attributes { get { return attributeList; } set { attributeList = value; } } /// <summary> /// Initializes a new instance of the <see cref="XMLElement"/> class. /// </summary> /// <param name='name'> /// Tage Name of this XMLElement. /// </param> /// <param name='parent'> /// The Parent node. /// </param> /// <param name='children'> /// List of child nodes /// </param> /// <param name='attributes'> /// List of attributes. /// </param> public XMLElement (string name, IXMLNode parent, List<IXMLNode> children, List<XMLAttribute> attributes) { valueString = name; parentNode = parent; childList = children; attributeList = attributes; if (parent != null) { parent.Children.Add (this); } } /// <summary> /// Initializes a new instance of the <see cref="XMLElement"/> class. /// </summary> /// <param name='name'> /// Tage Name of this XMLElement. /// </param> /// <param name='parent'> /// The Parent node. /// </param> /// <param name='children'> /// List of child nodes /// </param> public XMLElement (string name, IXMLNode parent, List<IXMLNode> children) { valueString = name; parentNode = parent; childList = children; attributeList = new List<XMLAttribute> (); if (parent != null) { parent.Children.Add (this); } } /// <summary> /// Initializes a new instance of the <see cref="XMLElement"/> class. /// </summary> /// <param name='name'> /// Tage Name of this XMLElement. /// </param> /// <param name='parent'> /// The Parent node. /// </param> public XMLElement (string name, IXMLNode parent) { valueString = name; parentNode = parent; childList = new List<IXMLNode> (); attributeList = new List<XMLAttribute> (); if (parent != null) { parent.Children.Add (this); } } } /// <summary> /// XMLParser is a static class used to parse XML formmated strings into a hierarchy of IXMLNode objects. /// </summary> public class XMLParser { protected XMLElement rootElement; protected XMLElement currentElement; protected bool rootflag; protected List<XMLAttribute> attributeList; protected string xmlString; /// <summary> /// Gets the XML Root element. /// </summary> /// <value> /// The root XMLElement of the last parsed xml string. /// </value> public XMLElement XMLRootElement { get { return rootElement; } } /// <summary> /// Gets the last XML string that was parsed by the parser or sets a new one for future parse calls. /// </summary> /// <value> /// The XML string. /// </value> public string XMLString { get { return xmlString; } set { xmlString = value; rootflag = false; } } /// <summary> /// Initializes a new instance of the <see cref="XMLParser"/> class. /// </summary> /// <param name='xmlString'> /// XML formatted string to parse. /// </param> public XMLParser(string xmlString) { this.xmlString = xmlString; } /// <summary> /// Initializes a new instance of the <see cref="XMLParser"/> class. /// </summary> public XMLParser() { this.xmlString = ""; } /// <summary> /// Parse the specified xmlString. /// </summary> /// <param name='xmlString'> /// Xml string. /// </param> /// <returns> /// A <see cref="IXMLNode"/> hierarchy of the given XML formatted string. /// </returns> public virtual XMLElement Parse(string xmlString) { this.xmlString = xmlString; return Parse(); } /// <summary> /// Parse the previously set xmlString. /// </summary> /// <returns> /// A <see cref="IXMLNode"/> hierarchy of the given XML formatted string. /// </returns> public XMLElement Parse () { rootflag = false; //this.xmlString = xmlString; string contentString = ""; string elementName = ""; string attributeName = ""; string entitySuspendedContent = ""; XMLTokenType currentToken = XMLTokenType.None; XMLTokenType previousToken = XMLTokenType.None; XMLParserAttrbuteMode attributeMode = XMLParserAttrbuteMode.Name; attributeList = new List<XMLAttribute> (); int i = 0; int xmlStringLength = xmlString.Length; // TOKENIZE XML FORMATTED STRING while (i < xmlStringLength) { char c = xmlString[i]; switch (c) { // TAG TOKEN START case '<': previousToken = currentToken; // switching token types... // deal with passive token handlers on active token start switch (previousToken) { case XMLTokenType.Entity: EntityHandler (contentString); break; case XMLTokenType.Text: TextHandler (contentString); break; } // What kind of tag start? switch (xmlString[i + 1]) { case '?': currentToken = XMLTokenType.Declaration; i++; break; case '!': currentToken = XMLTokenType.EntityElement; i++; break; case '/': currentToken = XMLTokenType.EndElement; i++; break; default: // Non specific token start, decide type based on previous token switch (previousToken) { case XMLTokenType.Declaration: currentToken = XMLTokenType.Declaration; break; case XMLTokenType.EntityElement: currentToken = XMLTokenType.EntityElement; break; default: currentToken = XMLTokenType.StartElement; break; } break; } // reset content string for new token contentString = ""; break; // TAG TOKEN END case '>': // switching token types... previousToken = currentToken; switch (currentToken) { case XMLTokenType.Declaration: DeclarationHandler (contentString); break; case XMLTokenType.EntityElement: EntityHandler (contentString); break; case XMLTokenType.StartElement: StartElementHandler (contentString); // handle special case for solo tags if (xmlString[i - 1] == '/') { EndElementHandler(contentString); } break; case XMLTokenType.EndElement: EndElementHandler (contentString); break; case XMLTokenType.Attribute: StartElementHandler (elementName); previousToken = XMLTokenType.StartElement; break; } // Default to text token untill we find something different... contentString = ""; currentToken = XMLTokenType.Text; break; // WHITESPACE & ATTRIBUTE START case ' ': // This ought to remove needless whitespace but it mucks up // entity parsing, not sure why :( - probably don't need // to agressively stip whitsepace for game use though. /* int contentStringLength = contentString.Length; if (contentStringLength > 1) { if (contentString[contentStringLength - 2] == ' ') break; // break and ignore extra whitespace } */ switch (currentToken) { case XMLTokenType.StartElement: previousToken = currentToken; currentToken = XMLTokenType.Attribute; elementName = contentString; contentString = ""; attributeMode = XMLParserAttrbuteMode.Name; break; case XMLTokenType.Text: contentString += c; break; case XMLTokenType.Attribute: if (attributeMode == XMLParserAttrbuteMode.Value) { contentString += c; } break; } break; // ATTRIBUTE ASSIGNMENT case '=': switch (currentToken) { case XMLTokenType.Attribute: switch (attributeMode) { case XMLParserAttrbuteMode.Name: attributeName = contentString.Trim(); contentString = ""; attributeMode = XMLParserAttrbuteMode.Assignment; break; case XMLParserAttrbuteMode.Value: contentString += c; break; } break; default: contentString += c; break; } break; // ATTRIBUTE VALUE case '"': switch (currentToken) { case XMLTokenType.Attribute: switch (attributeMode) { // Start Value case XMLParserAttrbuteMode.Assignment: attributeMode = XMLParserAttrbuteMode.Value; break; // End Value case XMLParserAttrbuteMode.Value: AttributeHandler (attributeName, contentString); contentString = ""; attributeMode = XMLParserAttrbuteMode.Name; break; } break; } break; // ENTITY REFERENCE START case '&': previousToken = currentToken; // siwtch to entity mode currentToken = XMLTokenType.Entity; entitySuspendedContent = contentString; // save current content while in entity mode contentString = ""; // clear content for recording entity break; // ENTITY REFERENCE END case ';': if(currentToken == XMLTokenType.Entity) { currentToken = previousToken; // swicth back to last token mode. contentString = entitySuspendedContent + ParseEntityReference(contentString); // restore content string with parsed entity } else { contentString += c; } break; // DEFAULT CONTENT default: contentString += c; // jsut add it to the content string... break; } i++; } return rootElement; } /// <summary> /// Handles XML decleration. Base implimentation does nothing. /// </summary> /// <param name='content'> /// Content of the entity tag /// </param> protected virtual void DeclarationHandler (string content) { // does nothing } /// <summary> /// Handles entitys like comments. Base implimentation does nothing. /// </summary> /// <param name='content'> /// Content of the entity tag /// </param> protected virtual void EntityHandler (string content) { // does nothing } /// <summary> /// Handles opening tags. /// </summary> /// <param name='tagName'> /// Tag name. /// </param> protected virtual void StartElementHandler (string tagName) { // placeholder for new element. XMLElement newElement; // no assignment is bad form but necessary if (!rootflag) { // need to setup root element... newElement = new XMLElement (tagName.Trim(), null); rootElement = newElement; rootflag = true; } else { // standard new element creations... newElement = new XMLElement (tagName.Trim(), currentElement); } // Add attributes we've encounted thus far int i = 0; int attributeCount = attributeList.Count; while (i < attributeCount) { newElement.Attributes.Add (attributeList[i]); i++; } // clear saved attribute list attributeList = new List<XMLAttribute> (); // advance current element currentElement = newElement; } /// <summary> /// Handles end tags. /// </summary> /// <param name='tagName'> /// Tag name. /// </param> protected virtual void EndElementHandler (string tagName) { if (rootflag) { if (rootElement != currentElement) { currentElement = (XMLElement)currentElement.Parent; } } } /// <summary> /// Handles attribute name = value pairs. /// </summary> /// <param name='name'> /// Name of the attribute. /// </param> /// <param name='value'> /// Value of the attribute. /// </param> protected virtual void AttributeHandler (string name, string value) { attributeList.Add (new XMLAttribute (name.Trim(), value)); } /// <summary> /// Handles text content inetween tags. Combines neighbouring text nodes where possible. /// </summary> /// <param name='text'> /// The text content of the node. /// </param> protected virtual void TextHandler (string text) { // only if usable text and root flag set if (rootflag && text.Trim ().Length > 0) { // check for text nodes made jsut before this append instead of creating a new node if (currentElement.Children.Count != 0) { IXMLNode lastOfCurrent = currentElement.Children[currentElement.Children.Count - 1]; if (lastOfCurrent.type == XMLNodeType.Text) { lastOfCurrent.value += text; return; // exit early } } // If we get here we need a new text node... new XMLText (text, currentElement); } } public static char ParseEntityReference(string entity) { switch(entity) { case "lt" : return '<'; case "gt" : return '>'; case "quot": return '"'; case "apos": return '\''; case "amp" : return '&'; } return '\0'; // return unicode 0 for unknown entities } public static string GetEntityReference(char c) { switch(c) { case '<' : return "&lt;"; case '>' : return "&gt;"; case '"' : return "&quot;"; case '\'': return "&apos;"; case '&' : return "&amp;"; } return c.ToString(); } }
// MIT License // // Copyright (c) 2017 Maarten van Sambeek. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. namespace ConnectQl.Intellisense { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using ConnectQl.DataSources; using ConnectQl.Expressions; using ConnectQl.Expressions.Visitors; using ConnectQl.Intellisense.Protocol; using ConnectQl.Interfaces; using ConnectQl.Internal; using ConnectQl.Parser.Ast; using ConnectQl.Parser.Ast.Expressions; using ConnectQl.Parser.Ast.Sources; using ConnectQl.Parser.Ast.Statements; using ConnectQl.Parser.Ast.Visitors; using ConnectQl.Query; using JetBrains.Annotations; /// <summary> /// The interpreter. /// </summary> internal class Evaluator : NodeVisitor { /// <summary> /// The parsed script. /// </summary> private ParsedDocument parsedScript; /// <summary> /// The statements. /// </summary> private EvaluationResult statements; /// <summary> /// Gets the sources. /// </summary> public IReadOnlyList<SerializableDataSourceDescriptorRange> Sources => this.statements.Sources; /// <summary> /// Gets the variables. /// </summary> public IReadOnlyList<SerializableVariableDescriptorRange> Variables => this.statements.Variables; /// <summary> /// Initializes a new instance of the <see cref="Evaluator"/> class. /// </summary> /// <param name="parsedScript"> /// The parsed script. /// </param> /// <param name="tokens"> /// The tokens. /// </param> /// <returns> /// The <see cref="EvaluationResult"/>. /// </returns> internal static IEvaluationResult GetIntellisenseData([NotNull] ParsedDocument parsedScript, IReadOnlyList<IClassifiedToken> tokens) { var evaluator = new Evaluator { parsedScript = parsedScript, statements = new EvaluationResult(parsedScript.Context, tokens), }; foreach (var statement in parsedScript.Root.Statements) { evaluator.statements.SetActiveStatement(statement); evaluator.Visit(statement); } return evaluator.statements; } /// <summary> /// Visits a <see cref="ConnectQl.Parser.Ast.Statements.UseStatement"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal override Node VisitUseStatement(UseStatement node) { try { ((IInternalExecutionContext)this.statements).RegisterDefault(node.SettingFunction.Name, node.FunctionName, this.Evaluate(node.SettingFunction, out var sideEffects)); } catch { // Ignore. } return base.VisitUseStatement(node); } /// <summary> /// Visits a <see cref="ConnectQl.Parser.Ast.VariableDeclaration"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal override Node VisitVariableDeclaration([NotNull] VariableDeclaration node) { this.statements.SetVariable(node.Name, this.Evaluate(node.Expression, out var sideEffects), !sideEffects); return base.VisitVariableDeclaration(node); } /// <summary> /// Visits a <see cref="ConnectQl.Parser.Ast.Statements.SelectFromStatement"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal override Node VisitSelectFromStatement([NotNull] SelectFromStatement node) { var descriptors = this.Evaluate(node.Source, out var hasSideEffects)?.GetDataSourceDescriptorsAsync(this.statements).Result.ToArray(); if (descriptors != null) { foreach (var descriptor in descriptors) { this.statements.SetSource(descriptor.Alias, descriptor); } } return base.VisitSelectFromStatement(node); } /// <summary> /// Evaluates the <see cref="ConnectQl.Parser.Ast.Expressions.ConnectQlExpressionBase"/>. /// </summary> /// <param name="expression"> /// The expression to evaluate. /// </param> /// <param name="sideEffects"> /// <c>true</c> if the expression has side effects, <c>false</c> otherwise. /// </param> /// <returns> /// The <see cref="object"/>. /// </returns> private object Evaluate(ConnectQlExpressionBase expression, out bool sideEffects) { try { if (this.parsedScript.Context.NodeData.HasSideEffects(expression, variable => this.statements.HasVariableSideEffects(variable))) { sideEffects = true; return null; } sideEffects = false; var linqExpression = GenericVisitor.Visit( (ExecutionContextExpression e) => Expression.Constant(this.statements), this.parsedScript.Context.NodeData.ConvertToLinqExpression(expression)); return Expression.Lambda(linqExpression).Compile().DynamicInvoke(); } catch { sideEffects = true; return null; } } /// <summary> /// Evaluates the <see cref="ConnectQl.Parser.Ast.Sources.SourceBase"/>. /// </summary> /// <param name="expression"> /// The expression to evaluate. /// </param> /// <param name="sideEffects"> /// <c>true</c> if the expression has side effects, <c>false</c> otherwise. /// </param> /// <returns> /// The <see cref="object"/>. /// </returns> private DataSource Evaluate(SourceBase expression, out bool sideEffects) { try { if (this.parsedScript.Context.NodeData.HasSideEffects(expression, variable => this.statements.HasVariableSideEffects(variable))) { sideEffects = true; return null; } sideEffects = false; var linqExpression = GenericVisitor.Visit( (ExecutionContextExpression e) => Expression.Constant(this.statements), this.parsedScript.Context.NodeData.ConvertToDataSource(expression)); return Expression.Lambda<Func<DataSource>>(linqExpression).Compile().Invoke(); } catch { sideEffects = true; return null; } } } }
using System; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; // Based on vbAccelerator article: // http://www.vbaccelerator.com/home/NET/Code/Controls/Popup_Windows/Popup_Windows/article.asp namespace DeadCode.WME.Controls { #region Event Argument Classes /// <summary> /// Contains event information for a <see cref="PopupClosed"/> event. /// </summary> public class PopupClosedEventArgs : EventArgs { /// <summary> /// The popup form. /// </summary> private Form popup = null; /// <summary> /// Gets the popup form which is being closed. /// </summary> public Form Popup { get { return this.popup; } } /// <summary> /// Constructs a new instance of this class for the specified /// popup form. /// </summary> /// <param name="popup">Popup Form which is being closed.</param> public PopupClosedEventArgs(Form popup) { this.popup = popup; } } /// <summary> /// Arguments to a <see cref="PopupCancelEvent"/>. Provides a /// reference to the popup form that is to be closed and /// allows the operation to be cancelled. /// </summary> public class PopupCancelEventArgs : EventArgs { /// <summary> /// Whether to cancel the operation /// </summary> private bool cancel = false; /// <summary> /// Mouse down location /// </summary> private Point location; /// <summary> /// Popup form. /// </summary> private Form popup = null; /// <summary> /// Constructs a new instance of this class. /// </summary> /// <param name="popup">The popup form</param> /// <param name="location">The mouse location, if any, where the /// mouse event that would cancel the popup occured.</param> public PopupCancelEventArgs(Form popup, Point location) { this.popup = popup; this.location = location; this.cancel = false; } /// <summary> /// Gets the popup form /// </summary> public Form Popup { get { return this.popup; } } /// <summary> /// Gets the location that the mouse down which would cancel this /// popup occurred /// </summary> public Point CursorLocation { get { return this.location; } } /// <summary> /// Gets/sets whether to cancel closing the form. Set to /// <c>true</c> to prevent the popup from being closed. /// </summary> public bool Cancel { get { return this.cancel; } set { this.cancel = value; } } } #endregion #region Delegates /// <summary> /// Represents the method which responds to a <see cref="PopupClosed"/> event. /// </summary> public delegate void PopupClosedEventHandler(object sender, PopupClosedEventArgs e); /// <summary> /// Represents the method which responds to a <see cref="PopupCancel"/> event. /// </summary> public delegate void PopupCancelEventHandler(object sender, PopupCancelEventArgs e); #endregion #region PopupWindowHelper /// <summary> /// A class to assist in creating popup windows like Combo Box drop-downs and Menus. /// This class includes functionality to keep the title bar of the popup owner form /// active whilst the popup is displayed, and to automatically cancel the popup /// whenever the user clicks outside the popup window or shifts focus to another /// application. /// </summary> public class PopupWindowHelper : NativeWindow { #region Member Variables /// <summary> /// Event Handler to detect when the popup window is closed /// </summary> private EventHandler popClosedHandler = null; /// <summary> /// Message filter to detect mouse clicks anywhere in the application /// whilst the popup window is being displayed. /// </summary> private PopupWindowHelperMessageFilter filter = null; /// <summary> /// The popup form that is being shown. /// </summary> private Form popup = null; /// <summary> /// The owner of the popup form that is being shown: /// </summary> private Form owner = null; /// <summary> /// Whether the popup is showing or not. /// </summary> private bool popupShowing = false; /// <summary> /// Whether the popup has been cancelled, notified by PopupCancel, /// rather than closed. /// </summary> private bool skipClose = false; #endregion /// <summary> /// Raised when the popup form is closed. /// </summary> public event PopupClosedEventHandler PopupClosed; /// <summary> /// Raised when the Popup Window is about to be cancelled. The /// <see cref="PopupCancelEventArgs.Cancel"/> property can be /// set to <c>true</c> to prevent the form from being cancelled. /// </summary> public event PopupCancelEventHandler PopupCancel; /// <summary> /// Shows the specified Form as a popup window, keeping the /// Owner's title bar active and preparing to cancel the popup /// should the user click anywhere outside the popup window. /// <para>Typical code to use this message is as follows:</para> /// <code> /// frmPopup popup = new frmPopup(); /// Point location = this.PointToScreen(new Point(button1.Left, button1.Bottom)); /// popupHelper.ShowPopup(this, popup, location); /// </code> /// <para>Put as much initialisation code as possible /// into the popup form's constructor, rather than the <see cref="System.Windows.Forms.Load"/> /// event as this will improve visual appearance.</para> /// </summary> /// <param name="owner">Main form which owns the popup</param> /// <param name="popup">Window to show as a popup</param> /// <param name="location">Location relative to the screen to show the popup at.</param> public void ShowPopup(Form owner, Form popup, Point location) { ShowPopup(owner, popup, location, true); } public void ShowPopup(Form owner, Form popup, Point location, bool TabOrderFix) { this.owner = owner; this.popup = popup; // Start checking for the popup being cancelled Application.AddMessageFilter(filter); // Set the location of the popup form: popup.StartPosition = FormStartPosition.Manual; popup.Location = location; // Make it owned by the window that's displaying it: owner.AddOwnedForm(popup); // Respond to the Closed event in case the popup // is closed by its own internal means popClosedHandler = new EventHandler(popup_Closed); popup.Closed += popClosedHandler; // Show the popup: this.popupShowing = true; popup.Show(); popup.Activate(); // A little bit of fun. We've shown the popup, // but because we've kept the main window's // title bar in focus the tab sequence isn't quite // right. This can be fixed by sending a tab, // but that on its own would shift focus to the // second control in the form. So send a tab, // followed by a reverse-tab. if (TabOrderFix) { // Send a Tab command: NativeMethods.keybd_event((byte)Keys.Tab, 0, 0, 0); NativeMethods.keybd_event((byte)Keys.Tab, 0, (int)NativeMethods.KeyboardEvent.KeyUp, 0); // Send a reverse Tab command: NativeMethods.keybd_event((byte)Keys.ShiftKey, 0, 0, 0); NativeMethods.keybd_event((byte)Keys.Tab, 0, 0, 0); NativeMethods.keybd_event((byte)Keys.Tab, 0, (int)NativeMethods.KeyboardEvent.KeyUp, 0); NativeMethods.keybd_event((byte)Keys.ShiftKey, 0, (int)NativeMethods.KeyboardEvent.KeyUp, 0); } // Start filtering for mouse clicks outside the popup filter.Popup = popup; } /// <summary> /// Responds to the <see cref="System.Windows.Forms.Form.Closed"/> /// event from the popup form. /// </summary> /// <param name="sender">Popup form that has been closed.</param> /// <param name="e">Not used.</param> private void popup_Closed(object sender, EventArgs e) { ClosePopup(); } /// <summary> /// Subclasses the owning form's existing Window Procedure to enables the /// title bar to remain active when a popup is show, and to detect if /// the user clicks onto another application whilst the popup is visible. /// </summary> /// <param name="m">Window Procedure Message</param> protected override void WndProc(ref Message m) { base.WndProc(ref m); if (this.popupShowing) { // check for WM_ACTIVATE and WM_NCACTIVATE if (m.Msg == (int)NativeMethods.WindowMessage.NonClientActivate) { // Check if the title bar will made inactive: if (((int) m.WParam) == 0) { // If so reactivate it. NativeMethods.SendMessage(this.Handle, (int)NativeMethods.WindowMessage.NonClientActivate, 1, IntPtr.Zero); // Note it's no good to try and consume this message; // if you try to do that you'll end up with windows // that don't respond. } } else if (m.Msg == (int)NativeMethods.WindowMessage.ActivateApplication) { // Check if the application is being deactivated. if ((int)m.WParam == 0) { // It is so cancel the popup: ClosePopup(); // And put the title bar into the inactive state: NativeMethods.PostMessage(this.Handle, (int)NativeMethods.WindowMessage.ActivateApplication, 0, IntPtr.Zero); } } } } public void CancelPopup() { skipClose = true; ClosePopup(); } /// <summary> /// Called when the popup is being hidden. /// </summary> public void ClosePopup() { if (this.popupShowing) { if (!skipClose) { // Raise event to owner OnPopupClosed(new PopupClosedEventArgs(this.popup)); } skipClose = false; // Make sure the popup is closed and we've cleaned // up: this.owner.RemoveOwnedForm(this.popup); this.popupShowing = false; this.popup.Closed -= popClosedHandler; this.popClosedHandler = null; this.popup.Close(); // No longer need to filter for clicks outside the // popup. Application.RemoveMessageFilter(filter); // If we did something from the popup which shifted // focus to a new form, like showing another popup // or dialog, then Windows won't know how to bring // the original owner back to the foreground, so // force it here: this.owner.Activate(); // Null out references for GC this.popup = null; this.owner = null; } } /// <summary> /// Raises the <see cref="PopupClosed"/> event. /// </summary> /// <param name="e"><see cref="PopupClosedEventArgs"/> describing the /// popup form that is being closed.</param> protected virtual void OnPopupClosed(PopupClosedEventArgs e) { if (this.PopupClosed != null) { this.PopupClosed(this, e); } } private void popup_Cancel(object sender, PopupCancelEventArgs e) { OnPopupCancel(e); } /// <summary> /// Raises the <see cref="PopupCancel"/> event. /// </summary> /// <param name="e"><see cref="PopupCancelEventArgs"/> describing the /// popup form that about to be cancelled.</param> protected virtual void OnPopupCancel(PopupCancelEventArgs e) { if (this.PopupCancel != null) { this.PopupCancel(this, e); if (!e.Cancel) { skipClose = true; } } } /// <summary> /// Default constructor. /// </summary> /// <remarks>Use the <see cref="System.Windows.Forms.NativeWindow.AssignHandle"/> /// method to attach this class to the form you want to show popups from.</remarks> public PopupWindowHelper() { filter = new PopupWindowHelperMessageFilter(this); filter.PopupCancel += new PopupCancelEventHandler(popup_Cancel); } } #endregion #region PopupWindowHelperMessageFilter /// <summary> /// A Message Loop filter which detect mouse events whilst the popup form is shown /// and notifies the owning <see cref="PopupWindowHelper"/> class when a mouse /// click outside the popup occurs. /// </summary> public class PopupWindowHelperMessageFilter : IMessageFilter { /// <summary> /// Raised when the Popup Window is about to be cancelled. The /// <see cref="PopupCancelEventArgs.Cancel"/> property can be /// set to <c>true</c> to prevent the form from being cancelled. /// </summary> public event PopupCancelEventHandler PopupCancel; /// <summary> /// The popup form /// </summary> private Form popup = null; /// <summary> /// The owning <see cref="PopupWindowHelper"/> object. /// </summary> private PopupWindowHelper owner = null; /// <summary> /// Constructs a new instance of this class and sets the owning /// object. /// </summary> /// <param name="owner">The <see cref="PopupWindowHelper"/> object /// which owns this class.</param> public PopupWindowHelperMessageFilter(PopupWindowHelper owner) { this.owner = owner; } /// <summary> /// Gets/sets the popup form which is being displayed. /// </summary> public Form Popup { get { return this.popup; } set { this.popup = value; } } /// <summary> /// Checks the message loop for mouse messages whilst the popup /// window is displayed. If one is detected the position is /// checked to see if it is outside the form, and the owner /// is notified if so. /// </summary> /// <param name="m">Windows Message about to be processed by the /// message loop</param> /// <returns><c>true</c> to filter the message, <c>false</c> otherwise. /// This implementation always returns <c>false</c>.</returns> public bool PreFilterMessage(ref Message m) { if (this.popup != null) { switch (m.Msg) { case (int)NativeMethods.WindowMessage.LeftButtonDown: case (int)NativeMethods.WindowMessage.RightButtonDown: case (int)NativeMethods.WindowMessage.MiddleButtonDown: case (int)NativeMethods.WindowMessage.NcLeftButtonDown: case (int)NativeMethods.WindowMessage.NcRightButtonDown: case (int)NativeMethods.WindowMessage.NcMiddleButtonDown: OnMouseDown(); break; } } return false; } /// <summary> /// Checks the mouse location and calls the OnCancelPopup method /// if the mouse is outside the popup form. /// </summary> private void OnMouseDown() { // Get the cursor location Point cursorPos = Cursor.Position; // Check if it is within the popup form if (!popup.Bounds.Contains(cursorPos)) { // If not, then call to see if it should be closed OnCancelPopup(new PopupCancelEventArgs(popup, cursorPos)); } } /// <summary> /// Raises the <see cref="PopupCancel"/> event. /// </summary> /// <param name="e">The <see cref="PopupCancelEventArgs"/> associated /// with the cancel event.</param> protected virtual void OnCancelPopup(PopupCancelEventArgs e) { if (this.PopupCancel != null) { this.PopupCancel(this, e); } if (!e.Cancel) { owner.ClosePopup(); // Clear reference for GC popup = null; } } } #endregion }
// // https://github.com/mythz/ServiceStack.Redis // ServiceStack.Redis: ECMA CLI Binding to the Redis key-value storage system // // Authors: // Demis Bellot ([email protected]) // // Copyright 2010 Liquidbit Ltd. // // Licensed under the same terms of Redis and ServiceStack: new BSD license. // using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using NServiceKit.Common.Extensions; using NServiceKit.Common.Utils; using NServiceKit.Redis.Generic; using NServiceKit.Text; namespace NServiceKit.Redis { /// <summary> /// The client wraps the native redis operations into a more readable c# API. /// /// Where possible these operations are also exposed in common c# interfaces, /// e.g. RedisClient.Lists => IList[string] /// RedisClient.Sets => ICollection[string] /// </summary> public partial class RedisClient : RedisNativeClient, IRedisClient { public RedisClient() { Init(); } public RedisClient(string host) : base(host) { Init(); } public RedisClient(string host, int port) : base(host, port) { Init(); } public void Init() { this.Lists = new RedisClientLists(this); this.Sets = new RedisClientSets(this); this.SortedSets = new RedisClientSortedSets(this); this.Hashes = new RedisClientHashes(this); } public string this[string key] { get { return GetValue(key); } set { SetEntry(key, value); } } public string GetTypeSequenceKey<T>() { return "seq:" + typeof(T).Name; } public string GetTypeIdsSetKey<T>() { return "ids:" + typeof(T).Name; } public void RewriteAppendOnlyFileAsync() { base.BgRewriteAof(); } public List<string> GetAllKeys() { return SearchKeys("*"); } public void SetEntry(string key, string value) { var bytesValue = value != null ? value.ToUtf8Bytes() : null; Set(key, bytesValue); } public void SetEntry(string key, string value, TimeSpan expireIn) { var bytesValue = value != null ? value.ToUtf8Bytes() : null; SetEx(key, (int)expireIn.TotalSeconds, bytesValue); } public bool SetEntryIfNotExists(string key, string value) { if (value == null) throw new ArgumentNullException("value"); return SetNX(key, value.ToUtf8Bytes()) == Success; } public string GetValue(string key) { var bytes = Get(key); return bytes == null ? null : bytes.FromUtf8Bytes(); } public string GetAndSetEntry(string key, string value) { return GetSet(key, value.ToUtf8Bytes()).FromUtf8Bytes(); } public bool ContainsKey(string key) { return Exists(key) == Success; } public bool Remove(string key) { return Del(key) == Success; } public bool RemoveEntry(params string[] keys) { if (keys.Length == 0) return false; return Del(keys) == Success; } public int IncrementValue(string key) { return Incr(key); } public int IncrementValueBy(string key, int count) { return IncrBy(key, count); } public int DecrementValue(string key) { return Decr(key); } public int DecrementValueBy(string key, int count) { return DecrBy(key, count); } public int AppendToValue(string key, string value) { return base.Append(key, value.ToUtf8Bytes()); } public string GetSubstring(string key, int fromIndex, int toIndex) { return base.Substr(key, fromIndex, toIndex).FromUtf8Bytes(); } public string GetRandomKey() { return RandomKey(); } public bool ExpireEntryIn(string key, TimeSpan expireIn) { return Expire(key, (int)expireIn.TotalSeconds) == Success; } public bool ExpireEntryAt(string key, DateTime expireAt) { return ExpireAt(key, expireAt.ToUnixTime()) == Success; } public TimeSpan GetTimeToLive(string key) { return TimeSpan.FromSeconds(Ttl(key)); } public IRedisTypedClient<T> GetTypedClient<T>() { return new RedisTypedClient<T>(this); } public IDisposable AcquireLock(string key) { return new RedisLock(this, key, null); } public IDisposable AcquireLock(string key, TimeSpan timeOut) { return new RedisLock(this, key, timeOut); } public IRedisTransaction CreateTransaction() { return new RedisTransaction(this); } public List<string> SearchKeys(string pattern) { var hasBug = IsPreVersion1_26; if (hasBug) { var spaceDelimitedKeys = KeysV126(pattern).FromUtf8Bytes(); return spaceDelimitedKeys.IsNullOrEmpty() ? new List<string>() : new List<string>(spaceDelimitedKeys.Split(' ')); } var multiDataList = Keys(pattern); return multiDataList.ToStringList(); } public List<string> GetValues(List<string> keys) { if (keys == null) throw new ArgumentNullException("keys"); var resultBytesArray = MGet(keys.ToArray()); var results = new List<string>(); foreach (var resultBytes in resultBytesArray) { if (resultBytes == null) continue; var resultString = resultBytes.FromUtf8Bytes(); results.Add(resultString); } return results; } public List<T> GetValues<T>(List<string> keys) { if (keys == null) throw new ArgumentNullException("keys"); if (keys.Count == 0) return new List<T>(); var resultBytesArray = MGet(keys.ToArray()); var results = new List<T>(); foreach (var resultBytes in resultBytesArray) { if (resultBytes == null) continue; var resultString = resultBytes.FromUtf8Bytes(); var result = JsonSerializer.DeserializeFromString<T>(resultString); results.Add(result); } return results; } public Dictionary<string, string> GetValuesMap(List<string> keys) { if (keys == null) throw new ArgumentNullException("keys"); if (keys.Count == 0) return new Dictionary<string, string>(); var keysArray = keys.ToArray(); var resultBytesArray = MGet(keysArray); var results = new Dictionary<string, string>(); for (var i = 0; i < resultBytesArray.Length; i++) { var key = keysArray[i]; var resultBytes = resultBytesArray[i]; if (resultBytes == null) { results.Add(key, null); } else { var resultString = resultBytes.FromUtf8Bytes(); results.Add(key, resultString); } } return results; } public Dictionary<string, T> GetValuesMap<T>(List<string> keys) { if (keys == null) throw new ArgumentNullException("keys"); if (keys.Count == 0) return new Dictionary<string, T>(); var keysArray = keys.ToArray(); var resultBytesArray = MGet(keysArray); var results = new Dictionary<string, T>(); for (var i = 0; i < resultBytesArray.Length; i++) { var key = keysArray[i]; var resultBytes = resultBytesArray[i]; if (resultBytes == null) { results.Add(key, default(T)); } else { var resultString = resultBytes.FromUtf8Bytes(); var result = JsonSerializer.DeserializeFromString<T>(resultString); results.Add(key, result); } } return results; } public IRedisSubscription CreateSubscription() { return new RedisSubscription(this); } public int PublishMessage(string toChannel, string message) { return base.Publish(toChannel, message.ToUtf8Bytes()); } #region IBasicPersistenceProvider Dictionary<string, HashSet<string>> registeredTypeIdsWithinTransactionMap = new Dictionary<string, HashSet<string>>(); internal HashSet<string> GetRegisteredTypeIdsWithinTransaction(string typeIdsSet) { HashSet<string> registeredTypeIdsWithinTransaction; if (!registeredTypeIdsWithinTransactionMap.TryGetValue(typeIdsSet, out registeredTypeIdsWithinTransaction)) { registeredTypeIdsWithinTransaction = new HashSet<string>(); registeredTypeIdsWithinTransactionMap[typeIdsSet] = registeredTypeIdsWithinTransaction; } return registeredTypeIdsWithinTransaction; } internal void RegisterTypeId<T>(T value) { var typeIdsSetKey = GetTypeIdsSetKey<T>(); var id = value.GetId().ToString(); if (this.CurrentTransaction != null) { var registeredTypeIdsWithinTransaction = GetRegisteredTypeIdsWithinTransaction(typeIdsSetKey); registeredTypeIdsWithinTransaction.Add(id); } else { this.AddItemToSet(typeIdsSetKey, id); } } internal void RegisterTypeIds<T>(IEnumerable<T> values) { var typeIdsSetKey = GetTypeIdsSetKey<T>(); var ids = values.ConvertAll(x => x.GetId().ToString()); if (this.CurrentTransaction != null) { var registeredTypeIdsWithinTransaction = GetRegisteredTypeIdsWithinTransaction(typeIdsSetKey); ids.ForEach(x => registeredTypeIdsWithinTransaction.Add(x)); } else { AddRangeToSet(typeIdsSetKey, ids); } } internal void RemoveTypeIds<T>(params string[] ids) { var typeIdsSetKey = GetTypeIdsSetKey<T>(); if (this.CurrentTransaction != null) { var registeredTypeIdsWithinTransaction = GetRegisteredTypeIdsWithinTransaction(typeIdsSetKey); ids.ForEach(x => registeredTypeIdsWithinTransaction.Remove(x)); } else { ids.ForEach(x => this.RemoveItemFromSet(typeIdsSetKey, x)); } } internal void RemoveTypeIds<T>(params T[] values) { var typeIdsSetKey = GetTypeIdsSetKey<T>(); if (this.CurrentTransaction != null) { var registeredTypeIdsWithinTransaction = GetRegisteredTypeIdsWithinTransaction(typeIdsSetKey); values.ForEach(x => registeredTypeIdsWithinTransaction.Remove(x.GetId().ToString())); } else { values.ForEach(x => this.RemoveItemFromSet(typeIdsSetKey, x.GetId().ToString())); } } internal void AddTypeIdsRegisteredDuringTransaction() { foreach (var entry in registeredTypeIdsWithinTransactionMap) { var typeIdsSetKey = entry.Key; foreach (var id in entry.Value) { var registeredTypeIdsWithinTransaction = GetRegisteredTypeIdsWithinTransaction(typeIdsSetKey); registeredTypeIdsWithinTransaction.ForEach(x => this.AddItemToSet(typeIdsSetKey, id)); } } registeredTypeIdsWithinTransactionMap = new Dictionary<string, HashSet<string>>(); } internal void ClearTypeIdsRegisteredDuringTransaction() { registeredTypeIdsWithinTransactionMap = new Dictionary<string, HashSet<string>>(); } public T GetById<T>(object id) where T : class, new() { var key = IdUtils.CreateUrn<T>(id); var valueString = this.GetValue(key); var value = JsonSerializer.DeserializeFromString<T>(valueString); return value; } public IList<T> GetByIds<T>(ICollection ids) where T : class, new() { if (ids == null || ids.Count == 0) return new List<T>(); var urnKeys = ids.ConvertAll(x => IdUtils.CreateUrn<T>(x)); return GetValues<T>(urnKeys); } public IList<T> GetAll<T>() where T : class, new() { var typeIdsSetKy = this.GetTypeIdsSetKey<T>(); var allTypeIds = this.GetAllItemsFromSet(typeIdsSetKy); var urnKeys = allTypeIds.ConvertAll(x => IdUtils.CreateUrn<T>(x)); return GetValues<T>(urnKeys); } public T Store<T>(T entity) where T : class, new() { var urnKey = entity.CreateUrn(); var valueString = JsonSerializer.SerializeToString(entity); this.SetEntry(urnKey, valueString); RegisterTypeId(entity); return entity; } public void StoreAll<TEntity>(IEnumerable<TEntity> entities) where TEntity : class, new() { if (entities == null) return; var entitiesList = entities.ToList(); var len = entitiesList.Count; var keys = new byte[len][]; var values = new byte[len][]; for (var i = 0; i < len; i++) { keys[i] = entitiesList[i].CreateUrn().ToUtf8Bytes(); values[i] = SerializeToUtf8Bytes(entitiesList[i]); } base.MSet(keys, values); RegisterTypeIds(entitiesList); } public void WriteAll<TEntity>(IEnumerable<TEntity> entities) { if (entities == null) return; var entitiesList = entities.ToList(); var len = entitiesList.Count; var keys = new byte[len][]; var values = new byte[len][]; for (var i = 0; i < len; i++) { keys[i] = entitiesList[i].CreateUrn().ToUtf8Bytes(); values[i] = SerializeToUtf8Bytes(entitiesList[i]); } base.MSet(keys, values); } public static byte[] SerializeToUtf8Bytes<T>(T value) { return Encoding.UTF8.GetBytes(JsonSerializer.SerializeToString(value)); } public void Delete<T>(T entity) where T : class, new() { var urnKey = entity.CreateUrn(); this.Remove(urnKey); this.RemoveTypeIds(entity); } public void DeleteById<T>(object id) where T : class, new() { var urnKey = IdUtils.CreateUrn<T>(id); this.Remove(urnKey); this.RemoveTypeIds<T>(id.ToString()); } public void DeleteByIds<T>(ICollection ids) where T : class, new() { if (ids == null) return; var urnKeys = ids.ConvertAll(x => IdUtils.CreateUrn<T>(x)); this.RemoveEntry(urnKeys.ToArray()); this.RemoveTypeIds<T>(ids.ConvertAll(x => x.ToString()).ToArray()); } public void DeleteAll<T>() where T : class, new() { var typeIdsSetKey = this.GetTypeIdsSetKey<T>(); var ids = this.GetAllItemsFromSet(typeIdsSetKey); var urnKeys = ids.ConvertAll(x => IdUtils.CreateUrn<T>(x)); this.RemoveEntry(urnKeys.ToArray()); this.Remove(typeIdsSetKey); } #endregion } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Auditable Tables Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class QSATDataSet : EduHubDataSet<QSAT> { /// <inheritdoc /> public override string Name { get { return "QSAT"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal QSATDataSet(EduHubContext Context) : base(Context) { Index_GROUPING = new Lazy<NullDictionary<string, IReadOnlyList<QSAT>>>(() => this.ToGroupedNullDictionary(i => i.GROUPING)); Index_TABLE_NAME = new Lazy<Dictionary<string, QSAT>>(() => this.ToDictionary(i => i.TABLE_NAME)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="QSAT" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="QSAT" /> fields for each CSV column header</returns> internal override Action<QSAT, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<QSAT, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TABLE_NAME": mapper[i] = (e, v) => e.TABLE_NAME = v; break; case "DESCRIPTION": mapper[i] = (e, v) => e.DESCRIPTION = v; break; case "GROUPING": mapper[i] = (e, v) => e.GROUPING = v; break; case "KEY_COLUMN": mapper[i] = (e, v) => e.KEY_COLUMN = v; break; case "DESCRIPTION_COLUMN": mapper[i] = (e, v) => e.DESCRIPTION_COLUMN = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="QSAT" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="QSAT" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="QSAT" /> entities</param> /// <returns>A merged <see cref="IEnumerable{QSAT}"/> of entities</returns> internal override IEnumerable<QSAT> ApplyDeltaEntities(IEnumerable<QSAT> Entities, List<QSAT> DeltaEntities) { HashSet<string> Index_TABLE_NAME = new HashSet<string>(DeltaEntities.Select(i => i.TABLE_NAME)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.TABLE_NAME; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_TABLE_NAME.Remove(entity.TABLE_NAME); if (entity.TABLE_NAME.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<NullDictionary<string, IReadOnlyList<QSAT>>> Index_GROUPING; private Lazy<Dictionary<string, QSAT>> Index_TABLE_NAME; #endregion #region Index Methods /// <summary> /// Find QSAT by GROUPING field /// </summary> /// <param name="GROUPING">GROUPING value used to find QSAT</param> /// <returns>List of related QSAT entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<QSAT> FindByGROUPING(string GROUPING) { return Index_GROUPING.Value[GROUPING]; } /// <summary> /// Attempt to find QSAT by GROUPING field /// </summary> /// <param name="GROUPING">GROUPING value used to find QSAT</param> /// <param name="Value">List of related QSAT entities</param> /// <returns>True if the list of related QSAT entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByGROUPING(string GROUPING, out IReadOnlyList<QSAT> Value) { return Index_GROUPING.Value.TryGetValue(GROUPING, out Value); } /// <summary> /// Attempt to find QSAT by GROUPING field /// </summary> /// <param name="GROUPING">GROUPING value used to find QSAT</param> /// <returns>List of related QSAT entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<QSAT> TryFindByGROUPING(string GROUPING) { IReadOnlyList<QSAT> value; if (Index_GROUPING.Value.TryGetValue(GROUPING, out value)) { return value; } else { return null; } } /// <summary> /// Find QSAT by TABLE_NAME field /// </summary> /// <param name="TABLE_NAME">TABLE_NAME value used to find QSAT</param> /// <returns>Related QSAT entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public QSAT FindByTABLE_NAME(string TABLE_NAME) { return Index_TABLE_NAME.Value[TABLE_NAME]; } /// <summary> /// Attempt to find QSAT by TABLE_NAME field /// </summary> /// <param name="TABLE_NAME">TABLE_NAME value used to find QSAT</param> /// <param name="Value">Related QSAT entity</param> /// <returns>True if the related QSAT entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTABLE_NAME(string TABLE_NAME, out QSAT Value) { return Index_TABLE_NAME.Value.TryGetValue(TABLE_NAME, out Value); } /// <summary> /// Attempt to find QSAT by TABLE_NAME field /// </summary> /// <param name="TABLE_NAME">TABLE_NAME value used to find QSAT</param> /// <returns>Related QSAT entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public QSAT TryFindByTABLE_NAME(string TABLE_NAME) { QSAT value; if (Index_TABLE_NAME.Value.TryGetValue(TABLE_NAME, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a QSAT table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[QSAT]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[QSAT]( [TABLE_NAME] varchar(10) NOT NULL, [DESCRIPTION] varchar(32) NULL, [GROUPING] varchar(10) NULL, [KEY_COLUMN] varchar(32) NULL, [DESCRIPTION_COLUMN] varchar(32) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [QSAT_Index_TABLE_NAME] PRIMARY KEY CLUSTERED ( [TABLE_NAME] ASC ) ); CREATE NONCLUSTERED INDEX [QSAT_Index_GROUPING] ON [dbo].[QSAT] ( [GROUPING] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[QSAT]') AND name = N'QSAT_Index_GROUPING') ALTER INDEX [QSAT_Index_GROUPING] ON [dbo].[QSAT] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[QSAT]') AND name = N'QSAT_Index_GROUPING') ALTER INDEX [QSAT_Index_GROUPING] ON [dbo].[QSAT] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="QSAT"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="QSAT"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<QSAT> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<string> Index_TABLE_NAME = new List<string>(); foreach (var entity in Entities) { Index_TABLE_NAME.Add(entity.TABLE_NAME); } builder.AppendLine("DELETE [dbo].[QSAT] WHERE"); // Index_TABLE_NAME builder.Append("[TABLE_NAME] IN ("); for (int index = 0; index < Index_TABLE_NAME.Count; index++) { if (index != 0) builder.Append(", "); // TABLE_NAME var parameterTABLE_NAME = $"@p{parameterIndex++}"; builder.Append(parameterTABLE_NAME); command.Parameters.Add(parameterTABLE_NAME, SqlDbType.VarChar, 10).Value = Index_TABLE_NAME[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the QSAT data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the QSAT data set</returns> public override EduHubDataSetDataReader<QSAT> GetDataSetDataReader() { return new QSATDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the QSAT data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the QSAT data set</returns> public override EduHubDataSetDataReader<QSAT> GetDataSetDataReader(List<QSAT> Entities) { return new QSATDataReader(new EduHubDataSetLoadedReader<QSAT>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class QSATDataReader : EduHubDataSetDataReader<QSAT> { public QSATDataReader(IEduHubDataSetReader<QSAT> Reader) : base (Reader) { } public override int FieldCount { get { return 8; } } public override object GetValue(int i) { switch (i) { case 0: // TABLE_NAME return Current.TABLE_NAME; case 1: // DESCRIPTION return Current.DESCRIPTION; case 2: // GROUPING return Current.GROUPING; case 3: // KEY_COLUMN return Current.KEY_COLUMN; case 4: // DESCRIPTION_COLUMN return Current.DESCRIPTION_COLUMN; case 5: // LW_DATE return Current.LW_DATE; case 6: // LW_TIME return Current.LW_TIME; case 7: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 1: // DESCRIPTION return Current.DESCRIPTION == null; case 2: // GROUPING return Current.GROUPING == null; case 3: // KEY_COLUMN return Current.KEY_COLUMN == null; case 4: // DESCRIPTION_COLUMN return Current.DESCRIPTION_COLUMN == null; case 5: // LW_DATE return Current.LW_DATE == null; case 6: // LW_TIME return Current.LW_TIME == null; case 7: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // TABLE_NAME return "TABLE_NAME"; case 1: // DESCRIPTION return "DESCRIPTION"; case 2: // GROUPING return "GROUPING"; case 3: // KEY_COLUMN return "KEY_COLUMN"; case 4: // DESCRIPTION_COLUMN return "DESCRIPTION_COLUMN"; case 5: // LW_DATE return "LW_DATE"; case 6: // LW_TIME return "LW_TIME"; case 7: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "TABLE_NAME": return 0; case "DESCRIPTION": return 1; case "GROUPING": return 2; case "KEY_COLUMN": return 3; case "DESCRIPTION_COLUMN": return 4; case "LW_DATE": return 5; case "LW_TIME": return 6; case "LW_USER": return 7; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V10.Services { /// <summary>Settings for <see cref="SharedSetServiceClient"/> instances.</summary> public sealed partial class SharedSetServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="SharedSetServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="SharedSetServiceSettings"/>.</returns> public static SharedSetServiceSettings GetDefault() => new SharedSetServiceSettings(); /// <summary>Constructs a new <see cref="SharedSetServiceSettings"/> object with default settings.</summary> public SharedSetServiceSettings() { } private SharedSetServiceSettings(SharedSetServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); MutateSharedSetsSettings = existing.MutateSharedSetsSettings; OnCopy(existing); } partial void OnCopy(SharedSetServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>SharedSetServiceClient.MutateSharedSets</c> and <c>SharedSetServiceClient.MutateSharedSetsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateSharedSetsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="SharedSetServiceSettings"/> object.</returns> public SharedSetServiceSettings Clone() => new SharedSetServiceSettings(this); } /// <summary> /// Builder class for <see cref="SharedSetServiceClient"/> to provide simple configuration of credentials, endpoint /// etc. /// </summary> internal sealed partial class SharedSetServiceClientBuilder : gaxgrpc::ClientBuilderBase<SharedSetServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public SharedSetServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public SharedSetServiceClientBuilder() { UseJwtAccessWithScopes = SharedSetServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref SharedSetServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<SharedSetServiceClient> task); /// <summary>Builds the resulting client.</summary> public override SharedSetServiceClient Build() { SharedSetServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<SharedSetServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<SharedSetServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private SharedSetServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return SharedSetServiceClient.Create(callInvoker, Settings); } private async stt::Task<SharedSetServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return SharedSetServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => SharedSetServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => SharedSetServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => SharedSetServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>SharedSetService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage shared sets. /// </remarks> public abstract partial class SharedSetServiceClient { /// <summary> /// The default endpoint for the SharedSetService service, which is a host of "googleads.googleapis.com" and a /// port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default SharedSetService scopes.</summary> /// <remarks> /// The default SharedSetService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="SharedSetServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="SharedSetServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="SharedSetServiceClient"/>.</returns> public static stt::Task<SharedSetServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new SharedSetServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="SharedSetServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="SharedSetServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="SharedSetServiceClient"/>.</returns> public static SharedSetServiceClient Create() => new SharedSetServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="SharedSetServiceClient"/> which uses the specified call invoker for remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="SharedSetServiceSettings"/>.</param> /// <returns>The created <see cref="SharedSetServiceClient"/>.</returns> internal static SharedSetServiceClient Create(grpccore::CallInvoker callInvoker, SharedSetServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } SharedSetService.SharedSetServiceClient grpcClient = new SharedSetService.SharedSetServiceClient(callInvoker); return new SharedSetServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC SharedSetService client</summary> public virtual SharedSetService.SharedSetServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes shared sets. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SharedSetError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateSharedSetsResponse MutateSharedSets(MutateSharedSetsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes shared sets. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SharedSetError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateSharedSetsResponse> MutateSharedSetsAsync(MutateSharedSetsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes shared sets. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SharedSetError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateSharedSetsResponse> MutateSharedSetsAsync(MutateSharedSetsRequest request, st::CancellationToken cancellationToken) => MutateSharedSetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes shared sets. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SharedSetError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose shared sets are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual shared sets. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateSharedSetsResponse MutateSharedSets(string customerId, scg::IEnumerable<SharedSetOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateSharedSets(new MutateSharedSetsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes shared sets. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SharedSetError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose shared sets are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual shared sets. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateSharedSetsResponse> MutateSharedSetsAsync(string customerId, scg::IEnumerable<SharedSetOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateSharedSetsAsync(new MutateSharedSetsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes shared sets. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SharedSetError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose shared sets are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual shared sets. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateSharedSetsResponse> MutateSharedSetsAsync(string customerId, scg::IEnumerable<SharedSetOperation> operations, st::CancellationToken cancellationToken) => MutateSharedSetsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>SharedSetService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage shared sets. /// </remarks> public sealed partial class SharedSetServiceClientImpl : SharedSetServiceClient { private readonly gaxgrpc::ApiCall<MutateSharedSetsRequest, MutateSharedSetsResponse> _callMutateSharedSets; /// <summary> /// Constructs a client wrapper for the SharedSetService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="SharedSetServiceSettings"/> used within this client.</param> public SharedSetServiceClientImpl(SharedSetService.SharedSetServiceClient grpcClient, SharedSetServiceSettings settings) { GrpcClient = grpcClient; SharedSetServiceSettings effectiveSettings = settings ?? SharedSetServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callMutateSharedSets = clientHelper.BuildApiCall<MutateSharedSetsRequest, MutateSharedSetsResponse>(grpcClient.MutateSharedSetsAsync, grpcClient.MutateSharedSets, effectiveSettings.MutateSharedSetsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateSharedSets); Modify_MutateSharedSetsApiCall(ref _callMutateSharedSets); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_MutateSharedSetsApiCall(ref gaxgrpc::ApiCall<MutateSharedSetsRequest, MutateSharedSetsResponse> call); partial void OnConstruction(SharedSetService.SharedSetServiceClient grpcClient, SharedSetServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC SharedSetService client</summary> public override SharedSetService.SharedSetServiceClient GrpcClient { get; } partial void Modify_MutateSharedSetsRequest(ref MutateSharedSetsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Creates, updates, or removes shared sets. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SharedSetError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateSharedSetsResponse MutateSharedSets(MutateSharedSetsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateSharedSetsRequest(ref request, ref callSettings); return _callMutateSharedSets.Sync(request, callSettings); } /// <summary> /// Creates, updates, or removes shared sets. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SharedSetError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateSharedSetsResponse> MutateSharedSetsAsync(MutateSharedSetsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateSharedSetsRequest(ref request, ref callSettings); return _callMutateSharedSets.Async(request, callSettings); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using System; using System.Diagnostics.Contracts; using System.Runtime.Serialization; namespace System.Text { // An Encoder is used to encode a sequence of blocks of characters into // a sequence of blocks of bytes. Following instantiation of an encoder, // sequential blocks of characters are converted into blocks of bytes through // calls to the GetBytes method. The encoder maintains state between the // conversions, allowing it to correctly encode character sequences that span // adjacent blocks. // // Instances of specific implementations of the Encoder abstract base // class are typically obtained through calls to the GetEncoder method // of Encoding objects. // internal class EncoderNLS : Encoder, ISerializable { // Need a place for the last left over character, most of our encodings use this internal char charLeftOver; protected EncodingNLS m_encoding; protected bool m_mustFlush; internal bool m_throwOnOverflow; internal int m_charsUsed; internal EncoderFallback m_fallback; internal EncoderFallbackBuffer m_fallbackBuffer; internal EncoderNLS(EncodingNLS encoding) { m_encoding = encoding; m_fallback = m_encoding.EncoderFallback; Reset(); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue(EncoderNLSSurrogate.EncodingKey, m_encoding); info.AddValue(EncoderNLSSurrogate.DecoderFallbackKey, m_fallback); info.AddValue(EncoderNLSSurrogate.CharLeftOverKey, charLeftOver); info.SetType(typeof(EncoderNLSSurrogate)); } internal sealed class EncoderNLSSurrogate : ISerializable, IObjectReference { internal const string EncodingKey = "Encoding"; internal const string DecoderFallbackKey = "EncoderFallback"; internal const string CharLeftOverKey = "CharLeftOver"; private readonly Encoding _encoding; private readonly EncoderFallback _fallback; private char _charLeftOver; internal EncoderNLSSurrogate(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException(nameof(info)); } _encoding = (Encoding)info.GetValue(EncodingKey, typeof(Encoding)); _fallback = (EncoderFallback)info.GetValue(DecoderFallbackKey, typeof(EncoderFallback)); _charLeftOver = (char)info.GetValue(CharLeftOverKey, typeof(char)); } public object GetRealObject(StreamingContext context) { Encoder encoder = _encoding.GetEncoder(); if (_fallback != null) { encoder.Fallback = _fallback; if (_charLeftOver != default(char)) { EncoderNLS encoderNls = encoder as EncoderNLS; if (encoderNls != null) { encoderNls.charLeftOver = _charLeftOver; } } } return encoder; } public void GetObjectData(SerializationInfo info, StreamingContext context) { // This should never be called. If it is, there's a bug in the formatter being used. throw new NotSupportedException(); } } internal new EncoderFallback Fallback { get { return m_fallback; } } internal bool InternalHasFallbackBuffer { get { return m_fallbackBuffer != null; } } public new EncoderFallbackBuffer FallbackBuffer { get { if (m_fallbackBuffer == null) { if (m_fallback != null) m_fallbackBuffer = m_fallback.CreateFallbackBuffer(); else m_fallbackBuffer = EncoderFallback.ReplacementFallback.CreateFallbackBuffer(); } return m_fallbackBuffer; } } // This one is used when deserializing (like UTF7Encoding.Encoder) internal EncoderNLS() { m_encoding = null; Reset(); } public override void Reset() { charLeftOver = (char)0; if (m_fallbackBuffer != null) m_fallbackBuffer.Reset(); } [System.Security.SecuritySafeCritical] // auto-generated public override unsafe int GetByteCount(char[] chars, int index, int count, bool flush) { // Validate input parameters if (chars == null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index): nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - index < count) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); // Avoid empty input problem if (chars.Length == 0) chars = new char[1]; // Just call the pointer version int result = -1; fixed (char* pChars = &chars[0]) { result = GetByteCount(pChars + index, count, flush); } return result; } [System.Security.SecurityCritical] // auto-generated public override unsafe int GetByteCount(char* chars, int count, bool flush) { // Validate input parameters if (chars == null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); m_mustFlush = flush; m_throwOnOverflow = true; return m_encoding.GetByteCount(chars, count, this); } [System.Security.SecuritySafeCritical] // auto-generated public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? nameof(chars): nameof(bytes)), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex): nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); if (chars.Length == 0) chars = new char[1]; int byteCount = bytes.Length - byteIndex; if (bytes.Length == 0) bytes = new byte[1]; // Just call pointer version fixed (char* pChars = &chars[0]) fixed (byte* pBytes = &bytes[0]) // Remember that charCount is # to decode, not size of array. return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, flush); } [System.Security.SecurityCritical] // auto-generated public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? nameof(chars): nameof(bytes)), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount): nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); m_mustFlush = flush; m_throwOnOverflow = true; return m_encoding.GetBytes(chars, charCount, bytes, byteCount, this); } // This method is used when your output buffer might not be large enough for the entire result. // Just call the pointer version. (This gets bytes) [System.Security.SecuritySafeCritical] // auto-generated public override unsafe void Convert(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? nameof(chars): nameof(bytes)), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex): nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex): nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); // Avoid empty input problem if (chars.Length == 0) chars = new char[1]; if (bytes.Length == 0) bytes = new byte[1]; // Just call the pointer version (can't do this for non-msft encoders) fixed (char* pChars = &chars[0]) { fixed (byte* pBytes = &bytes[0]) { Convert(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out completed); } } } // This is the version that uses pointers. We call the base encoding worker function // after setting our appropriate internal variables. This is getting bytes [System.Security.SecurityCritical] // auto-generated public override unsafe void Convert(char* chars, int charCount, byte* bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { // Validate input parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? nameof(bytes): nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount): nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // We don't want to throw m_mustFlush = flush; m_throwOnOverflow = false; m_charsUsed = 0; // Do conversion bytesUsed = m_encoding.GetBytes(chars, charCount, bytes, byteCount, this); charsUsed = m_charsUsed; // Its completed if they've used what they wanted AND if they didn't want flush or if we are flushed completed = (charsUsed == charCount) && (!flush || !HasState) && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0); // Our data thingies are now full, we can return } public Encoding Encoding { get { return m_encoding; } } public bool MustFlush { get { return m_mustFlush; } } // Anything left in our encoder? internal virtual bool HasState { get { return (charLeftOver != (char)0); } } // Allow encoding to clear our must flush instead of throwing (in ThrowBytesOverflow) internal void ClearMustFlush() { m_mustFlush = false; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Threading; namespace Nohros.Data { public class TransferQueue<T> : IEnumerable<T>, ICollection, IEnumerable where T: class { public delegate void QueueFullEventHandler(T[] array); public event QueueFullEventHandler QueueFull; #region State object private struct EventState { public QueueFullEventHandler handler; public T[] array; public EventWaitHandle waithandle; public EventState(QueueFullEventHandler handler, T[] array, EventWaitHandle waithandle) { this.handler = handler; this.array = array; this.waithandle = waithandle; } } #endregion static object _lock; private int _size; private object _syncRoot; protected T[] _array; protected int _head; protected int _tail; #region .ctor static TransferQueue() { _lock = new object(); } /// <summary> /// Initializes a new instance_ of the TransferQueue class that is empty and has the specified size. /// </summary> /// <param name="capacity">The maximun number of elements that the TransferQueue can contain.</param> public TransferQueue(int capacity) { _syncRoot = new object(); _size = 0; _array = new T[capacity]; } /// <summary> /// Initializes a new instance_ of the TransferQueue class that contains elements copied from the specified /// collection and has specified size. /// </summary> /// <param name="collection">The collection whose elements are copied to the new TransferQueue</param> /// <exception cref="ArgumentNullException">collection is null</exception> public TransferQueue(IEnumerable<T> collection, int size): this(size) { if (collection == null) Thrower.ThrowArgumentNullException(ExceptionArgument.collection); using (IEnumerator<T> enumerator = collection.GetEnumerator()) { while (enumerator.MoveNext()) Enqueue(enumerator.Current); } } #endregion /// <summary> /// Adds an object to the end of the TransferQueue /// </summary> /// <param name="item">The object to add to the TransferQueue. The value can be null for references types.</param> public void Enqueue(T item) { // TODO: throw an exception //if (_size == _array.Length) //Thrower.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_FullQueue); _array[_tail] = item; if (++_size == _array.Length) OnQueueFull(null); else _tail = (_tail + 1) % _array.Length; } /// <summary> /// Removes and returns the object at the beginning of the TransferQueue. /// </summary> /// <returns>The object that is removed from the beginning of the TransferQueue.</returns> public T Dequeue() { // TODO: throw an exception //if (_size == 0) //Thrower.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EmptyQueue); T local = _array[_head]; _array[_head] = null; _head = (_head + 1) % _array.Length; _size--; return local; } /// <summary> /// Returns the object at the beginning of the TransferQueue without removing it. /// </summary> /// <returns>The object at the beginning og the TransferQueue</returns> /// <exception cref="InvalidOperationException">The TransferQueue is empty</exception> public T Peek() { // TODO: throw an exception //if (_size == 0) //Thrower.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EmptyQueue); return _array[_head]; } /// <summary> /// Removes all objects from the TransferQueue. /// </summary> /// <remarks>Count is set to zero, and references to other objects from elements of the collection are /// released. This method does not fire any event.</remarks> public void Clear() { for (int i = 0, j = _array.Length; i < j; i++) _array[i] = null; _head = 0; _tail = 0; _size = 0; } /// <summary> /// Resets the queue to its initial state. /// </summary> /// <remarks>Count is set to zero but references to other objects from elements of the collection are not /// released(to release references call the <see cref="Clear"/> method.</remarks> public void Reset() { _head = 0; _tail = 0; _size = 0; } /// <summary> /// Removes all objects from the TransferQueue. /// </summary> /// <remarks>Count is set to zero, and references to other objects from elements of the collection are /// released. This method fire the OnQueueFull event.</remarks> public void Flush() { Flush(null); } public void Flush(EventWaitHandle waitHandle) { if (QueueFull != null) { // fix the tail: the tail must point to the current // node before the OnQueueFull method call. _tail = _tail - 1; OnQueueFull(waitHandle); } else { Clear(); if (waitHandle != null) waitHandle.Set(); } } protected virtual void OnQueueFull(EventWaitHandle waitHandle) { if (QueueFull != null && _size > 0) { T[] array = new T[_size]; int i = 0, j = 0, num = ((_tail < _head) ? _array.Length : _tail + 1) - _head; while (num-- > 0) { j = _head + i; array[i++] = _array[j]; _array[j] = null; } // If the head is above the tail we need to get the // elements that exists between the top of the queue and // the the tail. if (_tail < _head) { // when this method is called the tail points // to the last used slot and not to the next free slot. // So we need to include clean that node too. for (j = 0; j <= _tail; j++) { array[i++] = _array[j]; _array[j] = null; } } _tail = 0; _head = 0; _size = 0; // the event delegate will be executed in another thread EventState state = new EventState(QueueFull, array, waitHandle); ThreadPool.QueueUserWorkItem(delegate(object o) { EventState e = (EventState)o; e.handler(e.array); if (e.waithandle != null) e.waithandle.Set(); }, state); } else waitHandle.Set(); } #region ICollection /// <summary> /// Copies the TransferQueue elements to an existing one-dimensional Array, starting at the specified array index. /// </summary> /// <param name="array">The one-dimensional <see cref="Array"/> taht is destination of the elements copied /// from TransferQueue. The <see cref="Array"/>must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based indexin array at which copying begins.</param> /// <exception cref="ArgumentOutOfRangeException">index is less than zero or index is greater than the length of the array</exception> /// <exception cref="ArgumentNullException">array is null</exception> /// <exception cref="ArgumentException">The number of elements in the source TransferQueue is greater than the /// available space from index to the end of the destination array</exception> public void CopyTo(T[] array, int arrayIndex) { if (array == null) Thrower.ThrowArgumentNullException(ExceptionArgument.array); int length = array.Length; if ((arrayIndex < 0) || (arrayIndex > length)) Thrower.ThrowArgumentOutOfRangeException(ExceptionArgument.arrayIndex, ExceptionResource.ArgumentOutOfRange_Index); int num2 = (length - arrayIndex); if (num2 < _size) Thrower.ThrowArgumentException(ExceptionResource.Argument_InvalidOfLen); // If the head is above tha tail we need to do two copies. The first copy will get // the elements between the head and the end of the queue and the second copy will get // the elements between the top of the queue and the tail. if (_tail < _head) { int num3 = _array.Length - _head; Array.Copy(_array, _head, array, arrayIndex, num3); Array.Copy(_array, 0, array, arrayIndex + num3, _tail); } else { Array.Copy(_array, _head, array, arrayIndex, _head - _tail); } } void ICollection.CopyTo(Array array, int index) { if (array == null) Thrower.ThrowArgumentNullException(ExceptionArgument.array); int length = array.Length; if ((index < 0) || (index > length)) Thrower.ThrowArgumentOutOfRangeException(ExceptionArgument.arrayIndex, ExceptionResource.ArgumentOutOfRange_Index); int num2 = (length - index); if (num2 < _size) Thrower.ThrowArgumentException(ExceptionResource.Argument_InvalidOfLen); // If the head is above tha tail we need to do two copies. The first copy will get // the elements between the head and the end of the queue and the second copy will get // the elements between the top of the queue and the tail. if (_tail < _head) { int num3 = _array.Length - _head; Array.Copy(_array, _head, array, index, num3); Array.Copy(_array, 0, array, index + num3, _tail); } else { Array.Copy(_array, _head, array, index, _head - _tail); } } /// <summary> /// Gets the number of elements contained in the TransferQueue. /// </summary> public int Count { get { return _size; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (_syncRoot == null) System.Threading.Interlocked.CompareExchange(ref _syncRoot, new object(), null); return _syncRoot; } } #endregion #region IEnumerator /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>A <see cref="IEnumerator&alt;,&gt;"/>that can be used to iterate through the collection</returns> public IEnumerator<T> GetEnumerator() { for (int i = 0, j = _array.Length; i < j; i++) yield return _array[i]; } #endregion #region IEnumerable members /// <summary> /// Returns an enumerator that iterates through a collection /// </summary> /// <returns>An <see cref="IEnumerator"/> object that can be used to iterate /// through the collection</returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through the TransferQueue /// </summary> /// <returns>An <see cref="IEnumerator"/> object that can be used to iterate /// through the TransferQueue</returns> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return GetEnumerator(); } #endregion } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** Class: ConditionalWeakTable ** ** <OWNER>[....]</OWNER> ** ** Description: Compiler support for runtime-generated "object fields." ** ** Lets DLR and other language compilers expose the ability to ** attach arbitrary "properties" to instanced managed objects at runtime. ** ** We expose this support as a dictionary whose keys are the ** instanced objects and the values are the "properties." ** ** Unlike a regular dictionary, ConditionalWeakTables will not ** keep keys alive. ** ** ** Lifetimes of keys and values: ** ** Inserting a key and value into the dictonary will not ** prevent the key from dying, even if the key is strongly reachable ** from the value. ** ** Prior to ConditionalWeakTable, the CLR did not expose ** the functionality needed to implement this guarantee. ** ** Once the key dies, the dictionary automatically removes ** the key/value entry. ** ** ** Relationship between ConditionalWeakTable and Dictionary: ** ** ConditionalWeakTable mirrors the form and functionality ** of the IDictionary interface for the sake of api consistency. ** ** Unlike Dictionary, ConditionalWeakTable is fully thread-safe ** and requires no additional locking to be done by callers. ** ** ConditionalWeakTable defines equality as Object.ReferenceEquals(). ** ConditionalWeakTable does not invoke GetHashCode() overrides. ** ** It is not intended to be a general purpose collection ** and it does not formally implement IDictionary or ** expose the full public surface area. ** ** ** ** Thread safety guarantees: ** ** ConditionalWeakTable is fully thread-safe and requires no ** additional locking to be done by callers. ** ** ** OOM guarantees: ** ** Will not corrupt unmanaged handle table on OOM. No guarantees ** about managed weak table consistency. Native handles reclamation ** may be delayed until appdomain shutdown. ===========================================================*/ namespace System.Runtime.CompilerServices { using System; using System.Collections.Generic; using Alachisoft.NosDB.Common.DataStructures.Clustered; #region ConditionalWeakTable [System.Runtime.InteropServices.ComVisible(false)] public sealed class ConditionalWeakTable<TKey, TValue> where TKey : class where TValue : class { #region Constructors [System.Security.SecuritySafeCritical] public ConditionalWeakTable() { _buckets = new int[0]; _entries = new Entry[0]; _freeList = -1; _lock = new Object(); Resize(); // Resize at once (so won't need "if initialized" checks all over) } #endregion #region Public Members //-------------------------------------------------------------------------------------------- // key: key of the value to find. Cannot be null. // value: if the key is found, contains the value associated with the key upon method return. // if the key is not found, contains default(TValue). // // Method returns "true" if key was found, "false" otherwise. // // Note: The key may get garbaged collected during the TryGetValue operation. If so, TryGetValue // may at its discretion, return "false" and set "value" to the default (as if the key was not present.) //-------------------------------------------------------------------------------------------- [System.Security.SecuritySafeCritical] public bool TryGetValue(TKey key, out TValue value) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } lock (_lock) { VerifyIntegrity(); return TryGetValueWorker(key, out value); } } //-------------------------------------------------------------------------------------------- // key: key to add. May not be null. // value: value to associate with key. // // If the key is already entered into the dictionary, this method throws an exception. // // Note: The key may get garbage collected during the Add() operation. If so, Add() // has the right to consider any prior entries successfully removed and add a new entry without // throwing an exception. //-------------------------------------------------------------------------------------------- [System.Security.SecuritySafeCritical] public void Add(TKey key, TValue value) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } lock (_lock) { VerifyIntegrity(); _invalid = true; int entryIndex = FindEntry(key); if (entryIndex != -1) { _invalid = false; ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate); } CreateEntry(key, value); _invalid = false; } } //-------------------------------------------------------------------------------------------- // key: key to remove. May not be null. // // Returns true if the key is found and removed. Returns false if the key was not in the dictionary. // // Note: The key may get garbage collected during the Remove() operation. If so, // Remove() will not fail or throw, however, the return value can be either true or false // depending on who wins the ----. //-------------------------------------------------------------------------------------------- [System.Security.SecuritySafeCritical] public bool Remove(TKey key) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } lock (_lock) { VerifyIntegrity(); _invalid = true; int hashCode = RuntimeHelpers.GetHashCode(key) & Int32.MaxValue; int bucket = hashCode % _buckets.Length; int last = -1; for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next) { if (_entries[entriesIndex].hashCode == hashCode && _entries[entriesIndex].depHnd.GetPrimary() == key) { if (last == -1) { _buckets[bucket] = _entries[entriesIndex].next; } else { _entries[last].next = _entries[entriesIndex].next; } _entries[entriesIndex].depHnd.Free(); _entries[entriesIndex].next = _freeList; _freeList = entriesIndex; _invalid = false; return true; } last = entriesIndex; } _invalid = false; return false; } } //-------------------------------------------------------------------------------------------- // key: key of the value to find. Cannot be null. // createValueCallback: callback that creates value for key. Cannot be null. // // Atomically tests if key exists in table. If so, returns corresponding value. If not, // invokes createValueCallback() passing it the key. The returned value is bound to the key in the table // and returned as the result of GetValue(). // // If multiple threads ---- to initialize the same key, the table may invoke createValueCallback // multiple times with the same key. Exactly one of these calls will "win the ----" and the returned // value of that call will be the one added to the table and returned by all the racing GetValue() calls. // // This rule permits the table to invoke createValueCallback outside the internal table lock // to prevent deadlocks. //-------------------------------------------------------------------------------------------- [System.Security.SecuritySafeCritical] public TValue GetValue(TKey key, CreateValueCallback createValueCallback) { // Our call to TryGetValue() validates key so no need for us to. // // if (key == null) // { // ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); // } if (createValueCallback == null) { throw new ArgumentNullException("createValueCallback"); } TValue existingValue; if (TryGetValue(key, out existingValue)) { return existingValue; } // If we got here, the key is not currently in table. Invoke the callback (outside the lock) // to generate the new value for the key. TValue newValue = createValueCallback(key); lock (_lock) { VerifyIntegrity(); _invalid = true; // Now that we've retaken the lock, must recheck in case we lost a ---- to add the key. if (TryGetValueWorker(key, out existingValue)) { _invalid = false; return existingValue; } else { // Verified in-lock that we won the ---- to add the key. Add it now. CreateEntry(key, newValue); _invalid = false; return newValue; } } } //-------------------------------------------------------------------------------------------- // key: key of the value to find. Cannot be null. // // Helper method to call GetValue without passing a creation delegate. Uses Activator.CreateInstance // to create new instances as needed. If TValue does not have a default constructor, this will // throw. //-------------------------------------------------------------------------------------------- public TValue GetOrCreateValue(TKey key) { return GetValue(key, CreateValue); } private TValue CreateValue(TKey key) { return Activator.CreateInstance<TValue>(); } public delegate TValue CreateValueCallback(TKey key); #endregion #region internal members //-------------------------------------------------------------------------------------------- // Find a key that equals (value equality) with the given key - don't use in perf critical path // Note that it calls out to Object.Equals which may calls the override version of Equals // and that may take locks and leads to deadlock // Currently it is only used by WinRT event code and you should only use this function // if you know for sure that either you won't run into dead locks or you need to live with the // possiblity //-------------------------------------------------------------------------------------------- [System.Security.SecuritySafeCritical] //[FriendAccessAllowed] internal TKey FindEquivalentKeyUnsafe(TKey key, out TValue value) { lock (_lock) { for (int bucket = 0; bucket < _buckets.Length; ++bucket) { for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next) { object thisKey, thisValue; _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out thisKey, out thisValue); if (Object.Equals(thisKey, key)) { value = (TValue)thisValue; return (TKey)thisKey; } } } } value = default(TValue); return null; } //-------------------------------------------------------------------------------------------- // Returns a collection of keys - don't use in perf critical path //-------------------------------------------------------------------------------------------- internal ICollection<TKey> Keys { [System.Security.SecuritySafeCritical] get { List<TKey> list = new List<TKey>(); lock (_lock) { for (int bucket = 0; bucket < _buckets.Length; ++bucket) { for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next) { TKey thisKey = (TKey)_entries[entriesIndex].depHnd.GetPrimary(); if (thisKey != null) { list.Add(thisKey); } } } } return list; } } //-------------------------------------------------------------------------------------------- // Returns a collection of values - don't use in perf critical path //-------------------------------------------------------------------------------------------- internal ICollection<TValue> Values { [System.Security.SecuritySafeCritical] get { List<TValue> list = new List<TValue>(); lock (_lock) { for (int bucket = 0; bucket < _buckets.Length; ++bucket) { for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next) { Object primary = null; Object secondary = null; _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out primary, out secondary); // Now that we've secured a strong reference to the secondary, must check the primary again // to ensure it didn't expire (otherwise, we open a ---- where TryGetValue misreports an // expired key as a live key with a null value.) if (primary != null) { list.Add((TValue)secondary); } } } } return list; } } //-------------------------------------------------------------------------------------------- // Clear all the key/value pairs //-------------------------------------------------------------------------------------------- [System.Security.SecuritySafeCritical] internal void Clear() { lock (_lock) { // Clear the buckets for (int bucketIndex = 0; bucketIndex < _buckets.Length; bucketIndex++) { _buckets[bucketIndex] = -1; } // Clear the entries and link them backwards together as part of free list int entriesIndex; for (entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++) { if (_entries[entriesIndex].depHnd.IsAllocated) { _entries[entriesIndex].depHnd.Free(); } // Link back wards as free list _entries[entriesIndex].next = entriesIndex - 1; } _freeList = entriesIndex - 1; } } #endregion #region Private Members [System.Security.SecurityCritical] //---------------------------------------------------------------------------------------- // Worker for finding a key/value pair // // Preconditions: // Must hold _lock. // Key already validated as non-null //---------------------------------------------------------------------------------------- private bool TryGetValueWorker(TKey key, out TValue value) { int entryIndex = FindEntry(key); if (entryIndex != -1) { Object primary = null; Object secondary = null; _entries[entryIndex].depHnd.GetPrimaryAndSecondary(out primary, out secondary); // Now that we've secured a strong reference to the secondary, must check the primary again // to ensure it didn't expire (otherwise, we open a ---- where TryGetValue misreports an // expired key as a live key with a null value.) if (primary != null) { value = (TValue)secondary; return true; } } value = default(TValue); return false; } //---------------------------------------------------------------------------------------- // Worker for adding a new key/value pair. // // Preconditions: // Must hold _lock. // Key already validated as non-null and not already in table. //---------------------------------------------------------------------------------------- [System.Security.SecurityCritical] private void CreateEntry(TKey key, TValue value) { if (_freeList == -1) { Resize(); } int hashCode = RuntimeHelpers.GetHashCode(key) & Int32.MaxValue; int bucket = hashCode % _buckets.Length; int newEntry = _freeList; _freeList = _entries[newEntry].next; _entries[newEntry].hashCode = hashCode; _entries[newEntry].depHnd = new DependentHandle(key, value); _entries[newEntry].next = _buckets[bucket]; _buckets[bucket] = newEntry; } //---------------------------------------------------------------------------------------- // This does two things: resize and scrub expired keys off bucket lists. // // Precondition: // Must hold _lock. // // Postcondition: // _freeList is non-empty on exit. //---------------------------------------------------------------------------------------- [System.Security.SecurityCritical] private void Resize() { // Start by assuming we won't resize. int newSize = _buckets.Length; // If any expired keys exist, we won't resize. bool hasExpiredEntries = false; int entriesIndex; for (entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++) { if (_entries[entriesIndex].depHnd.IsAllocated && _entries[entriesIndex].depHnd.GetPrimary() == null) { hasExpiredEntries = true; break; } } if (!hasExpiredEntries) { newSize = HashHelpers.GetPrime(_buckets.Length == 0 ? _initialCapacity + 1 : _buckets.Length * 2); } // Reallocate both buckets and entries and rebuild the bucket and freelists from scratch. // This serves both to scrub entries with expired keys and to put the new entries in the proper bucket. int newFreeList = -1; int[] newBuckets = new int[newSize]; for (int bucketIndex = 0; bucketIndex < newSize; bucketIndex++) { newBuckets[bucketIndex] = -1; } Entry[] newEntries = new Entry[newSize]; // Migrate existing entries to the new table. for (entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++) { DependentHandle depHnd = _entries[entriesIndex].depHnd; if (depHnd.IsAllocated && depHnd.GetPrimary() != null) { // Entry is used and has not expired. Link it into the appropriate bucket list. int bucket = _entries[entriesIndex].hashCode % newSize; newEntries[entriesIndex].depHnd = depHnd; newEntries[entriesIndex].hashCode = _entries[entriesIndex].hashCode; newEntries[entriesIndex].next = newBuckets[bucket]; newBuckets[bucket] = entriesIndex; } else { // Entry has either expired or was on the freelist to begin with. Either way // insert it on the new freelist. _entries[entriesIndex].depHnd.Free(); newEntries[entriesIndex].depHnd = new DependentHandle(); newEntries[entriesIndex].next = newFreeList; newFreeList = entriesIndex; } } // Add remaining entries to freelist. while (entriesIndex != newEntries.Length) { newEntries[entriesIndex].depHnd = new DependentHandle(); newEntries[entriesIndex].next = newFreeList; newFreeList = entriesIndex; entriesIndex++; } _buckets = newBuckets; _entries = newEntries; _freeList = newFreeList; } //---------------------------------------------------------------------------------------- // Returns -1 if not found (if key expires during FindEntry, this can be treated as "not found.") // // Preconditions: // Must hold _lock. // Key already validated as non-null. //---------------------------------------------------------------------------------------- [System.Security.SecurityCritical] private int FindEntry(TKey key) { int hashCode = RuntimeHelpers.GetHashCode(key) & Int32.MaxValue; for (int entriesIndex = _buckets[hashCode % _buckets.Length]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next) { if (_entries[entriesIndex].hashCode == hashCode && _entries[entriesIndex].depHnd.GetPrimary() == key) { return entriesIndex; } } return -1; } //---------------------------------------------------------------------------------------- // Precondition: // Must hold _lock. //---------------------------------------------------------------------------------------- private void VerifyIntegrity() { if (_invalid) { throw new InvalidOperationException(ResourceHelper.GetResourceString("CollectionCorrupted")); } } //---------------------------------------------------------------------------------------- // Finalizer. //---------------------------------------------------------------------------------------- [System.Security.SecuritySafeCritical] ~ConditionalWeakTable() { // We're just freeing per-appdomain unmanaged handles here. If we're already shutting down the AD, // don't bother. // // (Despite its name, Environment.HasShutdownStart also returns true if the current AD is finalizing.) if (Environment.HasShutdownStarted) { return; } if (_lock != null) { lock (_lock) { if (_invalid) { return; } Entry[] entries = _entries; // Make sure anyone sneaking into the table post-resurrection // gets booted before they can damage the native handle table. _invalid = true; _entries = null; _buckets = null; for (int entriesIndex = 0; entriesIndex < entries.Length; entriesIndex++) { entries[entriesIndex].depHnd.Free(); } } } } #endregion #region Private Data Members //-------------------------------------------------------------------------------------------- // Entry can be in one of three states: // // - Linked into the freeList (_freeList points to first entry) // depHnd.IsAllocated == false // hashCode == <dontcare> // next links to next Entry on freelist) // // - Used with live key (linked into a bucket list where _buckets[hashCode % _buckets.Length] points to first entry) // depHnd.IsAllocated == true, depHnd.GetPrimary() != null // hashCode == RuntimeHelpers.GetHashCode(depHnd.GetPrimary()) & Int32.MaxValue // next links to next Entry in bucket. // // - Used with dead key (linked into a bucket list where _buckets[hashCode % _buckets.Length] points to first entry) // depHnd.IsAllocated == true, depHnd.GetPrimary() == null // hashCode == <notcare> // next links to next Entry in bucket. // // The only difference between "used with live key" and "used with dead key" is that // depHnd.GetPrimary() returns null. The transition from "used with live key" to "used with dead key" // happens asynchronously as a result of normal garbage collection. The dictionary itself // receives no notification when this happens. // // When the dictionary grows the _entries table, it scours it for expired keys and puts those // entries back on the freelist. //-------------------------------------------------------------------------------------------- private struct Entry { public DependentHandle depHnd; // Holds key and value using a weak reference for the key and a strong reference // for the value that is traversed only if the key is reachable without going through the value. public int hashCode; // Cached copy of key's hashcode public int next; // Index of next entry, -1 if last } private int[] _buckets; // _buckets[hashcode & _buckets.Length] contains index of first entry in bucket (-1 if empty) private Entry[] _entries; private int _freeList; // -1 = empty, else index of first unused Entry private const int _initialCapacity = 5; private readonly Object _lock; // this could be a ReaderWriterLock but CoreCLR does not support RWLocks. private bool _invalid; // flag detects if OOM or other background exception threw us out of the lock. #endregion } #endregion #region DependentHandle //========================================================================================= // This struct collects all operations on native DependentHandles. The DependentHandle // merely wraps an IntPtr so this struct serves mainly as a "managed typedef." // // DependentHandles exist in one of two states: // // IsAllocated == false // No actual handle is allocated underneath. Illegal to call GetPrimary // or GetPrimaryAndSecondary(). Ok to call Free(). // // Initializing a DependentHandle using the nullary ctor creates a DependentHandle // that's in the !IsAllocated state. // (! Right now, we get this guarantee for free because (IntPtr)0 == NULL unmanaged handle. // ! If that assertion ever becomes false, we'll have to add an _isAllocated field // ! to compensate.) // // // IsAllocated == true // There's a handle allocated underneath. You must call Free() on this eventually // or you cause a native handle table leak. // // This struct intentionally does no self-synchronization. It's up to the caller to // to use DependentHandles in a thread-safe way. //========================================================================================= // struct DependentHandle #endregion }
using System; using System.Collections.Generic; using System.Linq; using Signum.Utilities; using Signum.Engine.Maps; using Signum.Engine.Authorization; using Signum.Engine; using System.Xml.Linq; using Signum.Engine.Basics; using Signum.Entities.Basics; using System.Reflection; using Signum.Entities.Reflection; namespace Signum.Entities.Authorization { class TypeAuthCache : IManualAuth<Type, TypeAllowedAndConditions> { readonly ResetLazy<Dictionary<Lite<RoleEntity>, RoleAllowedCache>> runtimeRules; IMerger<Type, TypeAllowedAndConditions> merger; public TypeAuthCache(SchemaBuilder sb, IMerger<Type, TypeAllowedAndConditions> merger) { this.merger = merger; sb.Include<RuleTypeEntity>(); sb.AddUniqueIndex<RuleTypeEntity>(rt => new { rt.Resource, rt.Role }); runtimeRules = sb.GlobalLazy(NewCache, new InvalidateWith(typeof(RuleTypeEntity), typeof(RoleEntity)), AuthLogic.NotifyRulesChanged); sb.Schema.EntityEvents<RoleEntity>().PreUnsafeDelete += query => { Database.Query<RuleTypeEntity>().Where(r => query.Contains(r.Role.Entity)).UnsafeDelete(); return null; }; sb.Schema.Table<TypeEntity>().PreDeleteSqlSync += new Func<Entity, SqlPreCommand?>(AuthCache_PreDeleteSqlSync_Type); sb.Schema.Table<TypeConditionSymbol>().PreDeleteSqlSync += new Func<Entity, SqlPreCommand?>(AuthCache_PreDeleteSqlSync_Condition); Validator.PropertyValidator((RuleTypeEntity r) => r.Conditions).StaticPropertyValidation += TypeAuthCache_StaticPropertyValidation; } string? TypeAuthCache_StaticPropertyValidation(ModifiableEntity sender, PropertyInfo pi) { RuleTypeEntity rt = (RuleTypeEntity)sender; if (rt.Resource == null) { if (rt.Conditions.Any()) return "Default {0} should not have conditions".FormatWith(typeof(RuleTypeEntity).NiceName()); return null; } try { Type type = TypeLogic.EntityToType.GetOrThrow(rt.Resource); var conditions = rt.Conditions.Where(a => a.Condition.FieldInfo != null && /*Not 100% Sync*/ !TypeConditionLogic.IsDefined(type, a.Condition)); if (conditions.IsEmpty()) return null; return "Type {0} has no definitions for the conditions: {1}".FormatWith(type.Name, conditions.CommaAnd(a => a.Condition.Key)); } catch (Exception ex) when (StartParameters.IgnoredDatabaseMismatches != null) { //This try { throw } catch is here to alert developers. //In production, in some cases its OK to attempt starting an application with a slightly different schema (dynamic entities, green-blue deployments). //In development, consider synchronize. StartParameters.IgnoredDatabaseMismatches.Add(ex); return null; } } static SqlPreCommand? AuthCache_PreDeleteSqlSync_Type(Entity arg) { TypeEntity type = (TypeEntity)arg; var command = Administrator.UnsafeDeletePreCommand(Database.Query<RuleTypeEntity>().Where(a => a.Resource == type)); return command; } static SqlPreCommand? AuthCache_PreDeleteSqlSync_Condition(Entity arg) { TypeConditionSymbol condition = (TypeConditionSymbol)arg; var command = Administrator.UnsafeDeletePreCommandMList((RuleTypeEntity rt)=>rt.Conditions, Database.MListQuery((RuleTypeEntity rt) => rt.Conditions).Where(mle => mle.Element.Condition == condition)); return command; } TypeAllowedAndConditions IManualAuth<Type, TypeAllowedAndConditions>.GetAllowed(Lite<RoleEntity> role, Type key) { TypeEntity resource = TypeLogic.TypeToEntity.GetOrThrow(key); ManualResourceCache miniCache = new ManualResourceCache(resource, merger); return miniCache.GetAllowed(role); } void IManualAuth<Type, TypeAllowedAndConditions>.SetAllowed(Lite<RoleEntity> role, Type key, TypeAllowedAndConditions allowed) { TypeEntity resource = TypeLogic.TypeToEntity.GetOrThrow(key); ManualResourceCache miniCache = new ManualResourceCache(resource, merger); if (miniCache.GetAllowed(role).Equals(allowed)) return; IQueryable<RuleTypeEntity> query = Database.Query<RuleTypeEntity>().Where(a => a.Resource == resource && a.Role == role); if (miniCache.GetAllowedBase(role).Equals(allowed)) { if (query.UnsafeDelete() == 0) throw new InvalidOperationException("Inconsistency in the data"); } else { query.UnsafeDelete(); allowed.ToRuleType(role, resource).Save(); } } public class ManualResourceCache { readonly Dictionary<Lite<RoleEntity>, TypeAllowedAndConditions> rules; readonly IMerger<Type, TypeAllowedAndConditions> merger; readonly TypeEntity resource; public ManualResourceCache(TypeEntity resource, IMerger<Type, TypeAllowedAndConditions> merger) { this.resource = resource; var list = Database.Query<RuleTypeEntity>().Where(r => r.Resource == resource || r.Resource == null).ToList(); rules = list.Where(a => a.Resource != null).ToDictionary(a => a.Role, a => a.ToTypeAllowedAndConditions()); this.merger = merger; } public TypeAllowedAndConditions GetAllowed(Lite<RoleEntity> role) { if (rules.TryGetValue(role, out var result)) return result; return GetAllowedBase(role); } public TypeAllowedAndConditions GetAllowedBase(Lite<RoleEntity> role) { IEnumerable<Lite<RoleEntity>> related = AuthLogic.RelatedTo(role); return merger.Merge(resource.ToType(), role, related.Select(r => KeyValuePair.Create(r, GetAllowed(r)))); } } Dictionary<Lite<RoleEntity>, RoleAllowedCache> NewCache() { using (AuthLogic.Disable()) using (new EntityCache(EntityCacheType.ForceNewSealed)) { List<Lite<RoleEntity>> roles = AuthLogic.RolesInOrder().ToList(); var rules = Database.Query<RuleTypeEntity>().ToList(); var errors = GraphExplorer.FullIntegrityCheck(GraphExplorer.FromRoots(rules)); if (errors != null) throw new IntegrityCheckException(errors); Dictionary<Lite<RoleEntity>, Dictionary<Type, TypeAllowedAndConditions>> realRules = rules.AgGroupToDictionary(ru => ru.Role, gr => gr .SelectCatch(ru => KeyValuePair.Create(TypeLogic.EntityToType.GetOrThrow(ru.Resource), ru.ToTypeAllowedAndConditions())) .ToDictionaryEx()); Dictionary<Lite<RoleEntity>, RoleAllowedCache> newRules = new Dictionary<Lite<RoleEntity>, RoleAllowedCache>(); foreach (var role in roles) { var related = AuthLogic.RelatedTo(role); newRules.Add(role, new RoleAllowedCache(role, merger, related.Select(r => newRules.GetOrThrow(r)).ToList(), realRules.TryGetC(role))); } return newRules; } } internal void GetRules(BaseRulePack<TypeAllowedRule> rules, IEnumerable<TypeEntity> resources) { RoleAllowedCache cache = runtimeRules.Value.GetOrThrow(rules.Role); rules.MergeStrategy = AuthLogic.GetMergeStrategy(rules.Role); rules.SubRoles = AuthLogic.RelatedTo(rules.Role).ToMList(); rules.Rules = (from r in resources let type = TypeLogic.EntityToType.GetOrThrow(r) select new TypeAllowedRule() { Resource = r, AllowedBase = cache.GetAllowedBase(type), Allowed = cache.GetAllowed(type), AvailableConditions = TypeConditionLogic.ConditionsFor(type).ToList() }).ToMList(); } internal void SetRules(BaseRulePack<TypeAllowedRule> rules) { using (AuthLogic.Disable()) { var current = Database.Query<RuleTypeEntity>().Where(r => r.Role == rules.Role && r.Resource != null).ToDictionary(a => a.Resource); var should = rules.Rules.Where(a => a.Overriden).ToDictionary(r => r.Resource); Synchronizer.Synchronize(should, current, (type, ar) => ar.Allowed.ToRuleType(rules.Role, type).Save(), (type, pr) => pr.Delete(), (type, ar, pr) => { pr.Allowed = ar.Allowed.Fallback!.Value; var shouldConditions = ar.Allowed.Conditions.Select(a => new RuleTypeConditionEmbedded { Allowed = a.Allowed, Condition = a.TypeCondition, }).ToMList(); if (!pr.Conditions.SequenceEqual(shouldConditions)) pr.Conditions = shouldConditions; if (pr.IsGraphModified) pr.Save(); }); } } internal TypeAllowedAndConditions GetAllowed(Lite<RoleEntity> role, Type key) { return runtimeRules.Value.GetOrThrow(role).GetAllowed(key); } internal TypeAllowedAndConditions GetAllowedBase(Lite<RoleEntity> role, Type key) { return runtimeRules.Value.GetOrThrow(role).GetAllowedBase(key); } internal DefaultDictionary<Type, TypeAllowedAndConditions> GetDefaultDictionary() { return runtimeRules.Value.GetOrThrow(RoleEntity.Current).DefaultDictionary(); } public class RoleAllowedCache { readonly IMerger<Type, TypeAllowedAndConditions> merger; readonly DefaultDictionary<Type, TypeAllowedAndConditions> rules; readonly List<RoleAllowedCache> baseCaches; readonly Lite<RoleEntity> role; public RoleAllowedCache(Lite<RoleEntity> role, IMerger<Type, TypeAllowedAndConditions> merger, List<RoleAllowedCache> baseCaches, Dictionary<Type, TypeAllowedAndConditions>? newValues) { this.role = role; this.merger = merger; this.baseCaches = baseCaches; Func<Type, TypeAllowedAndConditions> defaultAllowed = merger.MergeDefault(role); Func<Type, TypeAllowedAndConditions> baseAllowed = k => merger.Merge(k, role, baseCaches.Select(b => KeyValuePair.Create(b.role, b.GetAllowed(k)))); var keys = baseCaches .Where(b => b.rules.OverrideDictionary != null) .SelectMany(a => a.rules.OverrideDictionary!.Keys) .ToHashSet(); Dictionary<Type, TypeAllowedAndConditions>? tmpRules = keys.ToDictionary(k => k, baseAllowed); if (newValues != null) tmpRules.SetRange(newValues); tmpRules = Simplify(tmpRules, defaultAllowed, baseAllowed); rules = new DefaultDictionary<Type, TypeAllowedAndConditions>(defaultAllowed, tmpRules); } internal static Dictionary<Type, TypeAllowedAndConditions>? Simplify(Dictionary<Type, TypeAllowedAndConditions> dictionary, Func<Type, TypeAllowedAndConditions> defaultAllowed, Func<Type, TypeAllowedAndConditions> baseAllowed) { if (dictionary == null || dictionary.Count == 0) return null; dictionary.RemoveRange(dictionary.Where(p => p.Value.Equals(defaultAllowed(p.Key)) && p.Value.Equals(baseAllowed(p.Key))).Select(p => p.Key).ToList()); if (dictionary.Count == 0) return null; return dictionary; } public TypeAllowedAndConditions GetAllowed(Type k) { return rules.GetAllowed(k); } public TypeAllowedAndConditions GetAllowedBase(Type k) { return merger.Merge(k, role, baseCaches.Select(b => KeyValuePair.Create(b.role, b.GetAllowed(k)))); } internal DefaultDictionary<Type, TypeAllowedAndConditions> DefaultDictionary() { return this.rules; } } internal XElement ExportXml(List<Type>? allTypes) { var rules = runtimeRules.Value; return new XElement("Types", (from r in AuthLogic.RolesInOrder() let rac = rules.GetOrThrow(r) select new XElement("Role", new XAttribute("Name", r.ToString()!), from k in allTypes ?? (rac.DefaultDictionary().OverrideDictionary?.Keys).EmptyIfNull() let allowedBase = rac.GetAllowedBase(k) let allowed = rac.GetAllowed(k) where allTypes != null || !allowed.Equals(allowedBase) let resource = TypeLogic.GetCleanName(k) orderby resource select new XElement("Type", new XAttribute("Resource", resource), new XAttribute("Allowed", allowed.Fallback.ToString()!), from c in allowed.Conditions select new XElement("Condition", new XAttribute("Name", c.TypeCondition.Key), new XAttribute("Allowed", c.Allowed.ToString())) ) ) )); } internal static readonly string typeReplacementKey = "AuthRules:" + typeof(TypeEntity).Name; internal static readonly string typeConditionReplacementKey = "AuthRules:" + typeof(TypeConditionSymbol).Name; internal SqlPreCommand? ImportXml(XElement element, Dictionary<string, Lite<RoleEntity>> roles, Replacements replacements) { var current = Database.RetrieveAll<RuleTypeEntity>().GroupToDictionary(a => a.Role); var xRoles = (element.Element("Types")?.Elements("Role")).EmptyIfNull(); var should = xRoles.ToDictionary(x => roles.GetOrThrow(x.Attribute("Name")!.Value)); Table table = Schema.Current.Table(typeof(RuleTypeEntity)); replacements.AskForReplacements( xRoles.SelectMany(x => x.Elements("Type")).Select(x => x.Attribute("Resource")!.Value).ToHashSet(), TypeLogic.NameToType.Where(a => !a.Value.IsEnumEntity()).Select(a => a.Key).ToHashSet(), typeReplacementKey); replacements.AskForReplacements( xRoles.SelectMany(x => x.Elements("Type")).SelectMany(t => t.Elements("Condition")).Select(x => x.Attribute("Name")!.Value).ToHashSet(), SymbolLogic<TypeConditionSymbol>.AllUniqueKeys(), typeConditionReplacementKey); Func<string, TypeEntity?> getResource = s => { Type? type = TypeLogic.NameToType.TryGetC(replacements.Apply(typeReplacementKey, s)); if (type == null) return null; return TypeLogic.TypeToEntity.GetOrThrow(type); }; return Synchronizer.SynchronizeScript(Spacing.Double, should, current, createNew: (role, x) => { var dic = (from xr in x.Elements("Type") let t = getResource(xr.Attribute("Resource")!.Value) where t != null select KeyValuePair.Create(t, new { Allowed = xr.Attribute("Allowed")!.Value.ToEnum<TypeAllowed>(), Condition = Conditions(xr, replacements) })).ToDictionaryEx("Type rules for {0}".FormatWith(role)); SqlPreCommand? restSql = dic.Select(kvp => table.InsertSqlSync(new RuleTypeEntity { Resource = kvp.Key, Role = role, Allowed = kvp.Value.Allowed, Conditions = kvp.Value.Condition! /*CSBUG*/ }, comment: Comment(role, kvp.Key, kvp.Value.Allowed))).Combine(Spacing.Simple)?.Do(p => p.GoBefore = true); return restSql; }, removeOld: (role, list) => list.Select(rt => table.DeleteSqlSync(rt, null)).Combine(Spacing.Simple)?.Do(p => p.GoBefore = true), mergeBoth: (role, x, list) => { var dic = (from xr in x.Elements("Type") let t = getResource(xr.Attribute("Resource")!.Value) where t != null && !t.ToType().IsEnumEntity() select KeyValuePair.Create(t, xr)).ToDictionaryEx("Type rules for {0}".FormatWith(role)); SqlPreCommand? restSql = Synchronizer.SynchronizeScript( Spacing.Simple, dic, list.Where(a => a.Resource != null).ToDictionary(a => a.Resource), createNew: (r, xr) => { var a = xr.Attribute("Allowed")!.Value.ToEnum<TypeAllowed>(); var conditions = Conditions(xr, replacements); return table.InsertSqlSync(new RuleTypeEntity { Resource = r, Role = role, Allowed = a, Conditions = conditions }, comment: Comment(role, r, a)); }, removeOld: (r, rt) => table.DeleteSqlSync(rt, null, Comment(role, r, rt.Allowed)), mergeBoth: (r, xr, pr) => { var oldA = pr.Allowed; pr.Allowed = xr.Attribute("Allowed")!.Value.ToEnum<TypeAllowed>(); var conditions = Conditions(xr, replacements); if (!pr.Conditions.SequenceEqual(conditions)) pr.Conditions = conditions; return table.UpdateSqlSync(pr, null, comment: Comment(role, r, oldA, pr.Allowed)); })?.Do(p => p.GoBefore = true); return restSql; }); } private static MList<RuleTypeConditionEmbedded> Conditions(XElement xr, Replacements replacements) { return (from xc in xr.Elements("Condition") let cn = SymbolLogic<TypeConditionSymbol>.TryToSymbol(replacements.Apply(typeConditionReplacementKey, xc.Attribute("Name")!.Value)) where cn != null select new RuleTypeConditionEmbedded { Condition = cn, Allowed = xc.Attribute("Allowed")!.Value.ToEnum<TypeAllowed>() }).ToMList(); } internal static string Comment(Lite<RoleEntity> role, TypeEntity resource, TypeAllowed allowed) { return "{0} {1} for {2} ({3})".FormatWith(typeof(TypeEntity).NiceName(), resource.ToString(), role, allowed); } internal static string Comment(Lite<RoleEntity> role, TypeEntity resource, TypeAllowed from, TypeAllowed to) { return "{0} {1} for {2} ({3} -> {4})".FormatWith(typeof(TypeEntity).NiceName(), resource.ToString(), role, from, to); } } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Collections.Generic; using System.Text; using Autodesk.Revit; using Autodesk.Revit.DB; namespace Revit.SDK.Samples.NewRebar.CS { using GeoElement = Autodesk.Revit.DB.GeometryElement; using GeoSolid = Autodesk.Revit.DB.Solid; using Element = Autodesk.Revit.DB.Element; /// <summary> /// The class which gives the base geometry operation, it is a static class. /// </summary> static class GeomUtil { // Private members const double Precision = 0.00001; //precision when judge whether two doubles are equal /// <summary> /// Judge whether the two double data are equal /// </summary> /// <param name="d1">The first double data</param> /// <param name="d2">The second double data</param> /// <returns>true if two double data is equal, otherwise false</returns> public static bool IsEqual(double d1, double d2) { //get the absolute value; double diff = Math.Abs(d1 - d2); return diff < Precision; } /// <summary> /// Judge whether the two Autodesk.Revit.DB.XYZ point are equal /// </summary> /// <param name="first">The first Autodesk.Revit.DB.XYZ point</param> /// <param name="second">The second Autodesk.Revit.DB.XYZ point</param> /// <returns>true if two Autodesk.Revit.DB.XYZ point is equal, otherwise false</returns> public static bool IsEqual(Autodesk.Revit.DB.XYZ first, Autodesk.Revit.DB.XYZ second) { bool flag = true; flag = flag && IsEqual(first.X, second.X); flag = flag && IsEqual(first.Y, second.Y); flag = flag && IsEqual(first.Z, second.Z); return flag; } /// <summary> /// Judge whether the line is perpendicular to the face /// </summary> /// <param name="face">The face reference</param> /// <param name="line">The line reference</param> /// <param name="faceTrans">The transform for the face</param> /// <param name="lineTrans">The transform for the line</param> /// <returns>True if line is perpendicular to the face, otherwise false</returns> public static bool IsVertical(Face face, Line line, Transform faceTrans, Transform lineTrans) { //get points which the face contains List<XYZ> points = face.Triangulate().Vertices as List<XYZ>; if (3 > points.Count) // face's point number should be above 2 { return false; } // get three points from the face points Autodesk.Revit.DB.XYZ first = points[0]; Autodesk.Revit.DB.XYZ second = points[1]; Autodesk.Revit.DB.XYZ third = points[2]; // get start and end point of line Autodesk.Revit.DB.XYZ lineStart = line.get_EndPoint(0); Autodesk.Revit.DB.XYZ lineEnd = line.get_EndPoint(1); // transForm the three points if necessary if (null != faceTrans) { first = TransformPoint(first, faceTrans); second = TransformPoint(second, faceTrans); third = TransformPoint(third, faceTrans); } // transform the start and end points if necessary if (null != lineTrans) { lineStart = TransformPoint(lineStart, lineTrans); lineEnd = TransformPoint(lineEnd, lineTrans); } // form two vectors from the face and a vector stand for the line // Use SubXYZ() method to get the vectors Autodesk.Revit.DB.XYZ vector1 = SubXYZ(first, second); // first vector of face Autodesk.Revit.DB.XYZ vector2 = SubXYZ(first, third); // second vector of face Autodesk.Revit.DB.XYZ vector3 = SubXYZ(lineStart, lineEnd); // line vector // get two dot products of the face vectors and line vector double result1 = DotMatrix(vector1, vector3); double result2 = DotMatrix(vector2, vector3); // if two dot products are all zero, the line is perpendicular to the face return (IsEqual(result1, 0) && IsEqual(result2, 0)); } /// <summary> /// Judge whether the two vectors have the same direction /// </summary> /// <param name="firstVec">The first vector</param> /// <param name="secondVec">The second vector</param> /// <returns>True if the two vector is in same direction, otherwise false</returns> public static bool IsSameDirection(Autodesk.Revit.DB.XYZ firstVec, Autodesk.Revit.DB.XYZ secondVec) { // get the unit vector for two vectors Autodesk.Revit.DB.XYZ first = UnitVector(firstVec); Autodesk.Revit.DB.XYZ second = UnitVector(secondVec); // if the dot product of two unit vectors is equal to 1, return true double dot = DotMatrix(first, second); return (IsEqual(dot, 1)); } /// <summary> /// Judge whether the two vectors have the opposite direction /// </summary> /// <param name="firstVec">The first vector</param> /// <param name="secondVec">The second vector</param> /// <returns>True if the two vector is in opposite direction, otherwise false</returns> public static bool IsOppositeDirection(Autodesk.Revit.DB.XYZ firstVec, Autodesk.Revit.DB.XYZ secondVec) { // get the unit vector for two vectors Autodesk.Revit.DB.XYZ first = UnitVector(firstVec); Autodesk.Revit.DB.XYZ second = UnitVector(secondVec); // if the dot product of two unit vectors is equal to -1, return true double dot = DotMatrix(first, second); return (IsEqual(dot, -1)); } /// <summary> /// Set the vector into unit length /// </summary> /// <param name="vector">The input vector</param> /// <returns>The vector in unit length</returns> public static Autodesk.Revit.DB.XYZ UnitVector(Autodesk.Revit.DB.XYZ vector) { // calculate the distance from grid origin to the XYZ double length = GetLength(vector); // changed the vector into the unit length double x = vector.X / length; double y = vector.Y / length; double z = vector.Z / length; return new Autodesk.Revit.DB.XYZ (x, y, z); } /// <summary> /// Calculate the distance from grid origin to the XYZ(vector length) /// </summary> /// <param name="vector">The input vector</param> /// <returns>The length of the vector</returns> public static double GetLength(Autodesk.Revit.DB.XYZ vector) { double x = vector.X; double y = vector.Y; double z = vector.Z; return Math.Sqrt(x * x + y * y + z * z); } /// <summary> /// Subtraction of two points(or vectors), get a new vector /// </summary> /// <param name="p1">The first point(vector)</param> /// <param name="p2">The second point(vector)</param> /// <returns>Return a new vector from point p2 to p1</returns> public static Autodesk.Revit.DB.XYZ SubXYZ(Autodesk.Revit.DB.XYZ p1, Autodesk.Revit.DB.XYZ p2) { double x = p1.X - p2.X; double y = p1.Y - p2.Y; double z = p1.Z - p2.Z; return new Autodesk.Revit.DB.XYZ (x, y, z); } /// <summary> /// Add of two points(or vectors), get a new point(vector) /// </summary> /// <param name="p1">The first point(vector)</param> /// <param name="p2">The first point(vector)</param> /// <returns>A new vector(point)</returns> public static Autodesk.Revit.DB.XYZ AddXYZ(Autodesk.Revit.DB.XYZ p1, Autodesk.Revit.DB.XYZ p2) { double x = p1.X + p2.X; double y = p1.Y + p2.Y; double z = p1.Z + p2.Z; return new Autodesk.Revit.DB.XYZ (x, y, z); } /// <summary> /// Multiply a vector with a number /// </summary> /// <param name="vector">A vector</param> /// <param name="rate">The rate number</param> /// <returns></returns> public static Autodesk.Revit.DB.XYZ MultiplyVector(Autodesk.Revit.DB.XYZ vector, double rate) { double x = vector.X * rate; double y = vector.Y * rate; double z = vector.Z * rate; return new Autodesk.Revit.DB.XYZ (x, y, z); } /// <summary> /// Transform old coordinate system in the new coordinate system /// </summary> /// <param name="point">The Autodesk.Revit.DB.XYZ which need to be transformed</param> /// <param name="transform">The value of the coordinate system to be transformed</param> /// <returns>The new Autodesk.Revit.DB.XYZ which has been transformed</returns> public static Autodesk.Revit.DB.XYZ TransformPoint(Autodesk.Revit.DB.XYZ point, Transform transform) { //get the coordinate value in X, Y, Z axis double x = point.X; double y = point.Y; double z = point.Z; //transform basis of the old coordinate system in the new coordinate system Autodesk.Revit.DB.XYZ b0 = transform.get_Basis(0); Autodesk.Revit.DB.XYZ b1 = transform.get_Basis(1); Autodesk.Revit.DB.XYZ b2 = transform.get_Basis(2); Autodesk.Revit.DB.XYZ origin = transform.Origin; //transform the origin of the old coordinate system in the new coordinate system double xTemp = x * b0.X + y * b1.X + z * b2.X + origin.X; double yTemp = x * b0.Y + y * b1.Y + z * b2.Y + origin.Y; double zTemp = x * b0.Z + y * b1.Z + z * b2.Z + origin.Z; return new Autodesk.Revit.DB.XYZ (xTemp, yTemp, zTemp); } /// <summary> /// Move a point a give offset along a given direction /// </summary> /// <param name="point">The point need to move</param> /// <param name="direction">The direction the point move to</param> /// <param name="offset">Tndicate how long to move</param> /// <returns>The moved point</returns> public static Autodesk.Revit.DB.XYZ OffsetPoint(Autodesk.Revit.DB.XYZ point, Autodesk.Revit.DB.XYZ direction, double offset) { Autodesk.Revit.DB.XYZ directUnit = UnitVector(direction); Autodesk.Revit.DB.XYZ offsetVect = MultiplyVector(directUnit, offset); return AddXYZ(point, offsetVect); } /// <summary> /// Dot product of two Autodesk.Revit.DB.XYZ as Matrix /// </summary> /// <param name="p1">The first XYZ</param> /// <param name="p2">The second XYZ</param> /// <returns>The cosine value of the angle between vector p1 an p2</returns> private static double DotMatrix(Autodesk.Revit.DB.XYZ p1, Autodesk.Revit.DB.XYZ p2) { //get the coordinate of the Autodesk.Revit.DB.XYZ double v1 = p1.X; double v2 = p1.Y; double v3 = p1.Z; double u1 = p2.X; double u2 = p2.Y; double u3 = p2.Z; return v1 * u1 + v2 * u2 + v3 * u3; } } }
// // Copyright 2010, Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Reflection; using System.Collections.Generic; using System.Runtime.InteropServices; using System.IO; using MonoMac.Foundation; using MonoMac.ObjCRuntime; namespace MonoMac.ObjCRuntime { public static class Runtime { static List <Assembly> assemblies; static Dictionary <IntPtr, WeakReference> object_map = new Dictionary <IntPtr, WeakReference> (); static object lock_obj = new object (); static IntPtr selClass = Selector.GetHandle ("class"); public static string FrameworksPath { get; set; } public static string ResourcesPath { get; set; } static Runtime() { // BaseDirectory may not be set in some Mono embedded environments // so try some reasonable fallbacks in these cases. string basePath = AppDomain.CurrentDomain.BaseDirectory; if(!string.IsNullOrEmpty(basePath)) basePath = Path.Combine (basePath, ".."); else { basePath = Assembly.GetExecutingAssembly().Location; if(!string.IsNullOrEmpty(basePath)) { basePath = Path.Combine (Path.GetDirectoryName(basePath), ".."); } else { // The executing assembly location may be null if loaded from // memory so the final fallback is the current directory basePath = Path.Combine (Environment.CurrentDirectory, ".."); } } ResourcesPath = Path.Combine (basePath, "Resources"); FrameworksPath = Path.Combine (basePath, "Frameworks"); } public static void RegisterAssembly (Assembly a) { var attributes = a.GetCustomAttributes (typeof (RequiredFrameworkAttribute), false); foreach (var attribute in attributes) { var requiredFramework = (RequiredFrameworkAttribute)attribute; string libPath; string libName = requiredFramework.Name; if (libName.Contains (".dylib")) { libPath = ResourcesPath; } else { libPath = FrameworksPath; libPath = Path.Combine (libPath, libName); libName = libName.Replace (".frameworks", ""); } libPath = Path.Combine (libPath, libName); if (Dlfcn.dlopen (libPath, 0) == IntPtr.Zero) throw new Exception (string.Format ("Unable to load required framework: '{0}'", requiredFramework.Name), new Exception (Dlfcn.dlerror())); } if (assemblies == null) { assemblies = new List <Assembly> (); Class.Register (typeof (NSObject)); } assemblies.Add (a); foreach (Type type in a.GetTypes ()) { if (type.IsSubclassOf (typeof (NSObject)) && !Attribute.IsDefined (type, typeof (ModelAttribute), false)) Class.Register (type); } } internal static List<Assembly> GetAssemblies () { if (assemblies == null) { var this_assembly = typeof (Runtime).Assembly.GetName (); assemblies = new List <Assembly> (); foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies ()){ var refs = a.GetReferencedAssemblies (); foreach (var aref in refs){ if (aref == this_assembly) assemblies.Add (a); } } } return assemblies; } internal static void UnregisterNSObject (IntPtr ptr) { lock (lock_obj) { object_map.Remove (ptr); } } internal static void RegisterNSObject (NSObject obj, IntPtr ptr) { lock (lock_obj) { object_map [ptr] = new WeakReference (obj); obj.Handle = ptr; } } internal static void NativeObjectHasDied (IntPtr ptr) { lock (lock_obj) { WeakReference wr; if (object_map.TryGetValue (ptr, out wr)) { object_map.Remove (ptr); var obj = (NSObject) wr.Target; if (obj != null) obj.ClearHandle (); } } } public static NSObject TryGetNSObject (IntPtr ptr) { lock (lock_obj) { WeakReference reference; if (object_map.TryGetValue (ptr, out reference)) return (NSObject) reference.Target; } return null; } public static NSObject GetNSObject (IntPtr ptr) { Type type; if (ptr == IntPtr.Zero) return null; lock (lock_obj) { WeakReference reference; if (object_map.TryGetValue (ptr, out reference)) { NSObject target = (NSObject) reference.Target; if (target != null) return target; } } type = Class.Lookup (Messaging.intptr_objc_msgSend (ptr, selClass)); if (type != null) { return (NSObject) Activator.CreateInstance (type, new object[] { ptr }); } else { Console.WriteLine ("WARNING: Cannot find type for {0} ({1}) using NSObject", new Class (ptr).Name, ptr); return new NSObject (ptr); } } public static void ConnectMethod (MethodInfo method, Selector selector) { if (method == null) throw new ArgumentNullException ("method"); if (selector == null) throw new ArgumentNullException ("selector"); var type = method.DeclaringType; if (!Class.IsCustomType (type)) throw new ArgumentException ("Cannot late bind methods on core types"); var ea = new ExportAttribute (selector.Name); var klass = new Class (type); Class.RegisterMethod (method, ea, type, klass.Handle); } } }
using System; using System.Collections; using xmljr.math; namespace xmljr { /// <summary> /// Summary description for Class1. /// </summary> /// namespace math { public class VoidPtr { } } public interface ProgressNotify { void SetProgress(double percent); void IncMinorProcess(); void Finish(); } namespace math { } public class XmlJrSimpleStringArray { public static string[] BreakOnSpace(string x) { ArrayList List = new ArrayList(); string STR = x.Trim(); int k = STR.IndexOf(" "); while(k >= 0) { List.Add(STR.Substring(0,k)); STR = STR.Substring(k+1).Trim(); k = STR.IndexOf(" "); } List.Add(STR); string[] VA = new string[List.Count]; int idx = 0; foreach(string s in List) { VA[idx] = s; idx++; } return VA; } } public class XmlJrBuffer { // public string _BigData; // public string _MediumData; public string _Data; public string _Name; public int _Addr; public System.IO.StringWriter StrWrit = new System.IO.StringWriter(new System.Text.StringBuilder( 8192 )); private void Commit() { StrWrit.Write(_Data); _Data = ""; /* if(_Data.Length > 512) { _MediumData += _Data; _Data = ""; } if(_MediumData.Length > 4096) { Console.WriteLine("Writing Major Block"); _BigData += _MediumData; _MediumData = ""; } */ } public XmlJrBuffer(string name, int addr) { _Name = name; _Addr = addr; _Data = ("<" + name) + ("><xmljr_addr>" + addr + "</xmljr_addr>"); Commit(); } public void finish() { _Data += "</" + _Name + ">"; Commit(); } public void write_int (string name, int v) { _Data += "<" + name + ">" + v + "</" + name + ">"; Commit(); } public void write_uint16 (string name, ushort v) { _Data += "<" + name + ">" + v + "</" + name + ">"; Commit(); } public void write_uint32 (string name, uint v) { _Data += "<" + name + ">" + v + "</" + name + ">"; Commit(); } public void write_long (string name, long v) { _Data += "<" + name + ">" + v + "</" + name + ">"; Commit(); } public void write_float (string name, float v) { _Data += "<" + name + ">" + v + "</" + name + ">"; Commit(); } public void write_double(string name, double v) { _Data += "<" + name + ">" + v + "</" + name + ">"; Commit(); } public void write_bool (string name, bool v) { if(v) _Data += "<" + name + ">T</" + name + ">"; else _Data += "<" + name + ">F</" + name + ">"; Commit(); } public void write_char (string name, char v) { _Data += "<" + name + ">" + (int)v + "</" + name + ">"; Commit(); } public void write_addr (string name, int addr) { _Data += "<" + name + ">" + addr + "</" + name + ">"; Commit(); } public void write_array (string name, long size) { _Data += "<" + name + " size=\""+size+"\">"; Commit(); } public void write_VoidPtr (string name, VoidPtr size) { _Data += "<" + name + "></" + name + ">"; Commit(); } public void write_string(string name,string data) { _Data += "<" + name + ">" + data + "</" + name + ">"; Commit(); } public void finish_array(string name) { _Data += "</" + name + ">"; Commit(); } public void write_Vector4(string name, Vector4 v) { _Data += "<" + name + ">" + v.x + " " + v.y + " " + v.z + " " + v.w + "</" + name + ">"; Commit(); } public void write_Vector3(string name, Vector3 v) { _Data += "<" + name + ">" + v.x + " " + v.y + " " + v.z + "</" + name + ">"; Commit(); } public void write_Vector2(string name, Vector2 v) { _Data += "<" + name + ">" + v.x + " " + v.y + "</" + name + ">"; Commit(); } public void write_fun(string name, string f) { _Data += "<" + name + ">@" + f + "</" + name + ">"; Commit(); } public void write_Matrix4x4(string name, Matrix4x4 m) { double [] glM = m.GetOpenGL_Matrix(); _Data += "<" + name + ">"; for(int k = 0; k < 16; k++) _Data += "" + glM[k] + " "; _Data += "</" + name + ">"; Commit(); } public void write_Matrix3x4(string name, Matrix3x4 m) { double [] Mat = m.Data; _Data += "<" + name + ">"; for(int k = 0; k < 12; k++) _Data += "" + Mat[k] + " "; _Data += "</" + name + ">"; Commit(); } public void write_AABB(string name, AABB aabb) { _Data += "<" + name + ">" + aabb.Position.x + " " + aabb.Position.y + " " + aabb.Position.z + " " + aabb.Dimension.x + " " + aabb.Dimension.y + " " + aabb.Dimension.z + "</" + name + ">"; Commit(); } } public class XmlJrReference { public Object Key; public XmlJrBuffer Buffer; } public class XmlJrWriter { private ArrayList Buffers; private ArrayList Obj2Buffer; private int AddrCounter; ProgressNotify _Note; public XmlJrWriter( ProgressNotify Note) { _Note = Note; Buffers = new ArrayList(); Obj2Buffer = new ArrayList(); AddrCounter = 1; if(Note != null) Note.IncMinorProcess(); } public int Exist(Object o) { if(o==null) return -1; foreach(XmlJrReference myref in Obj2Buffer) { if(myref.Key == o) return myref.Buffer._Addr; } return -1; } public void Map(Object o, XmlJrBuffer b) { XmlJrReference myref = new XmlJrReference(); myref.Key = o; myref.Buffer = b; Obj2Buffer.Add(myref); if(_Note != null) _Note.IncMinorProcess(); } public XmlJrBuffer NewObject(string name, Object o) { XmlJrBuffer next = new XmlJrBuffer(name, AddrCounter); Map(o,next); AddrCounter++; Buffers.Add(next); if(_Note != null) _Note.IncMinorProcess(); return next; } public string GetXML() { double max = 1.0 / ( Buffers.Count + 1); double percent = 0.0; System.IO.StringWriter StrWrit = new System.IO.StringWriter(new System.Text.StringBuilder( Buffers.Count * 8192 ) ); foreach(XmlJrBuffer b in Buffers) { string xml = b.StrWrit.ToString(); StrWrit.Write(xml); /* xml += b.StrWrit.ToString(); if(xml.Length > 8192) { xml_medium += xml; xml = ""; } if(xml_medium.Length > 32768) { xml_large += xml_medium; xml_medium = ""; } */ percent += max; if(_Note != null) _Note.SetProgress(percent); } return StrWrit.ToString(); //return xml_large + xml_medium + xml; } }; public class XmlJrObjectTable { private SortedList _Addr_to_Object; public XmlJrObjectTable() { _Addr_to_Object = new SortedList(); } public void Map(int addr, Object o) { if(o == null) return; _Addr_to_Object.Add(addr, o); } public Object LookUpObject(int addr) { if(addr==0) return null; return (Object) _Addr_to_Object[addr]; } } public class XmlJrLexer { private string _data; int Position = 0; int CountDown = 100; ProgressNotify _Note; public void upd() { if(_Note == null) return; if(CountDown == 0) { CountDown = 100; _Note.IncMinorProcess(); } CountDown --; } private int offset(char x) { return _data.IndexOf(x,Position); } private string copy_from_head_to_offset( int offset) { string x = _data.Substring(Position,offset - Position); return x; } public XmlJrLexer(string data, ProgressNotify note) { _data = data; _Note = note;} public string ReadElement() { if(Position >= _data.Length) return ""; int match; if(_data[Position] == '<') match = offset('>') + 1; else match = offset('<'); string x = copy_from_head_to_offset(match); Position = match; upd(); return x; } }; public class XmlJrParamLexer { private string str; public XmlJrParamLexer(string src) { str = src.TrimStart(); } public char LookAhead() { return str[0]; } public void ConsumeLook() { str = str.Substring(1).TrimStart(); } public string ReadString() { if(str.Length == 0) return ""; string res = ""; if(str[0] == '\"') { int k = 1; while(k < str.Length && str[k] != '\"') { if(str[k] == '\\') k++; k++; } res = str.Substring(1,k-1); str = str.Substring(k+1).TrimStart(); } else { int kSpace = str.IndexOf(" "); int kEnd = str.IndexOf(">"); int kEqual = str.IndexOf("="); int kSlash = str.IndexOf("/"); int k = Math.Max(Math.Max(Math.Max(kSpace,kEnd),kEqual),kSlash); if(k >= 0) { if(kSpace >= 0) k = Math.Min(k, kSpace); if(kEnd >= 0) k = Math.Min(k, kEnd); if(kEqual >= 0) k = Math.Min(k, kEqual); if(kSlash >= 0) k = Math.Min(k, kSlash); res = str.Substring(0,k); str = str.Substring(k).TrimStart(); } } return res; } } public class XmlJrDom { public ArrayList _Children; private SortedList _Parameters; public string _Name; public string _Data; private bool _AcceptingChildren; public XmlJrDom(string header) { _Children = new ArrayList(); _Parameters = new SortedList(); _Data = ""; _AcceptingChildren = true; XmlJrParamLexer pLex = new XmlJrParamLexer(header); if(pLex.LookAhead()=='<') { pLex.ConsumeLook(); _Name = pLex.ReadString(); char la = pLex.LookAhead(); while(la != '/' && la != '>') { string name = pLex.ReadString(); la = pLex.LookAhead(); if(la == '=') { pLex.ConsumeLook(); string data = pLex.ReadString(); _Parameters.Add(name,data); la = pLex.LookAhead(); } else { _Parameters.Add(name,""); } } if(la=='/') _AcceptingChildren = false; } } public bool AllowChildren() { return _AcceptingChildren; } public void AddChild(XmlJrDom child) { _Children.Add(child); } public XmlJrDom GetChildOf(string name) { foreach(XmlJrDom child in _Children) { if(child._Name.Equals(name)) return child; } return null; } public int GetAddr() { XmlJrDom addrnode = GetChildOf("xmljr_addr"); if(addrnode == null) return -1; return Int32.Parse(addrnode._Data); } public void AddData(string data) { _Data += data; } public string GetParam(string name) { return (string) _Parameters[name]; } public int GetIntParam(string name) { return Int32.Parse((string) _Parameters[name]); } public int read_int () { return Int32.Parse(_Data); } public ushort read_uint16 () { return UInt16.Parse(_Data); } public uint read_uint32 () { return UInt32.Parse(_Data); } public long read_long () { return Int32.Parse(_Data); } public float read_float () { return (float) Double.Parse(_Data); } public double read_double () { return Double.Parse(_Data); } public bool read_bool () { return _Data.Trim().Equals("T"); } public char read_char () { return (char) Int32.Parse(_Data); } public string read_string () { return _Data; } public string read_fun () { return (_Data.Length > 1) ? _Data.Substring(1) : "" ; } public Vector2 read_Vector2 () { string [] str = XmlJrSimpleStringArray.BreakOnSpace(_Data); if(str.Length != 2) throw new Exception("Error on read_Vector2"); return new Vector2( Double.Parse(str[0]), Double.Parse(str[1]) ); } public VoidPtr read_VoidPtr () { return null; } public Vector3 read_Vector3 () { string [] str = XmlJrSimpleStringArray.BreakOnSpace(_Data); if(str.Length != 3) throw new Exception("Error on read_Vector3"); return new Vector3( Double.Parse(str[0]), Double.Parse(str[1]), Double.Parse(str[2]) ); } public AABB read_AABB () { string [] str = XmlJrSimpleStringArray.BreakOnSpace(_Data); if(str.Length != 6) throw new Exception("Error on read_AABB"); return new AABB(new Vector3( Double.Parse(str[0]), Double.Parse(str[1]), Double.Parse(str[2]) ), new Vector3( Double.Parse(str[3]), Double.Parse(str[4]), Double.Parse(str[5]) )); } public Vector4 read_Vector4 () { string [] str = XmlJrSimpleStringArray.BreakOnSpace(_Data); if(str.Length != 4) throw new Exception("Error on read_Vector4"); return new Vector4( Double.Parse(str[0]), Double.Parse(str[1]), Double.Parse(str[2]), Double.Parse(str[3]) ); } public Matrix4x4 read_Matrix4x4 () { string [] str = XmlJrSimpleStringArray.BreakOnSpace(_Data); double [] mat = new double[str.Length]; if(str.Length != 16) throw new Exception("Error on read_Matrix4x4"); for(int k = 0; k < 16; k++) mat[k] = Double.Parse(str[k]); return new Matrix4x4(mat); } public Matrix3x4 read_Matrix3x4 () { string [] str = XmlJrSimpleStringArray.BreakOnSpace(_Data); double [] mat = new double[str.Length]; if(str.Length != 12) throw new Exception("Error on read_Matrix3x4"); for(int k = 0; k < 12; k++) mat[k] = Double.Parse(str[k]); return new Matrix3x4(mat); } public static XmlJrDom Read(string data, ProgressNotify note) { XmlJrLexer Lex = new XmlJrLexer(data,note); Stack Stk = new Stack(); XmlJrDom Current = new XmlJrDom("<xmljr>"); string rez = Lex.ReadElement(); while(rez.Length > 0) { if(rez[0] == '<') { if(rez[1] == '/') { Current = (XmlJrDom) Stk.Pop(); } else { XmlJrDom child = new XmlJrDom(rez); Current.AddChild(child); if(child.AllowChildren()) { Stk.Push(Current); Current = child; } } } else { Current.AddData(rez); } rez = Lex.ReadElement(); } return Current; } }; public class XmlJrTest { /// <summary> /// The main entry point for the application. /// </summary> /// static void Display(XmlJrDom Doc, int ident) { string buffer = ""; for(int k = 0; k < ident; k++) buffer += " "; if(Doc.AllowChildren()) { Console.WriteLine(buffer + "<" + Doc._Name + ">"); Console.WriteLine(Doc._Data); foreach(XmlJrDom C in Doc._Children) { Display(C,ident+1); } Console.WriteLine(buffer + "</" + Doc._Name + ">"); } else { Console.WriteLine(buffer + "<" + Doc._Name + "/>"); } } /* [STAThread] static void Main(string[] args) { XmlJrDom Test = XmlJrDom.Read("<X><xmljr_addr>1</xmljr_addr><Array size=\"16\"><r>0</r><r>0</r><r>0</r><r>0</r><r>0</r><r>666</r><r>0</r><r>0</r><r>0</r><r>0</r><r>0</r><r>0</r><r>0</r><r>0</r><r>0</r><r>0</r></Array><ON>F</ON><Num>0</Num><TempPtr>2</TempPtr></X><Y><xmljr_addr>2</xmljr_addr><sample>42</sample></Y>"); Display(Test,0); XmlJrObjectTable XJOT = zenerd.zenerd.BuildObjectTable(Test); zenerd.X a = (zenerd.X) XJOT.LookUpObject(1); XmlJrWriter writ = new XmlJrWriter(); a.WriteXML(writ); Console.WriteLine(writ.GetXML()); } */ } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.Threading; using System.Windows.Forms; using OpenLiveWriter.ApplicationFramework.Skinning; using OpenLiveWriter.Controls; using OpenLiveWriter.CoreServices; using OpenLiveWriter.BlogClient; using OpenLiveWriter.CoreServices.Layout; using OpenLiveWriter.Interop.Windows; using OpenLiveWriter.Localization; using OpenLiveWriter.Localization.Bidi; namespace OpenLiveWriter.PostEditor { public class UpdateWeblogProgressForm : BaseForm { private CheckBox checkBoxViewPost; private AnimatedBitmapControl progressAnimatedBitmap; private Label labelPublishingTo; /// <summary> /// Required designer variable. /// </summary> private Container components = null; private IWin32Window _parentFrame ; private IBlogPostPublishingContext _publishingContext ; private bool _publish ; private bool _republishOnSuccess ; private UpdateWeblogAsyncOperation _updateWeblogAsyncOperation ; private string _defaultProgressMessage; private string _cancelReason; /// <param name="parentFrame"></param> /// <param name="publishingContext"></param> /// <param name="isPage"></param> /// <param name="destinationName"></param> /// <param name="publish">If false, the publishing operation will post as draft</param> public UpdateWeblogProgressForm(IWin32Window parentFrame, IBlogPostPublishingContext publishingContext, bool isPage, string destinationName, bool publish) { InitializeComponent(); this.checkBoxViewPost.Text = Res.Get(StringId.UpdateWeblogViewPost); // reference to parent frame and editing context _parentFrame = parentFrame ; _publishingContext = publishingContext ; _publish = publish; // look and feel (no form border and theme dervied background color) FormBorderStyle = FormBorderStyle.None ; BackColor = ColorizedResources.Instance.FrameGradientLight ; // bitmaps for animation progressAnimatedBitmap.Bitmaps = AnimationBitmaps ; // initialize controls string entityName = isPage ? Res.Get(StringId.Page) : Res.Get(StringId.Post) ; Text = FormatFormCaption( entityName, publish ) ; ProgressMessage = _defaultProgressMessage = FormatPublishingToCaption(destinationName, entityName, publish); checkBoxViewPost.Visible = publish ; checkBoxViewPost.Checked = PostEditorSettings.ViewPostAfterPublish ; // hookup event handlers checkBoxViewPost.CheckedChanged +=new EventHandler(checkBoxViewPost_CheckedChanged); } /// <summary> /// Makes available the name of the plug-in that caused the publish /// operation to be canceled /// </summary> public string CancelReason { get { return _cancelReason; } } public event PublishHandler PrePublish; public event PublishingHandler Publishing; public event PublishHandler PostPublish; public delegate void PublishingHandler(object sender, PublishingEventArgs args); public class PublishingEventArgs : EventArgs { public readonly bool Publish; public bool RepublishOnSuccess = false; public PublishingEventArgs(bool publish) { Publish = publish; } } public delegate void PublishHandler(object sender, PublishEventArgs args); public class PublishEventArgs : EventArgs { public readonly bool Publish; public bool Cancel = false; public string CancelReason = null; public PublishEventArgs(bool publish) { Publish = publish; } } protected override void OnShown(EventArgs e) { base.OnShown(e); Update(); PublishEventArgs args = new PublishEventArgs(_publish); if (PrePublish != null) PrePublish(this, args); if (args.Cancel) { _cancelReason = args.CancelReason; SetDialogResult(DialogResult.Abort); return; } StartUpdate(); } private void StartUpdate() { PublishingEventArgs args = new PublishingEventArgs(_publish); if (Publishing != null) Publishing(this, args); _republishOnSuccess = args.RepublishOnSuccess; // kickoff weblog update // Blogger drafts don't have permalinks, therefore, we must do a full publish twice bool doPublish = _publish; // && (!_republishOnSuccess || !_publishingContext.Blog.ClientOptions.SupportsPostAsDraft); _updateWeblogAsyncOperation = new UpdateWeblogAsyncOperation(new BlogClientUIContextImpl(this), _publishingContext, doPublish); _updateWeblogAsyncOperation.Completed += new EventHandler(_updateWeblogAsyncOperation_Completed); _updateWeblogAsyncOperation.Cancelled += new EventHandler(_updateWeblogAsyncOperation_Cancelled); _updateWeblogAsyncOperation.Failed += new ThreadExceptionEventHandler(_updateWeblogAsyncOperation_Failed); _updateWeblogAsyncOperation.ProgressUpdated += new ProgressUpdatedEventHandler(_updateWeblogAsyncOperation_ProgressUpdated); _updateWeblogAsyncOperation.Start(); } public Exception Exception { get { return _updateWeblogAsyncOperation.Exception ; } } protected override CreateParams CreateParams { get { CreateParams createParams = base.CreateParams; // add system standard drop shadow const int CS_DROPSHADOW = 0x20000 ; createParams.ClassStyle |= CS_DROPSHADOW ; return createParams ; } } protected override void OnLoad(EventArgs e) { base.OnLoad (e); // fix up layout using (new AutoGrow(this, AnchorStyles.Bottom, false)) { LayoutHelper.NaturalizeHeight(checkBoxViewPost); } // position form RECT parentRect = new RECT(); User32.GetWindowRect( _parentFrame.Handle, ref parentRect ) ; Rectangle parentBounds = RectangleHelper.Convert(parentRect) ; Location = new Point( parentBounds.Left + ((parentBounds.Width - Width)/2), parentBounds.Top + (int)(1.5*Height) ); } private string FormatFormCaption( string entityName, bool publish ) { return String.Format( CultureInfo.CurrentCulture, Res.Get(StringId.UpdateWeblogPublish1), publish ? entityName : Res.Get(StringId.UpdateWeblogDraft)) ; } private string FormatPublishingToCaption( string destinationName, string entityName, bool publish ) { return String.Format( CultureInfo.CurrentCulture, Res.Get(StringId.UpdateWeblogPublish2), publish ? entityName : Res.Get(StringId.UpdateWeblogDraft), destinationName ) ; } private void _updateWeblogAsyncOperation_Completed( object sender, EventArgs ea) { Debug.Assert(!InvokeRequired); if (_republishOnSuccess) { _republishOnSuccess = false; Debug.Assert(_publishingContext.BlogPost.Id != null); StartUpdate(); } else { if (PostPublish != null) PostPublish(this, new PublishEventArgs(_publish)); SetDialogResult(DialogResult.OK); } } private void _updateWeblogAsyncOperation_Cancelled( object sender, EventArgs ea) { Debug.Assert(!InvokeRequired); Debug.Fail("Cancel not supported for UpdateWeblogAsyncOperation!"); SetDialogResult(DialogResult.OK) ; } private void _updateWeblogAsyncOperation_Failed(object sender, ThreadExceptionEventArgs e) { Debug.Assert(!InvokeRequired); SetDialogResult(DialogResult.Cancel); } private void SetDialogResult(DialogResult result) { _okToClose = true ; DialogResult = result ; } private bool _okToClose = false ; protected override void OnClosing(CancelEventArgs e) { base.OnClosing (e); if ( _okToClose ) { progressAnimatedBitmap.Stop(); } else { e.Cancel = true ; } } /// <summary> /// Override out Activated event to allow parent form to retains its 'activated' /// look (caption bar color, etc.) even when we are active /// </summary> /// <param name="e"></param> protected override void OnActivated(EventArgs e) { // start the animation if necessary (don't start until we are activated so that the // loading of the form is not delayed) if ( !progressAnimatedBitmap.Running ) progressAnimatedBitmap.Start(); } private void checkBoxViewPost_CheckedChanged(object sender, EventArgs e) { PostEditorSettings.ViewPostAfterPublish = checkBoxViewPost.Checked ; } private Bitmap[] AnimationBitmaps { get { if (_animationBitmaps == null) { ArrayList list = new ArrayList(); for( int i=1; i<=26; i++ ) { string resourceName = String.Format(CultureInfo.InvariantCulture, "Images.PublishAnimation.post{0:00}.png", i ); list.Add( ResourceHelper.LoadAssemblyResourceBitmap(resourceName) ) ; } _animationBitmaps = (Bitmap[])list.ToArray(typeof(Bitmap)); } return _animationBitmaps; } } private Bitmap[] _animationBitmaps; private Bitmap bottomBevelBitmap = ResourceHelper.LoadAssemblyResourceBitmap("Images.PublishAnimation.BottomBevel.png") ; /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.checkBoxViewPost = new System.Windows.Forms.CheckBox(); this.progressAnimatedBitmap = new OpenLiveWriter.Controls.AnimatedBitmapControl(); this.labelPublishingTo = new System.Windows.Forms.Label(); this.SuspendLayout(); // // checkBoxViewPost // this.checkBoxViewPost.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.checkBoxViewPost.FlatStyle = System.Windows.Forms.FlatStyle.System; this.checkBoxViewPost.Location = new System.Drawing.Point(19, 136); this.checkBoxViewPost.Name = "checkBoxViewPost"; this.checkBoxViewPost.Size = new System.Drawing.Size(325, 18); this.checkBoxViewPost.TabIndex = 1; this.checkBoxViewPost.Text = "View in browser after publishing"; this.checkBoxViewPost.TextAlign = System.Drawing.ContentAlignment.TopLeft; // // progressAnimatedBitmap // this.progressAnimatedBitmap.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.progressAnimatedBitmap.Bitmaps = null; this.progressAnimatedBitmap.Interval = 100; this.progressAnimatedBitmap.Location = new System.Drawing.Point(19, 25); this.progressAnimatedBitmap.Name = "progressAnimatedBitmap"; this.progressAnimatedBitmap.Running = false; this.progressAnimatedBitmap.Size = new System.Drawing.Size(321, 71); this.progressAnimatedBitmap.TabIndex = 2; this.progressAnimatedBitmap.UseVirtualTransparency = false; // // labelPublishingTo // this.labelPublishingTo.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.labelPublishingTo.FlatStyle = System.Windows.Forms.FlatStyle.System; this.labelPublishingTo.Location = new System.Drawing.Point(19, 105); this.labelPublishingTo.Name = "labelPublishingTo"; this.labelPublishingTo.Size = new System.Drawing.Size(317, 18); this.labelPublishingTo.TabIndex = 3; this.labelPublishingTo.Text = "Publishing to: My Random Ramblings"; this.labelPublishingTo.UseMnemonic = false; this.labelPublishingTo.Visible = false; // // UpdateWeblogProgressForm // this.AutoScaleBaseSize = new System.Drawing.Size(5, 14); this.ClientSize = new System.Drawing.Size(360, 164); this.ControlBox = false; this.Controls.Add(this.labelPublishingTo); this.Controls.Add(this.progressAnimatedBitmap); this.Controls.Add(this.checkBoxViewPost); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "UpdateWeblogProgressForm"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "Publishing {0} to Weblog"; this.ResumeLayout(false); } #endregion private void _updateWeblogAsyncOperation_ProgressUpdated(object sender, ProgressUpdatedEventArgs progressUpdatedHandler) { string msg = progressUpdatedHandler.ProgressMessage; if (msg != null) ProgressMessage = msg; } private string _progressMessage; private string ProgressMessage { get { return _progressMessage; } set { _progressMessage = value; Refresh(); } } protected override void OnPaint(PaintEventArgs e) { base.OnPaint (e); BidiGraphics g = new BidiGraphics(e.Graphics, ClientSize, false); ColorizedResources colRes = ColorizedResources.Instance; // draw the outer border using (Pen p = new Pen(colRes.BorderDarkColor, 1)) g.DrawRectangle(p, new Rectangle(0, 0, ClientSize.Width - 1, ClientSize.Height - 1)); // draw the caption using (Font f = Res.GetFont(FontSize.Large, FontStyle.Bold)) g.DrawText(Text, f, new Rectangle(19, 8, ClientSize.Width - 1, ClientSize.Height - 1),SystemColors.WindowText, TextFormatFlags.NoPrefix); GdiTextHelper.DrawString(this, labelPublishingTo.Font, _progressMessage, labelPublishingTo.Bounds, false, GdiTextDrawMode.EndEllipsis); } public void SetProgressMessage(string msg) { ProgressMessage = msg ?? _defaultProgressMessage; } } }
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 WebApiHttpBatchServer.Areas.HelpPage.ModelDescriptions; using WebApiHttpBatchServer.Areas.HelpPage.Models; namespace WebApiHttpBatchServer.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.IO; using System.Text; using System.Xml.Schema; using System.Collections; using System.Diagnostics; using System.Threading.Tasks; namespace System.Xml { // // XmlCharCheckingWriter // internal partial class XmlCharCheckingWriter : XmlWrappingWriter { public override Task WriteDocTypeAsync( string name, string pubid, string sysid, string subset ) { if ( checkNames ) { ValidateQName( name ); } if ( checkValues ) { if ( pubid != null ) { int i; if ( ( i = xmlCharType.IsPublicId( pubid ) ) >= 0 ) { throw XmlConvert.CreateInvalidCharException( pubid, i ); } } if ( sysid != null ) { CheckCharacters( sysid ); } if ( subset != null ) { CheckCharacters( subset ); } } if ( replaceNewLines ) { sysid = ReplaceNewLines( sysid ); pubid = ReplaceNewLines( pubid ); subset = ReplaceNewLines( subset ); } return writer.WriteDocTypeAsync(name, pubid, sysid, subset); } public override Task WriteStartElementAsync( string prefix, string localName, string ns ) { if ( checkNames ) { if ( localName == null || localName.Length == 0 ) { throw new ArgumentException( Res.GetString( Res.Xml_EmptyLocalName ) ); } ValidateNCName( localName ); if ( prefix != null && prefix.Length > 0 ) { ValidateNCName( prefix ); } } return writer.WriteStartElementAsync(prefix, localName, ns); } protected internal override Task WriteStartAttributeAsync( string prefix, string localName, string ns ) { if ( checkNames ) { if ( localName == null || localName.Length == 0 ) { throw new ArgumentException( Res.GetString( Res.Xml_EmptyLocalName ) ); } ValidateNCName( localName ); if ( prefix != null && prefix.Length > 0 ) { ValidateNCName( prefix ); } } return writer.WriteStartAttributeAsync(prefix, localName, ns); } public override async Task WriteCDataAsync( string text ) { if ( text != null ) { if ( checkValues ) { CheckCharacters( text ); } if ( replaceNewLines ) { text = ReplaceNewLines( text ); } int i; while ( ( i = text.IndexOf( "]]>", StringComparison.Ordinal ) ) >= 0 ) { await writer.WriteCDataAsync( text.Substring( 0, i + 2 ) ).ConfigureAwait(false); text = text.Substring( i + 2 ); } } await writer.WriteCDataAsync( text ).ConfigureAwait(false); } public override Task WriteCommentAsync( string text ) { if ( text != null ) { if ( checkValues ) { CheckCharacters( text ); text = InterleaveInvalidChars( text, '-', '-' ); } if ( replaceNewLines ) { text = ReplaceNewLines( text ); } } return writer.WriteCommentAsync( text ); } public override Task WriteProcessingInstructionAsync( string name, string text ) { if ( checkNames ) { ValidateNCName( name ); } if ( text != null ) { if ( checkValues ) { CheckCharacters( text ); text = InterleaveInvalidChars( text, '?', '>' ); } if ( replaceNewLines ) { text = ReplaceNewLines( text ); } } return writer.WriteProcessingInstructionAsync(name, text); } public override Task WriteEntityRefAsync( string name ) { if ( checkNames ) { ValidateQName( name ); } return writer.WriteEntityRefAsync(name); } public override Task WriteWhitespaceAsync( string ws ) { if ( ws == null ) { ws = string.Empty; } // "checkNames" is intentional here; if false, the whitespaces are checked in XmlWellformedWriter if ( checkNames ) { int i; if ( ( i = xmlCharType.IsOnlyWhitespaceWithPos( ws ) ) != -1 ) { throw new ArgumentException( Res.GetString( Res.Xml_InvalidWhitespaceCharacter, XmlException.BuildCharExceptionArgs( ws, i ) ) ); } } if ( replaceNewLines ) { ws = ReplaceNewLines( ws ); } return writer.WriteWhitespaceAsync(ws); } public override Task WriteStringAsync( string text ) { if ( text != null ) { if ( checkValues ) { CheckCharacters( text ); } if ( replaceNewLines && WriteState != WriteState.Attribute ) { text = ReplaceNewLines( text ); } } return writer.WriteStringAsync(text); } public override Task WriteSurrogateCharEntityAsync( char lowChar, char highChar ) { return writer.WriteSurrogateCharEntityAsync(lowChar, highChar); } public override Task WriteCharsAsync( char[] buffer, int index, int count ) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (count > buffer.Length - index) { throw new ArgumentOutOfRangeException("count"); } if (checkValues) { CheckCharacters( buffer, index, count ); } if ( replaceNewLines && WriteState != WriteState.Attribute ) { string text = ReplaceNewLines( buffer, index, count ); if ( text != null ) { return WriteStringAsync(text); } } return writer.WriteCharsAsync( buffer, index, count ); } public override Task WriteNmTokenAsync( string name ) { if ( checkNames ) { if ( name == null || name.Length == 0 ) { throw new ArgumentException( Res.GetString( Res.Xml_EmptyName ) ); } XmlConvert.VerifyNMTOKEN( name ); } return writer.WriteNmTokenAsync(name); } public override Task WriteNameAsync( string name ) { if ( checkNames ) { XmlConvert.VerifyQName( name, ExceptionType.XmlException ); } return writer.WriteNameAsync(name); } public override Task WriteQualifiedNameAsync( string localName, string ns ) { if ( checkNames ) { ValidateNCName( localName ); } return writer.WriteQualifiedNameAsync(localName, ns); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // NOTE: define this if you want to test the output on US machine and ASCII // characters //#define TEST_MULTICELL_ON_SINGLE_CELL_LOCALE using System; using System.Collections.Specialized; using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Host; using Dbg = System.Management.Automation.Diagnostics; // interfaces for host interaction namespace Microsoft.PowerShell.Commands.Internal.Format { #if TEST_MULTICELL_ON_SINGLE_CELL_LOCALE /// <summary> /// Test class to provide easily overridable behavior for testing on US machines /// using US data. /// NOTE: the class just forces any uppercase letter [A-Z] to be prepended /// with an underscore (e.g. "A" becomes "_A", but "a" stays the same) /// </summary> internal class DisplayCellsTest : DisplayCells { internal override int Length(string str, int offset) { int len = 0; for (int k = offset; k < str.Length; k++) { len += this.Length(str[k]); } return len; } internal override int Length(char character) { if (character >= 'A' && character <= 'Z') return 2; return 1; } internal override int GetHeadSplitLength(string str, int offset, int displayCells) { return GetSplitLengthInternalHelper(str, offset, displayCells, true); } internal override int GetTailSplitLength(string str, int offset, int displayCells) { return GetSplitLengthInternalHelper(str, offset, displayCells, false); } internal string GenerateTestString(string str) { StringBuilder sb = new StringBuilder(); for (int k = 0; k < str.Length; k++) { char ch = str[k]; if (this.Length(ch) == 2) { sb.Append('_'); } sb.Append(ch); } return sb.ToString(); } } #endif /// <summary> /// Tear off class. /// </summary> internal class DisplayCellsPSHost : DisplayCells { internal DisplayCellsPSHost(PSHostRawUserInterface rawUserInterface) { _rawUserInterface = rawUserInterface; } internal override int Length(string str, int offset) { Dbg.Assert(offset >= 0, "offset >= 0"); Dbg.Assert(string.IsNullOrEmpty(str) || (offset < str.Length), "offset < str.Length"); try { return _rawUserInterface.LengthInBufferCells(str, offset); } catch (Exception ex) when (ex is HostException || ex is NotImplementedException) { // thrown when external host rawui is not implemented, in which case // we will fallback to the default value. } return string.IsNullOrEmpty(str) ? 0 : str.Length - offset; } internal override int Length(string str) { try { return _rawUserInterface.LengthInBufferCells(str); } catch (Exception ex) when (ex is HostException || ex is NotImplementedException) { // thrown when external host rawui is not implemented, in which case // we will fallback to the default value. } return string.IsNullOrEmpty(str) ? 0 : str.Length; } internal override int Length(char character) { try { return _rawUserInterface.LengthInBufferCells(character); } catch (Exception ex) when (ex is HostException || ex is NotImplementedException) { // thrown when external host rawui is not implemented, in which case // we will fallback to the default value. } return 1; } internal override int GetHeadSplitLength(string str, int offset, int displayCells) { return GetSplitLengthInternalHelper(str, offset, displayCells, true); } internal override int GetTailSplitLength(string str, int offset, int displayCells) { return GetSplitLengthInternalHelper(str, offset, displayCells, false); } private PSHostRawUserInterface _rawUserInterface; } /// <summary> /// Implementation of the LineOutput interface on top of Console and RawConsole. /// </summary> internal sealed class ConsoleLineOutput : LineOutput { #region tracer [TraceSource("ConsoleLineOutput", "ConsoleLineOutput")] internal static PSTraceSource tracer = PSTraceSource.GetTracer("ConsoleLineOutput", "ConsoleLineOutput"); #endregion tracer #region LineOutput implementation /// <summary> /// The # of columns is just the width of the screen buffer (not the /// width of the window) /// </summary> /// <value></value> internal override int ColumnNumber { get { CheckStopProcessing(); PSHostRawUserInterface raw = _console.RawUI; // IMPORTANT NOTE: we subtract one because // we want to make sure the console's last column // is never considered written. This causes the writing // logic to always call WriteLine(), making sure a CR // is inserted. try { return _forceNewLine ? raw.BufferSize.Width - 1 : raw.BufferSize.Width; } catch (Exception ex) when (ex is HostException || ex is NotImplementedException) { // thrown when external host rawui is not implemented, in which case // we will fallback to the default value. } return _forceNewLine ? _fallbackRawConsoleColumnNumber - 1 : _fallbackRawConsoleColumnNumber; } } /// <summary> /// The # of rows is the # of rows visible in the window (and not the # of /// rows in the screen buffer) /// </summary> /// <value></value> internal override int RowNumber { get { CheckStopProcessing(); PSHostRawUserInterface raw = _console.RawUI; try { return raw.WindowSize.Height; } catch (Exception ex) when (ex is HostException || ex is NotImplementedException) { // thrown when external host rawui is not implemented, in which case // we will fallback to the default value. } return _fallbackRawConsoleRowNumber; } } /// <summary> /// Write a line to the output device. /// </summary> /// <param name="s">Line to write.</param> internal override void WriteLine(string s) { CheckStopProcessing(); // delegate the action to the helper, // that will properly break the string into // screen lines _writeLineHelper.WriteLine(s, this.ColumnNumber); } internal override DisplayCells DisplayCells { get { CheckStopProcessing(); if (_displayCellsPSHost != null) { return _displayCellsPSHost; } // fall back if we do not have a Msh host specific instance return _displayCellsPSHost; } } #endregion /// <summary> /// Constructor for the ConsoleLineOutput. /// </summary> /// <param name="hostConsole">PSHostUserInterface to wrap.</param> /// <param name="paging">True if we require prompting for page breaks.</param> /// <param name="errorContext">Error context to throw exceptions.</param> internal ConsoleLineOutput(PSHostUserInterface hostConsole, bool paging, TerminatingErrorContext errorContext) { if (hostConsole == null) throw PSTraceSource.NewArgumentNullException("hostConsole"); if (errorContext == null) throw PSTraceSource.NewArgumentNullException("errorContext"); _console = hostConsole; _errorContext = errorContext; if (paging) { tracer.WriteLine("paging is needed"); // if we need to do paging, instantiate a prompt handler // that will take care of the screen interaction string promptString = StringUtil.Format(FormatAndOut_out_xxx.ConsoleLineOutput_PagingPrompt); _prompt = new PromptHandler(promptString, this); } PSHostRawUserInterface raw = _console.RawUI; if (raw != null) { tracer.WriteLine("there is a valid raw interface"); #if TEST_MULTICELL_ON_SINGLE_CELL_LOCALE // create a test instance with fake behavior this._displayCellsPSHost = new DisplayCellsTest(); #else // set only if we have a valid raw interface _displayCellsPSHost = new DisplayCellsPSHost(raw); #endif } // instantiate the helper to do the line processing when ILineOutput.WriteXXX() is called WriteLineHelper.WriteCallback wl = new WriteLineHelper.WriteCallback(this.OnWriteLine); WriteLineHelper.WriteCallback w = new WriteLineHelper.WriteCallback(this.OnWrite); if (_forceNewLine) { _writeLineHelper = new WriteLineHelper(/*lineWrap*/false, wl, null, this.DisplayCells); } else { _writeLineHelper = new WriteLineHelper(/*lineWrap*/false, wl, w, this.DisplayCells); } } /// <summary> /// Callback to be called when ILineOutput.WriteLine() is called by WriteLineHelper. /// </summary> /// <param name="s">String to write.</param> private void OnWriteLine(string s) { #if TEST_MULTICELL_ON_SINGLE_CELL_LOCALE s = ((DisplayCellsTest)this._displayCellsPSHost).GenerateTestString(s); #endif // Do any default transcription. _console.TranscribeResult(s); switch (this.WriteStream) { case WriteStreamType.Error: _console.WriteErrorLine(s); break; case WriteStreamType.Warning: _console.WriteWarningLine(s); break; case WriteStreamType.Verbose: _console.WriteVerboseLine(s); break; case WriteStreamType.Debug: _console.WriteDebugLine(s); break; default: // If the host is in "transcribe only" // mode (due to an implicitly added call to Out-Default -Transcribe), // then don't call the actual host API. if (!_console.TranscribeOnly) { _console.WriteLine(s); } break; } LineWrittenEvent(); } /// <summary> /// Callback to be called when ILineOutput.Write() is called by WriteLineHelper /// This is called when the WriteLineHelper needs to write a line whose length /// is the same as the width of the screen buffer. /// </summary> /// <param name="s">String to write.</param> private void OnWrite(string s) { #if TEST_MULTICELL_ON_SINGLE_CELL_LOCALE s = ((DisplayCellsTest)this._displayCellsPSHost).GenerateTestString(s); #endif switch (this.WriteStream) { case WriteStreamType.Error: _console.WriteErrorLine(s); break; case WriteStreamType.Warning: _console.WriteWarningLine(s); break; case WriteStreamType.Verbose: _console.WriteVerboseLine(s); break; case WriteStreamType.Debug: _console.WriteDebugLine(s); break; default: _console.Write(s); break; } LineWrittenEvent(); } /// <summary> /// Called when a line was written to console. /// </summary> private void LineWrittenEvent() { // check to avoid reentrancy from the prompt handler // writing during the PromptUser() call if (_disableLineWrittenEvent) return; // if there is no prompting, we are done if (_prompt == null) return; // increment the count of lines written to the screen _linesWritten++; // check if we need to put out a prompt if (this.NeedToPrompt) { // put out the prompt _disableLineWrittenEvent = true; PromptHandler.PromptResponse response = _prompt.PromptUser(_console); _disableLineWrittenEvent = false; switch (response) { case PromptHandler.PromptResponse.NextPage: { // reset the counter, since we are starting a new page _linesWritten = 0; } break; case PromptHandler.PromptResponse.NextLine: { // roll back the counter by one, since we allow one more line _linesWritten--; } break; case PromptHandler.PromptResponse.Quit: // 1021203-2005/05/09-JonN // HaltCommandException will cause the command // to stop, but not be reported as an error. throw new HaltCommandException(); } } } /// <summary> /// Check if we need to put out a prompt. /// </summary> /// <value>true if we need to prompt</value> private bool NeedToPrompt { get { // NOTE: we recompute all the time to take into account screen resizing int rawRowNumber = this.RowNumber; if (rawRowNumber <= 0) { // something is wrong, there is no real estate, we suppress prompting return false; } // the prompt will occupy some lines, so we need to subtract them form the total // screen line count int computedPromptLines = _prompt.ComputePromptLines(this.DisplayCells, this.ColumnNumber); int availableLines = this.RowNumber - computedPromptLines; if (availableLines <= 0) { tracer.WriteLine("No available Lines; suppress prompting"); // something is wrong, there is no real estate, we suppress prompting return false; } return _linesWritten >= availableLines; } } #region Private Members /// <summary> /// Object to manage prompting. /// </summary> private class PromptHandler { /// <summary> /// Prompt handler with the given prompt. /// </summary> /// <param name="s">Prompt string to be used.</param> /// <param name="cmdlet">The Cmdlet using this prompt handler.</param> internal PromptHandler(string s, ConsoleLineOutput cmdlet) { if (string.IsNullOrEmpty(s)) throw PSTraceSource.NewArgumentNullException("s"); _promptString = s; _callingCmdlet = cmdlet; } /// <summary> /// Determine how many rows the prompt should take. /// </summary> /// <param name="cols">Current number of columns on the screen.</param> /// <param name="displayCells">String manipulation helper.</param> /// <returns></returns> internal int ComputePromptLines(DisplayCells displayCells, int cols) { // split the prompt string into lines _actualPrompt = StringManipulationHelper.GenerateLines(displayCells, _promptString, cols, cols); return _actualPrompt.Count; } /// <summary> /// Options returned by the PromptUser() call. /// </summary> internal enum PromptResponse { NextPage, NextLine, Quit } /// <summary> /// Do the actual prompting. /// </summary> /// <param name="console">PSHostUserInterface instance to prompt to.</param> internal PromptResponse PromptUser(PSHostUserInterface console) { // NOTE: assume the values passed to ComputePromptLines are still valid // write out the prompt line(s). The last one will not have a new line // at the end because we leave the prompt at the end of the line for (int k = 0; k < _actualPrompt.Count; k++) { if (k < (_actualPrompt.Count - 1)) console.WriteLine(_actualPrompt[k]); // intermediate line(s) else console.Write(_actualPrompt[k]); // last line } while (true) { _callingCmdlet.CheckStopProcessing(); KeyInfo ki = console.RawUI.ReadKey(ReadKeyOptions.IncludeKeyUp | ReadKeyOptions.NoEcho); char key = ki.Character; if (key == 'q' || key == 'Q') { // need to move to the next line since we accepted input, add a newline console.WriteLine(); return PromptResponse.Quit; } else if (key == ' ') { // need to move to the next line since we accepted input, add a newline console.WriteLine(); return PromptResponse.NextPage; } else if (key == '\r') { // need to move to the next line since we accepted input, add a newline console.WriteLine(); return PromptResponse.NextLine; } } } /// <summary> /// Cached string(s) valid during a sequence of ComputePromptLines()/PromptUser() /// </summary> private StringCollection _actualPrompt; /// <summary> /// Prompt string as passed at initialization. /// </summary> private string _promptString; /// <summary> /// The cmdlet that uses this prompt helper. /// </summary> private ConsoleLineOutput _callingCmdlet = null; } /// <summary> /// Flag to force new lines in CMD.EXE by limiting the /// usable width to N-1 (e.g. 80-1) and forcing a call /// to WriteLine() /// </summary> private bool _forceNewLine = true; /// <summary> /// Use this if IRawConsole is null; /// </summary> private int _fallbackRawConsoleColumnNumber = 80; /// <summary> /// Use this if IRawConsole is null; /// </summary> private int _fallbackRawConsoleRowNumber = 40; private WriteLineHelper _writeLineHelper; /// <summary> /// Handler to prompt the user for page breaks /// if this handler is not null, we have prompting. /// </summary> private PromptHandler _prompt = null; /// <summary> /// Conter for the # of lines written when prompting is on. /// </summary> private long _linesWritten = 0; /// <summary> /// Flag to avoid reentrancy on prompting. /// </summary> private bool _disableLineWrittenEvent = false; /// <summary> /// Refecence to the PSHostUserInterface interface we use. /// </summary> private PSHostUserInterface _console = null; /// <summary> /// Msh host specific string manipulation helper. /// </summary> private DisplayCells _displayCellsPSHost; /// <summary> /// Reference to error context to throw Msh exceptions. /// </summary> private TerminatingErrorContext _errorContext = null; #endregion } }
// // StationSource.cs // // Authors: // Gabriel Burt <[email protected]> // // Copyright (C) 2007-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Text.RegularExpressions; using System.Collections.Generic; using System.Threading; using Mono.Unix; using Gtk; using Hyena; using Hyena.Data.Sqlite; using Lastfm; using ConnectionState = Lastfm.ConnectionState; using Banshee.Base; using Banshee.Widgets; using Banshee.Database; using Banshee.Sources; using Banshee.Metadata; using Banshee.MediaEngine; using Banshee.Collection; using Banshee.ServiceStack; using Banshee.PlaybackController; using Banshee.Lastfm; using Selection=Hyena.Collections.Selection; namespace Banshee.LastfmStreaming.Radio { public class StationSource : Source, ITrackModelSource, IUnmapableSource, IDisposable, IBasicPlaybackController { private static string generic_name = Catalog.GetString ("Last.fm Station"); public static StationSource CreateFromUrl (LastfmSource lastfm, string url) { foreach (StationType type in StationType.Types) { string regex = Regex.Escape (type.GetStationFor ("XXX")).Replace ("XXX", "([^\\/]+)"); Match match = Regex.Match (url, regex); if (match.Groups.Count == 2 && match.Groups[0].Captures.Count > 0) { Log.DebugFormat ("Creating last.fm station from url {0}", url); string arg = match.Groups[1].Captures[0].Value; StationSource station = new StationSource (lastfm, arg, type.Name, arg); lastfm.AddChildSource (station); station.NotifyUser (); } } return null; } private MemoryTrackListModel track_model; private LastfmSource lastfm; public LastfmSource LastfmSource { get { return lastfm; } } private string station; public string Station { get { return station; } protected set { station = value; } } private StationType type; public StationType Type { get { return type; } set { type = value; if (type.IconName != null) Properties.SetString ("Icon.Name", type.IconName); } } public override string TypeName { get { return Type.Name; } } private string arg; public string Arg { get { return arg; } set { arg = value; } } private int play_count; public int PlayCount { get { return play_count; } set { play_count = value; } } private long dbid; // For StationSources that already exist in the db protected StationSource (LastfmSource lastfm, long dbId, string name, string type, string arg, int playCount) : base (generic_name, name, 150, dbId.ToString ()) { this.lastfm = lastfm; dbid = dbId; Type = StationType.FindByName (type); Arg = arg; PlayCount = playCount; Station = Type.GetStationFor (arg); StationInitialize (); } public StationSource (LastfmSource lastfm, string name, string type, string arg) : base (generic_name, name, 150) { this.lastfm = lastfm; Type = StationType.FindByName (type); Arg = arg; Station = Type.GetStationFor (arg); Save (); StationInitialize (); } private void StationInitialize () { track_model = new MemoryTrackListModel (); ServiceManager.PlayerEngine.ConnectEvent (OnPlayerEvent, PlayerEvent.StateChange); lastfm.Connection.StateChanged += HandleConnectionStateChanged; Properties.SetString ("GtkActionPath", "/LastfmStationSourcePopup"); Properties.SetString ("SourcePropertiesActionLabel", Catalog.GetString ("Edit Last.fm Station")); Properties.SetString ("UnmapSourceActionLabel", Catalog.GetString ("Delete Last.fm Station")); UpdateUI (lastfm.Connection.State); } public void Dispose () { ServiceManager.PlayerEngine.DisconnectEvent (OnPlayerEvent); lastfm.Connection.StateChanged -= HandleConnectionStateChanged; } public virtual void Save () { if (dbid <= 0) Create (); else Update (); OnUpdated (); } private void Create () { HyenaSqliteCommand command = new HyenaSqliteCommand ( @"INSERT INTO LastfmStations (Creator, Name, Type, Arg, PlayCount) VALUES (?, ?, ?, ?, ?)", lastfm.Account.UserName, Name, Type.ToString (), Arg, PlayCount ); dbid = ServiceManager.DbConnection.Execute (command); TypeUniqueId = dbid.ToString (); } private void Update () { HyenaSqliteCommand command = new HyenaSqliteCommand ( @"UPDATE LastfmStations SET Name = ?, Type = ?, Arg = ?, PlayCount = ? WHERE StationID = ?", Name, Type.ToString (), Arg, PlayCount, dbid ); ServiceManager.DbConnection.Execute (command); Station = Type.GetStationFor (Arg); OnUpdated (); } //private bool shuffle; public override void Activate () { base.Activate (); //action_service.GlobalActions ["PreviousAction"].Sensitive = false; // We lazy load the Last.fm connection, so if we're not already connected, do it if (lastfm.Connection.State == ConnectionState.Connected) TuneAndLoad (); else if (lastfm.Connection.State == ConnectionState.Disconnected) lastfm.Connection.Connect (); } private void TuneAndLoad () { ThreadPool.QueueUserWorkItem (delegate { if (ChangeToThisStation ()) { Thread.Sleep (250); // sleep for a bit to try to avoid Last.fm timeouts if (TracksLeft < 2) Refresh (); else HideStatus (); } }); } public override void Deactivate () { //Globals.ActionManager["PreviousAction"].Sensitive = true; } // Last.fm requires you to 'tune' to a station before requesting a track list/playing it public bool ChangeToThisStation () { if (lastfm.Connection.Station == Station) return false; Log.Debug (String.Format ("Tuning Last.fm to {0}", Name), null); SetStatus (Catalog.GetString ("Tuning Last.fm to {0}."), false); StationError error = lastfm.Connection.ChangeStationTo (Station); if (error == StationError.None) { Log.Debug (String.Format ("Successfully tuned Last.fm to {0}", station), null); return true; } else { Log.Debug (String.Format ("Failed to tune Last.fm to {0}", Name), RadioConnection.ErrorMessageFor (error)); SetStatus (String.Format ( // Translators: {0} is an error message sentence from RadioConnection.cs. Catalog.GetString ("Failed to tune in station. {0}"), RadioConnection.ErrorMessageFor (error)), true ); return false; } } public override void SetStatus (string message, bool error) { base.SetStatus (message, error); //LastfmSource.SetStatus (status_message, error, ConnectionState.Connected); } public void SetStatus (string message, bool error, ConnectionState state) { base.SetStatus (message, error); //LastfmSource.SetStatus (status_message, error, state); } /*public override void ShowPropertiesDialog () { Editor ed = new Editor (this); ed.RunDialog (); }*/ /*private bool playback_requested = false; public override void StartPlayback () { if (CurrentTrack != null) { ServiceManager.PlayerEngine.OpenPlay (CurrentTrack); } else if (playback_requested == false) { playback_requested = true; Refresh (); } }*/ private int current_track = 0; public TrackInfo CurrentTrack { get { return GetTrack (current_track); } set { int i = track_model.IndexOf (value); if (i != -1) current_track = i; } } #region IBasicPlaybackController bool IBasicPlaybackController.First () { return ((IBasicPlaybackController)this).Next (false, true); } private bool playback_requested; bool IBasicPlaybackController.Next (bool restart, bool changeImmediately) { TrackInfo next = NextTrack; if (changeImmediately) { if (next != null) { ServiceManager.PlayerEngine.OpenPlay (next); } else { playback_requested = true; } } else { // We want to unconditionally SetNextTrack. // Passing null is OK. ServiceManager.PlayerEngine.SetNextTrack (next); playback_requested = next == null; } return true; } bool IBasicPlaybackController.Previous (bool restart) { return true; } #endregion public TrackInfo NextTrack { get { return GetTrack (current_track + 1); } } private TrackInfo GetTrack (int track_num) { return (track_num > track_model.Count - 1) ? null : track_model[track_num]; } private int TracksLeft { get { int left = track_model.Count - current_track - 1; return (left < 0) ? 0 : left; } } public bool HasDependencies { get { return false; } } private bool refreshing = false; public void Refresh () { lock (this) { if (refreshing || lastfm.Connection.Station != Station) { return; } refreshing = true; } if (TracksLeft == 0) { SetStatus (Catalog.GetString ("Getting new songs for {0}."), false); } ThreadAssist.Spawn (delegate { Media.Playlists.Xspf.Playlist playlist = lastfm.Connection.LoadPlaylistFor (Station); if (playlist != null) { if (playlist.TrackCount == 0) { SetStatus (Catalog.GetString ("No new songs available for {0}."), true); } else { List<TrackInfo> new_tracks = new List<TrackInfo> (); foreach (Media.Playlists.Xspf.Track track in playlist.Tracks) { TrackInfo ti = new LastfmTrackInfo (track, this, track.GetExtendedValue ("trackauth")); new_tracks.Add (ti); lock (track_model) { track_model.Add (ti); } } HideStatus (); ThreadAssist.ProxyToMain (delegate { //OnTrackAdded (null, new_tracks); track_model.Reload (); OnUpdated (); if (playback_requested) { if (this == ServiceManager.PlaybackController.Source ) { ((IBasicPlaybackController)this).Next (false, true); } playback_requested = false; } }); } } else { SetStatus (Catalog.GetString ("Failed to get new songs for {0}."), true); } refreshing = false; }); } private void OnPlayerEvent (PlayerEventArgs args) { if (((PlayerEventStateChangeArgs)args).Current == PlayerState.Loaded && track_model.Contains (ServiceManager.PlayerEngine.CurrentTrack)) { CurrentTrack = ServiceManager.PlayerEngine.CurrentTrack; lock (track_model) { // Remove all but 5 played or skipped tracks if (current_track > 5) { for (int i = 0; i < (current_track - 5); i++) { track_model.Remove (track_model[0]); } current_track = 5; } // Set all previous tracks as CanPlay = false foreach (TrackInfo track in track_model) { if (track == CurrentTrack) break; if (track.CanPlay) { track.CanPlay = false; } } OnUpdated (); } if (TracksLeft <= 2) { Refresh (); } } } private void HandleConnectionStateChanged (object sender, ConnectionStateChangedArgs args) { UpdateUI (args.State); } private void UpdateUI (ConnectionState state) { if (state == ConnectionState.Connected) { HideStatus (); if (this == ServiceManager.SourceManager.ActiveSource) { TuneAndLoad (); } } else { track_model.Clear (); SetStatus (RadioConnection.MessageFor (state), state != ConnectionState.Connecting, state); OnUpdated (); } } public override string GetStatusText () { return String.Format ( Catalog.GetPluralString ("{0} song played", "{0} songs played", PlayCount), PlayCount ); } public override bool CanRename { get { return true; } } #region ITrackModelSource Implementation public TrackListModel TrackModel { get { return track_model; } } public AlbumListModel AlbumModel { get { return null; } } public ArtistListModel ArtistModel { get { return null; } } public void Reload () { track_model.Reload (); } public void RemoveTracks (Selection selection) { } public void DeleteTracks (Selection selection) { throw new Exception ("Should not call DeleteSelectedTracks on StationSource"); } public bool CanAddTracks { get { return false; } } public bool CanRemoveTracks { get { return false; } } public bool CanDeleteTracks { get { return false; } } public bool ConfirmRemoveTracks { get { return false; } } public virtual bool CanRepeat { get { return false; } } public virtual bool CanShuffle { get { return false; } } public bool ShowBrowser { get { return false; } } public bool Indexable { get { return false; } } #endregion #region IUnmapableSource Implementation public bool Unmap () { ServiceManager.DbConnection.Execute (String.Format ( @"DELETE FROM LastfmStations WHERE StationID = '{0}'", dbid )); Parent.RemoveChildSource (this); ServiceManager.SourceManager.RemoveSource (this); return true; } public bool CanUnmap { get { return true; } } public bool ConfirmBeforeUnmap { get { return true; } } #endregion public override void Rename (string newName) { base.Rename (newName); Save (); } public override bool HasProperties { get { return true; } } public static List<StationSource> LoadAll (LastfmSource lastfm, string creator) { List<StationSource> stations = new List<StationSource> (); HyenaSqliteCommand command = new HyenaSqliteCommand ( "SELECT StationID, Name, Type, Arg, PlayCount FROM LastfmStations WHERE Creator = ?", creator ); using (IDataReader reader = ServiceManager.DbConnection.Query (command)) { while (reader.Read ()) { try { stations.Add (new StationSource (lastfm, Convert.ToInt64 (reader[0]), reader[1] as string, reader[2] as string, reader[3] as string, Convert.ToInt32 (reader[4]) )); } catch (Exception e) { Log.Warning ("Error Loading Last.fm Station", e.ToString (), false); } } } // Create some default stations if the user has none if (stations.Count == 0) { stations.Add (new StationSource (lastfm, Catalog.GetString ("Recommended"), "Recommended", creator)); stations.Add (new StationSource (lastfm, Catalog.GetString ("Personal"), "Personal", creator)); stations.Add (new StationSource (lastfm, Catalog.GetString ("Mix"), "Mix", creator)); stations.Add (new StationSource (lastfm, Catalog.GetString ("Banshee Group"), "Group", "Banshee")); stations.Add (new StationSource (lastfm, Catalog.GetString ("Neighbors"), "Neighbor", creator)); stations.Add (new StationSource (lastfm, Catalog.GetString ("Creative Commons"), "Tag", "creative commons")); } return stations; } static StationSource () { if (!ServiceManager.DbConnection.TableExists ("LastfmStations")) { ServiceManager.DbConnection.Execute (@" CREATE TABLE LastfmStations ( StationID INTEGER PRIMARY KEY, Creator STRING NOT NULL, Name STRING NOT NULL, Type STRING NOT NULL, Arg STRING NOT NULL, PlayCount INTEGER NOT NULL ) "); } else { try { ServiceManager.DbConnection.Query<int> ("SELECT PlayCount FROM LastfmStations LIMIT 1"); } catch { Log.Debug ("Adding new database column", "Table: LastfmStations, Column: PlayCount INTEGER"); ServiceManager.DbConnection.Execute ("ALTER TABLE LastfmStations ADD PlayCount INTEGER"); ServiceManager.DbConnection.Execute ("UPDATE LastfmStations SET PlayCount = 0"); } // Last.fm has discontinued the Loved station : http://www.last.fm/stationchanges2010 ServiceManager.DbConnection.Execute ("DELETE FROM LastfmStations WHERE Type = 'Loved'"); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection; using System.Diagnostics; using System.Globalization; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Reflection.Runtime.General; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.CustomAttributes; using System.Reflection.Runtime.BindingFlagSupport; using Internal.Reflection.Core; using Internal.Reflection.Core.Execution; using Internal.Reflection.Tracing; namespace System.Reflection.Runtime.FieldInfos { // // The Runtime's implementation of fields. // [DebuggerDisplay("{_debugName}")] internal abstract partial class RuntimeFieldInfo : FieldInfo, ITraceableTypeMember { // // contextType - the type that supplies the type context (i.e. substitutions for generic parameters.) Though you // get your raw information from "definingType", you report "contextType" as your DeclaringType property. // // For example: // // typeof(Foo<>).GetTypeInfo().DeclaredMembers // // The definingType and contextType are both Foo<> // // typeof(Foo<int,String>).GetTypeInfo().DeclaredMembers // // The definingType is "Foo<,>" // The contextType is "Foo<int,String>" // // We don't report any DeclaredMembers for arrays or generic parameters so those don't apply. // protected RuntimeFieldInfo(RuntimeTypeInfo contextTypeInfo, RuntimeTypeInfo reflectedType) { _contextTypeInfo = contextTypeInfo; _reflectedType = reflectedType; } public sealed override IEnumerable<CustomAttributeData> CustomAttributes { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.FieldInfo_CustomAttributes(this); #endif foreach (CustomAttributeData cad in TrueCustomAttributes) yield return cad; if (DeclaringType.IsExplicitLayout) { int offset = ExplicitLayoutFieldOffsetData; CustomAttributeTypedArgument offsetArgument = new CustomAttributeTypedArgument(typeof(int), offset); yield return new RuntimePseudoCustomAttributeData(typeof(FieldOffsetAttribute), new CustomAttributeTypedArgument[] { offsetArgument }, null); } } } public sealed override Type DeclaringType { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.FieldInfo_DeclaringType(this); #endif return _contextTypeInfo; } } public sealed override Type FieldType { get { return this.FieldRuntimeType; } } public abstract override Type[] GetOptionalCustomModifiers(); public abstract override Type[] GetRequiredCustomModifiers(); public sealed override Object GetValue(Object obj) { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.FieldInfo_GetValue(this, obj); #endif FieldAccessor fieldAccessor = this.FieldAccessor; return fieldAccessor.GetField(obj); } public sealed override object GetValueDirect(TypedReference obj) { if (obj.IsNull) throw new ArgumentException(SR.Arg_TypedReference_Null); FieldAccessor fieldAccessor = this.FieldAccessor; return fieldAccessor.GetFieldDirect(obj); } public abstract override bool HasSameMetadataDefinitionAs(MemberInfo other); public sealed override Module Module { get { return DefiningType.Module; } } public sealed override Type ReflectedType { get { return _reflectedType; } } public sealed override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.FieldInfo_SetValue(this, obj, value); #endif FieldAccessor fieldAccessor = this.FieldAccessor; BinderBundle binderBundle = binder.ToBinderBundle(invokeAttr, culture); fieldAccessor.SetField(obj, value, binderBundle); } public sealed override void SetValueDirect(TypedReference obj, object value) { if (obj.IsNull) throw new ArgumentException(SR.Arg_TypedReference_Null); FieldAccessor fieldAccessor = this.FieldAccessor; fieldAccessor.SetFieldDirect(obj, value); } Type ITraceableTypeMember.ContainingType { get { return _contextTypeInfo; } } /// <summary> /// Override to provide the metadata based name of a field. (Different from the Name /// property in that it does not go into the reflection trace logic.) /// </summary> protected abstract string MetadataName { get; } public sealed override String Name { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.FieldInfo_Name(this); #endif return MetadataName; } } String ITraceableTypeMember.MemberName { get { return MetadataName; } } public sealed override object GetRawConstantValue() { if (!IsLiteral) throw new InvalidOperationException(); object defaultValue; if (!GetDefaultValueIfAvailable(raw: true, defaultValue: out defaultValue)) throw new BadImageFormatException(); // Field marked literal but has no default value. return defaultValue; } // Types that derive from RuntimeFieldInfo must implement the following public surface area members public abstract override FieldAttributes Attributes { get; } public abstract override int MetadataToken { get; } public abstract override String ToString(); public abstract override bool Equals(Object obj); public abstract override int GetHashCode(); public abstract override RuntimeFieldHandle FieldHandle { get; } /// <summary> /// Get the default value if exists for a field by parsing metadata. Return false if there is no default value. /// </summary> protected abstract bool GetDefaultValueIfAvailable(bool raw, out object defaultValue); /// <summary> /// Return a FieldAccessor object for accessing the value of a non-literal field. May rely on metadata to create correct accessor. /// </summary> protected abstract FieldAccessor TryGetFieldAccessor(); private FieldAccessor FieldAccessor { get { FieldAccessor fieldAccessor = _lazyFieldAccessor; if (fieldAccessor == null) { if (this.IsLiteral) { // Legacy: ECMA335 does not require that the metadata literal match the type of the field that declares it. // For desktop compat, we return the metadata literal as is and do not attempt to convert or validate against the Field type. Object defaultValue; if (!GetDefaultValueIfAvailable(raw: false, defaultValue: out defaultValue)) { throw new BadImageFormatException(); // Field marked literal but has no default value. } _lazyFieldAccessor = fieldAccessor = ReflectionCoreExecution.ExecutionEnvironment.CreateLiteralFieldAccessor(defaultValue, FieldType.TypeHandle); } else { _lazyFieldAccessor = fieldAccessor = TryGetFieldAccessor(); if (fieldAccessor == null) throw ReflectionCoreExecution.ExecutionDomain.CreateNonInvokabilityException(this); } } return fieldAccessor; } } /// <summary> /// Return the type of the field by parsing metadata. /// </summary> protected abstract RuntimeTypeInfo FieldRuntimeType { get; } protected RuntimeFieldInfo WithDebugName() { bool populateDebugNames = DeveloperExperienceState.DeveloperExperienceModeEnabled; #if DEBUG populateDebugNames = true; #endif if (!populateDebugNames) return this; if (_debugName == null) { _debugName = "Constructing..."; // Protect against any inadvertent reentrancy. _debugName = ((ITraceableTypeMember)this).MemberName; } return this; } /// <summary> /// Return the DefiningTypeInfo as a RuntimeTypeInfo (instead of as a format specific type info) /// </summary> protected abstract RuntimeTypeInfo DefiningType { get; } protected abstract IEnumerable<CustomAttributeData> TrueCustomAttributes { get; } protected abstract int ExplicitLayoutFieldOffsetData { get; } /// <summary> /// Returns the field offset (asserts and throws if not an instance field). Does not include the size of the object header. /// </summary> internal int Offset => FieldAccessor.Offset; protected readonly RuntimeTypeInfo _contextTypeInfo; protected readonly RuntimeTypeInfo _reflectedType; private volatile FieldAccessor _lazyFieldAccessor = null; private String _debugName; } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Nwc.XmlRpc; using OpenMetaverse.StructuredData; using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.IO.Compression; using System.Net; using System.Reflection; using System.Text; using System.Web; using System.Xml; using System.Xml.Linq; using System.Xml.Serialization; using XMLResponseHelper = OpenSim.Framework.SynchronousRestObjectRequester.XMLResponseHelper; using OpenSim.Framework.ServiceAuth; namespace OpenSim.Framework { /// <summary> /// Miscellaneous static methods and extension methods related to the web /// </summary> public static class WebUtil { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Control the printing of certain debug messages. /// </summary> /// <remarks> /// If DebugLevel >= 3 then short notices about outgoing HTTP requests are logged. /// </remarks> public static int DebugLevel { get; set; } /// <summary> /// Request number for diagnostic purposes. /// </summary> public static int RequestNumber { get; internal set; } /// <summary> /// Control where OSD requests should be serialized per endpoint. /// </summary> public static bool SerializeOSDRequestsPerEndpoint { get; set; } /// <summary> /// this is the header field used to communicate the local request id /// used for performance and debugging /// </summary> public const string OSHeaderRequestID = "opensim-request-id"; /// <summary> /// Number of milliseconds a call can take before it is considered /// a "long" call for warning & debugging purposes /// </summary> public const int LongCallTime = 3000; /// <summary> /// The maximum length of any data logged because of a long request time. /// </summary> /// <remarks> /// This is to truncate any really large post data, such as an asset. In theory, the first section should /// give us useful information about the call (which agent it relates to if applicable, etc.). /// This is also used to truncate messages when using DebugLevel 5. /// </remarks> public const int MaxRequestDiagLength = 200; /// <summary> /// Dictionary of end points /// </summary> private static Dictionary<string,object> m_endpointSerializer = new Dictionary<string,object>(); private static object EndPointLock(string url) { System.Uri uri = new System.Uri(url); string endpoint = string.Format("{0}:{1}",uri.Host,uri.Port); lock (m_endpointSerializer) { object eplock = null; if (! m_endpointSerializer.TryGetValue(endpoint,out eplock)) { eplock = new object(); m_endpointSerializer.Add(endpoint,eplock); // m_log.WarnFormat("[WEB UTIL] add a new host to end point serializer {0}",endpoint); } return eplock; } } #region JSONRequest /// <summary> /// PUT JSON-encoded data to a web service that returns LLSD or /// JSON data /// </summary> public static OSDMap PutToServiceCompressed(string url, OSDMap data, int timeout) { return ServiceOSDRequest(url,data, "PUT", timeout, true, false); } public static OSDMap PutToService(string url, OSDMap data, int timeout) { return ServiceOSDRequest(url,data, "PUT", timeout, false, false); } public static OSDMap PostToService(string url, OSDMap data, int timeout, bool rpc) { return ServiceOSDRequest(url, data, "POST", timeout, false, rpc); } public static OSDMap PostToServiceCompressed(string url, OSDMap data, int timeout) { return ServiceOSDRequest(url, data, "POST", timeout, true, false); } public static OSDMap GetFromService(string url, int timeout) { return ServiceOSDRequest(url, null, "GET", timeout, false, false); } public static OSDMap ServiceOSDRequest(string url, OSDMap data, string method, int timeout, bool compressed, bool rpc) { if (SerializeOSDRequestsPerEndpoint) { lock (EndPointLock(url)) { return ServiceOSDRequestWorker(url, data, method, timeout, compressed, rpc); } } else { return ServiceOSDRequestWorker(url, data, method, timeout, compressed, rpc); } } public static void LogOutgoingDetail(Stream outputStream) { LogOutgoingDetail("", outputStream); } public static void LogOutgoingDetail(string context, Stream outputStream) { using (StreamReader reader = new StreamReader(Util.Copy(outputStream), Encoding.UTF8)) { string output; if (DebugLevel == 5) { char[] chars = new char[WebUtil.MaxRequestDiagLength + 1]; // +1 so we know to add "..." only if needed int len = reader.Read(chars, 0, WebUtil.MaxRequestDiagLength + 1); output = new string(chars, 0, len); } else { output = reader.ReadToEnd(); } LogOutgoingDetail(context, output); } } public static void LogOutgoingDetail(string type, int reqnum, string output) { LogOutgoingDetail(string.Format("{0} {1}: ", type, reqnum), output); } public static void LogOutgoingDetail(string context, string output) { if (DebugLevel == 5) { if (output.Length > MaxRequestDiagLength) output = output.Substring(0, MaxRequestDiagLength) + "..."; } m_log.DebugFormat("[LOGHTTP]: {0}{1}", context, Util.BinaryToASCII(output)); } public static void LogResponseDetail(int reqnum, Stream inputStream) { LogOutgoingDetail(string.Format("RESPONSE {0}: ", reqnum), inputStream); } public static void LogResponseDetail(int reqnum, string input) { LogOutgoingDetail(string.Format("RESPONSE {0}: ", reqnum), input); } private static OSDMap ServiceOSDRequestWorker(string url, OSDMap data, string method, int timeout, bool compressed, bool rpc) { int reqnum = RequestNumber++; if (DebugLevel >= 3) m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} JSON-RPC {1} to {2}", reqnum, method, url); string errorMessage = "unknown error"; ServicePointManagerTimeoutSupport.ResetHosts(); int tickstart = Environment.TickCount; int tickdata = 0; string strBuffer = null; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = method; request.Timeout = timeout; request.KeepAlive = false; request.MaximumAutomaticRedirections = 10; request.ReadWriteTimeout = timeout / 4; request.Headers[OSHeaderRequestID] = reqnum.ToString(); // If there is some input, write it into the request if (data != null) { strBuffer = OSDParser.SerializeJsonString(data); if (DebugLevel >= 5) LogOutgoingDetail("SEND", reqnum, strBuffer); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(strBuffer); request.ContentType = rpc ? "application/json-rpc" : "application/json"; if (compressed) { request.Headers["X-Content-Encoding"] = "gzip"; // can't set "Content-Encoding" because old OpenSims fail if they get an unrecognized Content-Encoding using (MemoryStream ms = new MemoryStream()) { using (GZipStream comp = new GZipStream(ms, CompressionMode.Compress)) { comp.Write(buffer, 0, buffer.Length); // We need to close the gzip stream before we write it anywhere // because apparently something important related to gzip compression // gets written on the strteam upon Dispose() } byte[] buf = ms.ToArray(); request.ContentLength = buf.Length; //Count bytes to send using (Stream requestStream = request.GetRequestStream()) requestStream.Write(buf, 0, (int)buf.Length); } } else { request.ContentLength = buffer.Length; //Count bytes to send using (Stream requestStream = request.GetRequestStream()) requestStream.Write(buffer, 0, buffer.Length); //Send it } } // capture how much time was spent writing, this may seem silly // but with the number concurrent requests, this often blocks tickdata = Environment.TickCount - tickstart; using (WebResponse response = request.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream)) { string responseStr = reader.ReadToEnd(); if (WebUtil.DebugLevel >= 5) WebUtil.LogResponseDetail(reqnum, responseStr); return CanonicalizeResults(responseStr); } } } } catch (WebException we) { errorMessage = we.Message; if (we.Status == WebExceptionStatus.ProtocolError) { using (HttpWebResponse webResponse = (HttpWebResponse)we.Response) errorMessage = String.Format("[{0}] {1}", webResponse.StatusCode, webResponse.StatusDescription); } } catch (Exception ex) { errorMessage = ex.Message; } finally { int tickdiff = Environment.TickCount - tickstart; if (tickdiff > LongCallTime) { m_log.InfoFormat( "[LOGHTTP]: Slow JSON-RPC request {0} {1} to {2} took {3}ms, {4}ms writing, {5}", reqnum, method, url, tickdiff, tickdata, strBuffer != null ? (strBuffer.Length > MaxRequestDiagLength ? strBuffer.Remove(MaxRequestDiagLength) : strBuffer) : ""); } else if (DebugLevel >= 4) { m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms, {2}ms writing", reqnum, tickdiff, tickdata); } } m_log.DebugFormat( "[LOGHTTP]: JSON-RPC request {0} {1} to {2} FAILED: {3}", reqnum, method, url, errorMessage); return ErrorResponseMap(errorMessage); } /// <summary> /// Since there are no consistencies in the way web requests are /// formed, we need to do a little guessing about the result format. /// Keys: /// Success|success == the success fail of the request /// _RawResult == the raw string that came back /// _Result == the OSD unpacked string /// </summary> private static OSDMap CanonicalizeResults(string response) { OSDMap result = new OSDMap(); // Default values result["Success"] = OSD.FromBoolean(true); result["success"] = OSD.FromBoolean(true); result["_RawResult"] = OSD.FromString(response); result["_Result"] = new OSDMap(); if (response.Equals("true",System.StringComparison.OrdinalIgnoreCase)) return result; if (response.Equals("false",System.StringComparison.OrdinalIgnoreCase)) { result["Success"] = OSD.FromBoolean(false); result["success"] = OSD.FromBoolean(false); return result; } try { OSD responseOSD = OSDParser.Deserialize(response); if (responseOSD.Type == OSDType.Map) { result["_Result"] = (OSDMap)responseOSD; return result; } } catch { // don't need to treat this as an error... we're just guessing anyway // m_log.DebugFormat("[WEB UTIL] couldn't decode <{0}>: {1}",response,e.Message); } return result; } #endregion JSONRequest #region FormRequest /// <summary> /// POST URL-encoded form data to a web service that returns LLSD or /// JSON data /// </summary> public static OSDMap PostToService(string url, NameValueCollection data) { return ServiceFormRequest(url,data,10000); } public static OSDMap ServiceFormRequest(string url, NameValueCollection data, int timeout) { //lock (EndPointLock(url)) { return ServiceFormRequestWorker(url,data,timeout); } } private static OSDMap ServiceFormRequestWorker(string url, NameValueCollection data, int timeout) { int reqnum = RequestNumber++; string method = (data != null && data["RequestMethod"] != null) ? data["RequestMethod"] : "unknown"; if (DebugLevel >= 3) m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} ServiceForm '{1}' to {2}", reqnum, method, url); string errorMessage = "unknown error"; ServicePointManagerTimeoutSupport.ResetHosts(); int tickstart = Environment.TickCount; int tickdata = 0; string queryString = null; try { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = "POST"; request.Timeout = timeout; request.KeepAlive = false; request.MaximumAutomaticRedirections = 10; request.ReadWriteTimeout = timeout / 4; request.Headers[OSHeaderRequestID] = reqnum.ToString(); if (data != null) { queryString = BuildQueryString(data); if (DebugLevel >= 5) LogOutgoingDetail("SEND", reqnum, queryString); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(queryString); request.ContentLength = buffer.Length; request.ContentType = "application/x-www-form-urlencoded"; using (Stream requestStream = request.GetRequestStream()) requestStream.Write(buffer, 0, buffer.Length); } // capture how much time was spent writing, this may seem silly // but with the number concurrent requests, this often blocks tickdata = Environment.TickCount - tickstart; using (WebResponse response = request.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream)) { string responseStr = reader.ReadToEnd(); if (WebUtil.DebugLevel >= 5) WebUtil.LogResponseDetail(reqnum, responseStr); OSD responseOSD = OSDParser.Deserialize(responseStr); if (responseOSD.Type == OSDType.Map) return (OSDMap)responseOSD; } } } } catch (WebException we) { errorMessage = we.Message; if (we.Status == WebExceptionStatus.ProtocolError) { using (HttpWebResponse webResponse = (HttpWebResponse)we.Response) errorMessage = String.Format("[{0}] {1}",webResponse.StatusCode,webResponse.StatusDescription); } } catch (Exception ex) { errorMessage = ex.Message; } finally { int tickdiff = Environment.TickCount - tickstart; if (tickdiff > LongCallTime) { m_log.InfoFormat( "[LOGHTTP]: Slow ServiceForm request {0} '{1}' to {2} took {3}ms, {4}ms writing, {5}", reqnum, method, url, tickdiff, tickdata, queryString != null ? (queryString.Length > MaxRequestDiagLength) ? queryString.Remove(MaxRequestDiagLength) : queryString : ""); } else if (DebugLevel >= 4) { m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms, {2}ms writing", reqnum, tickdiff, tickdata); } } m_log.WarnFormat("[LOGHTTP]: ServiceForm request {0} '{1}' to {2} failed: {3}", reqnum, method, url, errorMessage); return ErrorResponseMap(errorMessage); } /// <summary> /// Create a response map for an error, trying to keep /// the result formats consistent /// </summary> private static OSDMap ErrorResponseMap(string msg) { OSDMap result = new OSDMap(); result["Success"] = "False"; result["Message"] = OSD.FromString("Service request failed: " + msg); return result; } #endregion FormRequest #region Uri /// <summary> /// Combines a Uri that can contain both a base Uri and relative path /// with a second relative path fragment /// </summary> /// <param name="uri">Starting (base) Uri</param> /// <param name="fragment">Relative path fragment to append to the end /// of the Uri</param> /// <returns>The combined Uri</returns> /// <remarks>This is similar to the Uri constructor that takes a base /// Uri and the relative path, except this method can append a relative /// path fragment on to an existing relative path</remarks> public static Uri Combine(this Uri uri, string fragment) { string fragment1 = uri.Fragment; string fragment2 = fragment; if (!fragment1.EndsWith("/")) fragment1 = fragment1 + '/'; if (fragment2.StartsWith("/")) fragment2 = fragment2.Substring(1); return new Uri(uri, fragment1 + fragment2); } /// <summary> /// Combines a Uri that can contain both a base Uri and relative path /// with a second relative path fragment. If the fragment is absolute, /// it will be returned without modification /// </summary> /// <param name="uri">Starting (base) Uri</param> /// <param name="fragment">Relative path fragment to append to the end /// of the Uri, or an absolute Uri to return unmodified</param> /// <returns>The combined Uri</returns> public static Uri Combine(this Uri uri, Uri fragment) { if (fragment.IsAbsoluteUri) return fragment; string fragment1 = uri.Fragment; string fragment2 = fragment.ToString(); if (!fragment1.EndsWith("/")) fragment1 = fragment1 + '/'; if (fragment2.StartsWith("/")) fragment2 = fragment2.Substring(1); return new Uri(uri, fragment1 + fragment2); } /// <summary> /// Appends a query string to a Uri that may or may not have existing /// query parameters /// </summary> /// <param name="uri">Uri to append the query to</param> /// <param name="query">Query string to append. Can either start with ? /// or just containg key/value pairs</param> /// <returns>String representation of the Uri with the query string /// appended</returns> public static string AppendQuery(this Uri uri, string query) { if (String.IsNullOrEmpty(query)) return uri.ToString(); if (query[0] == '?' || query[0] == '&') query = query.Substring(1); string uriStr = uri.ToString(); if (uriStr.Contains("?")) return uriStr + '&' + query; else return uriStr + '?' + query; } #endregion Uri #region NameValueCollection /// <summary> /// Convert a NameValueCollection into a query string. This is the /// inverse of HttpUtility.ParseQueryString() /// </summary> /// <param name="parameters">Collection of key/value pairs to convert</param> /// <returns>A query string with URL-escaped values</returns> public static string BuildQueryString(NameValueCollection parameters) { List<string> items = new List<string>(parameters.Count); foreach (string key in parameters.Keys) { string[] values = parameters.GetValues(key); if (values != null) { foreach (string value in values) items.Add(String.Concat(key, "=", HttpUtility.UrlEncode(value ?? String.Empty))); } } return String.Join("&", items.ToArray()); } /// <summary> /// /// </summary> /// <param name="collection"></param> /// <param name="key"></param> /// <returns></returns> public static string GetOne(this NameValueCollection collection, string key) { string[] values = collection.GetValues(key); if (values != null && values.Length > 0) return values[0]; return null; } #endregion NameValueCollection #region Stream /// <summary> /// Copies the contents of one stream to another, starting at the /// current position of each stream /// </summary> /// <param name="copyFrom">The stream to copy from, at the position /// where copying should begin</param> /// <param name="copyTo">The stream to copy to, at the position where /// bytes should be written</param> /// <param name="maximumBytesToCopy">The maximum bytes to copy</param> /// <returns>The total number of bytes copied</returns> /// <remarks> /// Copying begins at the streams' current positions. The positions are /// NOT reset after copying is complete. /// NOTE!! .NET 4.0 adds the method 'Stream.CopyTo(stream, bufferSize)'. /// This function could be replaced with that method once we move /// totally to .NET 4.0. For versions before, this routine exists. /// This routine used to be named 'CopyTo' but the int parameter has /// a different meaning so this method was renamed to avoid any confusion. /// </remarks> public static int CopyStream(this Stream copyFrom, Stream copyTo, int maximumBytesToCopy) { byte[] buffer = new byte[4096]; int readBytes; int totalCopiedBytes = 0; while ((readBytes = copyFrom.Read(buffer, 0, Math.Min(4096, maximumBytesToCopy))) > 0) { int writeBytes = Math.Min(maximumBytesToCopy, readBytes); copyTo.Write(buffer, 0, writeBytes); totalCopiedBytes += writeBytes; maximumBytesToCopy -= writeBytes; } return totalCopiedBytes; } #endregion Stream public class QBasedComparer : IComparer { public int Compare(Object x, Object y) { float qx = GetQ(x); float qy = GetQ(y); return qy.CompareTo(qx); // descending order } private float GetQ(Object o) { // Example: image/png;q=0.9 float qvalue = 1F; if (o is String) { string mime = (string)o; string[] parts = mime.Split(';'); if (parts.Length > 1) { string[] kvp = parts[1].Split('='); if (kvp.Length == 2 && kvp[0] == "q") float.TryParse(kvp[1], NumberStyles.Number, CultureInfo.InvariantCulture, out qvalue); } } return qvalue; } } /// <summary> /// Takes the value of an Accept header and returns the preferred types /// ordered by q value (if it exists). /// Example input: image/jpg;q=0.7, image/png;q=0.8, image/jp2 /// Exmaple output: ["jp2", "png", "jpg"] /// NOTE: This doesn't handle the semantics of *'s... /// </summary> /// <param name="accept"></param> /// <returns></returns> public static string[] GetPreferredImageTypes(string accept) { if (string.IsNullOrEmpty(accept)) return new string[0]; string[] types = accept.Split(new char[] { ',' }); if (types.Length > 0) { List<string> list = new List<string>(types); list.RemoveAll(delegate(string s) { return !s.ToLower().StartsWith("image"); }); ArrayList tlist = new ArrayList(list); tlist.Sort(new QBasedComparer()); string[] result = new string[tlist.Count]; for (int i = 0; i < tlist.Count; i++) { string mime = (string)tlist[i]; string[] parts = mime.Split(new char[] { ';' }); string[] pair = parts[0].Split(new char[] { '/' }); if (pair.Length == 2) result[i] = pair[1].ToLower(); else // oops, we don't know what this is... result[i] = pair[0]; } return result; } return new string[0]; } } public static class AsynchronousRestObjectRequester { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Perform an asynchronous REST request. /// </summary> /// <param name="verb">GET or POST</param> /// <param name="requestUrl"></param> /// <param name="obj"></param> /// <param name="action"></param> /// <returns></returns> /// /// <exception cref="System.Net.WebException">Thrown if we encounter a /// network issue while posting the request. You'll want to make /// sure you deal with this as they're not uncommon</exception> // public static void MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, Action<TResponse> action) { MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, action, 0); } public static void MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, Action<TResponse> action, int maxConnections) { MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, action, maxConnections, null); } public static void MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, Action<TResponse> action, int maxConnections, IServiceAuth auth) { int reqnum = WebUtil.RequestNumber++; if (WebUtil.DebugLevel >= 3) m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} AsynchronousRequestObject {1} to {2}", reqnum, verb, requestUrl); ServicePointManagerTimeoutSupport.ResetHosts(); int tickstart = Environment.TickCount; int tickdata = 0; Type type = typeof(TRequest); WebRequest request = WebRequest.Create(requestUrl); HttpWebRequest ht = (HttpWebRequest)request; if (auth != null) auth.AddAuthorization(ht.Headers); if (maxConnections > 0 && ht.ServicePoint.ConnectionLimit < maxConnections) ht.ServicePoint.ConnectionLimit = maxConnections; TResponse deserial = default(TResponse); request.Method = verb; MemoryStream buffer = null; try { if (verb == "POST") { request.ContentType = "text/xml"; buffer = new MemoryStream(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.UTF8; using (XmlWriter writer = XmlWriter.Create(buffer, settings)) { XmlSerializer serializer = new XmlSerializer(type); serializer.Serialize(writer, obj); writer.Flush(); } int length = (int)buffer.Length; request.ContentLength = length; byte[] data = buffer.ToArray(); if (WebUtil.DebugLevel >= 5) WebUtil.LogOutgoingDetail("SEND", reqnum, System.Text.Encoding.UTF8.GetString(data)); request.BeginGetRequestStream(delegate(IAsyncResult res) { using (Stream requestStream = request.EndGetRequestStream(res)) requestStream.Write(data, 0, length); // capture how much time was spent writing tickdata = Environment.TickCount - tickstart; request.BeginGetResponse(delegate(IAsyncResult ar) { using (WebResponse response = request.EndGetResponse(ar)) { try { using (Stream respStream = response.GetResponseStream()) { deserial = XMLResponseHelper.LogAndDeserialize<TRequest, TResponse>( reqnum, respStream, response.ContentLength); } } catch (System.InvalidOperationException) { } } action(deserial); }, null); }, null); } else { request.BeginGetResponse(delegate(IAsyncResult res2) { try { // If the server returns a 404, this appears to trigger a System.Net.WebException even though that isn't // documented in MSDN using (WebResponse response = request.EndGetResponse(res2)) { try { using (Stream respStream = response.GetResponseStream()) { deserial = XMLResponseHelper.LogAndDeserialize<TRequest, TResponse>( reqnum, respStream, response.ContentLength); } } catch (System.InvalidOperationException) { } } } catch (WebException e) { if (e.Status == WebExceptionStatus.ProtocolError) { if (e.Response is HttpWebResponse) { using (HttpWebResponse httpResponse = (HttpWebResponse)e.Response) { if (httpResponse.StatusCode != HttpStatusCode.NotFound) { // We don't appear to be handling any other status codes, so log these feailures to that // people don't spend unnecessary hours hunting phantom bugs. m_log.DebugFormat( "[ASYNC REQUEST]: Request {0} {1} failed with unexpected status code {2}", verb, requestUrl, httpResponse.StatusCode); } } } } else { m_log.ErrorFormat( "[ASYNC REQUEST]: Request {0} {1} failed with status {2} and message {3}", verb, requestUrl, e.Status, e.Message); } } catch (Exception e) { m_log.ErrorFormat( "[ASYNC REQUEST]: Request {0} {1} failed with exception {2}{3}", verb, requestUrl, e.Message, e.StackTrace); } // m_log.DebugFormat("[ASYNC REQUEST]: Received {0}", deserial.ToString()); try { action(deserial); } catch (Exception e) { m_log.ErrorFormat( "[ASYNC REQUEST]: Request {0} {1} callback failed with exception {2}{3}", verb, requestUrl, e.Message, e.StackTrace); } }, null); } int tickdiff = Environment.TickCount - tickstart; if (tickdiff > WebUtil.LongCallTime) { string originalRequest = null; if (buffer != null) { originalRequest = Encoding.UTF8.GetString(buffer.ToArray()); if (originalRequest.Length > WebUtil.MaxRequestDiagLength) originalRequest = originalRequest.Remove(WebUtil.MaxRequestDiagLength); } m_log.InfoFormat( "[LOGHTTP]: Slow AsynchronousRequestObject request {0} {1} to {2} took {3}ms, {4}ms writing, {5}", reqnum, verb, requestUrl, tickdiff, tickdata, originalRequest); } else if (WebUtil.DebugLevel >= 4) { m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms, {2}ms writing", reqnum, tickdiff, tickdata); } } finally { if (buffer != null) buffer.Dispose(); } } } public static class SynchronousRestFormsRequester { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Perform a synchronous REST request. /// </summary> /// <param name="verb"></param> /// <param name="requestUrl"></param> /// <param name="obj"> </param> /// <param name="timeoutsecs"> </param> /// <returns></returns> /// /// <exception cref="System.Net.WebException">Thrown if we encounter a network issue while posting /// the request. You'll want to make sure you deal with this as they're not uncommon</exception> public static string MakeRequest(string verb, string requestUrl, string obj, int timeoutsecs, IServiceAuth auth) { int reqnum = WebUtil.RequestNumber++; if (WebUtil.DebugLevel >= 3) m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} SynchronousRestForms {1} to {2}", reqnum, verb, requestUrl); ServicePointManagerTimeoutSupport.ResetHosts(); int tickstart = Environment.TickCount; int tickdata = 0; WebRequest request = WebRequest.Create(requestUrl); request.Method = verb; if (timeoutsecs > 0) request.Timeout = timeoutsecs * 1000; if (auth != null) auth.AddAuthorization(request.Headers); string respstring = String.Empty; using (MemoryStream buffer = new MemoryStream()) { if ((verb == "POST") || (verb == "PUT")) { request.ContentType = "application/x-www-form-urlencoded"; int length = 0; using (StreamWriter writer = new StreamWriter(buffer)) { writer.Write(obj); writer.Flush(); } length = (int)obj.Length; request.ContentLength = length; byte[] data = buffer.ToArray(); if (WebUtil.DebugLevel >= 5) WebUtil.LogOutgoingDetail("SEND", reqnum, System.Text.Encoding.UTF8.GetString(data)); Stream requestStream = null; try { requestStream = request.GetRequestStream(); requestStream.Write(data, 0, length); } catch (Exception e) { m_log.InfoFormat("[FORMS]: Error sending request to {0}: {1}. Request: {2}", requestUrl, e.Message, obj.Length > WebUtil.MaxRequestDiagLength ? obj.Remove(WebUtil.MaxRequestDiagLength) : obj); throw e; } finally { if (requestStream != null) requestStream.Dispose(); // capture how much time was spent writing tickdata = Environment.TickCount - tickstart; } } try { using (WebResponse resp = request.GetResponse()) { if (resp.ContentLength != 0) { using (Stream respStream = resp.GetResponseStream()) using (StreamReader reader = new StreamReader(respStream)) respstring = reader.ReadToEnd(); } } } catch (Exception e) { m_log.InfoFormat("[FORMS]: Error receiving response from {0}: {1}. Request: {2}", requestUrl, e.Message, obj.Length > WebUtil.MaxRequestDiagLength ? obj.Remove(WebUtil.MaxRequestDiagLength) : obj); throw e; } } int tickdiff = Environment.TickCount - tickstart; if (tickdiff > WebUtil.LongCallTime) { m_log.InfoFormat( "[LOGHTTP]: Slow SynchronousRestForms request {0} {1} to {2} took {3}ms, {4}ms writing, {5}", reqnum, verb, requestUrl, tickdiff, tickdata, obj.Length > WebUtil.MaxRequestDiagLength ? obj.Remove(WebUtil.MaxRequestDiagLength) : obj); } else if (WebUtil.DebugLevel >= 4) { m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms, {2}ms writing", reqnum, tickdiff, tickdata); } if (WebUtil.DebugLevel >= 5) WebUtil.LogResponseDetail(reqnum, respstring); return respstring; } public static string MakeRequest(string verb, string requestUrl, string obj, int timeoutsecs) { return MakeRequest(verb, requestUrl, obj, timeoutsecs, null); } public static string MakeRequest(string verb, string requestUrl, string obj) { return MakeRequest(verb, requestUrl, obj, -1); } public static string MakeRequest(string verb, string requestUrl, string obj, IServiceAuth auth) { return MakeRequest(verb, requestUrl, obj, -1, auth); } } public class SynchronousRestObjectRequester { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Perform a synchronous REST request. /// </summary> /// <param name="verb"></param> /// <param name="requestUrl"></param> /// <param name="obj"></param> /// <returns> /// The response. If there was an internal exception, then the default(TResponse) is returned. /// </returns> public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj) { return MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, 0); } public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, IServiceAuth auth) { return MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, 0, auth); } /// <summary> /// Perform a synchronous REST request. /// </summary> /// <param name="verb"></param> /// <param name="requestUrl"></param> /// <param name="obj"></param> /// <param name="pTimeout"> /// Request timeout in milliseconds. Timeout.Infinite indicates no timeout. If 0 is passed then the default HttpWebRequest timeout is used (100 seconds) /// </param> /// <returns> /// The response. If there was an internal exception or the request timed out, /// then the default(TResponse) is returned. /// </returns> public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, int pTimeout) { return MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, pTimeout, 0); } public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, int pTimeout, IServiceAuth auth) { return MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, pTimeout, 0, auth); } /// Perform a synchronous REST request. /// </summary> /// <param name="verb"></param> /// <param name="requestUrl"></param> /// <param name="obj"></param> /// <param name="pTimeout"> /// Request timeout in milliseconds. Timeout.Infinite indicates no timeout. If 0 is passed then the default HttpWebRequest timeout is used (100 seconds) /// </param> /// <param name="maxConnections"></param> /// <returns> /// The response. If there was an internal exception or the request timed out, /// then the default(TResponse) is returned. /// </returns> public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, int pTimeout, int maxConnections) { return MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, pTimeout, maxConnections, null); } /// <summary> /// Perform a synchronous REST request. /// </summary> /// <param name="verb"></param> /// <param name="requestUrl"></param> /// <param name="obj"></param> /// <param name="pTimeout"> /// Request timeout in milliseconds. Timeout.Infinite indicates no timeout. If 0 is passed then the default HttpWebRequest timeout is used (100 seconds) /// </param> /// <param name="maxConnections"></param> /// <returns> /// The response. If there was an internal exception or the request timed out, /// then the default(TResponse) is returned. /// </returns> public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, int pTimeout, int maxConnections, IServiceAuth auth) { int reqnum = WebUtil.RequestNumber++; if (WebUtil.DebugLevel >= 3) m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} SynchronousRestObject {1} to {2}", reqnum, verb, requestUrl); ServicePointManagerTimeoutSupport.ResetHosts(); int tickstart = Environment.TickCount; int tickdata = 0; Type type = typeof(TRequest); TResponse deserial = default(TResponse); WebRequest request = WebRequest.Create(requestUrl); HttpWebRequest ht = (HttpWebRequest)request; if (auth != null) auth.AddAuthorization(ht.Headers); if (pTimeout != 0) ht.Timeout = pTimeout; if (maxConnections > 0 && ht.ServicePoint.ConnectionLimit < maxConnections) ht.ServicePoint.ConnectionLimit = maxConnections; request.Method = verb; MemoryStream buffer = null; try { if ((verb == "POST") || (verb == "PUT")) { request.ContentType = "text/xml"; buffer = new MemoryStream(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.UTF8; using (XmlWriter writer = XmlWriter.Create(buffer, settings)) { XmlSerializer serializer = new XmlSerializer(type); serializer.Serialize(writer, obj); writer.Flush(); } int length = (int)buffer.Length; request.ContentLength = length; byte[] data = buffer.ToArray(); if (WebUtil.DebugLevel >= 5) WebUtil.LogOutgoingDetail("SEND", reqnum, System.Text.Encoding.UTF8.GetString(data)); try { using (Stream requestStream = request.GetRequestStream()) requestStream.Write(data, 0, length); } catch (Exception e) { m_log.DebugFormat( "[SynchronousRestObjectRequester]: Exception in making request {0} {1}: {2}{3}", verb, requestUrl, e.Message, e.StackTrace); return deserial; } finally { // capture how much time was spent writing tickdata = Environment.TickCount - tickstart; } } try { using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse()) { if (resp.ContentLength != 0) { using (Stream respStream = resp.GetResponseStream()) { deserial = XMLResponseHelper.LogAndDeserialize<TRequest, TResponse>( reqnum, respStream, resp.ContentLength); } } else { m_log.DebugFormat( "[SynchronousRestObjectRequester]: Oops! no content found in response stream from {0} {1}", verb, requestUrl); } } } catch (WebException e) { using (HttpWebResponse hwr = (HttpWebResponse)e.Response) { if (hwr != null) { if (hwr.StatusCode == HttpStatusCode.NotFound) return deserial; if (hwr.StatusCode == HttpStatusCode.Unauthorized) { m_log.Error(string.Format( "[SynchronousRestObjectRequester]: Web request {0} requires authentication ", requestUrl)); return deserial; } } else m_log.Error(string.Format( "[SynchronousRestObjectRequester]: WebException for {0} {1} {2} ", verb, requestUrl, typeof(TResponse).ToString()), e); } } catch (System.InvalidOperationException) { // This is what happens when there is invalid XML m_log.DebugFormat( "[SynchronousRestObjectRequester]: Invalid XML from {0} {1} {2}", verb, requestUrl, typeof(TResponse).ToString()); } catch (Exception e) { m_log.Debug(string.Format( "[SynchronousRestObjectRequester]: Exception on response from {0} {1} ", verb, requestUrl), e); } int tickdiff = Environment.TickCount - tickstart; if (tickdiff > WebUtil.LongCallTime) { string originalRequest = null; if (buffer != null) { originalRequest = Encoding.UTF8.GetString(buffer.ToArray()); if (originalRequest.Length > WebUtil.MaxRequestDiagLength) originalRequest = originalRequest.Remove(WebUtil.MaxRequestDiagLength); } m_log.InfoFormat( "[LOGHTTP]: Slow SynchronousRestObject request {0} {1} to {2} took {3}ms, {4}ms writing, {5}", reqnum, verb, requestUrl, tickdiff, tickdata, originalRequest); } else if (WebUtil.DebugLevel >= 4) { m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms, {2}ms writing", reqnum, tickdiff, tickdata); } } finally { if (buffer != null) buffer.Dispose(); } return deserial; } public static class XMLResponseHelper { public static TResponse LogAndDeserialize<TRequest, TResponse>(int reqnum, Stream respStream, long contentLength) { XmlSerializer deserializer = new XmlSerializer(typeof(TResponse)); if (WebUtil.DebugLevel >= 5) { byte[] data = new byte[contentLength]; Util.ReadStream(respStream, data); WebUtil.LogResponseDetail(reqnum, System.Text.Encoding.UTF8.GetString(data)); using (MemoryStream temp = new MemoryStream(data)) return (TResponse)deserializer.Deserialize(temp); } else { return (TResponse)deserializer.Deserialize(respStream); } } } } public static class XMLRPCRequester { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public static Hashtable SendRequest(Hashtable ReqParams, string method, string url) { int reqnum = WebUtil.RequestNumber++; if (WebUtil.DebugLevel >= 3) m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} XML-RPC '{1}' to {2}", reqnum, method, url); int tickstart = Environment.TickCount; string responseStr = null; try { ArrayList SendParams = new ArrayList(); SendParams.Add(ReqParams); XmlRpcRequest Req = new XmlRpcRequest(method, SendParams); if (WebUtil.DebugLevel >= 5) { string str = Req.ToString(); str = XElement.Parse(str).ToString(SaveOptions.DisableFormatting); WebUtil.LogOutgoingDetail("SEND", reqnum, str); } XmlRpcResponse Resp = Req.Send(url, 30000); try { responseStr = Resp.ToString(); responseStr = XElement.Parse(responseStr).ToString(SaveOptions.DisableFormatting); if (WebUtil.DebugLevel >= 5) WebUtil.LogResponseDetail(reqnum, responseStr); } catch (Exception e) { m_log.Error("Error parsing XML-RPC response", e); } if (Resp.IsFault) { m_log.DebugFormat( "[LOGHTTP]: XML-RPC request {0} '{1}' to {2} FAILED: FaultCode={3}, FaultMessage={4}", reqnum, method, url, Resp.FaultCode, Resp.FaultString); return null; } Hashtable RespData = (Hashtable)Resp.Value; return RespData; } finally { int tickdiff = Environment.TickCount - tickstart; if (tickdiff > WebUtil.LongCallTime) { m_log.InfoFormat( "[LOGHTTP]: Slow XML-RPC request {0} '{1}' to {2} took {3}ms, {4}", reqnum, method, url, tickdiff, responseStr != null ? (responseStr.Length > WebUtil.MaxRequestDiagLength ? responseStr.Remove(WebUtil.MaxRequestDiagLength) : responseStr) : ""); } else if (WebUtil.DebugLevel >= 4) { m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms", reqnum, tickdiff); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // //////////////////////////////////////////////////////////////////////////////// #pragma warning disable 0420 // turn off 'a reference to a volatile field will not be treated as volatile' during CAS. using System; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime; using System.Runtime.CompilerServices; using System.Security; namespace System.Threading { /// <summary> /// Propagates notification that operations should be canceled. /// </summary> /// <remarks> /// <para> /// A <see cref="CancellationToken"/> may be created directly in an unchangeable canceled or non-canceled state /// using the CancellationToken's constructors. However, to have a CancellationToken that can change /// from a non-canceled to a canceled state, /// <see cref="System.Threading.CancellationTokenSource">CancellationTokenSource</see> must be used. /// CancellationTokenSource exposes the associated CancellationToken that may be canceled by the source through its /// <see cref="System.Threading.CancellationTokenSource.Token">Token</see> property. /// </para> /// <para> /// Once canceled, a token may not transition to a non-canceled state, and a token whose /// <see cref="CanBeCanceled"/> is false will never change to one that can be canceled. /// </para> /// <para> /// All members of this struct are thread-safe and may be used concurrently from multiple threads. /// </para> /// </remarks> [ComVisible(false)] [DebuggerDisplay("IsCancellationRequested = {IsCancellationRequested}")] public struct CancellationToken { // The backing TokenSource. // if null, it implicitly represents the same thing as new CancellationToken(false). // When required, it will be instantiated to reflect this. private CancellationTokenSource m_source; //!! warning. If more fields are added, the assumptions in CreateLinkedToken may no longer be valid /* Properties */ /// <summary> /// Returns an empty CancellationToken value. /// </summary> /// <remarks> /// The <see cref="CancellationToken"/> value returned by this property will be non-cancelable by default. /// </remarks> public static CancellationToken None { get { return default(CancellationToken); } } /// <summary> /// Gets whether cancellation has been requested for this token. /// </summary> /// <value>Whether cancellation has been requested for this token.</value> /// <remarks> /// <para> /// This property indicates whether cancellation has been requested for this token, /// either through the token initially being construted in a canceled state, or through /// calling <see cref="System.Threading.CancellationTokenSource.Cancel()">Cancel</see> /// on the token's associated <see cref="CancellationTokenSource"/>. /// </para> /// <para> /// If this property is true, it only guarantees that cancellation has been requested. /// It does not guarantee that every registered handler /// has finished executing, nor that cancellation requests have finished propagating /// to all registered handlers. Additional synchronization may be required, /// particularly in situations where related objects are being canceled concurrently. /// </para> /// </remarks> public bool IsCancellationRequested { get { return m_source != null && m_source.IsCancellationRequested; } } /// <summary> /// Gets whether this token is capable of being in the canceled state. /// </summary> /// <remarks> /// If CanBeCanceled returns false, it is guaranteed that the token will never transition /// into a canceled state, meaning that <see cref="IsCancellationRequested"/> will never /// return true. /// </remarks> public bool CanBeCanceled { get { return m_source != null && m_source.CanBeCanceled; } } /// <summary> /// Gets a <see cref="T:System.Threading.WaitHandle"/> that is signaled when the token is canceled.</summary> /// <remarks> /// Accessing this property causes a <see cref="T:System.Threading.WaitHandle">WaitHandle</see> /// to be instantiated. It is preferable to only use this property when necessary, and to then /// dispose the associated <see cref="CancellationTokenSource"/> instance at the earliest opportunity (disposing /// the source will dispose of this allocated handle). The handle should not be closed or disposed directly. /// </remarks> /// <exception cref="T:System.ObjectDisposedException">The associated <see /// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception> public WaitHandle WaitHandle { get { if (m_source == null) { InitializeDefaultSource(); } return m_source.WaitHandle; } } // public CancellationToken() // this constructor is implicit for structs // -> this should behaves exactly as for new CancellationToken(false) /// <summary> /// Internal constructor only a CancellationTokenSource should create a CancellationToken /// </summary> internal CancellationToken(CancellationTokenSource source) { m_source = source; } /// <summary> /// Initializes the <see cref="T:System.Threading.CancellationToken">CancellationToken</see>. /// </summary> /// <param name="canceled"> /// The canceled state for the token. /// </param> /// <remarks> /// Tokens created with this constructor will remain in the canceled state specified /// by the <paramref name="canceled"/> parameter. If <paramref name="canceled"/> is false, /// both <see cref="CanBeCanceled"/> and <see cref="IsCancellationRequested"/> will be false. /// If <paramref name="canceled"/> is true, /// both <see cref="CanBeCanceled"/> and <see cref="IsCancellationRequested"/> will be true. /// </remarks> public CancellationToken(bool canceled) : this() { if(canceled) m_source = CancellationTokenSource.InternalGetStaticSource(canceled); } /* Methods */ private readonly static Action<Object> s_ActionToActionObjShunt = new Action<Object>(ActionToActionObjShunt); private static void ActionToActionObjShunt(object obj) { Action action = obj as Action; Debug.Assert(action != null, "Expected an Action here"); action(); } /// <summary> /// Registers a delegate that will be called when this <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled. /// </summary> /// <remarks> /// <para> /// If this token is already in the canceled state, the /// delegate will be run immediately and synchronously. Any exception the delegate generates will be /// propagated out of this method call. /// </para> /// <para> /// The current <see cref="System.Threading.ExecutionContext">ExecutionContext</see>, if one exists, will be captured /// along with the delegate and will be used when executing it. /// </para> /// </remarks> /// <param name="callback">The delegate to be executed when the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.</param> /// <returns>The <see cref="T:System.Threading.CancellationTokenRegistration"/> instance that can /// be used to deregister the callback.</returns> /// <exception cref="T:System.ArgumentNullException"><paramref name="callback"/> is null.</exception> public CancellationTokenRegistration Register(Action callback) { if (callback == null) throw new ArgumentNullException(nameof(callback)); return Register( s_ActionToActionObjShunt, callback, false, // useSync=false true // useExecutionContext=true ); } /// <summary> /// Registers a delegate that will be called when this /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled. /// </summary> /// <remarks> /// <para> /// If this token is already in the canceled state, the /// delegate will be run immediately and synchronously. Any exception the delegate generates will be /// propagated out of this method call. /// </para> /// <para> /// The current <see cref="System.Threading.ExecutionContext">ExecutionContext</see>, if one exists, will be captured /// along with the delegate and will be used when executing it. /// </para> /// </remarks> /// <param name="callback">The delegate to be executed when the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.</param> /// <param name="useSynchronizationContext">A Boolean value that indicates whether to capture /// the current <see cref="T:System.Threading.SynchronizationContext">SynchronizationContext</see> and use it /// when invoking the <paramref name="callback"/>.</param> /// <returns>The <see cref="T:System.Threading.CancellationTokenRegistration"/> instance that can /// be used to deregister the callback.</returns> /// <exception cref="T:System.ArgumentNullException"><paramref name="callback"/> is null.</exception> public CancellationTokenRegistration Register(Action callback, bool useSynchronizationContext) { if (callback == null) throw new ArgumentNullException(nameof(callback)); return Register( s_ActionToActionObjShunt, callback, useSynchronizationContext, true // useExecutionContext=true ); } /// <summary> /// Registers a delegate that will be called when this /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled. /// </summary> /// <remarks> /// <para> /// If this token is already in the canceled state, the /// delegate will be run immediately and synchronously. Any exception the delegate generates will be /// propagated out of this method call. /// </para> /// <para> /// The current <see cref="System.Threading.ExecutionContext">ExecutionContext</see>, if one exists, will be captured /// along with the delegate and will be used when executing it. /// </para> /// </remarks> /// <param name="callback">The delegate to be executed when the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.</param> /// <param name="state">The state to pass to the <paramref name="callback"/> when the delegate is invoked. This may be null.</param> /// <returns>The <see cref="T:System.Threading.CancellationTokenRegistration"/> instance that can /// be used to deregister the callback.</returns> /// <exception cref="T:System.ArgumentNullException"><paramref name="callback"/> is null.</exception> public CancellationTokenRegistration Register(Action<Object> callback, Object state) { if (callback == null) throw new ArgumentNullException(nameof(callback)); return Register( callback, state, false, // useSync=false true // useExecutionContext=true ); } /// <summary> /// Registers a delegate that will be called when this /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled. /// </summary> /// <remarks> /// <para> /// If this token is already in the canceled state, the /// delegate will be run immediately and synchronously. Any exception the delegate generates will be /// propagated out of this method call. /// </para> /// <para> /// The current <see cref="System.Threading.ExecutionContext">ExecutionContext</see>, if one exists, /// will be captured along with the delegate and will be used when executing it. /// </para> /// </remarks> /// <param name="callback">The delegate to be executed when the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.</param> /// <param name="state">The state to pass to the <paramref name="callback"/> when the delegate is invoked. This may be null.</param> /// <param name="useSynchronizationContext">A Boolean value that indicates whether to capture /// the current <see cref="T:System.Threading.SynchronizationContext">SynchronizationContext</see> and use it /// when invoking the <paramref name="callback"/>.</param> /// <returns>The <see cref="T:System.Threading.CancellationTokenRegistration"/> instance that can /// be used to deregister the callback.</returns> /// <exception cref="T:System.ArgumentNullException"><paramref name="callback"/> is null.</exception> /// <exception cref="T:System.ObjectDisposedException">The associated <see /// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception> public CancellationTokenRegistration Register(Action<Object> callback, Object state, bool useSynchronizationContext) { return Register( callback, state, useSynchronizationContext, true // useExecutionContext=true ); } // helper for internal registration needs that don't require an EC capture (e.g. creating linked token sources, or registering unstarted TPL tasks) // has a handy signature, and skips capturing execution context. internal CancellationTokenRegistration InternalRegisterWithoutEC(Action<object> callback, Object state) { return Register( callback, state, false, // useSyncContext=false false // useExecutionContext=false ); } // the real work.. [MethodImpl(MethodImplOptions.NoInlining)] private CancellationTokenRegistration Register(Action<Object> callback, Object state, bool useSynchronizationContext, bool useExecutionContext) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; if (callback == null) throw new ArgumentNullException(nameof(callback)); if (CanBeCanceled == false) { return new CancellationTokenRegistration(); // nothing to do for tokens than can never reach the canceled state. Give them a dummy registration. } // Capture sync/execution contexts if required. // Note: Only capture sync/execution contexts if IsCancellationRequested = false // as we know that if it is true that the callback will just be called synchronously. SynchronizationContext capturedSyncContext = null; ExecutionContext capturedExecutionContext = null; if (!IsCancellationRequested) { if (useSynchronizationContext) capturedSyncContext = SynchronizationContext.Current; if (useExecutionContext) capturedExecutionContext = ExecutionContext.Capture( ref stackMark, ExecutionContext.CaptureOptions.OptimizeDefaultCase); // ideally we'd also use IgnoreSyncCtx, but that could break compat } // Register the callback with the source. return m_source.InternalRegister(callback, state, capturedSyncContext, capturedExecutionContext); } /// <summary> /// Determines whether the current <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instance is equal to the /// specified token. /// </summary> /// <param name="other">The other <see cref="T:System.Threading.CancellationToken">CancellationToken</see> to which to compare this /// instance.</param> /// <returns>True if the instances are equal; otherwise, false. Two tokens are equal if they are associated /// with the same <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> or if they were both constructed /// from public CancellationToken constructors and their <see cref="IsCancellationRequested"/> values are equal.</returns> public bool Equals(CancellationToken other) { //if both sources are null, then both tokens represent the Empty token. if (m_source == null && other.m_source == null) { return true; } // one is null but other has inflated the default source // these are only equal if the inflated one is the staticSource(false) if (m_source == null) { return other.m_source == CancellationTokenSource.InternalGetStaticSource(false); } if (other.m_source == null) { return m_source == CancellationTokenSource.InternalGetStaticSource(false); } // general case, we check if the sources are identical return m_source == other.m_source; } /// <summary> /// Determines whether the current <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instance is equal to the /// specified <see cref="T:System.Object"/>. /// </summary> /// <param name="other">The other object to which to compare this instance.</param> /// <returns>True if <paramref name="other"/> is a <see cref="T:System.Threading.CancellationToken">CancellationToken</see> /// and if the two instances are equal; otherwise, false. Two tokens are equal if they are associated /// with the same <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> or if they were both constructed /// from public CancellationToken constructors and their <see cref="IsCancellationRequested"/> values are equal.</returns> /// <exception cref="T:System.ObjectDisposedException">An associated <see /// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception> public override bool Equals(Object other) { if (other is CancellationToken) { return Equals((CancellationToken) other); } return false; } /// <summary> /// Serves as a hash function for a <see cref="T:System.Threading.CancellationToken">CancellationToken</see>. /// </summary> /// <returns>A hash code for the current <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instance.</returns> public override Int32 GetHashCode() { if (m_source == null) { // link to the common source so that we have a source to interrogate. return CancellationTokenSource.InternalGetStaticSource(false).GetHashCode(); } return m_source.GetHashCode(); } /// <summary> /// Determines whether two <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instances are equal. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True if the instances are equal; otherwise, false.</returns> /// <exception cref="T:System.ObjectDisposedException">An associated <see /// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception> public static bool operator ==(CancellationToken left, CancellationToken right) { return left.Equals(right); } /// <summary> /// Determines whether two <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instances are not equal. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True if the instances are not equal; otherwise, false.</returns> /// <exception cref="T:System.ObjectDisposedException">An associated <see /// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception> public static bool operator !=(CancellationToken left, CancellationToken right) { return !left.Equals(right); } /// <summary> /// Throws a <see cref="T:System.OperationCanceledException">OperationCanceledException</see> if /// this token has had cancellation requested. /// </summary> /// <remarks> /// This method provides functionality equivalent to: /// <code> /// if (token.IsCancellationRequested) /// throw new OperationCanceledException(token); /// </code> /// </remarks> /// <exception cref="System.OperationCanceledException">The token has had cancellation requested.</exception> /// <exception cref="T:System.ObjectDisposedException">The associated <see /// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception> public void ThrowIfCancellationRequested() { if (IsCancellationRequested) ThrowOperationCanceledException(); } // Throw an ODE if this CancellationToken's source is disposed. internal void ThrowIfSourceDisposed() { if ((m_source != null) && m_source.IsDisposed) ThrowObjectDisposedException(); } // Throws an OCE; separated out to enable better inlining of ThrowIfCancellationRequested private void ThrowOperationCanceledException() { throw new OperationCanceledException(Environment.GetResourceString("OperationCanceled"), this); } private static void ThrowObjectDisposedException() { throw new ObjectDisposedException(null, Environment.GetResourceString("CancellationToken_SourceDisposed")); } // ----------------------------------- // Private helpers private void InitializeDefaultSource() { // Lazy is slower, and although multiple threads may try and set m_source repeatedly, the race condition is benign. // Alternative: LazyInititalizer.EnsureInitialized(ref m_source, ()=>CancellationTokenSource.InternalGetStaticSource(false)); m_source = CancellationTokenSource.InternalGetStaticSource(false); } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using BudgetAnalyser.Engine.Statement.Data; using JetBrains.Annotations; using Rees.TangyFruitMapper; namespace BudgetAnalyser.Engine.Statement { /// <summary> /// A repository for the <see cref="StatementModel" /> backed by Csv on local disk storage. /// </summary> /// <seealso cref="BudgetAnalyser.Engine.Statement.IVersionedStatementModelRepository" /> [AutoRegisterWithIoC(SingleInstance = true)] internal class CsvOnDiskStatementModelRepositoryV1 : IVersionedStatementModelRepository { private const string VersionHash = "15955E20-A2CC-4C69-AD42-94D84377FC0C"; private readonly BankImportUtilities importUtilities; private readonly ILogger logger; private readonly IDtoMapper<TransactionSetDto, StatementModel> mapper; private readonly IReaderWriterSelector readerWriterSelector; public CsvOnDiskStatementModelRepositoryV1( [NotNull] BankImportUtilities importUtilities, [NotNull] ILogger logger, [NotNull] IDtoMapper<TransactionSetDto, StatementModel> mapper, [NotNull] IReaderWriterSelector readerWriterSelector) { if (importUtilities == null) { throw new ArgumentNullException(nameof(importUtilities)); } if (logger == null) { throw new ArgumentNullException(nameof(logger)); } if (mapper == null) { throw new ArgumentNullException(nameof(mapper)); } if (readerWriterSelector == null) throw new ArgumentNullException(nameof(readerWriterSelector)); this.importUtilities = importUtilities; this.logger = logger; this.mapper = mapper; this.readerWriterSelector = readerWriterSelector; } public async Task CreateNewAndSaveAsync(string storageKey) { if (storageKey.IsNothing()) { throw new ArgumentNullException(nameof(storageKey)); } var newStatement = new StatementModel(this.logger) { StorageKey = storageKey }; await SaveAsync(newStatement, storageKey, false); } public async Task<StatementModel> LoadAsync(string storageKey, bool isEncrypted) { if (storageKey.IsNothing()) { throw new ArgumentNullException(nameof(storageKey)); } try { this.importUtilities.AbortIfFileDoesntExist(storageKey); } catch (FileNotFoundException ex) { throw new KeyNotFoundException(ex.Message, ex); } if (!await IsStatementModelAsync(storageKey, isEncrypted)) { throw new NotSupportedException("The CSV file is not supported by this version of the Budget Analyser."); } List<string> allLines = (await ReadLinesAsync(storageKey, isEncrypted)).ToList(); var totalLines = allLines.LongCount(); if (totalLines < 2) { return new StatementModel(this.logger) { StorageKey = storageKey }.LoadTransactions(new List<Transaction>()); } List<TransactionDto> transactions = ReadTransactions(totalLines, allLines); var transactionSet = CreateTransactionSet(storageKey, allLines, transactions); ValidateChecksumIntegrity(transactionSet); return this.mapper.ToModel(transactionSet); } [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "Stream and StreamWriter are designed with this pattern in mind")] public async Task SaveAsync(StatementModel model, string storageKey, bool isEncrypted) { if (model == null) { throw new ArgumentNullException(nameof(model)); } if (storageKey.IsNothing()) { throw new ArgumentNullException(nameof(storageKey)); } var transactionSet = this.mapper.ToDto(model); transactionSet.VersionHash = VersionHash; transactionSet.StorageKey = storageKey; transactionSet.Checksum = CalculateTransactionCheckSum(transactionSet); if (model.AllTransactions.Count() != transactionSet.Transactions.Count()) { throw new StatementModelChecksumException( string.Format( CultureInfo.InvariantCulture, "Only {0} out of {1} transactions have been mapped correctly. Aborting the save, to avoid data loss and corruption.", transactionSet.Transactions.Count, model.AllTransactions.Count())); } var writer = this.readerWriterSelector.SelectReaderWriter(isEncrypted); using (var stream = writer.CreateWritableStream(storageKey)) { using (var streamWriter = new StreamWriter(stream)) { WriteHeader(streamWriter, transactionSet); foreach (var transaction in transactionSet.Transactions) { var line = new StringBuilder(); line.Append(transaction.TransactionType); line.Append(","); line.Append(transaction.Description); line.Append(","); line.Append(transaction.Reference1); line.Append(","); line.Append(transaction.Reference2); line.Append(","); line.Append(transaction.Reference3); line.Append(","); line.Append(transaction.Amount); line.Append(","); line.Append(transaction.Date.ToString("O", CultureInfo.InvariantCulture)); line.Append(","); line.Append(transaction.BudgetBucketCode); line.Append(","); line.Append(transaction.Account); line.Append(","); line.Append(transaction.Id); line.Append(","); await streamWriter.WriteLineAsync(line.ToString()); } await streamWriter.FlushAsync(); } } } /// <summary> /// Reads the lines from the file asynchronously. /// </summary> protected virtual async Task<IEnumerable<string>> ReadLinesAsync(string fileName, bool isEncrypted) { var reader = this.readerWriterSelector.SelectReaderWriter(isEncrypted); var allText = await reader.LoadFromDiskAsync(fileName); return allText.SplitLines(); } /// <summary> /// Reads the lines from the file asynchronously. /// </summary> protected virtual async Task<IEnumerable<string>> ReadLinesAsync(string fileName, int lines, bool isEncrypted) { var reader = this.readerWriterSelector.SelectReaderWriter(isEncrypted); var textData = await reader.LoadFirstLinesFromDiskAsync(fileName, lines); string[] firstLines = textData.SplitLines(lines); return firstLines; } internal async Task<bool> IsStatementModelAsync(string storageKey, bool isEncrypted) { if (storageKey.IsNothing()) { throw new ArgumentNullException(nameof(storageKey)); } this.importUtilities.AbortIfFileDoesntExist(storageKey); List<string> allLines = (await ReadLinesAsync(storageKey, 2, isEncrypted)).ToList(); if (!VersionCheck(allLines)) { return false; } return true; } private static long CalculateTransactionCheckSum(TransactionSetDto setDto) { long txnCheckSum = 37; // prime unchecked { txnCheckSum *= 397; // also prime foreach (var txn in setDto.Transactions) { txnCheckSum += (long) txn.Amount * 100; txnCheckSum *= 829; } } return txnCheckSum; } private TransactionSetDto CreateTransactionSet(string fileName, List<string> allLines, List<TransactionDto> transactions) { var header = allLines[0]; if (string.IsNullOrWhiteSpace(header)) { throw new DataFormatException("The Budget Analyser file does not have a valid header row."); } string[] headerSplit = header.Split(','); var transactionSet = new TransactionSetDto { Checksum = this.importUtilities.FetchLong(headerSplit, 3), StorageKey = fileName, LastImport = this.importUtilities.FetchDate(headerSplit, 4), Transactions = transactions, VersionHash = this.importUtilities.FetchString(headerSplit, 1) }; return transactionSet; } private List<TransactionDto> ReadTransactions(long totalLines, List<string> allLines) { var transactions = new List<TransactionDto>(); for (var index = 1; index < totalLines; index++) { var line = allLines[index]; if (string.IsNullOrWhiteSpace(line)) { continue; } string[] split = line.Split(','); TransactionDto transaction; try { transaction = new TransactionDto { TransactionType = this.importUtilities.FetchString(split, 0), Description = this.importUtilities.FetchString(split, 1), Reference1 = this.importUtilities.FetchString(split, 2), Reference2 = this.importUtilities.FetchString(split, 3), Reference3 = this.importUtilities.FetchString(split, 4), Amount = this.importUtilities.FetchDecimal(split, 5), Date = this.importUtilities.FetchDate(split, 6), BudgetBucketCode = this.importUtilities.FetchString(split, 7), Account = this.importUtilities.FetchString(split, 8), Id = this.importUtilities.FetchGuid(split, 9) }; } catch (InvalidDataException ex) { throw new DataFormatException("The Budget Analyser is corrupt. The file has some invalid data in inappropriate columns.", ex); } catch (IndexOutOfRangeException ex) { throw new DataFormatException("The Budget Analyser is corrupt. The file does not have the correct number of columns.", ex); } if (transaction.Date == DateTime.MinValue || transaction.Id == Guid.Empty) { // Do not check for Amount == 0 here, sometimes memo transactions can appear with 0.00 or null amounts; which are valid. throw new DataFormatException( "The Budget Analyser file does not contain the correct data type for Date and/or Id in row " + index + 1); } transactions.Add(transaction); } return transactions; } private void ValidateChecksumIntegrity(TransactionSetDto transactionSet) { var calcTxnCheckSum = CalculateTransactionCheckSum(transactionSet); // Ignore a checksum of 1, this is used as a special case to bypass transaction checksum test. Useful for manual manipulation of the statement csv. if (transactionSet.Checksum > 1 && transactionSet.Checksum != calcTxnCheckSum) { this.logger.LogError(l => l.Format( "BudgetAnalyser statement file being loaded has an incorrect checksum of: {0}, transactions calculate to: {1}", transactionSet.Checksum, calcTxnCheckSum)); throw new StatementModelChecksumException( calcTxnCheckSum.ToString(CultureInfo.InvariantCulture), string.Format( CultureInfo.CurrentCulture, "The statement being loaded, does not match the internal checksum. {0} {1}", calcTxnCheckSum, transactionSet.Checksum)); } } private static bool VersionCheck(List<string> allLines) { var firstLine = allLines[0]; string[] split = firstLine.Split(','); if (split.Length != 5) { return false; } if (split[1] != VersionHash) { return false; } return true; } private static void WriteHeader(StreamWriter writer, TransactionSetDto setDto) { writer.WriteLine("VersionHash,{0},TransactionCheckSum,{1},{2}", setDto.VersionHash, setDto.Checksum, setDto.LastImport.ToString("O", CultureInfo.InvariantCulture)); } } }
using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif using UnityEngine.Serialization; using System; using System.Collections.Generic; namespace UMA { public partial class RaceData { public UMARecipeBase baseRaceRecipe; public List<string> wardrobeSlots = new List<string>(){ "None", "Face", "Hair", "Complexion", "Eyebrows", "Beard", "Ears", "Helmet", "Shoulders", "Chest", "Arms", "Hands", "Waist", "Legs", "Feet" }; //UMA26 we want to depricate this- how much do we need to worry about the fact that users could do backwardsCompatibleWith.Add/Remove via scripting before? [Obsolete("[RaceData backwardsCompatibleWith is deprecated and will be removed in a future version. Please use RaceData.CrossCompatibleRaces instead.")] public List<string> backwardsCompatibleWith = new List<string>(); //CrossCompatibilitySettings allows this race to wear wardrobe slots from another race, if this race has a wardrobe slot that the recipe is set to. //You can further configure the compatibility settings for each compatible race to define 'equivalent' slotdatas in the races' base recipes. For example you could define //that this races 'highpolyMaleChest' slotdata in its base recipe is equivalent to HumanMales 'MaleChest' slot data in its base recipe. This would mean that any recipes which hid or applied an overlay to 'MaleChest' //would hide or apply an overlay to 'highPolyMaleChest' on this race. If 'Overlays Match' is unchecked then overlays in a recipe wont be applied. [SerializeField] private CrossCompatibilitySettingsList _crossCompatibilitySettings = new CrossCompatibilitySettingsList(); public RaceThumbnails raceThumbnails; //Not sure if this is needed I think I could just set the wardrobe slots property to be this by default? public void AddDefaultWardrobeSlots(bool forceOverride = false) { if (wardrobeSlots.Count == 0 || forceOverride) { wardrobeSlots = new List<string>() { "None", "Face", "Hair", "Complexion", "Eyebrows", "Beard", "Ears", "Helmet", "Shoulders", "Chest", "Arms", "Hands", "Waist", "Legs", "Feet" }; } } /// <summary> /// Validates the wardrobe slots. /// </summary> /// <returns><c>true</c>, if wardrobe slots was validated, <c>false</c> otherwise.</returns> /// <param name="setToDefault">If set to <c>true</c> wardrobeSlots are set to default (returns true).</param> public bool ValidateWardrobeSlots(bool setToDefault = false) { if (wardrobeSlots.Count == 0) { AddDefaultWardrobeSlots(setToDefault); return setToDefault; } return true; } //For backwards compatibility [Obsolete("findBackwardsCompatibleWith has been depricated and will be removed in a future version. Please use 'IsCrossCompatibleWith' instead.")] public bool findBackwardsCompatibleWith(List<string> compatibleStrings) { return IsCrossCompatibleWith(compatibleStrings); } /// <summary> /// Given a raceNames returns whether this race has been set to be 'cross compatible' with that race. /// </summary> public bool IsCrossCompatibleWith(RaceData compatibleRace) { return GetCrossCompatibleRaces().Contains(compatibleRace.raceName); } /// <summary> /// Given a raceNames returns whether this race has been set to be 'cross compatible' with that race. /// </summary> public bool IsCrossCompatibleWith(string compatibleString) { return GetCrossCompatibleRaces().Contains(compatibleString); } /// <summary> /// Given a list of raceNames returns whether this race has been set to be 'cross compatible' with any of those races. /// </summary> public bool IsCrossCompatibleWith(List<string> compatibleStrings) { foreach (string val in compatibleStrings) { if (GetCrossCompatibleRaces().Contains(val)) { return true; } } return false; } /// <summary> /// backwards compatibility: Updates any Races from before _crossCompatibilitySettings so their backwards compatible races are added automatically. If the race is being inspected these changes are saved - remove in a future version /// </summary> private void UpdateOldRace() { #pragma warning disable 618 if (_crossCompatibilitySettings.settingsData.Count == 0 && backwardsCompatibleWith.Count > 0) { SetCrossCompatibleRaces(backwardsCompatibleWith); //then clear the backwardsCompatibleWith list and save the asset- the user wont be able to use 'backwardsCompatibleWith' //but they will have been shown a warning if their scripts access the field directly #if UNITY_EDITOR Debug.Log("RaceData for " + raceName + " updated its backwardsCompatibleWith value to the new CrossCompatibilitySettings. All good."); if (!Application.isPlaying) { //Debug.Log("RaceData for " + raceName + " updated its backwardsCompatibleWith value to the new CrossCompatibilitySettings. All good."); backwardsCompatibleWith.Clear(); EditorUtility.SetDirty(this); AssetDatabase.SaveAssets(); } #endif } #pragma warning restore 618 } /// <summary> /// Returns the list of raceNames that this race has set to be 'cross compatible' with /// </summary> public List<string> GetCrossCompatibleRaces() { UpdateOldRace(); List<string> ccRaces = new List<string>(); for (int i = 0; i < _crossCompatibilitySettings.settingsData.Count; i++) ccRaces.Add(_crossCompatibilitySettings.settingsData[i].ccRace); return ccRaces; } /// <summary> /// Sets the races that this race can be 'cross compatible with. /// </summary> public void SetCrossCompatibleRaces(List<string> ccRaces) { for (int i = 0; i < ccRaces.Count; i++) _crossCompatibilitySettings.Add(ccRaces[i]); //then remove any that were not in the list List<string> racesToRemove = new List<string>(); for (int i = 0; i < _crossCompatibilitySettings.settingsData.Count; i++) { if (!ccRaces.Contains(_crossCompatibilitySettings.settingsData[i].ccRace)) racesToRemove.Add(_crossCompatibilitySettings.settingsData[i].ccRace); } _crossCompatibilitySettings.Remove(racesToRemove); } /// <summary> /// Gets the cross compatibility settings that have been defined for this race /// </summary> protected List<CrossCompatibilityData> GetSettingsFor(string crossCompatibleRace) { for (int i = 0; i < _crossCompatibilitySettings.settingsData.Count; i++) { if (_crossCompatibilitySettings.settingsData[i].ccRace == crossCompatibleRace) return _crossCompatibilitySettings.settingsData[i].ccSettings; } return null; } /// <summary> /// If this race has been defined as being 'cross compatible' with any of the given races, this will return the slot in this races base recipe that has been defined as /// equivalent to the given slot in the given races (optionally only returning a value if the overlays have ALSO been defined as matching) /// </summary> /// <param name="races">The cross compatible races to check. i.e. is this race defined as compatible with any of these races</param> /// <param name="crossCompatibleSlot">The slot to check. i.e. if this race IS defined as compatible with one of the above races, does it define that it has a slot that is equivalent to the given slot</param> /// <param name="overlaysMustMatch">If this is true, an equivalent slot will only be returned if it has also been defined as having Overlay scales that match the cross compatible race</param> /// <returns></returns> public string FindEquivalentSlot(List<string> races, string crossCompatibleSlot, bool overlaysMustMatch = true) { for (int i = 0; i < races.Count; i++) { var foundEquivalent = FindEquivalentSlot(races[i], crossCompatibleSlot, overlaysMustMatch); if (foundEquivalent != "") return foundEquivalent; } return ""; } /// <param name="race">The cross compatible race to check. i.e. is this race defined as compatible with the given race</param> public string FindEquivalentSlot(string race, string crossCompatibleSlot, bool overlaysMustMatch = true) { for (int i = 0; i < _crossCompatibilitySettings.settingsData.Count; i++) { if (_crossCompatibilitySettings.settingsData[i].ccRace == race) { return _crossCompatibilitySettings.settingsData[i].GetEquivalentSlot(crossCompatibleSlot, overlaysMustMatch); } } return ""; } /// <summary> /// Searches this races Cross compatibility settings for the given slot and returns whether its equivalent slot (if defined) has been defined as having compatible overlays /// </summary> public bool GetOverlayCompatibility(string crossCompatibleSlot) { for (int i = 0; i < _crossCompatibilitySettings.settingsData.Count; i++) { var compatibilityForThisRace = _crossCompatibilitySettings.settingsData[i].GetOverlayCompatibility(crossCompatibleSlot); if (compatibilityForThisRace != -1) return compatibilityForThisRace == 1 ? true : false; } return false; } /// <summary> /// Searches this races Cross compatibility settings for the given race to find the given slot and returns whether its equivalent slot (if defined) has been defined as having compatible overlays /// </summary> public bool GetOverlayCompatibility(string race, string crossCompatibleSlot) { for (int i = 0; i < _crossCompatibilitySettings.settingsData.Count; i++) { if (_crossCompatibilitySettings.settingsData[i].ccRace == race) { return _crossCompatibilitySettings.settingsData[i].GetOverlayCompatibility(crossCompatibleSlot) == 1 ? true : false; } } return false; } #region SpecialTypes //new classes for CrossCompatibilitySettings //allows the user to define that a given slot in this races base recipe is equal to the named slot in the backwards compatible races base recipe [System.Serializable] protected class CrossCompatibilityData { //the slot in this race's baseRaceRecipe public string raceSlot = ""; //the slot in the other races baseRaceRecipe that should be considered equivalent public string compatibleRaceSlot = ""; //are the overlay resolutions the same, if not overlays in recipes on the compatible race will not be copied over public bool overlaysMatch; public CrossCompatibilityData() { } public CrossCompatibilityData(string _raceSlot, string _compatibleRaceSlot) { raceSlot = _raceSlot; compatibleRaceSlot = _compatibleRaceSlot; } public CrossCompatibilityData(string _raceSlot, string _compatibleRaceSlot, bool _overlaysMatch) { raceSlot = _raceSlot; compatibleRaceSlot = _compatibleRaceSlot; overlaysMatch = _overlaysMatch; } } [System.Serializable] protected class CrossCompatibilitySettings { public string ccRace = ""; public List<CrossCompatibilityData> ccSettings = new List<CrossCompatibilityData>(); public CrossCompatibilitySettings() { } public CrossCompatibilitySettings(string race) { ccRace = race; } public CrossCompatibilitySettings(string race, List<CrossCompatibilityData> settings) { ccRace = race; ccSettings = settings; } /// <summary> /// Returns the slot in the COMPATIBLE race that has been defined as equivalent to the given slot from THIS race /// </summary> public string GetCompatibleRacesSlot(string thisRacesSlot) { for (int i = 0; i < ccSettings.Count; i++) { if (ccSettings[i].raceSlot == thisRacesSlot) return ccSettings[i].compatibleRaceSlot; } return ""; } /// <summary> /// Returns the slot in THIS race that has been defined as equivalent to the given slot from the COMPATIBLE race /// </summary> public string GetEquivalentSlot(string compatibleSlot, bool overlaysMustMatch = true) { for (int i = 0; i < ccSettings.Count; i++) { if (ccSettings[i].compatibleRaceSlot == compatibleSlot) if ((overlaysMustMatch == true && ccSettings[i].overlaysMatch == true) || overlaysMustMatch == false) return ccSettings[i].raceSlot; } return ""; } /// <summary> /// Returns whether the given slot in THIS race has been defined as having compatible overlays with the given slot from the COMPATIBLE race /// </summary> public int GetOverlayCompatibility(string compatibleRaceSlot) { for (int i = 0; i < ccSettings.Count; i++) { if (ccSettings[i].compatibleRaceSlot == compatibleRaceSlot) return ccSettings[i].overlaysMatch ? 1 : 0; } return -1; } /// <summary> /// Defines that a slot in THIS race is compatible with the given slot from the COMPATIBLE race (optionally defining overlay compatibility as false) /// </summary> public void SetEquivalentSlot(string thisRacesSlot, string compatibleRacesSlot = "", bool overlayCompatibility = true) { bool found = false; for (int i = 0; i < ccSettings.Count; i++) { if (ccSettings[i].raceSlot == thisRacesSlot) { ccSettings[i].compatibleRaceSlot = compatibleRacesSlot; ccSettings[i].overlaysMatch = overlayCompatibility; found = true; } } if (!found) ccSettings.Add(new CrossCompatibilityData(thisRacesSlot, compatibleRacesSlot, overlayCompatibility)); } } [System.Serializable] protected class CrossCompatibilitySettingsList { public List<CrossCompatibilitySettings> settingsData = new List<CrossCompatibilitySettings>(); public bool Contains(string crossCompatibleRace) { for (int i = 0; i < settingsData.Count; i++) { if (settingsData[i].ccRace == crossCompatibleRace) return true; } return false; } public void Add(string crossCompatibleRace) { if (!Contains(crossCompatibleRace)) settingsData.Add(new CrossCompatibilitySettings(crossCompatibleRace)); } public void Remove(List<string> races) { for (int i = 0; i < races.Count; i++) Remove(races[i]); } public void Remove(string crossCompatibleRace) { int removeAt = -1; for (int i = 0; i < settingsData.Count; i++) { if (settingsData[i].ccRace == crossCompatibleRace) removeAt = i; } if (removeAt > -1) settingsData.RemoveAt(removeAt); } } //Race Thumbnails used in the GUI to give a visual representation of the race [System.Serializable] public class RaceThumbnails { [System.Serializable] public class WardrobeSlotThumb { [Tooltip("A comma separated list of wardrobe slots this is the base thumbnail for (no spaces)")] public string thumbIsFor = ""; public Sprite thumb = null; } public Sprite fullThumb = null; public Sprite faceThumb = null; [SerializeField] List<WardrobeSlotThumb> wardrobeSlotThumbs = new List<WardrobeSlotThumb>(); public Sprite GetThumbFor(string thumbToGet = "") { Sprite foundSprite = fullThumb != null ? fullThumb : null; foreach(WardrobeSlotThumb wardrobeThumb in wardrobeSlotThumbs) { string[] thumbIsForArray = null; wardrobeThumb.thumbIsFor.Replace(" ,", ",").Replace(", ", ","); if (wardrobeThumb.thumbIsFor.IndexOf(",") == -1) { thumbIsForArray = new string[1] { wardrobeThumb.thumbIsFor }; } else { thumbIsForArray = wardrobeThumb.thumbIsFor.Split(new string[1] { "," }, StringSplitOptions.RemoveEmptyEntries); } foreach(string thumbFor in thumbIsForArray) { if (thumbFor == thumbToGet) { foundSprite = wardrobeThumb.thumb; break; } } } return foundSprite; } } #endregion } }
//ybzuo-dena using UnityEngine; using System.Collections.Generic; public class N2Avatar { //quick public N2Avatar(GameObject _root,bool _only_ui) { m_go = GameCore.UIHandler.Instance.GetUnitInstance("Player"); m_avatar_unit=new AvatarUnit(m_go.transform); m_avatar_unit.QuickSet(_only_ui); InitBase(_root); } public N2Avatar(int _card_id, List<int> _mode_list, GameObject _root, GameObject player, int _team_id, bool _home) { m_go = player == null ? GameCore.UIHandler.Instance.GetUnitInstance("Player") : player; m_avatar_unit = new AvatarUnit(m_go.transform); m_avatar_unit.SetInfo(_card_id, _mode_list, _team_id, _home, false); InitBase(_root); } void InitBase(GameObject _root) { m_go.transform.parent=_root.transform; m_yingzi=m_go.transform.FindChild("shadow_yingzi").gameObject; m_yingzi.transform.parent=m_go.transform.parent; InitAvatarUnit(); } void InitAvatarUnit() { m_root=m_avatar_unit.GetGameObject(); m_root.transform.parent=m_go.transform; m_ani = m_go.GetComponentInChildren<Animation> (); m_right_hand = m_go.transform.Find ("Avatar/Bip001/Bip001 Prop1"); m_ball_trans=m_right_hand.Find("ball"); m_head_trans=m_go.transform.Find("Avatar/Bip001/Bip001 Pelvis/Bip001 Spine/Bip001 Spine1/Bip001 Neck/Bip001 Head"); } //Init Ani public void Init() { // if(m_ani.GetClipCount()!=N2AniDataBank.GetSingle().GetAniDataList().Count) // { // //ani not match // for(int i=0;i<N2AniDataBank.GetSingle().GetAniDataList().Count;++i) // { // string _ani_name=N2AniDataBank.GetSingle().GetAniDataList()[i].base_info.name; // if(m_ani.GetClip(_ani_name)==null) // { // Debug.LogWarning(_ani_name+" Clip is Not Find"); // } // } // } // List<N2AniData> aniDataList = N2AniDataBank.GetSingle().GetAniDataList(); // int count = aniDataList.Count; // for(int i=0;i<count;++i) // { // m_ani_list.Add(new N2Ani(aniDataList[i], m_ani, m_root, m_ball_trans)); // } // init_base (); } public void ChangeCard(int _card_id) { string _ani=m_current_ani.get_name(); m_avatar_unit.ChangeCard(_card_id); InitAvatarUnit(); Reset(m_ani); Play(_ani); } public void ChangeCloth(int _team_id,bool _home) { m_avatar_unit.ChangeCloth(_team_id,_home); } public GameObject get_go() { return m_go; } public GameObject get_avatar_go() { return m_avatar_unit.GetGameObject(); } public GameObject get_model_go() { return m_avatar_unit.GetAvatarBip(); } void Refresh() { } public void ShowMode(bool _full) { m_full_mode=_full; m_avatar_unit.ShowMode(_full); Refresh(); } public void Reset(Animation _ani) { m_ani=_ani; m_ani_name_list.Clear(); m_ani_list.Clear(); Init(); m_current_ani=null; } public void UpdateSingle(string _ani_name,N2AniData _ae) { foreach(N2Ani _ani in m_ani_list) { if(_ani.get_name()==_ani_name) { _ani.Adjust(_ani_name); break; } } } public void InitUpdate(Dictionary<string,N2AniData> _dic) { foreach(KeyValuePair<string,N2AniData> _kv in _dic) { bool _hit=false; foreach(N2Ani _ani in m_ani_list) { if(_ani.get_name()==_kv.Key) { _hit=true; break; } } if(!_hit) { N2Ani _ani= add_other_ani(_kv.Key); if(_ani!=null) { _ani.Adjust(_kv.Key); } } } init_base (); } bool m_need_refresh=false; N2Ani add_other_ani(string _ani) { foreach (N2Ani _aa in m_ani_list) { if(_aa.get_name()==_ani) { return null; } } N2AniData _data=new N2AniData(); Debug.Log(_ani); // _data.base_info = NewStaticDataExtern.GetSingle().m_AniData_dic[_ani]; N2Ani _a = new N2Ani (_data, m_ani,m_root,m_ball_trans); _a.set_info(); m_ani_list.Add (_a); return _a; } void init_base() { m_ani_name_list.Clear(); foreach (N2Ani _aa in m_ani_list) { m_ani_name_list.Add(_aa.get_name()); } foreach (N2Ani _ani in m_ani_list) { _ani.bound_ball(m_ball); } m_current_ani = m_ani_list[0]; // m_current_ani.focus (); } public void Play (string _ani,bool _imp=true) { if(!m_ani_name_list.Contains(_ani)) { Debug.LogWarning("Ani:"+_ani+" is not in AniConfig.txt!"); return; } RealPlay(_ani, _imp); } public bool GetCurrentAniState(out EHitState state) { state = EHitState.EBeforeHitBegin; if (m_current_ani != null) { state = m_current_ani.GetHitState(); return true; } return false; } void RealPlay(string _ani,bool _imp) { for(int i=0;i<m_ani_name_list.Count;++i) { if(m_ani_name_list[i]==_ani) { m_current_ani=m_ani_list[i]; } } // Debug.Log(m_current_ani.get_name()); switch_step_mode(m_step_mode); m_current_ani.bound_ball(m_ball); //m_current_ani.ReadyToPlay(_imp); // _imp=m_current_ani.get_raw_data().base_info.ball==1; if(_imp) { m_ani.Play(_ani); } else { //m_ani.Play(_ani); m_ani.CrossFade(_ani); } } public void play_current () { switch_step_mode(m_step_mode); m_current_ani.bound_ball(m_ball); m_ani.Play (m_current_ani.get_name ()); } public void set_pos(Vector3 _pos) { m_go.transform.position=NField.phy_pos_to_real_pos(_pos); } public void set_rotate(Quaternion _qua) { m_go.transform.rotation=_qua; } public void set_scale(Vector3 _scale) { //for debug //_scale=Vector3.one; m_go.transform.localScale=_scale; foreach(N2Ani _ani in m_ani_list) { _ani.set_scale(_scale); } } public List<string> get_ani_name_list () { return m_ani_name_list; } public void update (float _dtime,float scale) { if(m_current_ani!=null) { m_current_ani.update(_dtime, scale); } m_yingzi.transform.position=m_go.transform.position+new Vector3(0.0f,0.2f,0.0f); } public Vector3 get_right_hand_pos() { return m_right_hand.transform.position; } public void switch_step_mode () { m_step_mode = !m_step_mode; m_current_ani.switch_step_mode (m_step_mode); } public void switch_step_mode(bool _mode) { m_step_mode=_mode; m_current_ani.switch_step_mode (m_step_mode); } public void take_ball (NBall _ball) { if (_ball != null) { m_ball = _ball.get_go(); if (m_ball != null && m_go != null) { m_ball.transform.parent = m_go.transform; if (m_current_ani != null) { m_current_ani.bound_ball(m_ball); } } } if (m_ball) m_ball.SetActive(true); } public void lose_ball() { if(m_ball!=null) { Vector3 _pos=m_ball.transform.position; m_ball.transform.parent=null; m_ball.transform.position=_pos; m_ball=null; } if(m_current_ani!=null) { m_current_ani.bound_ball(m_ball); } //reset_idle(); } // public void reset_idle() // { // if(m_ball==null) // { // if(m_run) // { // Play("run_b",true); // } // else if(m_attack) // { // Play("stand",true); // } // else // { // Play("Defencetoball",true); // } // } // else // { // if(m_run) // { // Play("dribblefast_r",true); // } // else // { // Play("BallIdle",true); // } // } // } public N2Ani get_current_ani() { return m_current_ani; } public void face_look(Vector3 _pos,float _dtime) { if(_pos.y<m_head_trans.transform.position.y) { _pos.y=m_head_trans.transform.position.y; } Quaternion _rot=m_head_trans.transform.rotation; Quaternion _local_rot=m_head_trans.transform.localRotation; Vector3 _dir=_pos-m_head_trans.transform.position; _dir.Normalize(); Quaternion _adjust_rot=Quaternion.LookRotation(_dir)*Quaternion.Euler(m_face_look_adjust_vec); float _angle=Quaternion.Angle(_rot,_adjust_rot); // Debug.Log(_angle); if(_angle>35.0f) { if(m_ball_free) { m_head_trans.localRotation=m_last_head_rot; }else { if(m_head_roate_tick==-1.0f) { m_head_roate_tick=mc_head_roate_time; m_head_focus_tick=-1.0f; m_head_trans.transform.localRotation=m_last_head_rot; }else if(m_head_roate_tick>0.0f) { m_head_roate_tick-=_dtime; if(m_head_roate_tick<=0.0f) { m_head_roate_tick=-2.0f; } else { m_head_trans.transform.localRotation=Quaternion.Slerp(m_last_head_rot,_local_rot,1.0f-m_head_roate_tick/mc_head_roate_time); } } } } else { //m_last_head_rot=m_head_trans.transform.rotation=_adjust_rot; if(m_head_focus_tick==-1.0f) { m_head_focus_tick=mc_head_roate_time; m_head_roate_tick=-1.0f; } else if(m_head_focus_tick>0.0f) { m_head_focus_tick-=_dtime; if(m_head_focus_tick<=0.0f) { m_head_focus_tick=-2.0f; } else { m_head_trans.transform.rotation=Quaternion.Slerp(_rot,_adjust_rot,1.0f-m_head_focus_tick/mc_head_roate_time); } } else { m_head_trans.transform.rotation=_adjust_rot; m_last_head_rot=m_head_trans.transform.localRotation; } } } public void SetBallFree(bool _free) { m_ball_free=_free; } public void Release() { // Debug.Log("xxxx"); m_avatar_unit.Release(); GameObject.Destroy(m_yingzi); GameObject.Destroy(m_go); } public void SwitchRender(bool _render) { m_go.SetActive(_render); m_yingzi.SetActive(_render); } Vector3 m_face_look_adjust_vec=new Vector3(0,-90,-90); //Vector3 m_face_look_adjust_vec=Vector3.zero; GameObject m_go; GameObject m_root; GameObject m_ball; Animation m_ani; N2AvatarData m_avatar_data; bool m_step_mode = false; bool m_ball_free=true; N2Ani m_current_ani; List<N2Ani> m_ani_list = new List<N2Ani> (); List<string> m_ani_name_list = new List<string> (); Transform m_right_hand; Transform m_ball_trans; AvatarUnit m_avatar_unit; float m_speed=1.0f; Transform m_head_trans; Quaternion m_last_head_rot; float m_head_roate_tick=-1.0f; const float mc_head_roate_time=0.5f; float m_head_focus_tick=-1.0f; GameObject m_yingzi; bool m_full_mode=true; //bool m_in_edit=false; }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Text.RegularExpressions; using Banshee.Base; using Banshee.MediaEngine; using Banshee.Sources; using Banshee.Configuration.Schema; using Banshee.Plugins; using Banshee.Winforms; using Banshee.Base.Winforms.Widgets; using ComponentFactory.Krypton.Toolkit; namespace Banshee { public partial class MainForm : ComponentFactory.Krypton.Toolkit.KryptonForm { Banshee.Base.Gui.SourceView sourceView = null; private SeekSlider seek_slider = null; private StreamPositionLabel stream_position_label = null; public MainForm() { InitializeComponent(); SuspendLayout(); InitSystem(); playlistModel.Source.Updated += new EventHandler(Source_Updated); playlistModel.Source.Cleared += new EventHandler(Source_Cleared); ResumeLayout(); } private enum SearchTrackCriteria { Artist, Album, Genre } void Source_Cleared(object sender, EventArgs e) { this.UpdateStatusBar(); } void Source_Updated(object sender, EventArgs e) { this.UpdateStatusBar(); } void PlaceSearch() { searchEntry.Parent = mainHeader; searchEntry.Left = mainHeader.Width - searchEntry.Width - 5; searchEntry.Top = (mainHeader.Height - searchEntry.Height) / 2; searchEntry.Anchor = AnchorStyles.Top | AnchorStyles.Right; } int sourceViewWidth = 235; void InitSystem() { LogCore.PrintEntries = true; Globals.Initialize(); Globals.StartupInitializer.Run(); LoadColumns(); Globals.ShutdownRequested += new ShutdownRequestHandler(Globals_ShutdownRequested); SourceManager.ActiveSourceChanged += new SourceEventHandler(SourceManager_ActiveSourceChanged); trackSourceBindingSource.DataSource = playlistModel.Source; sourceView = new Banshee.Base.Gui.SourceView(); libraryGroup.Panel.Controls.Add(sourceView); sourceView.Dock = DockStyle.Fill; PlayerEngineCore.StateChanged += new PlayerEngineStateHandler(PlayerEngineCore_StateChanged); PlayerEngineCore.EventChanged += new PlayerEngineEventHandler(PlayerEngineCore_EventChanged); Banshee.Winforms.Controls.ActiveUserEventsManager event_manager = new Banshee.Winforms.Controls.ActiveUserEventsManager(); event_panel.Controls.Add(event_manager); event_manager.Dock = DockStyle.Fill; seek_slider = new SeekSlider(); seek_slider.Dock = DockStyle.Fill; seek_slider.SetIdle(); stream_position_label = new StreamPositionLabel(seek_slider); stream_position_label.Dock = DockStyle.Bottom; seekpanel.Controls.Add(stream_position_label); seekpanel.Controls.Add(seek_slider); playlistModel.Repeat = RepeatMode.All; this.Text = ApplicationLongName; PlaceSearch(); TogglePlugPanel(); KryptonManager.GlobalPaletteChanged += new EventHandler(KryptonManager_GlobalPaletteChanged); StartupComplete(); } void KryptonManager_GlobalPaletteChanged(object sender, EventArgs e) { Color back = KryptonManager.CurrentGlobalPalette.GetBackColor1(PaletteBackStyle.PanelClient, PaletteState.Normal); seek_slider.ViewColor = back; } void PlayerEngineCore_EventChanged(object o, PlayerEngineEventArgs args) { switch (args.Event) { case PlayerEngineEvent.Iterate: OnPlayerEngineTick(); break; case PlayerEngineEvent.Seek: break; case PlayerEngineEvent.Error: break; case PlayerEngineEvent.Metadata: break; case PlayerEngineEvent.StartOfStream: UpdateMetaDisplay(); OnPlayerEngineTick(); break; case PlayerEngineEvent.EndOfStream: if (playlistModel.Repeat != RepeatMode.All || playlistModel.Repeat != RepeatMode.ErrorHalt) { playlistModel.ChangeDirection(true); trackGrid.FirstDisplayedScrollingRowIndex = playlistModel.Current_index; } break; case PlayerEngineEvent.Volume: break; case PlayerEngineEvent.Buffering: break; case PlayerEngineEvent.TrackInfoUpdated: break; } } public string ApplicationLongName { get { return Catalog.GetString("Banshee Music Player"); } } public void UpdateMetaDisplay() { TrackInfo track = PlayerEngineCore.CurrentTrack; if (track == null) { this.Text = ApplicationLongName; trackInfoHeader.Visible = false; cover_art_view.FileName = null; cover_art_view.BorderStyle = BorderStyle.None; //trackInfoHeader.Cover.Image = Properties.Resources.editor_cover_album; return; } trackInfoHeader.Artist = track.DisplayArtist; trackInfoHeader.Title = track.DisplayTitle; trackInfoHeader.Album = track.Album; trackInfoHeader.MoreInfoUri = track.MoreInfoUri != null ? track.MoreInfoUri.AbsoluteUri : null; trackInfoHeader.Visible = true; this.Text = track.DisplayTitle + ((track.Artist != null && track.Artist != String.Empty) ? (" (" + track.DisplayArtist + ")") : ""); try { trackInfoHeader.FileName = track.CoverArtFileName; cover_art_view.FileName = track.CoverArtFileName; trackInfoHeader.Label = String.Format("{0} - {1}", track.DisplayArtist, track.DisplayAlbum); cover_art_view.Enabled = false; } catch (Exception) { } } void PlayerEngineCore_StateChanged(object o, PlayerEngineStateArgs args) { switch (args.State) { case PlayerEngineState.Idle: break; case PlayerEngineState.Contacting: break; case PlayerEngineState.Loaded: break; case PlayerEngineState.Playing: UpdateMetaDisplay(); break; case PlayerEngineState.Paused: break; default: break; } } void SourceManager_ActiveSourceChanged(SourceEventArgs args) { playlistModel.Source.Reload(); } void StartupComplete() { Application.DoEvents(); if (Globals.Library.IsLoaded) { Library_Reloaded(Globals.Library, new EventArgs()); } else { Globals.Library.Reloaded += new EventHandler(Library_Reloaded); } Application.DoEvents(); } void Library_Reloaded(object sender, EventArgs e) { if (this.Handle == IntPtr.Zero) { BeginInvoke((MethodInvoker)delegate() { if (Globals.Library.Tracks.Count <= 0) { PromptForImport(); } else { UpdateStatusBar(); sourceView.RefreshList(); } }); } else { if (Globals.Library.Tracks.Count <= 0) { PromptForImport(); } else { SuspendLayout(); UpdateStatusBar(); sourceView.RefreshList(); ResumeLayout(); } } } private void PromptForImport() { PromptForImport(true); } private void PromptForImport(bool startup) { bool show_dialog = System.Convert.ToBoolean(ImportSchema.ShowInitialImportDialog.Get()); if (startup && !show_dialog) { return; } Banshee.Winforms.ImportDialog dialog = new Banshee.Winforms.ImportDialog(); dialog.DoNotShowAgain = (bool)ImportSchema.ShowInitialImportDialog.Get(); DialogResult dr = dialog.ShowDialog(this); if (dr != DialogResult.OK) return; else { IImportSource import_source = dialog.ActiveSource; if (import_source != null) { import_source.Import(); } } if (startup) { ImportSchema.ShowInitialImportDialog.Set(!dialog.DoNotShowAgain); } } bool Globals_ShutdownRequested() { //throw new Exception("The method or operation is not implemented."); return true; } private void MainForm_Load(object sender, EventArgs e) { SuspendLayout(); SourceManager.SetActiveSource(LibrarySource.Instance); UpdateStatusBar(); //Color back = .GlobalPalette.GetBackColor1(ComponentFactory.Krypton.Toolkit.PaletteBackStyle.PanelClient, ComponentFactory.Krypton.Toolkit.PaletteState.Normal); //seek_slider.ViewColor = back; ResumeLayout(); Banshee.Controls.SplashScreen.CloseForm(); this.BringToFront(); } private void MainForm_Resize(object sender, EventArgs e) { if (!libraryGroup.Collapsed) { mainSplitter.SplitterDistance = sourceViewWidth; } } private void UpdateStatusBar() { long count = playlistModel.Source.Tracks.Count; if (count == 0 && SourceManager.ActiveSource == null) { LabelStatusBar.Text = ApplicationLongName; return; } else if (count == 0) { LabelStatusBar.Text = String.Empty; return; } TimeSpan span = playlistModel.Source.TotalDuration; StringBuilder builder = new StringBuilder(); builder.AppendFormat("{0} Items", count); builder.Append(", "); if (span.Days > 0) { builder.AppendFormat("{0} days", span.Days); builder.Append(", "); } if (span.Hours > 0) { builder.AppendFormat("{0} hours", span.Hours); builder.Append(", "); } builder.AppendFormat("{0} minutes", span.Minutes); builder.Append(", "); builder.AppendFormat("{0} seconds", span.Seconds); LabelStatusBar.Text = builder.ToString(); mainHeader.Text = SourceManager.ActiveSource.Name; } private bool incrementedCurrentSongPlayCount; private void OnPlayerEngineTick() { seekpanel.BeginInvoke((MethodInvoker)delegate() { uint stream_length = PlayerEngineCore.Length; uint stream_position = PlayerEngineCore.Position; stream_position_label.IsContacting = false; seek_slider.CanSeek = PlayerEngineCore.CanSeek; Console.WriteLine(PlayerEngineCore.Position); seek_slider.Duration = stream_length; seek_slider.SeekValue = stream_position; seek_slider.Value = Convert.ToInt32(stream_position); if (PlayerEngineCore.CurrentTrack == null) { return; } if (stream_length > 0 && PlayerEngineCore.CurrentTrack.Duration.TotalSeconds != (double)stream_length) { PlayerEngineCore.CurrentTrack.Duration = new TimeSpan(stream_length * TimeSpan.TicksPerSecond); PlayerEngineCore.CurrentTrack.Save(); } if (stream_length > 0 && stream_position > stream_length / 2 && !incrementedCurrentSongPlayCount) { PlayerEngineCore.CurrentTrack.IncrementPlayCount(); incrementedCurrentSongPlayCount = true; } }); } private void trackGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex > 0) { string uri = trackGrid[uriDataGridViewTextBoxColumn.Index, e.RowIndex].Value.ToString(); TrackInfo track = playlistModel.Source.Tracks[e.RowIndex]; playlistModel.PlayTrack(track); playlistModel.Current_index = e.RowIndex; } } private int _widthLeftRight; private void libraryCollapseBtn_Click(object sender, EventArgs e) { this.mainSplitter.SuspendLayout(); if (this.mainSplitter.FixedPanel == FixedPanel.None) { this.mainSplitter.FixedPanel = FixedPanel.Panel1; this.mainSplitter.IsSplitterFixed = true; _widthLeftRight = libraryGroup.Width; int newWidth = libraryGroup.PreferredSize.Height; this.mainSplitter.Panel1MinSize = newWidth; this.mainSplitter.SplitterDistance = newWidth; libraryGroup.HeaderPositionPrimary = VisualOrientation.Right; libraryGroup.ButtonSpecs[0].Edge = PaletteRelativeEdgeAlign.Near; } else { this.mainSplitter.FixedPanel = FixedPanel.None; this.mainSplitter.IsSplitterFixed = false; this.mainSplitter.Panel1MinSize = 100; this.mainSplitter.SplitterDistance = _widthLeftRight; libraryGroup.HeaderPositionPrimary = VisualOrientation.Top; libraryGroup.ButtonSpecs[0].Edge = PaletteRelativeEdgeAlign.Far; } this.mainSplitter.ResumeLayout(); } int _heightUpDown; void TogglePlugPanel() { if (plugPlaySplitter.FixedPanel == FixedPanel.None) { plugPlaySplitter.FixedPanel = FixedPanel.Panel2; plugPlaySplitter.IsSplitterFixed = true; _heightUpDown = pluginGroup.Height; int newHeight = pluginGroup.PreferredSize.Height; plugPlaySplitter.Panel2MinSize = newHeight; plugPlaySplitter.SplitterDistance = plugPlaySplitter.Height; } else { plugPlaySplitter.FixedPanel = FixedPanel.None; plugPlaySplitter.IsSplitterFixed = false; plugPlaySplitter.Panel2MinSize = 100; plugPlaySplitter.SplitterDistance = plugPlaySplitter.Height - _heightUpDown - plugPlaySplitter.SplitterWidth; } } private void btnFwd_Click(object sender, EventArgs e) { playlistModel.ChangeDirection(true); } private void btnPrev_Click(object sender, EventArgs e) { playlistModel.ChangeDirection(false); } private void btnPlayPause_Click(object sender, EventArgs e) { if (PlayerEngineCore.CurrentState == PlayerEngineState.Playing) { PlayerEngineCore.Pause(); } else if (PlayerEngineCore.CurrentState == PlayerEngineState.Paused || PlayerEngineCore.CurrentState == PlayerEngineState.Idle) { PlayerEngineCore.Play(); } } public void LoadColumns() { for (int i = 0; i < trackGrid.Columns.Count; i++) { DataGridViewColumn col = trackGrid.Columns[i]; if (col.HeaderText == "Title") col.Visible = TitleVisibleSchema.Get(); else if (col.HeaderText == "Artist") col.Visible = ArtistVisibleSchema.Get(); else if (col.HeaderText == "Album") col.Visible = AlbumVisibleSchema.Get(); else if (col.HeaderText == "Genre") col.Visible = GenreVisibleSchema.Get(); else if (col.HeaderText == "Time") col.Visible = TimeVisibleSchema.Get(); else if (col.HeaderText == "Year") col.Visible = YearVisibleSchema.Get(); else if (col.HeaderText == "Track") col.Visible = TrackVisibleSchema.Get(); else if (col.HeaderText == "Last Played") col.Visible = LastPlayVisibleSchema.Get(); else if (col.HeaderText == "Rating") col.Visible = RatingVisibleSchema.Get(); else if (col.HeaderText == "Plays") col.Visible = PlayCountVisibleSchema.Get(); } } #region Column Schemas public static Banshee.Configuration.SchemaEntry<bool> year_schema = new Banshee.Configuration.SchemaEntry<bool>( "view_columns", "yearvisible", false, "Visiblity", "Visibility of Year column" ); protected Banshee.Configuration.SchemaEntry<bool> YearVisibleSchema { get { return year_schema; } } public static Banshee.Configuration.SchemaEntry<bool> title_schema = new Banshee.Configuration.SchemaEntry<bool>( "view_columns", "titlevisible", true, "Visiblity", "Visibility of Title column" ); protected Banshee.Configuration.SchemaEntry<bool> TitleVisibleSchema { get { return title_schema; } } public static Banshee.Configuration.SchemaEntry<bool> artist_schema = new Banshee.Configuration.SchemaEntry<bool>( "view_columns", "artistvisible", true, "Visiblity", "Visibility of Artist column" ); protected Banshee.Configuration.SchemaEntry<bool> ArtistVisibleSchema { get { return artist_schema; } } public static Banshee.Configuration.SchemaEntry<bool> album_schema = new Banshee.Configuration.SchemaEntry<bool>( "view_columns", "albumvisible", true, "Visiblity", "Visibility of Album column" ); protected Banshee.Configuration.SchemaEntry<bool> AlbumVisibleSchema { get { return album_schema; } } public static Banshee.Configuration.SchemaEntry<bool> genre_schema = new Banshee.Configuration.SchemaEntry<bool>( "view_columns", "genrevisible", false, "Visiblity", "Visibility of Genre column" ); protected Banshee.Configuration.SchemaEntry<bool> GenreVisibleSchema { get { return genre_schema; } } public static Banshee.Configuration.SchemaEntry<bool> tracknumber_schema = new Banshee.Configuration.SchemaEntry<bool>( "view_columns", "tracknumbervisible", true, "Visiblity", "Visibility of Track Number column" ); protected Banshee.Configuration.SchemaEntry<bool> TrackVisibleSchema { get { return tracknumber_schema; } } public static Banshee.Configuration.SchemaEntry<bool> time_schema = new Banshee.Configuration.SchemaEntry<bool>( "view_columns", "durationvisible", true, "Visiblity", "Visibility of Duration column" ); protected Banshee.Configuration.SchemaEntry<bool> TimeVisibleSchema { get { return time_schema; } } public static Banshee.Configuration.SchemaEntry<bool> lastplay_schema = new Banshee.Configuration.SchemaEntry<bool>( "view_columns", "lastplayvisible", false, "Visiblity", "Visibility of Track Number column" ); protected Banshee.Configuration.SchemaEntry<bool> LastPlayVisibleSchema { get { return lastplay_schema; } } public static Banshee.Configuration.SchemaEntry<bool> playcount_schema = new Banshee.Configuration.SchemaEntry<bool>( "view_columns", "playcountvisible", false, "Visiblity", "Visibility of Play Count column" ); protected Banshee.Configuration.SchemaEntry<bool> PlayCountVisibleSchema { get { return playcount_schema; } } public static Banshee.Configuration.SchemaEntry<bool> rating_schema = new Banshee.Configuration.SchemaEntry<bool>( "view_columns", "ratingvisible", false, "Visiblity", "Visibility of Rating column" ); protected Banshee.Configuration.SchemaEntry<bool> RatingVisibleSchema { get { return rating_schema; } } #endregion private void quitToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } TrackInfo PathTreeInfo(string path) { TrackInfo pathtrackinfo = null; foreach (TrackInfo track in SourceManager.ActiveSource.Tracks) { if (track.Uri.ToString() == path) { pathtrackinfo = track; break; } } return pathtrackinfo; } public IList<TrackInfo> SelectedTrackInfoMultiple { get { if (trackGrid.SelectedRows.Count == 0) { return null; } List<TrackInfo> list = new List<TrackInfo>(); foreach (DataGridViewRow row in trackGrid.SelectedRows) { string uri = row.Cells[uriDataGridViewTextBoxColumn.Index].Value.ToString(); list.Add(PathTreeInfo(uri)); } return list; } } private void SearchBySelectedTrack(SearchTrackCriteria criteria) { TrackInfo track = playlistModel.Selected_track; if (track == null) { return; } // suspend the search functionality (for performance reasons) suspendSearch = true; switch (criteria) { case SearchTrackCriteria.Album: this.searchEntry.Field = Catalog.GetString("Album Title"); searchEntry.Query = track.Album; break; case SearchTrackCriteria.Artist: searchEntry.Field = Catalog.GetString("Artist Name"); searchEntry.Query = track.Artist; break; case SearchTrackCriteria.Genre: searchEntry.Field = Catalog.GetString("Genre"); searchEntry.Query = track.Genre; break; } suspendSearch = false; OnSimpleSearch(this, null); } private bool suspendSearch; private void OnSimpleSearch(object o, EventArgs args) { //Cornel - I found the BackgroundWorker gives me the most responsive UI UpdateViewName(SourceManager.ActiveSource, "Searching..."); SourceManager.ActiveSource.FilterField = searchEntry.Field; SourceManager.ActiveSource.FilterQuery = searchEntry.Query; Source source = SourceManager.ActiveSource; Source searchResult = new PlaylistSource(); if (SourceManager.ActiveSource.HandlesSearch) { return; } if (suspendSearch) { return; } if (!searchEntry.IsQueryAvailable) { playlistModel.Source.Reload(); return; } lock (SourceManager.ActiveSource.TracksMutex) { foreach (TrackInfo track in SourceManager.ActiveSource.Tracks) { try { if (DoesTrackMatchSearch(track)) { searchResult.AddTrack(track); } } catch (Exception) { continue; } } playlistModel.Source.SetCustomSource(searchResult); } } private void UpdateViewName(Source source, string info) { this.mainHeader.Text = string.Format("{0} {1}", source.Name, info); } private bool DoesTrackMatchSearch(TrackInfo ti) { if (!searchEntry.IsQueryAvailable) { return false; } string query = searchEntry.Query; string field = searchEntry.Field; string[] matches; if (field == Catalog.GetString("Artist Name")) { matches = new string[] { ti.Artist }; } else if (field == Catalog.GetString("Song Name")) { matches = new string[] { ti.Title }; } else if (field == Catalog.GetString("Album Title")) { matches = new string[] { ti.Album }; } else if (field == Catalog.GetString("Genre")) { matches = new string[] { ti.Genre }; } else if (field == Catalog.GetString("Year")) { matches = new string[] { ti.Year.ToString() }; } else { matches = new string[] { ti.Artist, ti.Album, ti.Title, ti.Genre, ti.Year.ToString() }; } List<string> words_include = new List<string>(); List<string> words_exclude = new List<string>(); Array.ForEach<string>(Regex.Split(query, @"\s+"), delegate(string word) { bool exclude = word.StartsWith("-"); if (exclude && word.Length > 1) { words_exclude.Add(word.Substring(1)); } else if (!exclude) { words_include.Add(word); } }); foreach (string word in words_exclude) { foreach (string match in matches) { if (match == null || match == String.Empty) { continue; } if (StringUtil.RelaxedIndexOf(match, word) >= 0) { return false; } } } bool found; foreach (string word in words_include) { found = false; foreach (string match in matches) { if (match == null || match == string.Empty) { continue; } if (StringUtil.RelaxedIndexOf(match, word) >= 0) { found = true; break; } } if (!found) { return false; } } return true; } private void song_properties_button_Click(object sender, EventArgs e) { Banshee.Base.Gui.Dialogs.TrackEditor propEdit = new Banshee.Base.Gui.Dialogs.TrackEditor(SelectedTrackInfoMultiple); propEdit.ShowDialog(this); } private void searchEntry_Changed(object sender, EventArgs e) { OnSimpleSearch(this, null); UpdateViewName(SourceManager.ActiveSource, "Searching"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Threading; namespace System.Net.Mime { internal class MimeMultiPart : MimeBasePart { private Collection<MimeBasePart> _parts; private static int s_boundary; private AsyncCallback _mimePartSentCallback; private bool _allowUnicode; internal MimeMultiPart(MimeMultiPartType type) { MimeMultiPartType = type; } internal MimeMultiPartType MimeMultiPartType { set { if (value > MimeMultiPartType.Related || value < MimeMultiPartType.Mixed) { throw new NotSupportedException(value.ToString()); } SetType(value); } } private void SetType(MimeMultiPartType type) { ContentType.MediaType = "multipart" + "/" + type.ToString().ToLower(CultureInfo.InvariantCulture); ContentType.Boundary = GetNextBoundary(); } internal Collection<MimeBasePart> Parts { get { if (_parts == null) { _parts = new Collection<MimeBasePart>(); } return _parts; } } internal void Complete(IAsyncResult result, Exception e) { //if we already completed and we got called again, //it mean's that there was an exception in the callback and we //should just rethrow it. MimePartContext context = (MimePartContext)result.AsyncState; if (context._completed) { throw e; } try { context._outputStream.Close(); } catch (Exception ex) { if (e == null) { e = ex; } } context._completed = true; context._result.InvokeCallback(e); } internal void MimeWriterCloseCallback(IAsyncResult result) { if (result.CompletedSynchronously) { return; } ((MimePartContext)result.AsyncState)._completedSynchronously = false; try { MimeWriterCloseCallbackHandler(result); } catch (Exception e) { Complete(result, e); } } private void MimeWriterCloseCallbackHandler(IAsyncResult result) { MimePartContext context = (MimePartContext)result.AsyncState; ((MimeWriter)context._writer).EndClose(result); Complete(result, null); } internal void MimePartSentCallback(IAsyncResult result) { if (result.CompletedSynchronously) { return; } ((MimePartContext)result.AsyncState)._completedSynchronously = false; try { MimePartSentCallbackHandler(result); } catch (Exception e) { Complete(result, e); } } private void MimePartSentCallbackHandler(IAsyncResult result) { MimePartContext context = (MimePartContext)result.AsyncState; MimeBasePart part = (MimeBasePart)context._partsEnumerator.Current; part.EndSend(result); if (context._partsEnumerator.MoveNext()) { part = (MimeBasePart)context._partsEnumerator.Current; IAsyncResult sendResult = part.BeginSend(context._writer, _mimePartSentCallback, _allowUnicode, context); if (sendResult.CompletedSynchronously) { MimePartSentCallbackHandler(sendResult); } return; } else { IAsyncResult closeResult = ((MimeWriter)context._writer).BeginClose(new AsyncCallback(MimeWriterCloseCallback), context); if (closeResult.CompletedSynchronously) { MimeWriterCloseCallbackHandler(closeResult); } } } internal void ContentStreamCallback(IAsyncResult result) { if (result.CompletedSynchronously) { return; } ((MimePartContext)result.AsyncState)._completedSynchronously = false; try { ContentStreamCallbackHandler(result); } catch (Exception e) { Complete(result, e); } } private void ContentStreamCallbackHandler(IAsyncResult result) { MimePartContext context = (MimePartContext)result.AsyncState; context._outputStream = context._writer.EndGetContentStream(result); context._writer = new MimeWriter(context._outputStream, ContentType.Boundary); if (context._partsEnumerator.MoveNext()) { MimeBasePart part = (MimeBasePart)context._partsEnumerator.Current; _mimePartSentCallback = new AsyncCallback(MimePartSentCallback); IAsyncResult sendResult = part.BeginSend(context._writer, _mimePartSentCallback, _allowUnicode, context); if (sendResult.CompletedSynchronously) { MimePartSentCallbackHandler(sendResult); } return; } else { IAsyncResult closeResult = ((MimeWriter)context._writer).BeginClose(new AsyncCallback(MimeWriterCloseCallback), context); if (closeResult.CompletedSynchronously) { MimeWriterCloseCallbackHandler(closeResult); } } } internal override IAsyncResult BeginSend(BaseWriter writer, AsyncCallback callback, bool allowUnicode, object state) { _allowUnicode = allowUnicode; PrepareHeaders(allowUnicode); writer.WriteHeaders(Headers, allowUnicode); MimePartAsyncResult result = new MimePartAsyncResult(this, state, callback); MimePartContext context = new MimePartContext(writer, result, Parts.GetEnumerator()); IAsyncResult contentResult = writer.BeginGetContentStream(new AsyncCallback(ContentStreamCallback), context); if (contentResult.CompletedSynchronously) { ContentStreamCallbackHandler(contentResult); } return result; } internal class MimePartContext { internal MimePartContext(BaseWriter writer, LazyAsyncResult result, IEnumerator<MimeBasePart> partsEnumerator) { _writer = writer; _result = result; _partsEnumerator = partsEnumerator; } internal IEnumerator<MimeBasePart> _partsEnumerator; internal Stream _outputStream; internal LazyAsyncResult _result; internal BaseWriter _writer; internal bool _completed; internal bool _completedSynchronously = true; } internal override void Send(BaseWriter writer, bool allowUnicode) { PrepareHeaders(allowUnicode); writer.WriteHeaders(Headers, allowUnicode); Stream outputStream = writer.GetContentStream(); MimeWriter mimeWriter = new MimeWriter(outputStream, ContentType.Boundary); foreach (MimeBasePart part in Parts) { part.Send(mimeWriter, allowUnicode); } mimeWriter.Close(); outputStream.Close(); } internal string GetNextBoundary() { int b = Interlocked.Increment(ref s_boundary) - 1; string boundaryString = "--boundary_" + b.ToString(CultureInfo.InvariantCulture) + "_" + Guid.NewGuid().ToString(null, CultureInfo.InvariantCulture); return boundaryString; } } }
using Project858.Diagnostics; using Project858.ComponentModel.Client; using System; using System.IO.Ports; namespace Project858.IO.Ports { /// <summary> /// Zakladna komunikacna vrstva, pracujuca na linkovej urovni seriovej linky /// </summary> public class SerialPortClient : ClientBase { #region - Constructor - /// <summary> /// Initialize this class /// </summary> /// <exception cref="ArgumentException"> /// Arguments provided to a method is not valid. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The value of an argument is outside the allowable range of values. /// </exception> /// <param name="portName">Meno COM portu</param> public SerialPortClient(String portName) : this(portName, 9600, Parity.None, 8, StopBits.One) { } /// <summary> /// Initialize this class /// </summary> /// <exception cref="ArgumentException"> /// Arguments provided to a method is not valid. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The value of an argument is outside the allowable range of values. /// </exception> /// <param name="portName">Meno COM portu</param> /// <param name="readTimeout">Timeout na citanie</param> /// <param name="writeTimeout">Timeout na zapis</param> public SerialPortClient(String portName, Int32 readTimeout, Int32 writeTimeout) : this(portName, 9600, Parity.None, 8, StopBits.One, readTimeout, writeTimeout) { } /// <summary> /// Initialize this class /// </summary> /// <exception cref="ArgumentException"> /// Arguments provided to a method is not valid. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The value of an argument is outside the allowable range of values. /// </exception> /// <param name="portName">Meno COM portu</param> /// <param name="baudRate">Prenosova rychlost</param> public SerialPortClient(String portName, Int32 baudRate) : this(portName, baudRate, Parity.None, 8, StopBits.One) { } /// <summary> /// Initialize this class /// </summary> /// <exception cref="ArgumentException"> /// Arguments provided to a method is not valid. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The value of an argument is outside the allowable range of values. /// </exception> /// <param name="portName">Meno COM portu</param> /// <param name="baudRate">Prenosova rychlost</param> /// <param name="readTimeout">Timeout na citanie</param> /// <param name="writeTimeout">Timeout na zapis</param> public SerialPortClient(String portName, Int32 baudRate, Int32 readTimeout, Int32 writeTimeout) : this(portName, baudRate, Parity.None, 8, StopBits.One, readTimeout, writeTimeout) { } /// <summary> /// Initialize this class /// </summary> /// <exception cref="ArgumentException"> /// Arguments provided to a method is not valid. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The value of an argument is outside the allowable range of values. /// </exception> /// <param name="portName">Meno COM portu</param> /// <param name="baudRate">Prenosova rychlost</param> /// <param name="parity">Parity</param> public SerialPortClient(String portName, Int32 baudRate, Parity parity) : this(portName, baudRate, parity, 8, StopBits.One) { } /// <summary> /// Initialize this class /// </summary> /// <exception cref="ArgumentException"> /// Arguments provided to a method is not valid. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The value of an argument is outside the allowable range of values. /// </exception> /// <param name="portName">Meno COM portu</param> /// <param name="baudRate">Prenosova rychlost</param> /// <param name="parity">Parity</param> /// <param name="readTimeout">Timeout na citanie</param> /// <param name="writeTimeout">Timeout na zapis</param> public SerialPortClient(String portName, Int32 baudRate, Parity parity, Int32 readTimeout, Int32 writeTimeout) : this(portName, baudRate, parity, 8, StopBits.One, readTimeout, writeTimeout) { } /// <summary> /// Initialize this class /// </summary> /// <exception cref="ArgumentException"> /// Arguments provided to a method is not valid. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The value of an argument is outside the allowable range of values. /// </exception> /// <param name="portName">Meno COM portu</param> /// <param name="baudRate">Prenosova rychlost</param> /// <param name="parity">Parity</param> /// <param name="dataBits">DataBits</param> public SerialPortClient(String portName, Int32 baudRate, Parity parity, int dataBits) : this(portName, baudRate, parity, dataBits, StopBits.One) { } /// <summary> /// Initialize this class /// </summary> /// <exception cref="ArgumentException"> /// Arguments provided to a method is not valid. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The value of an argument is outside the allowable range of values. /// </exception> /// <param name="portName">Meno COM portu</param> /// <param name="baudRate">Prenosova rychlost</param> /// <param name="parity">Parity</param> /// <param name="dataBits">DataBits</param> /// <param name="readTimeout">Timeout na citanie</param> /// <param name="writeTimeout">Timeout na zapis</param> public SerialPortClient(String portName, Int32 baudRate, Parity parity, int dataBits, Int32 readTimeout, Int32 writeTimeout) : this(portName, baudRate, parity, dataBits, StopBits.One, readTimeout, writeTimeout) { } /// <summary> /// Initialize this class /// </summary> /// <exception cref="ArgumentException"> /// Arguments provided to a method is not valid. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The value of an argument is outside the allowable range of values. /// </exception> /// <param name="portName">Meno COM portu</param> /// <param name="baudRate">Prenosova rychlost</param> /// <param name="parity">Parity</param> /// <param name="dataBits">DataBits</param> /// <param name="stopBits">StopBits</param> public SerialPortClient(String portName, Int32 baudRate, Parity parity, Int32 dataBits, StopBits stopBits) : this(portName, baudRate, parity, dataBits, stopBits, 1000, 2000) { } /// <summary> /// Initialize this class /// </summary> /// <exception cref="ArgumentException"> /// Arguments provided to a method is not valid. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The value of an argument is outside the allowable range of values. /// </exception> /// <param name="portName">Meno COM portu</param> /// <param name="baudRate">Prenosova rychlost</param> /// <param name="parity">Parity</param> /// <param name="dataBits">DataBits</param> /// <param name="stopBits">StopBits</param> /// <param name="readTimeout">Timeout na citanie</param> /// <param name="writeTimeout">Timeout na zapis</param> public SerialPortClient(String portName, Int32 baudRate, Parity parity, int dataBits, StopBits stopBits, Int32 readTimeout, Int32 writeTimeout) { //osetrenie portu if (String.IsNullOrEmpty(portName) || portName.StartsWith("\\\\")) throw new ArgumentException("portName"); //osetrenie baudRate if (baudRate <= 0) throw new ArgumentOutOfRangeException("baudRate must be > 0."); //osetrenie dataBits if (dataBits < 5 || dataBits > 8) throw new ArgumentOutOfRangeException("dataBits must be between 6 and 8."); //osetrenie read timeoutu if (readTimeout <= 0 && readTimeout != SerialPort.InfiniteTimeout) throw new ArgumentOutOfRangeException("readTimeout must be > 0"); //osetrenie write timeoutu if (writeTimeout <= 0 && writeTimeout != SerialPort.InfiniteTimeout) throw new ArgumentOutOfRangeException("writeTimeout must be > 0."); this.port = null; this.portName = portName; this.baudRate = baudRate; this.parity = parity; this.dataBits = dataBits; this.stopBits = stopBits; this.readTimeout = readTimeout; this.writeTimeout = writeTimeout; } /// <summary> /// Initialize this class /// </summary> /// <exception cref="ArgumentException"> /// Arguments provided to a method is not valid. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The value of an argument is outside the allowable range of values. /// </exception> /// <param name="port">Port, cez ktory sa bude komunikovat</param> public SerialPortClient(SerialPort port) { //osetrenie portu if (port == null) throw new ArgumentException("port null"); //osetrenie baudRate if (port.BaudRate <= 0) throw new ArgumentOutOfRangeException("baudRate must be > 0"); //osetrenie dataBits if (port.DataBits < 5 || port.DataBits > 8) throw new ArgumentOutOfRangeException("dataBits must be between 6 and 8."); //osetrenie read timeoutu if (port.ReadTimeout <= 0 && port.ReadTimeout != SerialPort.InfiniteTimeout) throw new ArgumentOutOfRangeException("readTimeout must be > 0."); //osetrenie write timeoutu if (port.WriteTimeout <= 0 && port.WriteTimeout != SerialPort.InfiniteTimeout) throw new ArgumentOutOfRangeException("writeTimeout must be > 0."); this.port = port; } #endregion #region - Event - /// <summary> /// Event na oznamenie spustenia spojenia pre vyssu vrstvu /// </summary> private event EventHandler transportConnected = null; /// <summary> /// Event na oznamenie spustenia spojenia pre vyssu vrstvu /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave disposed /// </exception> public event EventHandler ConnectedEvent { add { try { //je objekt disposed ? if (this.disposed) throw new ObjectDisposedException("ComPortClient", "Object was disposed"); lock (this.eventLock) this.transportConnected += value; } catch (Exception ex) { TraceLogger.Info(ex.ToString()); throw; } } remove { try { //je objekt disposed ? if (this.disposed) throw new ObjectDisposedException("ComPortClient", "Object was disposed"); lock (this.eventLock) this.transportConnected -= value; } catch (Exception ex) { TraceLogger.Info(ex.ToString()); throw; } } } /// <summary> /// Event na oznamenie ukoncenia spojenia pre vyssu vrstvu /// </summary> private event EventHandler transportDisconnected = null; /// <summary> /// Event na oznamenie ukoncenia spojenia pre vyssu vrstvu /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave disposed /// </exception> public event EventHandler TransportDisconnected { add { try { //je objekt disposed ? if (this.disposed) throw new ObjectDisposedException("ComPortClient", "Object was disposed"); lock (this.eventLock) this.transportDisconnected += value; } catch (Exception ex) { TraceLogger.Info(ex.ToString()); throw; } } remove { try { //je objekt disposed ? if (this.disposed) throw new ObjectDisposedException("ComPortClient", "Object was disposed"); lock (this.eventLock) this.transportDisconnected -= value; } catch (Exception ex) { TraceLogger.Info(ex.ToString()); throw; } } } /// <summary> /// Event na oznamenue prichodu dat na transportnej vrstve /// </summary> private event DataEventHandler transportDataReceived = null; /// <summary> /// Event na oznamenue prichodu dat na transportnej vrstve /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave disposed /// </exception> public event DataEventHandler TransportDataReceived { add { try { //je objekt disposed ? if (this.disposed) throw new ObjectDisposedException("ComPortClient", "Object was disposed"); lock (this.eventLock) this.transportDataReceived += value; } catch (Exception ex) { TraceLogger.Info(ex.ToString()); throw; } } remove { try { //je objekt disposed ? if (this.disposed) throw new ObjectDisposedException("ComPortClient", "Object was disposed"); //netusim preco ale to mi zvykne zamrznut thread a ja fakt neviem preco lock (this.eventLock) this.transportDataReceived -= value; } catch (Exception ex) { TraceLogger.Info(ex.ToString()); throw; } } } #endregion #region - Properties - /// <summary> /// (Get) Detekcia pripojenia /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave disposed /// </exception> public Boolean IsConnected { get { try { //je objekt disposed ? if (this.disposed) throw new ObjectDisposedException("ComPortClient", "Object was disposed"); return this.isConnected; } catch (Exception ex) { TraceLogger.Info(ex.ToString()); throw; } } } /// <summary> /// (Get) BaudRate /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave disposed /// </exception> public Int32 BaudRate { get { try { //je objekt disposed ? if (this.disposed) throw new ObjectDisposedException("ComPortClient", "Object was disposed"); return this.baudRate; } catch (Exception ex) { TraceLogger.Info(ex.ToString()); throw; } } } /// <summary> /// (Get) DataBits /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave disposed /// </exception> public int DataBits { get { try { //je objekt disposed ? if (this.disposed) throw new ObjectDisposedException("ComPortClient", "Object was disposed"); return this.dataBits; } catch (Exception ex) { TraceLogger.Info(ex.ToString()); throw; } } } /// <summary> /// (Get / Set) Handshake /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave disposed /// </exception> public Handshake Handshake { get { try { //je objekt disposed ? if (this.disposed) throw new ObjectDisposedException("ComPortClient", "Object was disposed"); return this.handshake; } catch (Exception ex) { TraceLogger.Info(ex.ToString()); throw; } } set { try { //je objekt disposed ? if (this.disposed) throw new ObjectDisposedException("ComPortClient", "Object was disposed"); this.handshake = value; } catch (Exception ex) { TraceLogger.Info(ex.ToString()); throw; } } } /// <summary> /// (Get) Parity /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave disposed /// </exception> public Parity Parity { get { try { //je objekt disposed ? if (this.disposed) throw new ObjectDisposedException("ComPortClient", "Object was disposed"); return this.parity; } catch (Exception ex) { TraceLogger.Info(ex.ToString()); throw; } } } /// <summary> /// (Get) Meno COM portu /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave disposed /// </exception> public String PortName { get { try { //je objekt disposed ? if (this.disposed) throw new ObjectDisposedException("ComPortClient", "Object was disposed"); return this.portName; } catch (Exception ex) { TraceLogger.Info(ex.ToString()); throw; } } } /// <summary> /// (Get) Timeout na citanie z portu /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave disposed /// </exception> public int ReadTimeout { get { try { //je objekt disposed ? if (this.disposed) throw new ObjectDisposedException("ComPortClient", "Object was disposed"); return this.readTimeout; } catch (Exception ex) { TraceLogger.Info(ex.ToString()); throw; } } } /// <summary> /// (Get) StopBits /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave disposed /// </exception> public StopBits StopBits { get { try { //je objekt disposed ? if (this.disposed) throw new ObjectDisposedException("ComPortClient", "Object was disposed"); return this.stopBits; } catch (Exception ex) { TraceLogger.Info(ex.ToString()); throw; } } } /// <summary> /// (Get) Timeout na zapis na port /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave disposed /// </exception> public int WriteTimeout { get { try { //je objekt disposed ? if (this.disposed) throw new ObjectDisposedException("ComPortClient", "Object was disposed"); return this.writeTimeout; } catch (Exception ex) { TraceLogger.Info(ex.ToString()); throw; } } } #endregion #region - Variable - /// <summary> /// Handshake /// </summary> private Handshake handshake = Handshake.None; /// <summary> /// Timeout na zapis na port /// </summary> private Int32 writeTimeout = SerialPort.InfiniteTimeout; /// <summary> /// Timeout na citanie z portu /// </summary> private Int32 readTimeout = SerialPort.InfiniteTimeout; /// <summary> /// StopBits /// </summary> private StopBits stopBits = StopBits.None; /// <summary> /// Data Bits /// </summary> private Int32 dataBits = 0; /// <summary> /// Parity /// </summary> private Parity parity = Parity.None; /// <summary> /// Prenosova rychlost /// </summary> private Int32 baudRate = 0; /// <summary> /// Meno COM portu cez ktory komunikujeme /// </summary> private String portName = String.Empty; /// <summary> /// Detekuje ci je funkcia vrstvy spustena /// </summary> private volatile Boolean isRun = false; /// <summary> /// Detekuje ci logovania errorov pozadovane stale /// </summary> private Boolean traceErrorAlways = false; /// <summary> /// Typ logovania ktory je nastaveny /// </summary> private TraceTypes traceType = TraceTypes.Off; /// <summary> /// Pomocny objekt na synchronizaciu pristupu k eventom /// </summary> private readonly Object eventLock = new Object(); /// <summary> /// detekcia pripojenia /// </summary> private bool isConnected = false; /// <summary> /// Track if dispose has been called /// </summary> private Boolean disposed = false; /// <summary> /// Seriovy port cez ktory komunikujeme /// </summary> private SerialPort port = null; #endregion #region - Private Method - /// <summary> /// This function is raised when client is starting /// </summary> /// <exception cref="NotImplementedException"> /// Metoda nie je implementovana /// </exception> /// <returns>NotImplementedException</returns> protected override Boolean InternalStart() { return this.InternalInitialize(); } /// <summary> /// This function is raised when client is stoping /// </summary> /// <exception cref="NotImplementedException"> /// Metoda nie je implementovana /// </exception> protected override void InternalStop() { this.InternalDeinitialize(); } /// <summary> /// This function is raised when client is pausing /// </summary> /// <exception cref="NotImplementedException"> /// Metoda nie je implementovana /// </exception> protected override void InternalPause() { } /// <summary> /// This function is raised when client is disposing /// </summary> /// <exception cref="NotImplementedException"> /// Metoda nie je implementovana /// </exception> protected override void InternalDispose() { } /// <summary> /// Podla inicializacia otvori pozadovany COM port /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave disposed /// </exception> /// <exception cref="InvalidOperationException"> /// Osetrenie, pripadu nastavenie spojenia an typ none /// </exception> /// <returns>True = uspesne otvorene spojenie, False = chyba pri otvarani spojenia</returns> private Boolean InternalInitialize() { //trace message this.InternalTrace(TraceTypes.Info, "Initializing {0}...", this); try { if (port == null) { //inicializujeme port this.port = new SerialPort(this.portName); this.port.BaudRate = this.baudRate; this.port.Parity = this.parity; this.port.DataBits = this.dataBits; this.port.StopBits = this.stopBits; this.port.WriteTimeout = this.writeTimeout; this.port.ReadTimeout = this.readTimeout; } //otvorime port if (!this.port.IsOpen) this.port.Open(); //vyprazdnime buffre this.port.DiscardInBuffer(); this.port.DiscardOutBuffer(); //asynchronne citanie z portu this.port.DataReceived += new SerialDataReceivedEventHandler(this.port_DataReceived); //nastavime detekciu spjenia this.isConnected = true; this.OnConnected(new EventArgs()); //uspesne ukoncenie metody return true; } catch (Exception ex) { //zalogujeme this.InternalException(ex, "Error during initializing {0}. {1}", this, ex.Message); //nastavime detekciu spjenia this.isConnected = false; this.isRun = false; //preposleme vynimku return false; } } /// <summary> /// Zatvori spojenie /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave disposed /// </exception> /// <returns>True = uspesne zatvorene spojenie, False = chyba pri zatvarani spojenia</returns> public void InternalDeinitialize() { //trace message this.InternalTrace(TraceTypes.Info, "Deinitializing {0}...", this); try { //toto volanie eventu len ak je volana metoda stupo pocas behu if (this.isConnected) { //nastavime detekciu spojenia this.isConnected = false; //event o ukonceni spojenia this.OnDisconnected(new EventArgs()); } //ak je port otvoreny tak ho ukoncime if (this.port != null) { //odstranime event oznnamujuci prijatie dat this.port.DataReceived -= new SerialDataReceivedEventHandler(this.port_DataReceived); //ak je port ukonceny tak ho otvorime if (this.port.IsOpen) this.port.Close(); } } catch (Exception ex) { //trace message this.InternalException(ex, "Error during deinitializing {0}. {1}", this, ex.Message); } } /// <summary> /// Zapise data na komunikacnu linku /// </summary> /// <exception cref="InvalidOperationException"> /// Vynimka v pripade ze sa snazime zapisat data, ale spojenie nie je. /// </exception> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave disposed /// </exception> /// <returns>True = data boli uspesne zapisane, False = chyba pri zapise dat</returns> public Boolean Write(Byte[] data) { try { //je objekt disposed ? if (this.disposed) throw new ObjectDisposedException("ComPortClient", "Object was disposed"); //otvorenie nie je mozne ak je connection == true if (!this.isConnected) throw new InvalidOperationException("Writing data is not possible! The client is not connected!"); try { //len ak je port inicializovany a ak je otvoreny if (this.port != null && this.port.IsOpen) { //zalogujeme prijate dat this.InternalTrace(TraceTypes.Verbose, "Sending data: [{0}]", data.ToHexaString()); //zapiseme data na port this.port.Write(data, 0, data.Length); //zalogujeme prijate dat this.InternalTrace(TraceTypes.Verbose, "Sending the data has been successfully"); } else { //vynimka throw new Exception("Error writing to port. SerialPort is not available!"); } //uspesne ukoncenie metody return true; } catch (Exception ex) { //spojenie uz nie je aktivne this.isConnected = false; this.isRun = false; //zalogujeme this.InternalTrace(TraceTypes.Error, ex.ToString()); //chybne ukoncenie metody return false; } } catch (Exception ex) { TraceLogger.Info(ex.ToString()); throw; } } /// <summary> /// Metoda obsluhujuca event oznamujuci prichod dat na port /// </summary> /// <param name="sender">Odosielatel udalosti</param> /// <param name="e">SerialDataReceivedEventArgs</param> private void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { //synchronny pristup k metode lock (this) { try { //len ak port existuje if (this.port == null) { //vynimka oznamujuca nedostupnost portu throw new Exception("SerialPort is not available!"); } else if (!this.port.IsOpen) { //vynimka oznamujuca nedostupnost portu throw new Exception("SerialPort is closed!"); } else { //je nieco na citanie ??? if (this.port.BytesToRead != 0) { //pocet bytov ktore su dostupne na citanie Int32 count = this.port.BytesToRead; //inicializujeme referenciu na pozadovanu dlzku Byte[] data = new byte[count]; //vycitame data this.port.Read(data, 0, count); //zalogujeme prijate dat this.InternalTrace(TraceTypes.Verbose, "Received data: [{0}]", data.ToHexaString()); //vytvorime udalost a posleme data if (this.IsRun) { this.OnReceivedData(new DataEventArgs(data, this.PortName)); } } } } catch (Exception ex) { //zalogujeme prijate dat this.InternalException(ex, "Error during reading data from SerialPort {0}", ex.Message); //spojenie je ukoncene this.isRun = false; this.isConnected = false; //error comunication this.OnDisconnected(EventArgs.Empty); } } } #endregion #region - Call Event Method - /// <summary> /// Virtualna metoda na obsluhu eventu (posielanie dat do vyssej urovne) /// </summary> /// <param name="e">EventArgs obsahujuci data</param> protected virtual void OnReceivedData(DataEventArgs e) { DataEventHandler handler = this.transportDataReceived; if (handler != null) handler.BeginInvoke(this, e, null, null); } /// <summary> /// Trieda generujuca event na oznamenie vytvorenia spojenia /// </summary> /// <param name="e">EventArgs</param> private void OnConnected(EventArgs e) { EventHandler handler = this.transportConnected; if (handler != null) handler.BeginInvoke(this, e, null, null); } /// <summary> /// Trieda generujuca event na oznamenie padu spojenia /// </summary> /// <param name="e">EventArgs</param> private void OnDisconnected(EventArgs e) { EventHandler handler = this.transportDisconnected; if (handler != null) handler.BeginInvoke(this, e, null, null); } #endregion #region - Public Override Method - /// <summary> /// Vrati meno triedy /// </summary> /// <returns>Meno triedy</returns> public override string ToString() { return "SerialPortClient"; } #endregion } }
using AjaxControlToolkit.Design; using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Drawing; using System.Drawing.Design; using System.Globalization; using System.Reflection; using System.Security.Permissions; using System.Web; using System.Web.UI; using System.Web.UI.Design.WebControls; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; namespace AjaxControlToolkit { /// <summary> /// Like AutoCompleteExtender, a combo box is an ASP.NET AJAX control that combines the flexibility of the TextBox with a list of options from which users are able to choose. /// </summary> [SupportsEventValidation()] [ValidationProperty("SelectedItem")] [AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)] [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)] [Designer(typeof(ComboBoxDesigner))] [Bindable(true, BindingDirection.TwoWay)] [DataBindingHandler(typeof(ListControlDataBindingHandler))] [DefaultEvent("SelectedIndexChanged")] [DefaultProperty("SelectedValue")] [ControlValueProperty("SelectedValue")] [ParseChildren(true, "Items")] [ToolboxData("<{0}:ComboBox runat=\"server\"></{0}:ComboBox>")] [ClientCssResource(Constants.ComboBoxName)] [ClientScriptResource("Sys.Extended.UI.ComboBox", Constants.ComboBoxName)] [RequiredScript(typeof(ScriptControlBase), 2)] [RequiredScript(typeof(PopupExtender), 3)] [RequiredScript(typeof(CommonToolkitScripts), 4)] [ToolboxBitmap(typeof(ToolboxIcons.Accessor), Constants.ComboBoxName + Constants.IconPostfix)] public class ComboBox : ListControl, IScriptControl, IPostBackDataHandler, INamingContainer, IControlResolver { TextBox _textBoxControl; ScriptManager _scriptManager; ComboBoxButton _buttonControl; HiddenField _hiddenFieldControl; System.Web.UI.WebControls.BulletedList _optionListControl; Table _comboTable; TableRow _comboTableRow; TableCell _comboTableTextBoxCell; TableCell _comboTableButtonCell; static readonly object EventItemInserting = new object(); static readonly object EventItemInserted = new object(); protected virtual ScriptManager ScriptManager { set { _scriptManager = value; } get { if(_scriptManager == null) { _scriptManager = ScriptManager.GetCurrent(Page); if(_scriptManager == null) throw new HttpException("A ScriptManager is required on the page to use ASP.NET AJAX Script Components."); } return _scriptManager; } } protected virtual string ClientControlType { get { var attr = (ClientScriptResourceAttribute)TypeDescriptor.GetAttributes(this)[typeof(ClientScriptResourceAttribute)]; return attr.ComponentType; } } /// <summary> /// Resolves a control /// </summary> /// <param name="controlId">ID of the control</param> /// <returns>Found control</returns> public Control ResolveControl(string controlId) { return FindControl(controlId); } /// <summary> /// Specifies whether or not the ComboBox is rendered as an Inline or Block level HTML element. The default is Inline. /// </summary> [Category("Layout")] [DefaultValue(typeof(ComboBoxRenderMode), "Inline")] [Description("Whether the ComboBox will render as a block or inline HTML element.")] public ComboBoxRenderMode RenderMode { set { ViewState["RenderMode"] = value; } get { return (ViewState["RenderMode"] == null) ? ComboBoxRenderMode.Inline : (ComboBoxRenderMode)ViewState["RenderMode"]; } } /// <summary> /// Determines whether or not a user is allowed to enter text that does not match an item in the list and if the list is always displayed. /// </summary> /// <remarks> /// If "DropDownList" is specified, users are not allowed to enter text that does not match an item in the list. When "DropDown" /// (the default value) is specified, any text is allowed. If "Simple" is specified, any text is allowed and the list is /// always displayed regardless of the AutoCompleteMode property value. /// </remarks> [Category("Behavior")] [DefaultValue(typeof(ComboBoxStyle), "DropDown")] [Description("Whether the ComboBox requires typed text to match an item in the list or allows new items to be created.")] public virtual ComboBoxStyle DropDownStyle { set { ViewState["DropDownStyle"] = value; } get { var o = ViewState["DropDownStyle"]; return (o != null) ? (ComboBoxStyle)o : ComboBoxStyle.DropDown; } } /// <summary> /// Determines how the ComboBox automatically completes typed text. /// </summary> /// <remarks> /// When Suggest is specified, the ComboBox will show a list, highlight the first matched item, and if necessary, scroll the list to show the highlighted item. /// If Append is specified, the ComboBox will append the remainder of the first matched item to the user-typed text and highlight the appended text. /// When SuggestAppend is specified, both of the above behaviors are applied. /// If None (the default value) is specified, the ComboBox' auto-complete behaviors are disabled. /// </remarks> [Category("Behavior")] [DefaultValue(typeof(ComboBoxAutoCompleteMode), "None")] [Description("Whether the ComboBox auto-completes typing by suggesting an item in the list or appending matches as the user types.")] public virtual ComboBoxAutoCompleteMode AutoCompleteMode { set { ViewState["AutoCompleteMode"] = value; } get { var o = ViewState["AutoCompleteMode"]; return (o != null) ? (ComboBoxAutoCompleteMode)o : ComboBoxAutoCompleteMode.None; } } /// <summary> /// Determines if to "Append" or "Prepend" new items when they are inserted into the list /// or insert them in an "Ordinal" manner (alphabetically) based on the item Text or Value. /// The default is "Append" /// </summary> [Category("Behavior")] [DefaultValue(typeof(ComboBoxItemInsertLocation), "Append")] [Description("Whether a new item will be appended, prepended, or inserted ordinally into the items collection.")] public virtual ComboBoxItemInsertLocation ItemInsertLocation { set { ViewState["ItemInsertLocation"] = value; } get { var o = ViewState["ItemInsertLocation"]; return (o != null) ? (ComboBoxItemInsertLocation)o : ComboBoxItemInsertLocation.Append; } } /// <summary> /// Specifies whether or not user-typed text matches items in the list in a case-sensitive manner. The default is false. /// </summary> [Category("Behavior")] [DefaultValue(false)] [Description("Whether the ComboBox auto-completes user typing on a case-sensitive basis.")] [ExtenderControlProperty] [ClientPropertyName("caseSensitive")] public virtual bool CaseSensitive { set { ViewState["CaseSensitive"] = value; } get { var o = ViewState["CaseSensitive"]; return (o != null) ? (bool)o : false; } } /// <summary> /// When specified, replaces default styles applied to highlighted items in the list with a custom css class. /// </summary> [Category("Style")] [DefaultValue("")] [Description("The CSS class to apply to a hovered item in the list.")] [ExtenderControlProperty] [ClientPropertyName("listItemHoverCssClass")] public virtual string ListItemHoverCssClass { set { ViewState["ListItemHoverCssClass"] = value; } get { var o = ViewState["ListItemHoverCssClass"]; return (o != null) ? (String)o : String.Empty; } } /// <summary> /// The ComboBox selected item index. /// </summary> [ExtenderControlProperty] [ClientPropertyName("selectedIndex")] public override int SelectedIndex { get { var selectedIndex = base.SelectedIndex; return selectedIndex; } set { base.SelectedIndex = value; } } /// <summary> /// Determines whether or not AutoPostBack should be used. /// </summary> [ExtenderControlProperty] [ClientPropertyName("autoPostBack")] public override bool AutoPostBack { get { return base.AutoPostBack; } set { base.AutoPostBack = value; } } /// <summary> /// Specifies maximum length of the associated TextBox control. /// </summary> public virtual int MaxLength { get { return TextBoxControl.MaxLength; } set { TextBoxControl.MaxLength = value; } } /// <summary> /// The ComboBox tab index. /// </summary> public override short TabIndex { get { return TextBoxControl.TabIndex; } set { TextBoxControl.TabIndex = value; } } /// <summary> /// Determines whether or not the ComboBox is enabled. /// </summary> public override bool Enabled { get { return base.Enabled; } set { base.Enabled = value; TextBoxControl.Enabled = base.Enabled; ButtonControl.Enabled = base.Enabled; } } /// <summary> /// ComboBox height. /// </summary> public override Unit Height { get { return TextBoxControl.Height; } set { TextBoxControl.Height = value; } } /// <summary> /// ComboBox width. /// </summary> public override Unit Width { get { return TextBoxControl.Width; } set { TextBoxControl.Width = value; } } /// <summary> /// A foreground color. /// </summary> public override Color ForeColor { get { return TextBoxControl.ForeColor; } set { TextBoxControl.ForeColor = value; } } /// <summary> /// A background color. /// </summary> public override Color BackColor { get { return TextBoxControl.BackColor; } set { TextBoxControl.BackColor = value; } } /// <summary> /// The ComboBox control font. /// </summary> public override FontInfo Font { get { return TextBoxControl.Font; } } /// <summary> /// The ComboBox border color. /// </summary> public override Color BorderColor { get { return TextBoxControl.BorderColor; } set { TextBoxControl.BorderColor = value; ButtonControl.BorderColor = value; TextBoxControl.Style.Add("border-right", "0px none"); } } /// <summary> /// The ComboBox border style. /// </summary> public override BorderStyle BorderStyle { get { return TextBoxControl.BorderStyle; } set { TextBoxControl.BorderStyle = value; ButtonControl.BorderStyle = value; } } /// <summary> /// The ComboBox border width. /// </summary> public override Unit BorderWidth { get { return TextBoxControl.BorderWidth; } set { TextBoxControl.BorderWidth = value; ButtonControl.BorderWidth = value; } } protected virtual TextBox TextBoxControl { get { if(_textBoxControl == null) { _textBoxControl = new TextBox(); _textBoxControl.ID = ID + "_TextBox"; } return _textBoxControl; } } protected virtual ComboBoxButton ButtonControl { get { if(_buttonControl == null) { _buttonControl = new ComboBoxButton(); _buttonControl.ID = ID + "_Button"; } return _buttonControl; } } protected virtual HiddenField HiddenFieldControl { get { if(_hiddenFieldControl == null) { _hiddenFieldControl = new HiddenField(); _hiddenFieldControl.ID = ID + "_HiddenField"; } return _hiddenFieldControl; } } protected virtual System.Web.UI.WebControls.BulletedList OptionListControl { get { if(_optionListControl == null) { _optionListControl = new System.Web.UI.WebControls.BulletedList(); _optionListControl.ID = ID + "_OptionList"; } return _optionListControl; } } protected virtual Table ComboTable { get { if(_comboTable == null) { _comboTable = new Table(); _comboTable.ID = ID + "_Table"; _comboTable.Rows.Add(ComboTableRow); } return _comboTable; } } protected virtual TableRow ComboTableRow { get { if(_comboTableRow == null) { _comboTableRow = new TableRow(); _comboTableRow.Cells.Add(ComboTableTextBoxCell); _comboTableRow.Cells.Add(ComboTableButtonCell); } return _comboTableRow; } } protected virtual TableCell ComboTableTextBoxCell { get { if(_comboTableTextBoxCell == null) _comboTableTextBoxCell = new TableCell(); return _comboTableTextBoxCell; } } protected virtual TableCell ComboTableButtonCell { get { if(_comboTableButtonCell == null) _comboTableButtonCell = new TableCell(); return _comboTableButtonCell; } } IEnumerable<ScriptReference> IScriptControl.GetScriptReferences() { return GetScriptReferences(); } protected virtual IEnumerable<ScriptReference> GetScriptReferences() { if(!Visible) return null; return ToolkitResourceManager.GetControlScriptReferences(GetType()); } IEnumerable<ScriptDescriptor> IScriptControl.GetScriptDescriptors() { return GetScriptDescriptors(); } protected virtual IEnumerable<ScriptDescriptor> GetScriptDescriptors() { if(!Visible) return null; var descriptor = new ScriptControlDescriptor(ClientControlType, ClientID); ComponentDescriber.DescribeComponent(this, new ScriptComponentDescriptorWrapper(descriptor), this, this); descriptor.AddElementProperty("textBoxControl", TextBoxControl.ClientID); descriptor.AddElementProperty("buttonControl", ButtonControl.ClientID); descriptor.AddElementProperty("hiddenFieldControl", HiddenFieldControl.ClientID); descriptor.AddElementProperty("optionListControl", OptionListControl.ClientID); descriptor.AddElementProperty("comboTableControl", ComboTable.ClientID); descriptor.AddProperty("autoCompleteMode", AutoCompleteMode); descriptor.AddProperty("dropDownStyle", DropDownStyle); return new List<ScriptDescriptor> { descriptor }; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); ToolkitResourceManager.RegisterCssReferences(this); } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); ScriptManager.RegisterScriptControl<ComboBox>(this); Page.RegisterRequiresPostBack(this); } protected override void Render(HtmlTextWriter writer) { base.Render(writer); if(!DesignMode) ScriptManager.RegisterScriptDescriptors(this); } protected override void CreateChildControls() { if(Controls.Count < 1 || Controls[0] != ComboTable) { Controls.Clear(); ComboTableTextBoxCell.Controls.Add(TextBoxControl); ComboTableButtonCell.Controls.Add(ButtonControl); Controls.Add(ComboTable); Controls.Add(OptionListControl); Controls.Add(HiddenFieldControl); } } protected override HtmlTextWriterTag TagKey { get { return HtmlTextWriterTag.Div; } } protected override void AddAttributesToRender(HtmlTextWriter writer) { AddContainerAttributesToRender(writer); AddTableAttributesToRender(writer); AddTextBoxAttributesToRender(writer); AddButtonAttributesToRender(writer); AddOptionListAttributesToRender(writer); } protected virtual void AddContainerAttributesToRender(HtmlTextWriter writer) { if(RenderMode == ComboBoxRenderMode.Inline) Style.Add(HtmlTextWriterStyle.Display, GetInlineDisplayStyle()); base.AddAttributesToRender(writer); } protected virtual void AddTableAttributesToRender(HtmlTextWriter writer) { ComboTable.CssClass = "ajax__combobox_inputcontainer"; ComboTableTextBoxCell.CssClass = "ajax__combobox_textboxcontainer"; ComboTableButtonCell.CssClass = "ajax__combobox_buttoncontainer"; ComboTable.BorderStyle = BorderStyle.None; ComboTable.BorderWidth = Unit.Pixel(0); if(RenderMode == ComboBoxRenderMode.Inline) { ComboTable.Style.Add(HtmlTextWriterStyle.Display, GetInlineDisplayStyle()); if(!DesignMode) { // when rendered inline, the combobox displays slightly above adjacent inline elements ComboTable.Style.Add(HtmlTextWriterStyle.Position, "relative"); ComboTable.Style.Add(HtmlTextWriterStyle.Top, "5px"); } } } protected virtual void AddTextBoxAttributesToRender(HtmlTextWriter writer) { TextBoxControl.AutoCompleteType = AutoCompleteType.None; TextBoxControl.Attributes.Add("autocomplete", "off"); } protected virtual void AddButtonAttributesToRender(HtmlTextWriter writer) { if(!DesignMode) { ButtonControl.TabIndex = -1; return; } ButtonControl.Width = Unit.Pixel(14); ButtonControl.Height = Unit.Pixel(14); } protected virtual void AddOptionListAttributesToRender(HtmlTextWriter writer) { OptionListControl.CssClass = "ajax__combobox_itemlist"; OptionListControl.Style.Add(HtmlTextWriterStyle.Display, "none"); OptionListControl.Style.Add(HtmlTextWriterStyle.Visibility, "hidden"); } /// <summary> /// Renders a control. /// </summary> /// <param name="writer">HTML text writer</param> public override void RenderControl(HtmlTextWriter writer) { if(DesignMode) { CreateChildControls(); AddAttributesToRender(writer); ComboTable.RenderControl(writer); } else { HiddenFieldControl.Value = SelectedIndex.ToString(); base.RenderControl(writer); } } protected override void RenderContents(HtmlTextWriter writer) { ComboTable.RenderControl(writer); OptionListControl.Items.Clear(); var copy = new ListItem[Items.Count]; Items.CopyTo(copy, 0); OptionListControl.Items.AddRange(copy); OptionListControl.RenderControl(writer); HiddenFieldControl.RenderControl(writer); } bool IPostBackDataHandler.LoadPostData(string postDataKey, NameValueCollection postCollection) { return LoadPostData(postDataKey, postCollection); } void IPostBackDataHandler.RaisePostDataChangedEvent() { RaisePostDataChangedEvent(); } protected virtual bool LoadPostData(string postDataKey, NameValueCollection postCollection) { if(!Enabled) return false; var postCollectionValues = postCollection.GetValues(HiddenFieldControl.UniqueID); if(postCollectionValues == null) return false; var newSelectedIndex = Convert.ToInt32(postCollectionValues[0], CultureInfo.InvariantCulture); EnsureDataBound(); if(newSelectedIndex == -2 && (DropDownStyle == ComboBoxStyle.Simple || DropDownStyle == ComboBoxStyle.DropDown)) { var newText = postCollection.GetValues(TextBoxControl.UniqueID)[0]; var eventArgs = new ComboBoxItemInsertEventArgs(newText, ItemInsertLocation); OnItemInserting(eventArgs); if(!eventArgs.Cancel) InsertItem(eventArgs); else TextBoxControl.Text = (SelectedIndex < 0) ? String.Empty : SelectedItem.Text; } else if(newSelectedIndex != SelectedIndex) { SelectedIndex = newSelectedIndex; return true; } return false; } /// <summary> /// Raises PostDataChangeEvent. /// </summary> public virtual void RaisePostDataChangedEvent() { OnSelectedIndexChanged(EventArgs.Empty); } /// <summary> /// Fires on inserting an item. /// </summary> public event EventHandler<ComboBoxItemInsertEventArgs> ItemInserting { add { Events.AddHandler(EventItemInserting, value); } remove { Events.RemoveHandler(EventItemInserting, value); } } /// <summary> /// Fires when an item is inserted. /// </summary> public event EventHandler<ComboBoxItemInsertEventArgs> ItemInserted { add { Events.AddHandler(EventItemInserted, value); } remove { Events.RemoveHandler(EventItemInserted, value); } } protected virtual void OnItemInserting(ComboBoxItemInsertEventArgs e) { var handler = (EventHandler<ComboBoxItemInsertEventArgs>)Events[EventItemInserting]; if(handler != null) handler(this, e); } protected virtual void OnItemInserted(ComboBoxItemInsertEventArgs e) { var handler = (EventHandler<ComboBoxItemInsertEventArgs>)Events[EventItemInserted]; if(handler != null) handler(this, e); } protected virtual void InsertItem(ComboBoxItemInsertEventArgs e) { if(!e.Cancel) { var insertIndex = -1; if(e.InsertLocation == ComboBoxItemInsertLocation.Prepend) insertIndex = 0; else if(e.InsertLocation == ComboBoxItemInsertLocation.Append) insertIndex = Items.Count; else if(e.InsertLocation == ComboBoxItemInsertLocation.OrdinalText) { // loop through items collection to find proper insertion point insertIndex = 0; foreach(ListItem li in Items) { var compareValue = String.Compare(e.Item.Text, li.Text, StringComparison.Ordinal); if(compareValue > 0) ++insertIndex; else break; } } else if(e.InsertLocation == ComboBoxItemInsertLocation.OrdinalValue) { // loop through items collection to find proper insertion point insertIndex = 0; foreach(ListItem li in Items) { var compareValue = String.Compare(e.Item.Value, li.Value, StringComparison.Ordinal); if(compareValue > 0) ++insertIndex; else break; } } if(insertIndex >= Items.Count) { Items.Add(e.Item); SelectedIndex = Items.Count - 1; } else { Items.Insert(insertIndex, e.Item); SelectedIndex = insertIndex; } OnItemInserted(e); } } string GetInlineDisplayStyle() { var display = "inline"; if(!DesignMode && (Page.Request.Browser.Browser.ToLower().Contains("safari") || Page.Request.Browser.Browser.ToLower().Contains("firefox"))) display += "-block"; return display; } } }
// ReSharper disable All using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Web.Http; using Frapid.ApplicationState.Cache; using Frapid.ApplicationState.Models; using Newtonsoft.Json.Linq; using Frapid.Config.DataAccess; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Frapid.Framework; using Frapid.Framework.Extensions; namespace Frapid.Config.Api { /// <summary> /// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Custom Field Definition Views. /// </summary> [RoutePrefix("api/v1.0/config/custom-field-definition-view")] public class CustomFieldDefinitionViewController : FrapidApiController { /// <summary> /// The CustomFieldDefinitionView repository. /// </summary> private readonly ICustomFieldDefinitionViewRepository CustomFieldDefinitionViewRepository; public CustomFieldDefinitionViewController() { this._LoginId = AppUsers.GetCurrent().View.LoginId.To<long>(); this._UserId = AppUsers.GetCurrent().View.UserId.To<int>(); this._OfficeId = AppUsers.GetCurrent().View.OfficeId.To<int>(); this._Catalog = AppUsers.GetCatalog(); this.CustomFieldDefinitionViewRepository = new Frapid.Config.DataAccess.CustomFieldDefinitionView { _Catalog = this._Catalog, _LoginId = this._LoginId, _UserId = this._UserId }; } public CustomFieldDefinitionViewController(ICustomFieldDefinitionViewRepository repository, string catalog, LoginView view) { this._LoginId = view.LoginId.To<long>(); this._UserId = view.UserId.To<int>(); this._OfficeId = view.OfficeId.To<int>(); this._Catalog = catalog; this.CustomFieldDefinitionViewRepository = repository; } public long _LoginId { get; } public int _UserId { get; private set; } public int _OfficeId { get; private set; } public string _Catalog { get; } /// <summary> /// Counts the number of custom field definition views. /// </summary> /// <returns>Returns the count of the custom field definition views.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count")] [Route("~/api/config/custom-field-definition-view/count")] [Authorize] public long Count() { try { return this.CustomFieldDefinitionViewRepository.Count(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns collection of custom field definition view for export. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("export")] [Route("all")] [Route("~/api/config/custom-field-definition-view/export")] [Route("~/api/config/custom-field-definition-view/all")] [Authorize] public IEnumerable<Frapid.Config.Entities.CustomFieldDefinitionView> Get() { try { return this.CustomFieldDefinitionViewRepository.Get(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a paginated collection containing 10 custom field definition views on each page, sorted by the property . /// </summary> /// <returns>Returns the first page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("")] [Route("~/api/config/custom-field-definition-view")] [Authorize] public IEnumerable<Frapid.Config.Entities.CustomFieldDefinitionView> GetPaginatedResult() { try { return this.CustomFieldDefinitionViewRepository.GetPaginatedResult(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a paginated collection containing 10 custom field definition views on each page, sorted by the property . /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset.</param> /// <returns>Returns the requested page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("page/{pageNumber}")] [Route("~/api/config/custom-field-definition-view/page/{pageNumber}")] [Authorize] public IEnumerable<Frapid.Config.Entities.CustomFieldDefinitionView> GetPaginatedResult(long pageNumber) { try { return this.CustomFieldDefinitionViewRepository.GetPaginatedResult(pageNumber); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Counts the number of custom field definition views using the supplied filter(s). /// </summary> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the count of filtered custom field definition views.</returns> [AcceptVerbs("POST")] [Route("count-where")] [Route("~/api/config/custom-field-definition-view/count-where")] [Authorize] public long CountWhere([FromBody]JArray filters) { try { List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer()); return this.CustomFieldDefinitionViewRepository.CountWhere(f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a filtered and paginated collection containing 10 custom field definition views on each page, sorted by the property . /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset.</param> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("POST")] [Route("get-where/{pageNumber}")] [Route("~/api/config/custom-field-definition-view/get-where/{pageNumber}")] [Authorize] public IEnumerable<Frapid.Config.Entities.CustomFieldDefinitionView> GetWhere(long pageNumber, [FromBody]JArray filters) { try { List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer()); return this.CustomFieldDefinitionViewRepository.GetWhere(pageNumber, f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Counts the number of custom field definition views using the supplied filter name. /// </summary> /// <param name="filterName">The named filter.</param> /// <returns>Returns the count of filtered custom field definition views.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count-filtered/{filterName}")] [Route("~/api/config/custom-field-definition-view/count-filtered/{filterName}")] [Authorize] public long CountFiltered(string filterName) { try { return this.CustomFieldDefinitionViewRepository.CountFiltered(filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a filtered and paginated collection containing 10 custom field definition views on each page, sorted by the property . /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset.</param> /// <param name="filterName">The named filter.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("GET", "HEAD")] [Route("get-filtered/{pageNumber}/{filterName}")] [Route("~/api/config/custom-field-definition-view/get-filtered/{pageNumber}/{filterName}")] [Authorize] public IEnumerable<Frapid.Config.Entities.CustomFieldDefinitionView> GetFiltered(long pageNumber, string filterName) { try { return this.CustomFieldDefinitionViewRepository.GetFiltered(pageNumber, filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace WebApiContrib.Formatting.Xlsx.Sample.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
#region Apache Notice /***************************************************************************** * $Header: $ * $Revision: $ * $Date: $ * * iBATIS.NET Data Mapper * Copyright (C) 2005 - Gilles Bayon * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ********************************************************************************/ #endregion #region Imports using System; using System.Data; using System.Collections; using IBatisNet.Common; using IBatisNet.Common.Utilities.Objects; using IBatisNet.DataMapper.Configuration.Statements; using IBatisNet.DataMapper.Configuration.ParameterMapping; using IBatisNet.DataMapper.Exceptions; using IBatisNet.DataMapper.Scope; #endregion namespace IBatisNet.DataMapper.Commands { /// <summary> /// Summary description for EmbedParamsPreparedCommand. /// </summary> internal class EmbedParamsPreparedCommand : DefaultPreparedCommand { #region EmbedParamsPreparedCommand Members /// <summary> /// /// </summary> /// <param name="session"></param> /// <param name="command"></param> /// <param name="request"></param> /// <param name="statement"></param> /// <param name="parameterObject"></param> protected override void ApplyParameterMap (IDalSession session, IDbCommand command, RequestScope request, IStatement statement, object parameterObject) { ArrayList properties = request.PreparedStatement.DbParametersName; ArrayList parameters = request.PreparedStatement.DbParameters; object parameterValue = null; for (int i = 0; i < properties.Count; ++i) { IDataParameter sqlParameter = (IDataParameter) parameters[i]; string propertyName = (string) properties[i]; if (command.CommandType == CommandType.Text) { if (propertyName != "value") // Inline Parameters && Parameters via ParameterMap { ParameterProperty property = request.ParameterMap.GetProperty(i); // parameterValue = request.ParameterMap.GetValueOfProperty(parameterObject, // property.PropertyName); } else // 'value' parameter { parameterValue = parameterObject; } } else // CommandType.StoredProcedure { // A store procedure must always use a ParameterMap // to indicate the mapping order of the properties to the columns if (request.ParameterMap == null) // Inline Parameters { throw new DataMapperException("A procedure statement tag must alway have a parameterMap attribute, which is not the case for the procedure '" + statement.Id + "'."); } else // Parameters via ParameterMap { ParameterProperty property = request.ParameterMap.GetProperty(i); if (property.DirectionAttribute.Length == 0) { property.Direction = sqlParameter.Direction; } // IDbDataParameter dataParameter = (IDbDataParameter)parameters[i]; // property.Precision = dataParameter.Precision; // property.Scale = dataParameter.Scale; // property.Size = dataParameter.Size; sqlParameter.Direction = property.Direction; // parameterValue = request.ParameterMap.GetValueOfProperty(parameterObject, property.PropertyName); } } IDataParameter parameterCopy = command.CreateParameter(); // Fix JIRA 20 sqlParameter.Value = parameterValue; parameterCopy.Value = parameterValue; parameterCopy.Direction = sqlParameter.Direction; // With a ParameterMap, we could specify the ParameterDbTypeProperty if (statement.ParameterMap != null) { if (request.ParameterMap.GetProperty(i).DbType != null && request.ParameterMap.GetProperty(i).DbType.Length >0) { string dbTypePropertyName = session.DataSource.Provider.ParameterDbTypeProperty; ObjectProbe.SetPropertyValue(parameterCopy, dbTypePropertyName, ObjectProbe.GetPropertyValue(sqlParameter, dbTypePropertyName)); } else { //parameterCopy.DbType = sqlParameter.DbType; } } else { //parameterCopy.DbType = sqlParameter.DbType; } // JIRA-49 Fixes (size, precision, and scale) if (session.DataSource.Provider.SetDbParameterSize) { if (((IDbDataParameter)sqlParameter).Size > 0) { ((IDbDataParameter)parameterCopy).Size = ((IDbDataParameter)sqlParameter).Size; } } if (session.DataSource.Provider.SetDbParameterPrecision) { ((IDbDataParameter)parameterCopy).Precision = ((IDbDataParameter)sqlParameter).Precision; } if (session.DataSource.Provider.SetDbParameterScale) { ((IDbDataParameter)parameterCopy).Scale = ((IDbDataParameter)sqlParameter).Scale; } parameterCopy.ParameterName = sqlParameter.ParameterName; command.Parameters.Add(parameterCopy); // NOTE: // Code from Oleksa Borodie to embed parameter values // into command text/sql statement. // NEED TO MERGE WITH ABOVE AFTER INITIAL TESTING // TO REMOVE REDUNDANT LOOPING! // replace parameter names with parameter values // only for parameters with names, parameterMaps will be ignored IDataParameter p; for (int iCnt = command.Parameters.Count - 1; iCnt >= 0; iCnt--) { p = (IDataParameter) command.Parameters[iCnt]; if (p.Direction == ParameterDirection.Input && command.CommandText.IndexOf(p.ParameterName) > 0) { switch (p.DbType) { case DbType.String: case DbType.AnsiString: case DbType.AnsiStringFixedLength: case DbType.StringFixedLength: command.CommandText = command.CommandText.Replace(p.ParameterName, "\'" + p.Value.ToString().Replace("\'", "\'\'") + "\'"); break; case DbType.Date: case DbType.DateTime: DateTime v = Convert.ToDateTime(p.Value); command.CommandText = command.CommandText.Replace(p.ParameterName, String.Format("\'{0}.{1}.{2} {3}:{4}:{5}.{6}\'", v.Year, v.Month, v.Day, v.Hour, v.Minute, v.Second, v.Millisecond)); // command.CommandText = command.CommandText.Replace(p.ParameterName, "\'" + p.Value.ToString() + "\'"); break; case DbType.Double: case DbType.Decimal: case DbType.Currency: case DbType.Single: command.CommandText = command.CommandText.Replace(p.ParameterName, p.Value.ToString().Replace(',', '.')); break; default: command.CommandText = command.CommandText.Replace(p.ParameterName, p.Value.ToString()); break; } command.Parameters.RemoveAt(iCnt); } } } } #endregion } }
namespace CarCtrl { partial class formCtrl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(formCtrl)); this.panelButtons = new System.Windows.Forms.Panel(); this.btRight = new System.Windows.Forms.Panel(); this.lbRight = new System.Windows.Forms.Label(); this.btDown = new System.Windows.Forms.Panel(); this.lbDown = new System.Windows.Forms.Label(); this.btLeft = new System.Windows.Forms.Panel(); this.lbLeft = new System.Windows.Forms.Label(); this.btUp = new System.Windows.Forms.Panel(); this.lbUp = new System.Windows.Forms.Label(); this.mmLog = new System.Windows.Forms.TextBox(); this.lbCmdLog = new System.Windows.Forms.Label(); this.lbSerial = new System.Windows.Forms.Label(); this.cbbSerialPort = new System.Windows.Forms.ComboBox(); this.lbBitSend = new System.Windows.Forms.Label(); this.edtBitSync = new System.Windows.Forms.NumericUpDown(); this.edtPacketSync = new System.Windows.Forms.NumericUpDown(); this.lbPacketSend = new System.Windows.Forms.Label(); this.btStartStop = new System.Windows.Forms.Button(); this.mmStatus = new System.Windows.Forms.TextBox(); this.lbPortStat = new System.Windows.Forms.Label(); this.timerLog = new System.Windows.Forms.Timer(this.components); this.lbSent = new System.Windows.Forms.Label(); this.panelButtons.SuspendLayout(); this.btRight.SuspendLayout(); this.btDown.SuspendLayout(); this.btLeft.SuspendLayout(); this.btUp.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.edtBitSync)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.edtPacketSync)).BeginInit(); this.SuspendLayout(); // // panelButtons // this.panelButtons.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.panelButtons.Controls.Add(this.btRight); this.panelButtons.Controls.Add(this.btDown); this.panelButtons.Controls.Add(this.btLeft); this.panelButtons.Controls.Add(this.btUp); this.panelButtons.Location = new System.Drawing.Point(271, 225); this.panelButtons.Name = "panelButtons"; this.panelButtons.Size = new System.Drawing.Size(192, 187); this.panelButtons.TabIndex = 0; // // btRight // this.btRight.BackColor = System.Drawing.Color.Gray; this.btRight.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.btRight.Controls.Add(this.lbRight); this.btRight.Font = new System.Drawing.Font("Webdings", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(2))); this.btRight.Location = new System.Drawing.Point(125, 63); this.btRight.Name = "btRight"; this.btRight.Size = new System.Drawing.Size(60, 60); this.btRight.TabIndex = 3; // // lbRight // this.lbRight.Dock = System.Windows.Forms.DockStyle.Fill; this.lbRight.Font = new System.Drawing.Font("Webdings", 24F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(2))); this.lbRight.Location = new System.Drawing.Point(0, 0); this.lbRight.Name = "lbRight"; this.lbRight.Size = new System.Drawing.Size(58, 58); this.lbRight.TabIndex = 1; this.lbRight.Text = "4"; this.lbRight.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // btDown // this.btDown.BackColor = System.Drawing.Color.Gray; this.btDown.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.btDown.Controls.Add(this.lbDown); this.btDown.Font = new System.Drawing.Font("Webdings", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(2))); this.btDown.Location = new System.Drawing.Point(65, 123); this.btDown.Name = "btDown"; this.btDown.Size = new System.Drawing.Size(60, 60); this.btDown.TabIndex = 2; // // lbDown // this.lbDown.Dock = System.Windows.Forms.DockStyle.Fill; this.lbDown.Font = new System.Drawing.Font("Webdings", 24F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(2))); this.lbDown.Location = new System.Drawing.Point(0, 0); this.lbDown.Name = "lbDown"; this.lbDown.Size = new System.Drawing.Size(58, 58); this.lbDown.TabIndex = 1; this.lbDown.Text = "6"; this.lbDown.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // btLeft // this.btLeft.BackColor = System.Drawing.Color.Gray; this.btLeft.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.btLeft.Controls.Add(this.lbLeft); this.btLeft.Font = new System.Drawing.Font("Webdings", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(2))); this.btLeft.Location = new System.Drawing.Point(5, 63); this.btLeft.Name = "btLeft"; this.btLeft.Size = new System.Drawing.Size(60, 60); this.btLeft.TabIndex = 2; // // lbLeft // this.lbLeft.Dock = System.Windows.Forms.DockStyle.Fill; this.lbLeft.Font = new System.Drawing.Font("Webdings", 24F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(2))); this.lbLeft.Location = new System.Drawing.Point(0, 0); this.lbLeft.Name = "lbLeft"; this.lbLeft.Size = new System.Drawing.Size(58, 58); this.lbLeft.TabIndex = 1; this.lbLeft.Text = "3"; this.lbLeft.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // btUp // this.btUp.BackColor = System.Drawing.Color.Gray; this.btUp.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.btUp.Controls.Add(this.lbUp); this.btUp.Font = new System.Drawing.Font("Webdings", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(2))); this.btUp.Location = new System.Drawing.Point(65, 3); this.btUp.Name = "btUp"; this.btUp.Size = new System.Drawing.Size(60, 60); this.btUp.TabIndex = 1; // // lbUp // this.lbUp.Dock = System.Windows.Forms.DockStyle.Fill; this.lbUp.Font = new System.Drawing.Font("Webdings", 24F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(2))); this.lbUp.Location = new System.Drawing.Point(0, 0); this.lbUp.Name = "lbUp"; this.lbUp.Size = new System.Drawing.Size(58, 58); this.lbUp.TabIndex = 0; this.lbUp.Text = "5"; this.lbUp.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // mmLog // this.mmLog.Location = new System.Drawing.Point(5, 20); this.mmLog.Multiline = true; this.mmLog.Name = "mmLog"; this.mmLog.ReadOnly = true; this.mmLog.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.mmLog.Size = new System.Drawing.Size(325, 167); this.mmLog.TabIndex = 1; this.mmLog.KeyUp += new System.Windows.Forms.KeyEventHandler(this.lb_KeyUp); this.mmLog.KeyDown += new System.Windows.Forms.KeyEventHandler(this.lb_KeyDown); // // lbCmdLog // this.lbCmdLog.AutoSize = true; this.lbCmdLog.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.lbCmdLog.Location = new System.Drawing.Point(2, 4); this.lbCmdLog.Name = "lbCmdLog"; this.lbCmdLog.Size = new System.Drawing.Size(90, 13); this.lbCmdLog.TabIndex = 2; this.lbCmdLog.Text = "Command Log:"; // // lbSerial // this.lbSerial.AutoSize = true; this.lbSerial.Location = new System.Drawing.Point(2, 225); this.lbSerial.Name = "lbSerial"; this.lbSerial.Size = new System.Drawing.Size(58, 13); this.lbSerial.TabIndex = 3; this.lbSerial.Text = "Serial Port:"; // // cbbSerialPort // this.cbbSerialPort.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbbSerialPort.FormattingEnabled = true; this.cbbSerialPort.Location = new System.Drawing.Point(5, 241); this.cbbSerialPort.Name = "cbbSerialPort"; this.cbbSerialPort.Size = new System.Drawing.Size(136, 21); this.cbbSerialPort.TabIndex = 4; // // lbBitSend // this.lbBitSend.AutoSize = true; this.lbBitSend.Location = new System.Drawing.Point(2, 267); this.lbBitSend.Name = "lbBitSend"; this.lbBitSend.Size = new System.Drawing.Size(76, 13); this.lbBitSend.TabIndex = 5; this.lbBitSend.Text = "Bit Sync Delay"; // // edtBitSync // this.edtBitSync.Location = new System.Drawing.Point(5, 283); this.edtBitSync.Maximum = new decimal(new int[] { 1000, 0, 0, 0}); this.edtBitSync.Minimum = new decimal(new int[] { 10, 0, 0, 0}); this.edtBitSync.Name = "edtBitSync"; this.edtBitSync.Size = new System.Drawing.Size(136, 20); this.edtBitSync.TabIndex = 6; this.edtBitSync.Value = new decimal(new int[] { 50, 0, 0, 0}); // // edtPacketSync // this.edtPacketSync.Location = new System.Drawing.Point(5, 324); this.edtPacketSync.Maximum = new decimal(new int[] { 1000, 0, 0, 0}); this.edtPacketSync.Minimum = new decimal(new int[] { 20, 0, 0, 0}); this.edtPacketSync.Name = "edtPacketSync"; this.edtPacketSync.Size = new System.Drawing.Size(136, 20); this.edtPacketSync.TabIndex = 8; this.edtPacketSync.Value = new decimal(new int[] { 300, 0, 0, 0}); // // lbPacketSend // this.lbPacketSend.AutoSize = true; this.lbPacketSend.Location = new System.Drawing.Point(2, 308); this.lbPacketSend.Name = "lbPacketSend"; this.lbPacketSend.Size = new System.Drawing.Size(98, 13); this.lbPacketSend.TabIndex = 7; this.lbPacketSend.Text = "Packet Sync Delay"; // // btStartStop // this.btStartStop.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.btStartStop.Location = new System.Drawing.Point(5, 389); this.btStartStop.Name = "btStartStop"; this.btStartStop.Size = new System.Drawing.Size(75, 23); this.btStartStop.TabIndex = 9; this.btStartStop.Text = "Start"; this.btStartStop.UseVisualStyleBackColor = true; this.btStartStop.Click += new System.EventHandler(this.btStartStop_Click); this.btStartStop.KeyUp += new System.Windows.Forms.KeyEventHandler(this.lb_KeyUp); this.btStartStop.KeyDown += new System.Windows.Forms.KeyEventHandler(this.lb_KeyDown); // // mmStatus // this.mmStatus.Cursor = System.Windows.Forms.Cursors.Arrow; this.mmStatus.Font = new System.Drawing.Font("Lucida Console", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.mmStatus.Location = new System.Drawing.Point(336, 20); this.mmStatus.Multiline = true; this.mmStatus.Name = "mmStatus"; this.mmStatus.ReadOnly = true; this.mmStatus.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.mmStatus.Size = new System.Drawing.Size(127, 167); this.mmStatus.TabIndex = 10; this.mmStatus.WordWrap = false; this.mmStatus.KeyUp += new System.Windows.Forms.KeyEventHandler(this.lb_KeyUp); this.mmStatus.KeyDown += new System.Windows.Forms.KeyEventHandler(this.lb_KeyDown); // // lbPortStat // this.lbPortStat.AutoSize = true; this.lbPortStat.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.lbPortStat.Location = new System.Drawing.Point(335, 6); this.lbPortStat.Name = "lbPortStat"; this.lbPortStat.Size = new System.Drawing.Size(110, 13); this.lbPortStat.TabIndex = 11; this.lbPortStat.Text = "DTR RTS STAT"; // // timerLog // this.timerLog.Enabled = true; this.timerLog.Interval = 50; this.timerLog.Tick += new System.EventHandler(this.timerLog_Tick); // // lbSent // this.lbSent.AutoSize = true; this.lbSent.Location = new System.Drawing.Point(335, 190); this.lbSent.Name = "lbSent"; this.lbSent.Size = new System.Drawing.Size(61, 13); this.lbSent.TabIndex = 12; this.lbSent.Text = "Bits Sent: 0"; // // formCtrl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(468, 416); this.Controls.Add(this.lbSent); this.Controls.Add(this.lbPortStat); this.Controls.Add(this.mmStatus); this.Controls.Add(this.btStartStop); this.Controls.Add(this.edtPacketSync); this.Controls.Add(this.lbPacketSend); this.Controls.Add(this.edtBitSync); this.Controls.Add(this.lbBitSend); this.Controls.Add(this.cbbSerialPort); this.Controls.Add(this.lbSerial); this.Controls.Add(this.lbCmdLog); this.Controls.Add(this.mmLog); this.Controls.Add(this.panelButtons); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.Name = "formCtrl"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Car Control"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.formCtrl_FormClosing); this.KeyUp += new System.Windows.Forms.KeyEventHandler(this.lb_KeyUp); this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.lb_KeyDown); this.panelButtons.ResumeLayout(false); this.btRight.ResumeLayout(false); this.btDown.ResumeLayout(false); this.btLeft.ResumeLayout(false); this.btUp.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.edtBitSync)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.edtPacketSync)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Panel panelButtons; private System.Windows.Forms.Panel btRight; private System.Windows.Forms.Panel btDown; private System.Windows.Forms.Panel btLeft; private System.Windows.Forms.Panel btUp; private System.Windows.Forms.Label lbRight; private System.Windows.Forms.Label lbDown; private System.Windows.Forms.Label lbLeft; private System.Windows.Forms.Label lbUp; private System.Windows.Forms.TextBox mmLog; private System.Windows.Forms.Label lbCmdLog; private System.Windows.Forms.Label lbSerial; private System.Windows.Forms.ComboBox cbbSerialPort; private System.Windows.Forms.Label lbBitSend; private System.Windows.Forms.NumericUpDown edtBitSync; private System.Windows.Forms.NumericUpDown edtPacketSync; private System.Windows.Forms.Label lbPacketSend; private System.Windows.Forms.Button btStartStop; private System.Windows.Forms.TextBox mmStatus; private System.Windows.Forms.Label lbPortStat; private System.Windows.Forms.Timer timerLog; private System.Windows.Forms.Label lbSent; } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using DotVVM.Framework.Binding; using DotVVM.Framework.Compilation.Parser.Dothtml.Parser; using DotVVM.Framework.Runtime; using DotVVM.Framework.Compilation.Parser.Binding.Parser; using DotVVM.Framework.Compilation.Binding; using DotVVM.Framework.Utils; using System.Diagnostics.CodeAnalysis; using DotVVM.Framework.Compilation.ViewCompiler; namespace DotVVM.Framework.Compilation.ControlTree.Resolved { public class ResolvedTreeBuilder : IAbstractTreeBuilder { private readonly BindingCompilationService bindingService; private readonly CompiledAssemblyCache compiledAssemblyCache; private readonly ExtensionMethodsCache extensionMethodsCache; public ResolvedTreeBuilder(BindingCompilationService bindingService, CompiledAssemblyCache compiledAssemblyCache, ExtensionMethodsCache extensionsMethodsCache) { this.bindingService = bindingService; this.compiledAssemblyCache = compiledAssemblyCache; this.extensionMethodsCache = extensionsMethodsCache; } public IAbstractTreeRoot BuildTreeRoot(IControlTreeResolver controlTreeResolver, IControlResolverMetadata metadata, DothtmlRootNode node, IDataContextStack dataContext, IReadOnlyDictionary<string, IReadOnlyList<IAbstractDirective>> directives, IAbstractControlBuilderDescriptor? masterPage) { return new ResolvedTreeRoot((ControlResolverMetadata)metadata, node, (DataContextStack)dataContext, directives, (ControlBuilderDescriptor?)masterPage); } public IAbstractControl BuildControl(IControlResolverMetadata metadata, DothtmlNode? node, IDataContextStack dataContext) { return new ResolvedControl((ControlResolverMetadata)metadata, node, (DataContextStack)dataContext); } public IAbstractBinding BuildBinding(BindingParserOptions bindingOptions, IDataContextStack dataContext, DothtmlBindingNode node, IPropertyDescriptor? property) { return new ResolvedBinding(bindingService, bindingOptions, (DataContextStack)dataContext, node.Value, property: property as DotvvmProperty) { DothtmlNode = node, }; } public IAbstractPropertyBinding BuildPropertyBinding(IPropertyDescriptor property, IAbstractBinding binding, DothtmlAttributeNode? sourceAttribute) { return new ResolvedPropertyBinding((DotvvmProperty)property, (ResolvedBinding)binding) { DothtmlNode = sourceAttribute }; } public IAbstractPropertyControl BuildPropertyControl(IPropertyDescriptor property, IAbstractControl? control, DothtmlElementNode? wrapperElement) { return new ResolvedPropertyControl((DotvvmProperty)property, (ResolvedControl?)control) { DothtmlNode = wrapperElement }; } public IAbstractPropertyControlCollection BuildPropertyControlCollection(IPropertyDescriptor property, IEnumerable<IAbstractControl> controls, DothtmlElementNode? wrapperElement) { return new ResolvedPropertyControlCollection((DotvvmProperty)property, controls.Cast<ResolvedControl>().ToList()) { DothtmlNode = wrapperElement }; } public IAbstractPropertyTemplate BuildPropertyTemplate(IPropertyDescriptor property, IEnumerable<IAbstractControl> templateControls, DothtmlElementNode? wrapperElement) { return new ResolvedPropertyTemplate((DotvvmProperty)property, templateControls.Cast<ResolvedControl>().ToList()) { DothtmlNode = wrapperElement }; } public IAbstractPropertyValue BuildPropertyValue(IPropertyDescriptor property, object? value, DothtmlNode? sourceNode) { return new ResolvedPropertyValue((DotvvmProperty)property, value) { DothtmlNode = sourceNode }; } public IAbstractServiceInjectDirective BuildServiceInjectDirective( DothtmlDirectiveNode node, SimpleNameBindingParserNode nameSyntax, BindingParserNode typeSyntax) { foreach (var syntaxNode in nameSyntax.EnumerateNodes().Concat(typeSyntax.EnumerateNodes() ?? Enumerable.Empty<BindingParserNode>())) { syntaxNode.NodeErrors.ForEach(node.AddError); } var expression = ParseDirectiveExpression(node, typeSyntax); if (expression is UnknownStaticClassIdentifierExpression) { node.AddError($"{typeSyntax.ToDisplayString()} is not a valid type."); return new ResolvedServiceInjectDirective(nameSyntax, typeSyntax, null) { DothtmlNode = node }; } else if (expression is StaticClassIdentifierExpression) { return new ResolvedServiceInjectDirective(nameSyntax, typeSyntax, expression.Type) { DothtmlNode = node }; } else { return new ResolvedServiceInjectDirective(nameSyntax, typeSyntax, null) { DothtmlNode = node }; } } public IAbstractImportDirective BuildImportDirective( DothtmlDirectiveNode node, BindingParserNode? aliasSyntax, BindingParserNode nameSyntax) { foreach (var syntaxNode in nameSyntax.EnumerateNodes().Concat(aliasSyntax?.EnumerateNodes() ?? Enumerable.Empty<BindingParserNode>())) { syntaxNode.NodeErrors.ForEach(node.AddError); } var expression = ParseDirectiveExpression(node, nameSyntax); if (expression is UnknownStaticClassIdentifierExpression) { var namespaceValid = expression .CastTo<UnknownStaticClassIdentifierExpression>().Name .Apply(compiledAssemblyCache.IsAssemblyNamespace); if (!namespaceValid) { node.AddError($"{nameSyntax.ToDisplayString()} is unknown type or namespace."); } return new ResolvedImportDirective(aliasSyntax, nameSyntax, null) { DothtmlNode = node }; } else if (expression is StaticClassIdentifierExpression) { return new ResolvedImportDirective(aliasSyntax, nameSyntax, expression.Type) { DothtmlNode = node }; } node.AddError($"{nameSyntax.ToDisplayString()} is not a type or namespace."); return new ResolvedImportDirective(aliasSyntax, nameSyntax, null) { DothtmlNode = node }; } public IAbstractViewModelDirective BuildViewModelDirective(DothtmlDirectiveNode directive, BindingParserNode nameSyntax) { var type = ResolveTypeNameDirective(directive, nameSyntax); return new ResolvedViewModelDirective(nameSyntax, type!) { DothtmlNode = directive }; } public IAbstractBaseTypeDirective BuildBaseTypeDirective(DothtmlDirectiveNode directive, BindingParserNode nameSyntax) { var type = ResolveTypeNameDirective(directive, nameSyntax); return new ResolvedBaseTypeDirective(nameSyntax, type!) { DothtmlNode = directive }; } public IAbstractDirective BuildViewModuleDirective(DothtmlDirectiveNode directiveNode, string modulePath, string resourceName) => new ResolvedViewModuleDirective(modulePath, resourceName) { DothtmlNode = directiveNode }; private ResolvedTypeDescriptor? ResolveTypeNameDirective(DothtmlDirectiveNode directive, BindingParserNode nameSyntax) { var expression = ParseDirectiveExpression(directive, nameSyntax) as StaticClassIdentifierExpression; if (expression == null) { directive.AddError($"Could not resolve type '{nameSyntax.ToDisplayString()}'."); return null; } else return new ResolvedTypeDescriptor(expression.Type); } private Expression? ParseDirectiveExpression(DothtmlDirectiveNode directive, BindingParserNode expressionSyntax) { TypeRegistry registry; if (expressionSyntax is TypeOrFunctionReferenceBindingParserNode typeOrFunction) expressionSyntax = typeOrFunction.ToTypeReference(); if (expressionSyntax is AssemblyQualifiedNameBindingParserNode assemblyQualifiedName) { registry = TypeRegistry.DirectivesDefault(compiledAssemblyCache, assemblyQualifiedName.AssemblyName.ToDisplayString()); } else { registry = TypeRegistry.DirectivesDefault(compiledAssemblyCache); } var visitor = new ExpressionBuildingVisitor(registry, new MemberExpressionFactory(extensionMethodsCache)) { ResolveOnlyTypeName = true, Scope = null }; try { return visitor.Visit(expressionSyntax); } catch (Exception ex) { directive.AddError($"{expressionSyntax.ToDisplayString()} is not a valid type or namespace: {ex.Message}"); return null; } } public IAbstractDirective BuildDirective(DothtmlDirectiveNode node) { return new ResolvedDirective() { DothtmlNode = node }; } public bool AddProperty(IAbstractControl control, IAbstractPropertySetter setter, [NotNullWhen(false)] out string? error) { return ((ResolvedControl)control).SetProperty((ResolvedPropertySetter)setter, false, out error); } public void AddChildControl(IAbstractContentNode control, IAbstractControl child) { ((ResolvedContentNode)control).AddChild((ResolvedControl)child); } } }
using System; using System.Collections.Generic; /// <summary> /// A binary heap, useful for sorting data and priority queues. /// </summary> /// <typeparam name="T"><![CDATA[IComparable<T> type of item in the heap]]>.</typeparam> public class BinaryHeap<T> : ICollection<T> where T : IComparable<T> { // Constants private const int DEFAULT_SIZE = 4; // Fields private T[] _data = new T[DEFAULT_SIZE]; private int _count = 0; private int _capacity = DEFAULT_SIZE; private bool _sorted; // Properties /// <summary> /// Gets the number of values in the heap. /// </summary> public int Count { get { return _count; } } /// <summary> /// Gets or sets the capacity of the heap. /// </summary> public int Capacity { get { return _capacity; } set { int previousCapacity = _capacity; _capacity = Math.Max (value, _count); if (_capacity != previousCapacity) { T[] temp = new T[_capacity]; Array.Copy (_data, temp, _count); _data = temp; } } } // Methods /// <summary> /// Creates a new binary heap. /// </summary> public BinaryHeap () { } private BinaryHeap (T[] data, int count) { Capacity = count; _count = count; Array.Copy (data, _data, count); } /// <summary> /// Gets the first value in the heap without removing it. /// </summary> /// <returns>The lowest value of type TValue.</returns> public T Peek () { return _data [0]; } /// <summary> /// Removes all items from the heap. /// </summary> public void Clear () { this._count = 0; _data = new T[_capacity]; } /// <summary> /// Adds a key and value to the heap. /// </summary> /// <param name="item">The item to add to the heap.</param> public void Add (T item) { if (_count == _capacity) { Capacity *= 2; } _data [_count] = item; UpHeap (); _count++; } /// <summary> /// Removes and returns the first item in the heap. /// </summary> /// <returns>The next value in the heap.</returns> public T Remove () { if (this._count == 0) { throw new InvalidOperationException ("Cannot remove item, heap is empty."); } T v = _data [0]; _count--; _data [0] = _data [_count]; _data [_count] = default(T); //Clears the Last Node DownHeap (); return v; } private void UpHeap () //helper function that performs up-heap bubbling { _sorted = false; int p = _count; T item = _data [p]; int par = Parent (p); while (par > -1 && item.CompareTo(_data[par]) < 0) { _data [p] = _data [par]; //Swap nodes p = par; par = Parent (p); } _data [p] = item; } private void DownHeap () //helper function that performs down-heap bubbling { _sorted = false; int n; int p = 0; T item = _data [p]; while (true) { int ch1 = Child1 (p); if (ch1 >= _count) break; int ch2 = Child2 (p); if (ch2 >= _count) { n = ch1; } else { n = _data [ch1].CompareTo (_data [ch2]) < 0 ? ch1 : ch2; } if (item.CompareTo (_data [n]) > 0) { _data [p] = _data [n]; //Swap nodes p = n; } else { break; } } _data [p] = item; } private void EnsureSort () { if (_sorted) return; Array.Sort (_data, 0, _count); _sorted = true; } private static int Parent (int index) //helper function that calculates the parent of a node { return (index - 1) >> 1; } private static int Child1 (int index) //helper function that calculates the first child of a node { return (index << 1) + 1; } private static int Child2 (int index) //helper function that calculates the second child of a node { return (index << 1) + 2; } /// <summary> /// Creates a new instance of an identical binary heap. /// </summary> /// <returns>A BinaryHeap.</returns> public BinaryHeap<T> Copy () { return new BinaryHeap<T> (_data, _count); } /// <summary> /// Gets an enumerator for the binary heap. /// </summary> /// <returns>An IEnumerator of type T.</returns> public IEnumerator<T> GetEnumerator () { EnsureSort (); for (int i = 0; i < _count; i++) { yield return _data [i]; } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () { return GetEnumerator (); } /// <summary> /// Checks to see if the binary heap contains the specified item. /// </summary> /// <param name="item">The item to search the binary heap for.</param> /// <returns>A boolean, true if binary heap contains item.</returns> public bool Contains (T item) { EnsureSort (); return Array.BinarySearch<T> (_data, 0, _count, item) >= 0; } /// <summary> /// Copies the binary heap to an array at the specified index. /// </summary> /// <param name="array">One dimensional array that is the destination of the copied elements.</param> /// <param name="arrayIndex">The zero-based index at which copying begins.</param> public void CopyTo (T[] array, int arrayIndex) { EnsureSort (); Array.Copy (_data, array, _count); } /// <summary> /// Gets whether or not the binary heap is readonly. /// </summary> public bool IsReadOnly { get { return false; } } /// <summary> /// Removes an item from the binary heap. This utilizes the type T's Comparer and will not remove duplicates. /// </summary> /// <param name="item">The item to be removed.</param> /// <returns>Boolean true if the item was removed.</returns> public bool Remove (T item) { EnsureSort (); int i = Array.BinarySearch<T> (_data, 0, _count, item); if (i < 0) return false; Array.Copy (_data, i + 1, _data, i, _count - i); _data [_count] = default(T); _count--; return true; } }
using System.Globalization; using System.Reactive; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using Autofac; using AutoMapper; using Miningcore.Blockchain.Bitcoin; using Miningcore.Blockchain.Equihash.Configuration; using Miningcore.Configuration; using Miningcore.Extensions; using Miningcore.JsonRpc; using Miningcore.Messaging; using Miningcore.Mining; using Miningcore.Nicehash; using Miningcore.Notifications.Messages; using Miningcore.Persistence; using Miningcore.Persistence.Repositories; using Miningcore.Stratum; using Miningcore.Time; using Miningcore.Util; using Newtonsoft.Json; using static Miningcore.Util.ActionUtils; namespace Miningcore.Blockchain.Equihash; [CoinFamily(CoinFamily.Equihash)] public class EquihashPool : PoolBase { public EquihashPool(IComponentContext ctx, JsonSerializerSettings serializerSettings, IConnectionFactory cf, IStatsRepository statsRepo, IMapper mapper, IMasterClock clock, IMessageBus messageBus, NicehashService nicehashService) : base(ctx, serializerSettings, cf, statsRepo, mapper, clock, messageBus, nicehashService) { } protected EquihashJobManager manager; protected object currentJobParams; private double hashrateDivisor; private EquihashPoolConfigExtra extraConfig; private EquihashCoinTemplate coin; public override void Configure(PoolConfig poolConfig, ClusterConfig clusterConfig) { coin = poolConfig.Template.As<EquihashCoinTemplate>(); base.Configure(poolConfig, clusterConfig); extraConfig = poolConfig.Extra.SafeExtensionDataAs<EquihashPoolConfigExtra>(); if(poolConfig.Template.As<EquihashCoinTemplate>().UsesZCashAddressFormat && string.IsNullOrEmpty(extraConfig?.ZAddress)) logger.ThrowLogPoolStartupException("Pool z-address is not configured"); } protected override async Task SetupJobManager(CancellationToken ct) { manager = ctx.Resolve<EquihashJobManager>( new TypedParameter(typeof(IExtraNonceProvider), new EquihashExtraNonceProvider(poolConfig.Id, clusterConfig.InstanceId))); manager.Configure(poolConfig, clusterConfig); await manager.StartAsync(ct); if(poolConfig.EnableInternalStratum == true) { disposables.Add(manager.Jobs .Select(job => Observable.FromAsync(() => Guard(()=> OnNewJobAsync(job), ex=> logger.Debug(() => $"{nameof(OnNewJobAsync)}: {ex.Message}")))) .Concat() .Subscribe(_ => { }, ex => { logger.Debug(ex, nameof(OnNewJobAsync)); })); // start with initial blocktemplate await manager.Jobs.Take(1).ToTask(ct); } else { // keep updating NetworkStats disposables.Add(manager.Jobs.Subscribe()); } hashrateDivisor = (double) new BigRational(manager.ChainConfig.Diff1BValue, EquihashConstants.ZCashDiff1b); } protected override async Task InitStatsAsync() { await base.InitStatsAsync(); blockchainStats = manager.BlockchainStats; } protected async Task OnSubscribeAsync(StratumConnection connection, Timestamped<JsonRpcRequest> tsRequest) { var request = tsRequest.Value; var context = connection.ContextAs<BitcoinWorkerContext>(); if(request.Id == null) throw new StratumException(StratumError.MinusOne, "missing request id"); var requestParams = request.ParamsAs<string[]>(); var data = new object[] { connection.ConnectionId, } .Concat(manager.GetSubscriberData(connection)) .ToArray(); await connection.RespondAsync(data, request.Id); // setup worker context context.IsSubscribed = true; context.UserAgent = requestParams?.Length > 0 ? requestParams[0].Trim() : null; } protected async Task OnAuthorizeAsync(StratumConnection connection, Timestamped<JsonRpcRequest> tsRequest, CancellationToken ct) { var request = tsRequest.Value; if(request.Id == null) throw new StratumException(StratumError.MinusOne, "missing request id"); var context = connection.ContextAs<BitcoinWorkerContext>(); var requestParams = request.ParamsAs<string[]>(); var workerValue = requestParams?.Length > 0 ? requestParams[0] : null; var password = requestParams?.Length > 1 ? requestParams[1] : null; var passParts = password?.Split(PasswordControlVarsSeparator); // extract worker/miner var split = workerValue?.Split('.'); var minerName = split?.FirstOrDefault()?.Trim(); var workerName = split?.Skip(1).FirstOrDefault()?.Trim() ?? string.Empty; // assumes that workerName is an address context.IsAuthorized = await manager.ValidateAddressAsync(minerName, ct); context.Miner = minerName; context.Worker = workerName; if(context.IsAuthorized) { // respond await connection.RespondAsync(context.IsAuthorized, request.Id); // log association logger.Info(() => $"[{connection.ConnectionId}] Authorized worker {workerValue}"); // extract control vars from password var staticDiff = GetStaticDiffFromPassparts(passParts); // Nicehash support var nicehashDiff = await GetNicehashStaticMinDiff(connection, context.UserAgent, coin.Name, coin.GetAlgorithmName()); if(nicehashDiff.HasValue) { if(!staticDiff.HasValue || nicehashDiff > staticDiff) { logger.Info(() => $"[{connection.ConnectionId}] Nicehash detected. Using API supplied difficulty of {nicehashDiff.Value}"); staticDiff = nicehashDiff; } else logger.Info(() => $"[{connection.ConnectionId}] Nicehash detected. Using miner supplied difficulty of {staticDiff.Value}"); } // Static diff if(staticDiff.HasValue && (context.VarDiff != null && staticDiff.Value >= context.VarDiff.Config.MinDiff || context.VarDiff == null && staticDiff.Value > context.Difficulty)) { context.VarDiff = null; // disable vardiff context.SetDifficulty(staticDiff.Value); logger.Info(() => $"[{connection.ConnectionId}] Setting static difficulty of {staticDiff.Value}"); await connection.NotifyAsync(BitcoinStratumMethods.SetDifficulty, new object[] { context.Difficulty }); } // send intial update await connection.NotifyAsync(EquihashStratumMethods.SetTarget, new object[] { EncodeTarget(context.Difficulty) }); await connection.NotifyAsync(BitcoinStratumMethods.MiningNotify, currentJobParams); } else { await connection.RespondErrorAsync(StratumError.UnauthorizedWorker, "Authorization failed", request.Id, context.IsAuthorized); // issue short-time ban if unauthorized to prevent DDos on daemon (validateaddress RPC) logger.Info(() => $"[{connection.ConnectionId}] Banning unauthorized worker {minerName} for {loginFailureBanTimeout.TotalSeconds} sec"); banManager.Ban(connection.RemoteEndpoint.Address, loginFailureBanTimeout); CloseConnection(connection); } } protected virtual async Task OnSubmitAsync(StratumConnection connection, Timestamped<JsonRpcRequest> tsRequest, CancellationToken ct) { var request = tsRequest.Value; var context = connection.ContextAs<BitcoinWorkerContext>(); try { if(request.Id == null) throw new StratumException(StratumError.MinusOne, "missing request id"); // check age of submission (aged submissions are usually caused by high server load) var requestAge = clock.Now - tsRequest.Timestamp.UtcDateTime; if(requestAge > maxShareAge) { logger.Warn(() => $"[{connection.ConnectionId}] Dropping stale share submission request (server overloaded?)"); return; } // check worker state context.LastActivity = clock.Now; // validate worker if(!context.IsAuthorized) throw new StratumException(StratumError.UnauthorizedWorker, "unauthorized worker"); else if(!context.IsSubscribed) throw new StratumException(StratumError.NotSubscribed, "not subscribed"); // submit var requestParams = request.ParamsAs<string[]>(); var poolEndpoint = poolConfig.Ports[connection.LocalEndpoint.Port]; var share = await manager.SubmitShareAsync(connection, requestParams, poolEndpoint.Difficulty, ct); await connection.RespondAsync(true, request.Id); // publish messageBus.SendMessage(new StratumShare(connection, share)); // telemetry PublishTelemetry(TelemetryCategory.Share, clock.Now - tsRequest.Timestamp.UtcDateTime, true); logger.Info(() => $"[{connection.ConnectionId}] Share accepted: D={Math.Round(share.Difficulty, 3)}"); // update pool stats if(share.IsBlockCandidate) poolStats.LastPoolBlockTime = clock.Now; // update client stats context.Stats.ValidShares++; await UpdateVarDiffAsync(connection); } catch(StratumException ex) { // telemetry PublishTelemetry(TelemetryCategory.Share, clock.Now - tsRequest.Timestamp.UtcDateTime, false); // update client stats context.Stats.InvalidShares++; logger.Info(() => $"[{connection.ConnectionId}] Share rejected: {ex.Message} [{context.UserAgent}]"); // banning ConsiderBan(connection, context, poolConfig.Banning); throw; } } private async Task OnSuggestTargetAsync(StratumConnection connection, Timestamped<JsonRpcRequest> tsRequest) { var request = tsRequest.Value; var context = connection.ContextAs<BitcoinWorkerContext>(); if(request.Id == null) throw new StratumException(StratumError.MinusOne, "missing request id"); var requestParams = request.ParamsAs<string[]>(); var target = requestParams.FirstOrDefault(); if(!string.IsNullOrEmpty(target)) { if(System.Numerics.BigInteger.TryParse(target, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var targetBig)) { var newDiff = (double) new BigRational(manager.ChainConfig.Diff1BValue, targetBig); var poolEndpoint = poolConfig.Ports[connection.LocalEndpoint.Port]; if(newDiff >= poolEndpoint.Difficulty) { context.EnqueueNewDifficulty(newDiff); context.ApplyPendingDifficulty(); await connection.NotifyAsync(EquihashStratumMethods.SetTarget, new object[] { EncodeTarget(context.Difficulty) }); } else await connection.RespondErrorAsync(StratumError.Other, "suggested difficulty too low", request.Id); } else await connection.RespondErrorAsync(StratumError.Other, "invalid target", request.Id); } else await connection.RespondErrorAsync(StratumError.Other, "invalid target", request.Id); } protected override async Task OnRequestAsync(StratumConnection connection, Timestamped<JsonRpcRequest> tsRequest, CancellationToken ct) { var request = tsRequest.Value; try { switch(request.Method) { case BitcoinStratumMethods.Subscribe: await OnSubscribeAsync(connection, tsRequest); break; case BitcoinStratumMethods.Authorize: await OnAuthorizeAsync(connection, tsRequest, ct); break; case BitcoinStratumMethods.SubmitShare: await OnSubmitAsync(connection, tsRequest, ct); break; case EquihashStratumMethods.SuggestTarget: await OnSuggestTargetAsync(connection, tsRequest); break; case BitcoinStratumMethods.ExtraNonceSubscribe: // ignored break; default: logger.Debug(() => $"[{connection.ConnectionId}] Unsupported RPC request: {JsonConvert.SerializeObject(request, serializerSettings)}"); await connection.RespondErrorAsync(StratumError.Other, $"Unsupported request {request.Method}", request.Id); break; } } catch(StratumException ex) { await connection.RespondErrorAsync(ex.Code, ex.Message, request.Id, false); } } protected Task OnNewJobAsync(object jobParams) { currentJobParams = jobParams; logger.Info(() => "Broadcasting job"); return Guard(()=> Task.WhenAll(ForEachConnection(async connection => { if(!connection.IsAlive) return; var context = connection.ContextAs<BitcoinWorkerContext>(); if(!context.IsSubscribed || !context.IsAuthorized || CloseIfDead(connection, context)) return; // varDiff: if the client has a pending difficulty change, apply it now if(context.ApplyPendingDifficulty()) await connection.NotifyAsync(EquihashStratumMethods.SetTarget, new object[] { EncodeTarget(context.Difficulty) }); // send job await connection.NotifyAsync(BitcoinStratumMethods.MiningNotify, currentJobParams); })), ex=> logger.Debug(() => $"{nameof(OnNewJobAsync)}: {ex.Message}")); } public override double HashrateFromShares(double shares, double interval) { var multiplier = BitcoinConstants.Pow2x32; var result = shares * multiplier / interval / 1000000 * 2; result /= hashrateDivisor; return result; } public override double ShareMultiplier => 1; protected override async Task OnVarDiffUpdateAsync(StratumConnection connection, double newDiff) { var context = connection.ContextAs<BitcoinWorkerContext>(); context.EnqueueNewDifficulty(newDiff); // apply immediately and notify client if(context.HasPendingDifficulty) { context.ApplyPendingDifficulty(); await connection.NotifyAsync(EquihashStratumMethods.SetTarget, new object[] { EncodeTarget(context.Difficulty) }); await connection.NotifyAsync(BitcoinStratumMethods.MiningNotify, currentJobParams); } } protected override WorkerContextBase CreateWorkerContext() { return new BitcoinWorkerContext(); } private string EncodeTarget(double difficulty) { return EquihashUtils.EncodeTarget(difficulty, manager.ChainConfig); } }
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using WebApplication.Data; namespace WebApplication.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] partial class ApplicationDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "1.0.0-rc2-20901"); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasName("RoleNameIndex"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.HasIndex("UserId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("WebApplication.Models.ApplicationUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasAnnotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .HasName("UserNameIndex"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b => { b.HasOne("WebApplication.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b => { b.HasOne("WebApplication.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("WebApplication.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); } } }
// // AudioCdSource.cs // // Author: // Aaron Bockover <[email protected]> // Alex Launi <[email protected]> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.Threading; using Mono.Unix; using Hyena; using Banshee.Base; using Banshee.ServiceStack; using Banshee.Sources; using Banshee.Library; using Banshee.Collection; using Banshee.Collection.Database; using Gtk; using Banshee.Gui; namespace Banshee.OpticalDisc.AudioCd { public class AudioCdSource : DiscSource, IImportSource, IDurationAggregator, IFileSizeAggregator { private SourceMessage query_message; public AudioCdSource (AudioCdService service, AudioCdDiscModel discModel) : base ((DiscService) service, (DiscModel) discModel, Catalog.GetString ("Audio CD"), discModel.Title, 59) { TypeUniqueId = ""; Properties.SetString ("TrackView.ColumnControllerXml", String.Format (@" <column-controller> <column> <renderer type=""Hyena.Data.Gui.ColumnCellCheckBox"" property=""RipEnabled""/> </column> <add-all-defaults /> </column-controller> ")); Model.MetadataQueryStarted += OnMetadataQueryStarted; Model.MetadataQueryFinished += OnMetadataQueryFinished; Model.EnabledCountChanged += OnEnabledCountChanged; Model.LoadModelFromDisc (); SetupGui (); } public TimeSpan Duration { get { return Model.Duration; } } public long FileSize { get { return Model.FileSize; } } public new AudioCdDiscModel Model { get { return (AudioCdDiscModel) base.DiscModel; } set { base.DiscModel = value; } } public override void Dispose () { StopPlayingDisc (); ClearMessages (); Model.MetadataQueryStarted -= OnMetadataQueryStarted; Model.MetadataQueryFinished -= OnMetadataQueryFinished; Model.EnabledCountChanged -= OnEnabledCountChanged; Service = null; Model = null; } private void OnEnabledCountChanged (object o, EventArgs args) { UpdateActions (); } private void OnMetadataQueryStarted (object o, EventArgs args) { if (query_message != null) { DestroyQueryMessage (); } query_message = new SourceMessage (this); query_message.FreezeNotify (); query_message.CanClose = false; query_message.IsSpinning = true; query_message.Text = Catalog.GetString ("Searching for track information..."); query_message.ThawNotify (); PushMessage (query_message); } private void OnMetadataQueryFinished (object o, EventArgs args) { if (Model.Title != Name) { Name = Model.Title; OnUpdated (); } if (Model.MetadataQuerySuccess) { DestroyQueryMessage (); if (DiscIsPlaying) { ServiceManager.PlayerEngine.TrackInfoUpdated (); } if (AudioCdService.AutoRip.Get ()) { BeginAutoRip (); } return; } if (query_message == null) { return; } query_message.FreezeNotify (); query_message.IsSpinning = false; query_message.SetIconName ("dialog-error"); query_message.Text = Catalog.GetString ("Could not fetch track information"); query_message.CanClose = true; query_message.ThawNotify (); } private void DestroyQueryMessage () { if (query_message != null) { RemoveMessage (query_message); query_message = null; } } private void BeginAutoRip () { // Make sure the album isn't already in the Library TrackInfo track = Model[0]; int count = ServiceManager.DbConnection.Query<int> (String.Format ( @"SELECT Count(*) FROM CoreTracks, CoreArtists, CoreAlbums WHERE CoreTracks.PrimarySourceID = ? AND CoreTracks.ArtistID = CoreArtists.ArtistID AND CoreTracks.AlbumID = CoreAlbums.AlbumID AND CoreArtists.Name = ? AND CoreAlbums.Title = ? AND ({0} = ? OR {0} = 0)", Banshee.Query.BansheeQuery.DiscNumberField.Column), ServiceManager.SourceManager.MusicLibrary.DbId, track.ArtistName, track.AlbumTitle, track.DiscNumber ); if (count > 0) { SetStatus (Catalog.GetString ("Automatic import off since this album is already in the Music Library."), true, false, null); return; } Log.DebugFormat ("Beginning auto rip of {0}", Name); ImportDisc (); } internal void ImportDisc () { AudioCdRipper ripper = null; try { if (AudioCdRipper.Supported) { ripper = new AudioCdRipper (this); ripper.Finished += OnRipperFinished; ripper.Start (); } } catch (Exception e) { if (ripper != null) { ripper.Dispose (); } Log.Error (Catalog.GetString ("Could not import CD"), e.Message, true); Log.Exception (e); } } private void OnRipperFinished (object o, EventArgs args) { if (AudioCdService.EjectAfterRipped.Get ()) { Unmap (); } } internal void DuplicateDisc () { try { AudioCdDuplicator.Duplicate (Model); } catch (Exception e) { Hyena.Log.Error (Catalog.GetString ("Could not duplicate audio CD"), e.Message, true); Hyena.Log.Exception (e); } } internal void LockAllTracks () { StopPlayingDisc (); foreach (AudioCdTrackInfo track in Model) { track.CanPlay = false; } Model.NotifyUpdated (); } internal void UnlockAllTracks () { foreach (AudioCdTrackInfo track in Model) { track.CanPlay = true; } Model.NotifyUpdated (); } internal void UnlockTrack (AudioCdTrackInfo track) { track.CanPlay = true; Model.NotifyUpdated (); } #region DiscSource public override bool CanRepeat { get { return true;} } public override bool CanShuffle { get { return true; } } #endregion #region Source Overrides public override int Count { get { return Model.Count; } } public override string PreferencesPageId { get { return "audio-cd"; } } public override bool HasEditableTrackProperties { get { return true; } } public override bool HasViewableTrackProperties { get { return true; } } #endregion #region GUI/ThickClient private bool actions_loaded = false; private void SetupGui () { Properties.SetStringList ("Icon.Name", "media-optical-cd-audio", "media-optical-cd", "media-optical", "gnome-dev-cdrom-audio", "source-cd-audio"); Properties.SetString ("SourcePreferencesActionLabel", Catalog.GetString ("Audio CD Preferences")); Properties.SetString ("UnmapSourceActionLabel", Catalog.GetString ("Eject Disc")); Properties.SetString ("UnmapSourceActionIconName", "media-eject"); Properties.SetString ("ActiveSourceUIResource", "ActiveSourceUI.xml"); Properties.SetString ("GtkActionPath", "/AudioCdContextMenu"); actions_loaded = true; UpdateActions (); } private void UpdateActions () { InterfaceActionService uia_service = ServiceManager.Get<InterfaceActionService> (); if (uia_service == null) { return; } Gtk.Action rip_action = uia_service.GlobalActions["RipDiscAction"]; if (rip_action != null) { string title = Model.Title; int max_title_length = 20; title = title.Length > max_title_length ? String.Format ("{0}\u2026", title.Substring (0, max_title_length).Trim ()) : title; rip_action.Label = String.Format (Catalog.GetString ("Import \u201f{0}\u201d"), title); rip_action.ShortLabel = Catalog.GetString ("Import CD"); rip_action.IconName = "media-import-audio-cd"; rip_action.Sensitive = AudioCdRipper.Supported && Model.EnabledCount > 0; } Gtk.Action duplicate_action = uia_service.GlobalActions["DuplicateDiscAction"]; if (duplicate_action != null) { duplicate_action.IconName = "media-optical"; duplicate_action.Visible = AudioCdDuplicator.Supported; } } protected override void OnUpdated () { if (actions_loaded) { UpdateActions (); } base.OnUpdated (); } #endregion #region IImportSource void IImportSource.Import () { ImportDisc (); } string [] IImportSource.IconNames { get { return Properties.GetStringList ("Icon.Name"); } } bool IImportSource.CanImport { get { return true; } } int IImportSource.SortOrder { get { return -10; } } string IImportSource.ImportLabel { get { return null; } } #endregion } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: uploads/uploads_events.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace KillrVideo.Uploads.Events { /// <summary>Holder for reflection information generated from uploads/uploads_events.proto</summary> public static partial class UploadsEventsReflection { #region Descriptor /// <summary>File descriptor for uploads/uploads_events.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static UploadsEventsReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Chx1cGxvYWRzL3VwbG9hZHNfZXZlbnRzLnByb3RvEhlraWxscnZpZGVvLnVw", "bG9hZHMuZXZlbnRzGh9nb29nbGUvcHJvdG9idWYvdGltZXN0YW1wLnByb3Rv", "Ghljb21tb24vY29tbW9uX3R5cGVzLnByb3RvInkKHVVwbG9hZGVkVmlkZW9Q", "cm9jZXNzaW5nRmFpbGVkEikKCHZpZGVvX2lkGAEgASgLMhcua2lsbHJ2aWRl", "by5jb21tb24uVXVpZBItCgl0aW1lc3RhbXAYAiABKAsyGi5nb29nbGUucHJv", "dG9idWYuVGltZXN0YW1wInoKHlVwbG9hZGVkVmlkZW9Qcm9jZXNzaW5nU3Rh", "cnRlZBIpCgh2aWRlb19pZBgBIAEoCzIXLmtpbGxydmlkZW8uY29tbW9uLlV1", "aWQSLQoJdGltZXN0YW1wGAIgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVz", "dGFtcCJ8CiBVcGxvYWRlZFZpZGVvUHJvY2Vzc2luZ1N1Y2NlZWRlZBIpCgh2", "aWRlb19pZBgBIAEoCzIXLmtpbGxydmlkZW8uY29tbW9uLlV1aWQSLQoJdGlt", "ZXN0YW1wGAIgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcCKcAQoW", "VXBsb2FkZWRWaWRlb1B1Ymxpc2hlZBIpCgh2aWRlb19pZBgBIAEoCzIXLmtp", "bGxydmlkZW8uY29tbW9uLlV1aWQSLQoJdGltZXN0YW1wGAIgASgLMhouZ29v", "Z2xlLnByb3RvYnVmLlRpbWVzdGFtcBIRCgl2aWRlb191cmwYAyABKAkSFQoN", "dGh1bWJuYWlsX3VybBgEIAEoCUIcqgIZS2lsbHJWaWRlby5VcGxvYWRzLkV2", "ZW50c2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, global::KillrVideo.Protobuf.CommonTypesReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::KillrVideo.Uploads.Events.UploadedVideoProcessingFailed), global::KillrVideo.Uploads.Events.UploadedVideoProcessingFailed.Parser, new[]{ "VideoId", "Timestamp" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::KillrVideo.Uploads.Events.UploadedVideoProcessingStarted), global::KillrVideo.Uploads.Events.UploadedVideoProcessingStarted.Parser, new[]{ "VideoId", "Timestamp" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::KillrVideo.Uploads.Events.UploadedVideoProcessingSucceeded), global::KillrVideo.Uploads.Events.UploadedVideoProcessingSucceeded.Parser, new[]{ "VideoId", "Timestamp" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::KillrVideo.Uploads.Events.UploadedVideoPublished), global::KillrVideo.Uploads.Events.UploadedVideoPublished.Parser, new[]{ "VideoId", "Timestamp", "VideoUrl", "ThumbnailUrl" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// Event that's published when there's a problem processing an uploaded video /// </summary> public sealed partial class UploadedVideoProcessingFailed : pb::IMessage<UploadedVideoProcessingFailed> { private static readonly pb::MessageParser<UploadedVideoProcessingFailed> _parser = new pb::MessageParser<UploadedVideoProcessingFailed>(() => new UploadedVideoProcessingFailed()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<UploadedVideoProcessingFailed> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::KillrVideo.Uploads.Events.UploadsEventsReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UploadedVideoProcessingFailed() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UploadedVideoProcessingFailed(UploadedVideoProcessingFailed other) : this() { VideoId = other.videoId_ != null ? other.VideoId.Clone() : null; Timestamp = other.timestamp_ != null ? other.Timestamp.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UploadedVideoProcessingFailed Clone() { return new UploadedVideoProcessingFailed(this); } /// <summary>Field number for the "video_id" field.</summary> public const int VideoIdFieldNumber = 1; private global::KillrVideo.Protobuf.Uuid videoId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::KillrVideo.Protobuf.Uuid VideoId { get { return videoId_; } set { videoId_ = value; } } /// <summary>Field number for the "timestamp" field.</summary> public const int TimestampFieldNumber = 2; private global::Google.Protobuf.WellKnownTypes.Timestamp timestamp_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Timestamp Timestamp { get { return timestamp_; } set { timestamp_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as UploadedVideoProcessingFailed); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(UploadedVideoProcessingFailed other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(VideoId, other.VideoId)) return false; if (!object.Equals(Timestamp, other.Timestamp)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (videoId_ != null) hash ^= VideoId.GetHashCode(); if (timestamp_ != null) hash ^= Timestamp.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (videoId_ != null) { output.WriteRawTag(10); output.WriteMessage(VideoId); } if (timestamp_ != null) { output.WriteRawTag(18); output.WriteMessage(Timestamp); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (videoId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(VideoId); } if (timestamp_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Timestamp); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(UploadedVideoProcessingFailed other) { if (other == null) { return; } if (other.videoId_ != null) { if (videoId_ == null) { videoId_ = new global::KillrVideo.Protobuf.Uuid(); } VideoId.MergeFrom(other.VideoId); } if (other.timestamp_ != null) { if (timestamp_ == null) { timestamp_ = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } Timestamp.MergeFrom(other.Timestamp); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (videoId_ == null) { videoId_ = new global::KillrVideo.Protobuf.Uuid(); } input.ReadMessage(videoId_); break; } case 18: { if (timestamp_ == null) { timestamp_ = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } input.ReadMessage(timestamp_); break; } } } } } /// <summary> /// Event that's published when an uploaded video has started being processed /// </summary> public sealed partial class UploadedVideoProcessingStarted : pb::IMessage<UploadedVideoProcessingStarted> { private static readonly pb::MessageParser<UploadedVideoProcessingStarted> _parser = new pb::MessageParser<UploadedVideoProcessingStarted>(() => new UploadedVideoProcessingStarted()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<UploadedVideoProcessingStarted> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::KillrVideo.Uploads.Events.UploadsEventsReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UploadedVideoProcessingStarted() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UploadedVideoProcessingStarted(UploadedVideoProcessingStarted other) : this() { VideoId = other.videoId_ != null ? other.VideoId.Clone() : null; Timestamp = other.timestamp_ != null ? other.Timestamp.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UploadedVideoProcessingStarted Clone() { return new UploadedVideoProcessingStarted(this); } /// <summary>Field number for the "video_id" field.</summary> public const int VideoIdFieldNumber = 1; private global::KillrVideo.Protobuf.Uuid videoId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::KillrVideo.Protobuf.Uuid VideoId { get { return videoId_; } set { videoId_ = value; } } /// <summary>Field number for the "timestamp" field.</summary> public const int TimestampFieldNumber = 2; private global::Google.Protobuf.WellKnownTypes.Timestamp timestamp_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Timestamp Timestamp { get { return timestamp_; } set { timestamp_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as UploadedVideoProcessingStarted); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(UploadedVideoProcessingStarted other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(VideoId, other.VideoId)) return false; if (!object.Equals(Timestamp, other.Timestamp)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (videoId_ != null) hash ^= VideoId.GetHashCode(); if (timestamp_ != null) hash ^= Timestamp.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (videoId_ != null) { output.WriteRawTag(10); output.WriteMessage(VideoId); } if (timestamp_ != null) { output.WriteRawTag(18); output.WriteMessage(Timestamp); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (videoId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(VideoId); } if (timestamp_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Timestamp); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(UploadedVideoProcessingStarted other) { if (other == null) { return; } if (other.videoId_ != null) { if (videoId_ == null) { videoId_ = new global::KillrVideo.Protobuf.Uuid(); } VideoId.MergeFrom(other.VideoId); } if (other.timestamp_ != null) { if (timestamp_ == null) { timestamp_ = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } Timestamp.MergeFrom(other.Timestamp); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (videoId_ == null) { videoId_ = new global::KillrVideo.Protobuf.Uuid(); } input.ReadMessage(videoId_); break; } case 18: { if (timestamp_ == null) { timestamp_ = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } input.ReadMessage(timestamp_); break; } } } } } /// <summary> /// Event that's published when an uploaded video has been successfully processed /// </summary> public sealed partial class UploadedVideoProcessingSucceeded : pb::IMessage<UploadedVideoProcessingSucceeded> { private static readonly pb::MessageParser<UploadedVideoProcessingSucceeded> _parser = new pb::MessageParser<UploadedVideoProcessingSucceeded>(() => new UploadedVideoProcessingSucceeded()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<UploadedVideoProcessingSucceeded> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::KillrVideo.Uploads.Events.UploadsEventsReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UploadedVideoProcessingSucceeded() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UploadedVideoProcessingSucceeded(UploadedVideoProcessingSucceeded other) : this() { VideoId = other.videoId_ != null ? other.VideoId.Clone() : null; Timestamp = other.timestamp_ != null ? other.Timestamp.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UploadedVideoProcessingSucceeded Clone() { return new UploadedVideoProcessingSucceeded(this); } /// <summary>Field number for the "video_id" field.</summary> public const int VideoIdFieldNumber = 1; private global::KillrVideo.Protobuf.Uuid videoId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::KillrVideo.Protobuf.Uuid VideoId { get { return videoId_; } set { videoId_ = value; } } /// <summary>Field number for the "timestamp" field.</summary> public const int TimestampFieldNumber = 2; private global::Google.Protobuf.WellKnownTypes.Timestamp timestamp_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Timestamp Timestamp { get { return timestamp_; } set { timestamp_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as UploadedVideoProcessingSucceeded); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(UploadedVideoProcessingSucceeded other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(VideoId, other.VideoId)) return false; if (!object.Equals(Timestamp, other.Timestamp)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (videoId_ != null) hash ^= VideoId.GetHashCode(); if (timestamp_ != null) hash ^= Timestamp.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (videoId_ != null) { output.WriteRawTag(10); output.WriteMessage(VideoId); } if (timestamp_ != null) { output.WriteRawTag(18); output.WriteMessage(Timestamp); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (videoId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(VideoId); } if (timestamp_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Timestamp); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(UploadedVideoProcessingSucceeded other) { if (other == null) { return; } if (other.videoId_ != null) { if (videoId_ == null) { videoId_ = new global::KillrVideo.Protobuf.Uuid(); } VideoId.MergeFrom(other.VideoId); } if (other.timestamp_ != null) { if (timestamp_ == null) { timestamp_ = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } Timestamp.MergeFrom(other.Timestamp); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (videoId_ == null) { videoId_ = new global::KillrVideo.Protobuf.Uuid(); } input.ReadMessage(videoId_); break; } case 18: { if (timestamp_ == null) { timestamp_ = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } input.ReadMessage(timestamp_); break; } } } } } /// <summary> /// Event that's published when an uploaded video is available and ready for playback /// </summary> public sealed partial class UploadedVideoPublished : pb::IMessage<UploadedVideoPublished> { private static readonly pb::MessageParser<UploadedVideoPublished> _parser = new pb::MessageParser<UploadedVideoPublished>(() => new UploadedVideoPublished()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<UploadedVideoPublished> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::KillrVideo.Uploads.Events.UploadsEventsReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UploadedVideoPublished() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UploadedVideoPublished(UploadedVideoPublished other) : this() { VideoId = other.videoId_ != null ? other.VideoId.Clone() : null; Timestamp = other.timestamp_ != null ? other.Timestamp.Clone() : null; videoUrl_ = other.videoUrl_; thumbnailUrl_ = other.thumbnailUrl_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UploadedVideoPublished Clone() { return new UploadedVideoPublished(this); } /// <summary>Field number for the "video_id" field.</summary> public const int VideoIdFieldNumber = 1; private global::KillrVideo.Protobuf.Uuid videoId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::KillrVideo.Protobuf.Uuid VideoId { get { return videoId_; } set { videoId_ = value; } } /// <summary>Field number for the "timestamp" field.</summary> public const int TimestampFieldNumber = 2; private global::Google.Protobuf.WellKnownTypes.Timestamp timestamp_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Timestamp Timestamp { get { return timestamp_; } set { timestamp_ = value; } } /// <summary>Field number for the "video_url" field.</summary> public const int VideoUrlFieldNumber = 3; private string videoUrl_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string VideoUrl { get { return videoUrl_; } set { videoUrl_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "thumbnail_url" field.</summary> public const int ThumbnailUrlFieldNumber = 4; private string thumbnailUrl_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ThumbnailUrl { get { return thumbnailUrl_; } set { thumbnailUrl_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as UploadedVideoPublished); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(UploadedVideoPublished other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(VideoId, other.VideoId)) return false; if (!object.Equals(Timestamp, other.Timestamp)) return false; if (VideoUrl != other.VideoUrl) return false; if (ThumbnailUrl != other.ThumbnailUrl) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (videoId_ != null) hash ^= VideoId.GetHashCode(); if (timestamp_ != null) hash ^= Timestamp.GetHashCode(); if (VideoUrl.Length != 0) hash ^= VideoUrl.GetHashCode(); if (ThumbnailUrl.Length != 0) hash ^= ThumbnailUrl.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (videoId_ != null) { output.WriteRawTag(10); output.WriteMessage(VideoId); } if (timestamp_ != null) { output.WriteRawTag(18); output.WriteMessage(Timestamp); } if (VideoUrl.Length != 0) { output.WriteRawTag(26); output.WriteString(VideoUrl); } if (ThumbnailUrl.Length != 0) { output.WriteRawTag(34); output.WriteString(ThumbnailUrl); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (videoId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(VideoId); } if (timestamp_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Timestamp); } if (VideoUrl.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(VideoUrl); } if (ThumbnailUrl.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ThumbnailUrl); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(UploadedVideoPublished other) { if (other == null) { return; } if (other.videoId_ != null) { if (videoId_ == null) { videoId_ = new global::KillrVideo.Protobuf.Uuid(); } VideoId.MergeFrom(other.VideoId); } if (other.timestamp_ != null) { if (timestamp_ == null) { timestamp_ = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } Timestamp.MergeFrom(other.Timestamp); } if (other.VideoUrl.Length != 0) { VideoUrl = other.VideoUrl; } if (other.ThumbnailUrl.Length != 0) { ThumbnailUrl = other.ThumbnailUrl; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (videoId_ == null) { videoId_ = new global::KillrVideo.Protobuf.Uuid(); } input.ReadMessage(videoId_); break; } case 18: { if (timestamp_ == null) { timestamp_ = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } input.ReadMessage(timestamp_); break; } case 26: { VideoUrl = input.ReadString(); break; } case 34: { ThumbnailUrl = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Security.Claims { public partial class Claim { public Claim(System.IO.BinaryReader reader) { } public Claim(System.IO.BinaryReader reader, System.Security.Claims.ClaimsIdentity subject) { } protected Claim(System.Security.Claims.Claim other) { } protected Claim(System.Security.Claims.Claim other, System.Security.Claims.ClaimsIdentity subject) { } public Claim(string type, string value) { } public Claim(string type, string value, string valueType) { } public Claim(string type, string value, string valueType, string issuer) { } public Claim(string type, string value, string valueType, string issuer, string originalIssuer) { } public Claim(string type, string value, string valueType, string issuer, string originalIssuer, System.Security.Claims.ClaimsIdentity subject) { } protected virtual byte[] CustomSerializationData { get { throw null; } } public string Issuer { get { throw null; } } public string OriginalIssuer { get { throw null; } } public System.Collections.Generic.IDictionary<string, string> Properties { get { throw null; } } public System.Security.Claims.ClaimsIdentity Subject { get { throw null; } } public string Type { get { throw null; } } public string Value { get { throw null; } } public string ValueType { get { throw null; } } public virtual System.Security.Claims.Claim Clone() { throw null; } public virtual System.Security.Claims.Claim Clone(System.Security.Claims.ClaimsIdentity identity) { throw null; } public override string ToString() { throw null; } public virtual void WriteTo(System.IO.BinaryWriter writer) { } protected virtual void WriteTo(System.IO.BinaryWriter writer, byte[] userData) { } } public partial class ClaimsIdentity : System.Security.Principal.IIdentity { public const string DefaultIssuer = "LOCAL AUTHORITY"; public const string DefaultNameClaimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"; public const string DefaultRoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"; public ClaimsIdentity() { } public ClaimsIdentity(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims) { } public ClaimsIdentity(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims, string authenticationType) { } public ClaimsIdentity(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims, string authenticationType, string nameType, string roleType) { } public ClaimsIdentity(System.IO.BinaryReader reader) { } protected ClaimsIdentity(System.Runtime.Serialization.SerializationInfo info) { } protected ClaimsIdentity(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } protected ClaimsIdentity(System.Security.Claims.ClaimsIdentity other) { } public ClaimsIdentity(System.Security.Principal.IIdentity identity) { } public ClaimsIdentity(System.Security.Principal.IIdentity identity, System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims) { } public ClaimsIdentity(System.Security.Principal.IIdentity identity, System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims, string authenticationType, string nameType, string roleType) { } public ClaimsIdentity(string authenticationType) { } public ClaimsIdentity(string authenticationType, string nameType, string roleType) { } public System.Security.Claims.ClaimsIdentity Actor { get { throw null; } set { } } public virtual string AuthenticationType { get { throw null; } } public object BootstrapContext { get { throw null; } set { } } public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> Claims { get { throw null; } } protected virtual byte[] CustomSerializationData { get { throw null; } } public virtual bool IsAuthenticated { get { throw null; } } public string Label { get { throw null; } set { } } public virtual string Name { get { throw null; } } public string NameClaimType { get { throw null; } } public string RoleClaimType { get { throw null; } } public virtual void AddClaim(System.Security.Claims.Claim claim) { } public virtual void AddClaims(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims) { } public virtual System.Security.Claims.ClaimsIdentity Clone() { throw null; } protected virtual System.Security.Claims.Claim CreateClaim(System.IO.BinaryReader reader) { throw null; } public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> FindAll(System.Predicate<System.Security.Claims.Claim> match) { throw null; } public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> FindAll(string type) { throw null; } public virtual System.Security.Claims.Claim FindFirst(System.Predicate<System.Security.Claims.Claim> match) { throw null; } public virtual System.Security.Claims.Claim FindFirst(string type) { throw null; } protected virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public virtual bool HasClaim(System.Predicate<System.Security.Claims.Claim> match) { throw null; } public virtual bool HasClaim(string type, string value) { throw null; } public virtual void RemoveClaim(System.Security.Claims.Claim claim) { } public virtual bool TryRemoveClaim(System.Security.Claims.Claim claim) { throw null; } public virtual void WriteTo(System.IO.BinaryWriter writer) { } protected virtual void WriteTo(System.IO.BinaryWriter writer, byte[] userData) { } } public partial class ClaimsPrincipal : System.Security.Principal.IPrincipal { public ClaimsPrincipal() { } public ClaimsPrincipal(System.Collections.Generic.IEnumerable<System.Security.Claims.ClaimsIdentity> identities) { } public ClaimsPrincipal(System.IO.BinaryReader reader) { } protected ClaimsPrincipal(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public ClaimsPrincipal(System.Security.Principal.IIdentity identity) { } public ClaimsPrincipal(System.Security.Principal.IPrincipal principal) { } public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> Claims { get { throw null; } } public static System.Func<System.Security.Claims.ClaimsPrincipal> ClaimsPrincipalSelector { get { throw null; } set { } } public static System.Security.Claims.ClaimsPrincipal Current { get { throw null; } } protected virtual byte[] CustomSerializationData { get { throw null; } } public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.ClaimsIdentity> Identities { get { throw null; } } public virtual System.Security.Principal.IIdentity Identity { get { throw null; } } public static System.Func<System.Collections.Generic.IEnumerable<System.Security.Claims.ClaimsIdentity>, System.Security.Claims.ClaimsIdentity> PrimaryIdentitySelector { get { throw null; } set { } } public virtual void AddIdentities(System.Collections.Generic.IEnumerable<System.Security.Claims.ClaimsIdentity> identities) { } public virtual void AddIdentity(System.Security.Claims.ClaimsIdentity identity) { } public virtual System.Security.Claims.ClaimsPrincipal Clone() { throw null; } protected virtual System.Security.Claims.ClaimsIdentity CreateClaimsIdentity(System.IO.BinaryReader reader) { throw null; } public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> FindAll(System.Predicate<System.Security.Claims.Claim> match) { throw null; } public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> FindAll(string type) { throw null; } public virtual System.Security.Claims.Claim FindFirst(System.Predicate<System.Security.Claims.Claim> match) { throw null; } public virtual System.Security.Claims.Claim FindFirst(string type) { throw null; } protected virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public virtual bool HasClaim(System.Predicate<System.Security.Claims.Claim> match) { throw null; } public virtual bool HasClaim(string type, string value) { throw null; } public virtual bool IsInRole(string role) { throw null; } public virtual void WriteTo(System.IO.BinaryWriter writer) { } protected virtual void WriteTo(System.IO.BinaryWriter writer, byte[] userData) { } } public static partial class ClaimTypes { public const string Actor = "http://schemas.xmlsoap.org/ws/2009/09/identity/claims/actor"; public const string Anonymous = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/anonymous"; public const string Authentication = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/authentication"; public const string AuthenticationInstant = "http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationinstant"; public const string AuthenticationMethod = "http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod"; public const string AuthorizationDecision = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/authorizationdecision"; public const string CookiePath = "http://schemas.microsoft.com/ws/2008/06/identity/claims/cookiepath"; public const string Country = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/country"; public const string DateOfBirth = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dateofbirth"; public const string DenyOnlyPrimaryGroupSid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlyprimarygroupsid"; public const string DenyOnlyPrimarySid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlyprimarysid"; public const string DenyOnlySid = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/denyonlysid"; public const string DenyOnlyWindowsDeviceGroup = "http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlywindowsdevicegroup"; public const string Dns = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dns"; public const string Dsa = "http://schemas.microsoft.com/ws/2008/06/identity/claims/dsa"; public const string Email = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"; public const string Expiration = "http://schemas.microsoft.com/ws/2008/06/identity/claims/expiration"; public const string Expired = "http://schemas.microsoft.com/ws/2008/06/identity/claims/expired"; public const string Gender = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/gender"; public const string GivenName = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"; public const string GroupSid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid"; public const string Hash = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/hash"; public const string HomePhone = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/homephone"; public const string IsPersistent = "http://schemas.microsoft.com/ws/2008/06/identity/claims/ispersistent"; public const string Locality = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality"; public const string MobilePhone = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/mobilephone"; public const string Name = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"; public const string NameIdentifier = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"; public const string OtherPhone = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/otherphone"; public const string PostalCode = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/postalcode"; public const string PrimaryGroupSid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/primarygroupsid"; public const string PrimarySid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid"; public const string Role = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"; public const string Rsa = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/rsa"; public const string SerialNumber = "http://schemas.microsoft.com/ws/2008/06/identity/claims/serialnumber"; public const string Sid = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/sid"; public const string Spn = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/spn"; public const string StateOrProvince = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/stateorprovince"; public const string StreetAddress = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/streetaddress"; public const string Surname = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname"; public const string System = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/system"; public const string Thumbprint = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/thumbprint"; public const string Upn = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn"; public const string Uri = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/uri"; public const string UserData = "http://schemas.microsoft.com/ws/2008/06/identity/claims/userdata"; public const string Version = "http://schemas.microsoft.com/ws/2008/06/identity/claims/version"; public const string Webpage = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/webpage"; public const string WindowsAccountName = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname"; public const string WindowsDeviceClaim = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsdeviceclaim"; public const string WindowsDeviceGroup = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsdevicegroup"; public const string WindowsFqbnVersion = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsfqbnversion"; public const string WindowsSubAuthority = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowssubauthority"; public const string WindowsUserClaim = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsuserclaim"; public const string X500DistinguishedName = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/x500distinguishedname"; } public static partial class ClaimValueTypes { public const string Base64Binary = "http://www.w3.org/2001/XMLSchema#base64Binary"; public const string Base64Octet = "http://www.w3.org/2001/XMLSchema#base64Octet"; public const string Boolean = "http://www.w3.org/2001/XMLSchema#boolean"; public const string Date = "http://www.w3.org/2001/XMLSchema#date"; public const string DateTime = "http://www.w3.org/2001/XMLSchema#dateTime"; public const string DaytimeDuration = "http://www.w3.org/TR/2002/WD-xquery-operators-20020816#dayTimeDuration"; public const string DnsName = "http://schemas.xmlsoap.org/claims/dns"; public const string Double = "http://www.w3.org/2001/XMLSchema#double"; public const string DsaKeyValue = "http://www.w3.org/2000/09/xmldsig#DSAKeyValue"; public const string Email = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"; public const string Fqbn = "http://www.w3.org/2001/XMLSchema#fqbn"; public const string HexBinary = "http://www.w3.org/2001/XMLSchema#hexBinary"; public const string Integer = "http://www.w3.org/2001/XMLSchema#integer"; public const string Integer32 = "http://www.w3.org/2001/XMLSchema#integer32"; public const string Integer64 = "http://www.w3.org/2001/XMLSchema#integer64"; public const string KeyInfo = "http://www.w3.org/2000/09/xmldsig#KeyInfo"; public const string Rfc822Name = "urn:oasis:names:tc:xacml:1.0:data-type:rfc822Name"; public const string Rsa = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/rsa"; public const string RsaKeyValue = "http://www.w3.org/2000/09/xmldsig#RSAKeyValue"; public const string Sid = "http://www.w3.org/2001/XMLSchema#sid"; public const string String = "http://www.w3.org/2001/XMLSchema#string"; public const string Time = "http://www.w3.org/2001/XMLSchema#time"; public const string UInteger32 = "http://www.w3.org/2001/XMLSchema#uinteger32"; public const string UInteger64 = "http://www.w3.org/2001/XMLSchema#uinteger64"; public const string UpnName = "http://schemas.xmlsoap.org/claims/UPN"; public const string X500Name = "urn:oasis:names:tc:xacml:1.0:data-type:x500Name"; public const string YearMonthDuration = "http://www.w3.org/TR/2002/WD-xquery-operators-20020816#yearMonthDuration"; } } namespace System.Security.Principal { public partial class GenericIdentity : System.Security.Claims.ClaimsIdentity { protected GenericIdentity(System.Security.Principal.GenericIdentity identity) { } public GenericIdentity(string name) { } public GenericIdentity(string name, string type) { } public override string AuthenticationType { get { throw null; } } public override System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> Claims { get { throw null; } } public override bool IsAuthenticated { get { throw null; } } public override string Name { get { throw null; } } public override System.Security.Claims.ClaimsIdentity Clone() { throw null; } } public partial class GenericPrincipal : System.Security.Claims.ClaimsPrincipal { public GenericPrincipal(System.Security.Principal.IIdentity identity, string[] roles) { } public override System.Security.Principal.IIdentity Identity { get { throw null; } } public override bool IsInRole(string role) { throw null; } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.HSSF.Record.Chart { using System; using System.Text; using NPOI.Util; /* * The font basis record stores various font metrics. * NOTE: This source is automatically generated please do not modify this file. Either subclass or * Remove the record in src/records/definitions. * @author Glen Stampoultzis (glens at apache.org) */ //public class FontBasisRecord /// <summary> /// The Fbi record specifies the font information at the time the scalable font is added to the chart. /// </summary> public class FbiRecord : StandardRecord { public const short sid = 0x1060; private short field_1_xBasis; private short field_2_yBasis; private short field_3_heightBasis; private short field_4_scale; private short field_5_indexToFontTable; public FbiRecord() { } /** * Constructs a FontBasis record and Sets its fields appropriately. * * @param in the RecordInputstream to Read the record from */ public FbiRecord(RecordInputStream in1) { field_1_xBasis = in1.ReadShort(); field_2_yBasis = in1.ReadShort(); field_3_heightBasis = in1.ReadShort(); field_4_scale = in1.ReadShort(); field_5_indexToFontTable = in1.ReadShort(); } public override String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append("[FBI]\n"); buffer.Append(" .xBasis = ") .Append("0x").Append(HexDump.ToHex(XBasis)) .Append(" (").Append(XBasis).Append(" )"); buffer.Append(Environment.NewLine); buffer.Append(" .yBasis = ") .Append("0x").Append(HexDump.ToHex(YBasis)) .Append(" (").Append(YBasis).Append(" )"); buffer.Append(Environment.NewLine); buffer.Append(" .heightBasis = ") .Append("0x").Append(HexDump.ToHex(HeightBasis)) .Append(" (").Append(HeightBasis).Append(" )"); buffer.Append(Environment.NewLine); buffer.Append(" .scale = ") .Append("0x").Append(HexDump.ToHex(Scale)) .Append(" (").Append(Scale).Append(" )"); buffer.Append(Environment.NewLine); buffer.Append(" .indexToFontTable = ") .Append("0x").Append(HexDump.ToHex(IndexToFontTable)) .Append(" (").Append(IndexToFontTable).Append(" )"); buffer.Append(Environment.NewLine); buffer.Append("[/FBI]\n"); return buffer.ToString(); } public override void Serialize(ILittleEndianOutput out1) { out1.WriteShort(field_1_xBasis); out1.WriteShort(field_2_yBasis); out1.WriteShort(field_3_heightBasis); out1.WriteShort(field_4_scale); out1.WriteShort(field_5_indexToFontTable); } /** * Size of record (exluding 4 byte header) */ protected override int DataSize { get { return 2 + 2 + 2 + 2 + 2; } } public override short Sid { get { return sid; } } public override Object Clone() { FbiRecord rec = new FbiRecord(); rec.field_1_xBasis = field_1_xBasis; rec.field_2_yBasis = field_2_yBasis; rec.field_3_heightBasis = field_3_heightBasis; rec.field_4_scale = field_4_scale; rec.field_5_indexToFontTable = field_5_indexToFontTable; return rec; } /** * Get the x Basis field for the FontBasis record. */ public short XBasis { get { return field_1_xBasis; } set { field_1_xBasis = value; } } /** * Get the y Basis field for the FontBasis record. */ public short YBasis { get { return field_2_yBasis; } set { field_2_yBasis = value; } } /** * Get the height basis field for the FontBasis record. */ public short HeightBasis { get { return field_3_heightBasis; } set { this.field_3_heightBasis = value; } } /** * Get the scale field for the FontBasis record. */ public short Scale { get { return field_4_scale; } set { field_4_scale = value; } } /** * Get the index to font table field for the FontBasis record. */ public short IndexToFontTable { get { return field_5_indexToFontTable; } set { this.field_5_indexToFontTable = value; } } } }
/* Copyright 2010, Object Management Group, Inc. * Copyright 2010, PrismTech, Inc. * Copyright 2010, Real-Time Innovations, 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.Collections.Generic; using DDS.ConversionUtils; using org.omg.dds.core; using org.omg.dds.core.modifiable; using org.omg.dds.core.status; using org.omg.dds.pub; using org.omg.dds.sub; using org.omg.dds.topic; using org.omg.dds.type; using System; namespace org.omg.dds.domain { /// <summary> /// The DomainParticipant object plays several roles: /// <ul> /// <li>It acts as a container for all other {@link Entity} objects.</li> /// <li>It acts as factory for the {@link Publisher}, {@link Subscriber}, /// {@link Topic}, {@link ContentFilteredTopic}, and {@link MultiTopic} /// objects.</li> /// <li>It represents the participation of the application on a communication /// plane that isolates applications running on the same Set of physical /// computers from each other. A domain establishes a "virtual network" /// linking all applications that share the same domainId and isolating /// them from applications running on different domains. In this way, /// several independent distributed applications can coexist in the same /// physical network without interfering, or even being aware of each /// other.</li> /// <li>It provides administration services in the domain, offering operations /// that allow the application to "ignore" locally any information about a /// given participant ({@link #IgnoreParticipant(InstanceHandle)}), /// publication ({@link #IgnorePublication(InstanceHandle)}), /// subscription ({@link #IgnoreSubscription(InstanceHandle)}), or topic /// ({@link #IgnoreTopic(InstanceHandle)})</li> /// </ul> /// </summary> public interface DomainParticipant : Entity<DomainParticipant, DomainParticipantListener, DomainParticipantQos> { // --- Create Publisher: ------------------------------------------------- Publisher CreatePublisher(); /// <summary> /// Create a new publisher. /// </summary> /// <param name="qos"></param> /// <param name="listener"></param> /// <param name="statuses">Of which status changes the listener should be /// notified. A null collection signifies all status /// changes</param> /// <returns></returns> Publisher CreatePublisher(PublisherQos qos, PublisherListener listener, ICollection<Type> statuses); /// <summary> /// Create a new publisher. /// </summary> /// <param name="qosLibraryName"></param> /// <param name="qosProfileName"></param> /// <param name="listener"></param> /// <param name="statuses">Of which status changes the listener should be /// notified. A null collection signifies all status /// changes</param> /// <returns></returns> Publisher CreatePublisher(string qosLibraryName, string qosProfileName, PublisherListener listener, ICollection<Type> statuses); // --- Create Subscriber: ------------------------------------------------ /// <summary> /// Create Subscriber /// </summary> /// <returns></returns> Subscriber CreateSubscriber(); /// <summary> /// Create a new subscriber. /// </summary> /// <param name="qos"></param> /// <param name="listener"></param> /// <param name="statuses">Of which status changes the listener should be /// notified. A null collection signifies all status /// changes</param> /// <returns></returns> Subscriber CreateSubscriber(SubscriberQos qos, SubscriberListener listener, ICollection<Type> statuses); /// <summary> /// Create a new subscriber. /// </summary> /// <param name="qosLibraryName"></param> /// <param name="qosProfileName"></param> /// <param name="listener"></param> /// <param name="statuses">Of which status changes the listener should be /// notified. A null collection signifies all status /// changes</param> /// <returns></returns> Subscriber CreateSubscriber(string qosLibraryName, string qosProfileName, SubscriberListener listener, ICollection<Type> statuses); Subscriber BuiltinSubscriber { get; } /// <summary> /// Create a new topic with implicit TypeSupport /// </summary> Topic<TYPE> CreateTopic<TYPE>(string topicName); /// <summary> /// Create a new topic. /// </summary> /// <typeparam name="TYPE"></typeparam> /// <param name="topicName"></param> /// <param name="type"></param> /// <param name="qos"></param> /// <param name="listener"></param> /// <param name="statuses"> /// Of which status changes the listener should be /// notified. A null collection signifies all status /// changes /// </param> /// <returns></returns> Topic<TYPE> CreateTopic<TYPE>(string topicName, Type type, TopicQos qos, TopicListener<TYPE> listener, ICollection<Type> statuses); /// <summary> /// Create a new topic. /// </summary> /// <typeparam name="TYPE"></typeparam> /// <param name="topicName"></param> /// <param name="qosLibraryName"></param> /// <param name="qosProfileName"></param> /// <param name="listener"></param> /// <param name="statuses">Of which status changes the listener should be /// notified. A null collection signifies all status /// changes</param> /// <returns></returns> Topic<TYPE> CreateTopic<TYPE>(string topicName, string qosLibraryName, string qosProfileName, TopicListener<TYPE> listener, ICollection<Type> statuses); // --- Create Topic with explicit TypeSupport: --------------------------- Topic<TYPE> CreateTopic<TYPE>(string topicName, TypeSupport<TYPE> type); /// <summary> /// Create a new topic. /// </summary> /// <typeparam name="TYPE"></typeparam> /// <param name="topicName"></param> /// <param name="type"></param> /// <param name="qos"></param> /// <param name="listener"></param> /// <param name="statuses">Of which status changes the listener should be /// notified. A null collection signifies all status /// changes</param> /// <returns></returns> Topic<TYPE> CreateTopic<TYPE>(string topicName, TypeSupport<TYPE> type, TopicQos qos, TopicListener<TYPE> listener, ICollection<Type> statuses); /// <summary> /// Create a new topic. /// </summary> /// <typeparam name="TYPE"></typeparam> /// <param name="topicName"></param> /// <param name="type"></param> /// <param name="qosLibraryName"></param> /// <param name="qosProfileName"></param> /// <param name="listener"></param> /// <param name="statuses">Of which status changes the listener should be /// notified. A null collection signifies all status /// changes</param> /// <returns></returns> Topic<TYPE> CreateTopic<TYPE>(string topicName, TypeSupport<TYPE> type, string qosLibraryName, string qosProfileName, TopicListener<TYPE> listener, ICollection<Type> statuses); // --- Other operations: ------------------------------------------------- Topic<TYPE> FindTopic<TYPE>(string topicName, Duration timeout); Topic<TYPE> FindTopic<TYPE>(string topicName, long timeout, TimeUnit unit); TopicDescription<TYPE> LookupTopicDescription<TYPE>(string name); ContentFilteredTopic<TYPE> CreateContentFilteredTopic<TYPE>(string name, Topic<TYPE> relatedTopic, string filterExpression, IList<string> expressionParameters); MultiTopic<TYPE> CreateMultiTopic<TYPE>( string name, string typeName, string subscriptionExpression, List<string> expressionParameters); void CloseContainedEntities(); void IgnoreParticipant(InstanceHandle handle); void IgnoreTopic(InstanceHandle handle); void IgnorePublication(InstanceHandle handle); void IgnoreSubscription(InstanceHandle handle); int DomainId { get; } void AssertLiveliness(); PublisherQos DefaultPublisherQos { get; set; } void SetDefaultPublisherQos(string qosLibraryName, string qosProfileName); SubscriberQos DefaultSubscriberQos { get; set; } void SetDefaultSubscriberQos(string qosLibraryName, string qosProfileName); TopicQos DefaultTopicQos { get; set; } void SetDefaultTopicQos(string qosLibraryName, string qosProfileName); ICollection<InstanceHandle> GetDiscoveredParticipants(ICollection<InstanceHandle> participantHandles); ParticipantBuiltinTopicData GetDiscoveredParticipantData(ParticipantBuiltinTopicData participantData, InstanceHandle participantHandle); ICollection<InstanceHandle> GetDiscoveredTopics(ICollection<InstanceHandle> topicHandles); TopicBuiltinTopicData GetDiscoveredTopicData(TopicBuiltinTopicData topicData, InstanceHandle topicHandle); bool ContainsEntity(InstanceHandle handle); ModifiableTime CurrentTime(ModifiableTime currentTime); } }
// Copyright (c) 2012, Event Store LLP // 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 Event Store LLP 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.Security.Principal; using EventStore.Common.Utils; using EventStore.Core.Data; using EventStore.Core.Messaging; using EventStore.Core.Services.Storage.ReaderIndex; using EventStore.Core.TransactionLog.LogRecords; namespace EventStore.Core.Messages { public static class StorageMessage { public interface IPreconditionedWriteMessage { Guid CorrelationId { get; } IEnvelope Envelope { get; } string EventStreamId { get; } int ExpectedVersion { get; } } public interface IFlushableMessage { } public interface IMasterWriteMessage { } public class WritePrepares : Message, IPreconditionedWriteMessage, IFlushableMessage, IMasterWriteMessage { private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public Guid CorrelationId { get; private set; } public IEnvelope Envelope { get; private set; } public string EventStreamId { get; private set; } public int ExpectedVersion { get; private set; } public readonly Event[] Events; public readonly DateTime LiveUntil; public WritePrepares(Guid correlationId, IEnvelope envelope, string eventStreamId, int expectedVersion, Event[] events, DateTime liveUntil) { CorrelationId = correlationId; Envelope = envelope; EventStreamId = eventStreamId; ExpectedVersion = expectedVersion; Events = events; LiveUntil = liveUntil; } public override string ToString() { return string.Format("WRITE_PREPARES: CorrelationId: {0}, EventStreamId: {1}, ExpectedVersion: {2}, LiveUntil: {3}", CorrelationId, EventStreamId, ExpectedVersion, LiveUntil); } } public class WriteDelete : Message, IPreconditionedWriteMessage, IFlushableMessage, IMasterWriteMessage { private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public Guid CorrelationId { get; private set; } public IEnvelope Envelope { get; private set; } public string EventStreamId { get; private set; } public int ExpectedVersion { get; private set; } public readonly bool HardDelete; public readonly DateTime LiveUntil; public WriteDelete(Guid correlationId, IEnvelope envelope, string eventStreamId, int expectedVersion, bool hardDelete, DateTime liveUntil) { Ensure.NotEmptyGuid(correlationId, "correlationId"); Ensure.NotNull(envelope, "envelope"); Ensure.NotNull(eventStreamId, "eventStreamId"); CorrelationId = correlationId; Envelope = envelope; EventStreamId = eventStreamId; ExpectedVersion = expectedVersion; HardDelete = hardDelete; LiveUntil = liveUntil; } } public class WriteCommit : Message, IFlushableMessage, IMasterWriteMessage { private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly Guid CorrelationId; public readonly IEnvelope Envelope; public readonly long TransactionPosition; public WriteCommit(Guid correlationId, IEnvelope envelope, long transactionPosition) { CorrelationId = correlationId; Envelope = envelope; TransactionPosition = transactionPosition; } } public class WriteTransactionStart : Message, IPreconditionedWriteMessage, IFlushableMessage, IMasterWriteMessage { private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public Guid CorrelationId { get; private set; } public IEnvelope Envelope { get; private set; } public string EventStreamId { get; private set; } public int ExpectedVersion { get; private set; } public readonly DateTime LiveUntil; public WriteTransactionStart(Guid correlationId, IEnvelope envelope, string eventStreamId, int expectedVersion, DateTime liveUntil) { Ensure.NotEmptyGuid(correlationId, "correlationId"); Ensure.NotNull(envelope, "envelope"); Ensure.NotNull(eventStreamId, "eventStreamId"); CorrelationId = correlationId; Envelope = envelope; EventStreamId = eventStreamId; ExpectedVersion = expectedVersion; LiveUntil = liveUntil; } } public class WriteTransactionData : Message, IFlushableMessage, IMasterWriteMessage { private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly Guid CorrelationId; public readonly IEnvelope Envelope; public readonly long TransactionId; public readonly Event[] Events; public WriteTransactionData(Guid correlationId, IEnvelope envelope, long transactionId, Event[] events) { CorrelationId = correlationId; Envelope = envelope; TransactionId = transactionId; Events = events; } } public class WriteTransactionPrepare : Message, IFlushableMessage, IMasterWriteMessage { private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly Guid CorrelationId; public readonly IEnvelope Envelope; public readonly long TransactionId; public readonly DateTime LiveUntil; public WriteTransactionPrepare(Guid correlationId, IEnvelope envelope, long transactionId, DateTime liveUntil) { CorrelationId = correlationId; Envelope = envelope; TransactionId = transactionId; LiveUntil = liveUntil; } } public class PrepareAck : Message { private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly Guid CorrelationId; public readonly long LogPosition; public readonly PrepareFlags Flags; public PrepareAck(Guid correlationId, long logPosition, PrepareFlags flags) { Ensure.NotEmptyGuid(correlationId, "correlationId"); Ensure.Nonnegative(logPosition, "logPosition"); CorrelationId = correlationId; LogPosition = logPosition; Flags = flags; } } public class CommitAck : Message { private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly Guid CorrelationId; public readonly long LogPosition; public readonly long TransactionPosition; public readonly int FirstEventNumber; public readonly int LastEventNumber; public CommitAck(Guid correlationId, long logPosition, long transactionPosition, int firstEventNumber, int lastEventNumber) { Ensure.NotEmptyGuid(correlationId, "correlationId"); Ensure.Nonnegative(logPosition, "logPosition"); Ensure.Nonnegative(transactionPosition, "transactionPosition"); if (firstEventNumber < -1) throw new ArgumentOutOfRangeException("firstEventNumber", string.Format("FirstEventNumber: {0}", firstEventNumber)); if (lastEventNumber - firstEventNumber + 1 < 0) throw new ArgumentOutOfRangeException("lastEventNumber", string.Format("LastEventNumber {0}, FirstEventNumber {1}.", lastEventNumber, firstEventNumber)); CorrelationId = correlationId; LogPosition = logPosition; TransactionPosition = transactionPosition; FirstEventNumber = firstEventNumber; LastEventNumber = lastEventNumber; } } public class EventCommited: Message { private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly long CommitPosition; public readonly EventRecord Event; public EventCommited(long commitPosition, EventRecord @event) { CommitPosition = commitPosition; Event = @event; } } public class AlreadyCommitted: Message { private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly Guid CorrelationId; public readonly string EventStreamId; public readonly int FirstEventNumber; public readonly int LastEventNumber; public AlreadyCommitted(Guid correlationId, string eventStreamId, int firstEventNumber, int lastEventNumber) { Ensure.NotEmptyGuid(correlationId, "correlationId"); Ensure.NotNullOrEmpty(eventStreamId, "eventStreamId"); Ensure.Nonnegative(firstEventNumber, "FirstEventNumber"); if (lastEventNumber < firstEventNumber) throw new ArgumentOutOfRangeException("lastEventNumber", "LastEventNumber is less than FirstEventNumber"); CorrelationId = correlationId; EventStreamId = eventStreamId; FirstEventNumber = firstEventNumber; LastEventNumber = lastEventNumber; } public override string ToString() { return string.Format("EventStreamId: {0}, CorrelationId: {1}, FirstEventNumber: {2}, LastEventNumber: {3}", EventStreamId, CorrelationId, FirstEventNumber, LastEventNumber); } } public class InvalidTransaction : Message { private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly Guid CorrelationId; public InvalidTransaction(Guid correlationId) { CorrelationId = correlationId; } } public class WrongExpectedVersion : Message { private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly Guid CorrelationId; public WrongExpectedVersion(Guid correlationId) { Ensure.NotEmptyGuid(correlationId, "correlationId"); CorrelationId = correlationId; } } public class StreamDeleted : Message { private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly Guid CorrelationId; public StreamDeleted(Guid correlationId) { Ensure.NotEmptyGuid(correlationId, "correlationId"); CorrelationId = correlationId; } } public class RequestCompleted : Message { private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly Guid CorrelationId; public readonly bool Success; public RequestCompleted(Guid correlationId, bool success) { Ensure.NotEmptyGuid(correlationId, "correlationId"); CorrelationId = correlationId; Success = success; } } public class RequestManagerTimerTick: Message { private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public DateTime UtcNow { get { return _now ?? DateTime.UtcNow; } } private readonly DateTime? _now; public RequestManagerTimerTick() { } public RequestManagerTimerTick(DateTime now) { _now = now; } } public class CheckStreamAccess: ClientMessage.ReadRequestMessage { private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly string EventStreamId; public readonly long? TransactionId; public readonly StreamAccessType AccessType; public CheckStreamAccess(IEnvelope envelope, Guid correlationId, string eventStreamId, long? transactionId, StreamAccessType accessType, IPrincipal user) : base(correlationId, correlationId, envelope, user) { if (eventStreamId == null && transactionId == null) throw new ArgumentException("Neither eventStreamId nor transactionId is specified."); EventStreamId = eventStreamId; TransactionId = transactionId; AccessType = accessType; } } public class CheckStreamAccessCompleted: ClientMessage.ReadResponseMessage { private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly Guid CorrelationId; public readonly string EventStreamId; public readonly long? TransactionId; public readonly StreamAccessType AccessType; public readonly StreamAccess AccessResult; public CheckStreamAccessCompleted(Guid correlationId, string eventStreamId, long? transactionId, StreamAccessType accessType, StreamAccess accessResult) { CorrelationId = correlationId; EventStreamId = eventStreamId; TransactionId = transactionId; AccessType = accessType; AccessResult = accessResult; } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation { /// <summary> /// Define all the output streams and one input stream for a workflow. /// </summary> public sealed class PowerShellStreams<TInput, TOutput> : IDisposable { /// <summary> /// Input stream for incoming objects. /// </summary> private PSDataCollection<TInput> _inputStream; /// <summary> /// Output stream for returned objects. /// </summary> private PSDataCollection<TOutput> _outputStream; /// <summary> /// Error stream for error messages. /// </summary> private PSDataCollection<ErrorRecord> _errorStream; /// <summary> /// Warning stream for warning messages. /// </summary> private PSDataCollection<WarningRecord> _warningStream; /// <summary> /// Progress stream for progress messages. /// </summary> private PSDataCollection<ProgressRecord> _progressStream; /// <summary> /// Verbose stream for verbose messages. /// </summary> private PSDataCollection<VerboseRecord> _verboseStream; /// <summary> /// Debug stream for debug messages. /// </summary> private PSDataCollection<DebugRecord> _debugStream; /// <summary> /// Information stream for Information messages. /// </summary> private PSDataCollection<InformationRecord> _informationStream; /// <summary> /// If the object is already disposed or not. /// </summary> private bool _disposed; /// <summary> /// Private object for thread-safe execution. /// </summary> private readonly object _syncLock = new object(); /// <summary> /// Default constructor. /// </summary> public PowerShellStreams() { _inputStream = null; _outputStream = null; _errorStream = null; _warningStream = null; _progressStream = null; _verboseStream = null; _debugStream = null; _informationStream = null; _disposed = false; } /// <summary> /// Default constructor. /// </summary> public PowerShellStreams(PSDataCollection<TInput> pipelineInput) { // Populate the input collection if there is any... _inputStream = pipelineInput ?? new PSDataCollection<TInput>(); _inputStream.Complete(); _outputStream = new PSDataCollection<TOutput>(); _errorStream = new PSDataCollection<ErrorRecord>(); _warningStream = new PSDataCollection<WarningRecord>(); _progressStream = new PSDataCollection<ProgressRecord>(); _verboseStream = new PSDataCollection<VerboseRecord>(); _debugStream = new PSDataCollection<DebugRecord>(); _informationStream = new PSDataCollection<InformationRecord>(); _disposed = false; } /// <summary> /// Dispose implementation. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Protected virtual implementation of Dispose. /// </summary> /// <param name="disposing"></param> private void Dispose(bool disposing) { if (_disposed) return; lock (_syncLock) { if (!_disposed) { if (disposing) { _inputStream.Dispose(); _outputStream.Dispose(); _errorStream.Dispose(); _warningStream.Dispose(); _progressStream.Dispose(); _verboseStream.Dispose(); _debugStream.Dispose(); _informationStream.Dispose(); _inputStream = null; _outputStream = null; _errorStream = null; _warningStream = null; _progressStream = null; _verboseStream = null; _debugStream = null; _informationStream = null; } _disposed = true; } } } /// <summary> /// Gets input stream. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public PSDataCollection<TInput> InputStream { get { return _inputStream; } set { _inputStream = value; } } /// <summary> /// Gets output stream. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public PSDataCollection<TOutput> OutputStream { get { return _outputStream; } set { _outputStream = value; } } /// <summary> /// Gets error stream. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public PSDataCollection<ErrorRecord> ErrorStream { get { return _errorStream; } set { _errorStream = value; } } /// <summary> /// Gets warning stream. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public PSDataCollection<WarningRecord> WarningStream { get { return _warningStream; } set { _warningStream = value; } } /// <summary> /// Gets progress stream. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public PSDataCollection<ProgressRecord> ProgressStream { get { return _progressStream; } set { _progressStream = value; } } /// <summary> /// Gets verbose stream. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public PSDataCollection<VerboseRecord> VerboseStream { get { return _verboseStream; } set { _verboseStream = value; } } /// <summary> /// Get debug stream. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public PSDataCollection<DebugRecord> DebugStream { get { return _debugStream; } set { _debugStream = value; } } /// <summary> /// Gets Information stream. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public PSDataCollection<InformationRecord> InformationStream { get { return _informationStream; } set { _informationStream = value; } } /// <summary> /// Marking all the streams as completed so that no further data can be added and /// jobs will know that there is no more data coming in. /// </summary> public void CloseAll() { if (!_disposed) { lock (_syncLock) { if (!_disposed) { _outputStream.Complete(); _errorStream.Complete(); _warningStream.Complete(); _progressStream.Complete(); _verboseStream.Complete(); _debugStream.Complete(); _informationStream.Complete(); } } } } } }
using System; using System.Collections; namespace Python.Runtime { /// <summary> /// Implements a Python type for managed arrays. This type is essentially /// the same as a ClassObject, except that it provides sequence semantics /// to support natural array usage (indexing) from Python. /// </summary> [Serializable] internal class ArrayObject : ClassBase { internal ArrayObject(Type tp) : base(tp) { } internal override bool CanSubclass() { return false; } public static IntPtr tp_new(IntPtr tpRaw, IntPtr args, IntPtr kw) { if (kw != IntPtr.Zero) { return Exceptions.RaiseTypeError("array constructor takes no keyword arguments"); } var tp = new BorrowedReference(tpRaw); var self = GetManagedObject(tp) as ArrayObject; if (!self.type.Valid) { return Exceptions.RaiseTypeError(self.type.DeletedMessage); } Type arrType = self.type.Value; long[] dimensions = new long[Runtime.PyTuple_Size(args)]; if (dimensions.Length == 0) { return Exceptions.RaiseTypeError("array constructor requires at least one integer argument or an object convertible to array"); } if (dimensions.Length != 1) { return CreateMultidimensional(arrType.GetElementType(), dimensions, shapeTuple: new BorrowedReference(args), pyType: tp) .DangerousMoveToPointerOrNull(); } IntPtr op = Runtime.PyTuple_GetItem(args, 0); // create single dimensional array if (Runtime.PyInt_Check(op)) { dimensions[0] = Runtime.PyLong_AsSignedSize_t(op); if (dimensions[0] == -1 && Exceptions.ErrorOccurred()) { Exceptions.Clear(); } else { return NewInstance(arrType.GetElementType(), tp, dimensions) .DangerousMoveToPointerOrNull(); } } object result; // this implements casting to Array[T] if (!Converter.ToManaged(op, arrType, out result, true)) { return IntPtr.Zero; } return CLRObject.GetInstHandle(result, tp) .DangerousGetAddress(); } static NewReference CreateMultidimensional(Type elementType, long[] dimensions, BorrowedReference shapeTuple, BorrowedReference pyType) { for (int dimIndex = 0; dimIndex < dimensions.Length; dimIndex++) { BorrowedReference dimObj = Runtime.PyTuple_GetItem(shapeTuple, dimIndex); PythonException.ThrowIfIsNull(dimObj); if (!Runtime.PyInt_Check(dimObj)) { Exceptions.RaiseTypeError("array constructor expects integer dimensions"); return default; } dimensions[dimIndex] = Runtime.PyLong_AsSignedSize_t(dimObj); if (dimensions[dimIndex] == -1 && Exceptions.ErrorOccurred()) { Exceptions.RaiseTypeError("array constructor expects integer dimensions"); return default; } } return NewInstance(elementType, pyType, dimensions); } static NewReference NewInstance(Type elementType, BorrowedReference arrayPyType, long[] dimensions) { object result; try { result = Array.CreateInstance(elementType, dimensions); } catch (ArgumentException badArgument) { Exceptions.SetError(Exceptions.ValueError, badArgument.Message); return default; } catch (OverflowException overflow) { Exceptions.SetError(overflow); return default; } catch (NotSupportedException notSupported) { Exceptions.SetError(notSupported); return default; } catch (OutOfMemoryException oom) { Exceptions.SetError(Exceptions.MemoryError, oom.Message); return default; } return CLRObject.GetInstHandle(result, arrayPyType); } /// <summary> /// Implements __getitem__ for array types. /// </summary> public new static IntPtr mp_subscript(IntPtr ob, IntPtr idx) { var obj = (CLRObject)GetManagedObject(ob); var items = obj.inst as Array; Type itemType = obj.inst.GetType().GetElementType(); int rank = items.Rank; int index; object value; // Note that CLR 1.0 only supports int indexes - methods to // support long indices were introduced in 1.1. We could // support long indices automatically, but given that long // indices are not backward compatible and a relative edge // case, we won't bother for now. // Single-dimensional arrays are the most common case and are // cheaper to deal with than multi-dimensional, so check first. if (rank == 1) { if (!Runtime.PyInt_Check(idx)) { return RaiseIndexMustBeIntegerError(idx); } index = Runtime.PyInt_AsLong(idx); if (Exceptions.ErrorOccurred()) { return Exceptions.RaiseTypeError("invalid index value"); } if (index < 0) { index = items.Length + index; } try { value = items.GetValue(index); } catch (IndexOutOfRangeException) { Exceptions.SetError(Exceptions.IndexError, "array index out of range"); return IntPtr.Zero; } return Converter.ToPython(value, itemType); } // Multi-dimensional arrays can be indexed a la: list[1, 2, 3]. if (!Runtime.PyTuple_Check(idx)) { Exceptions.SetError(Exceptions.TypeError, "invalid index value"); return IntPtr.Zero; } var count = Runtime.PyTuple_Size(idx); var args = new int[count]; for (var i = 0; i < count; i++) { IntPtr op = Runtime.PyTuple_GetItem(idx, i); if (!Runtime.PyInt_Check(op)) { return RaiseIndexMustBeIntegerError(op); } index = Runtime.PyInt_AsLong(op); if (Exceptions.ErrorOccurred()) { return Exceptions.RaiseTypeError("invalid index value"); } if (index < 0) { index = items.GetLength(i) + index; } args.SetValue(index, i); } try { value = items.GetValue(args); } catch (IndexOutOfRangeException) { Exceptions.SetError(Exceptions.IndexError, "array index out of range"); return IntPtr.Zero; } return Converter.ToPython(value, itemType); } /// <summary> /// Implements __setitem__ for array types. /// </summary> public static new int mp_ass_subscript(IntPtr ob, IntPtr idx, IntPtr v) { var obj = (CLRObject)GetManagedObject(ob); var items = obj.inst as Array; Type itemType = obj.inst.GetType().GetElementType(); int rank = items.Rank; int index; object value; if (items.IsReadOnly) { Exceptions.RaiseTypeError("array is read-only"); return -1; } if (!Converter.ToManaged(v, itemType, out value, true)) { return -1; } if (rank == 1) { if (!Runtime.PyInt_Check(idx)) { RaiseIndexMustBeIntegerError(idx); return -1; } index = Runtime.PyInt_AsLong(idx); if (Exceptions.ErrorOccurred()) { Exceptions.RaiseTypeError("invalid index value"); return -1; } if (index < 0) { index = items.Length + index; } try { items.SetValue(value, index); } catch (IndexOutOfRangeException) { Exceptions.SetError(Exceptions.IndexError, "array index out of range"); return -1; } return 0; } if (!Runtime.PyTuple_Check(idx)) { Exceptions.RaiseTypeError("invalid index value"); return -1; } var count = Runtime.PyTuple_Size(idx); var args = new int[count]; for (var i = 0; i < count; i++) { IntPtr op = Runtime.PyTuple_GetItem(idx, i); if (!Runtime.PyInt_Check(op)) { RaiseIndexMustBeIntegerError(op); return -1; } index = Runtime.PyInt_AsLong(op); if (Exceptions.ErrorOccurred()) { Exceptions.RaiseTypeError("invalid index value"); return -1; } if (index < 0) { index = items.GetLength(i) + index; } args.SetValue(index, i); } try { items.SetValue(value, args); } catch (IndexOutOfRangeException) { Exceptions.SetError(Exceptions.IndexError, "array index out of range"); return -1; } return 0; } private static IntPtr RaiseIndexMustBeIntegerError(IntPtr idx) { string tpName = Runtime.PyObject_GetTypeName(idx); return Exceptions.RaiseTypeError($"array index has type {tpName}, expected an integer"); } /// <summary> /// Implements __contains__ for array types. /// </summary> public static int sq_contains(IntPtr ob, IntPtr v) { var obj = (CLRObject)GetManagedObject(ob); Type itemType = obj.inst.GetType().GetElementType(); var items = obj.inst as IList; object value; if (!Converter.ToManaged(v, itemType, out value, false)) { return 0; } if (items.Contains(value)) { return 1; } return 0; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class OTTouch { /// <summary> /// The active. /// </summary> public static bool active = false; /// <summary> /// Touch gesture delegate. /// </summary> public delegate void TouchGestureDelegate(OTTouchGesture gesture); /// <summary> /// delegate that is called when a touch gesture has begun /// </summary> public static TouchGestureDelegate onGestureBegan = null; /// <summary> /// delegate that is called when a touch gesture is running /// </summary> public static TouchGestureDelegate onGestureRunning = null; /// <summary> /// delegate that is called when a touch gesture has ended /// </summary> public static TouchGestureDelegate onGestureEnded = null; static bool _isRotating = false; /// <summary> /// Indicates if a rotation gesture is being performed /// </summary> public static bool isRotating { get { return _isRotating; } } static bool _isPinching = false; /// <summary> /// Indicates if a pinch gesture is being performed /// </summary> public static bool isPinching { get { return _isPinching; } } static bool _isPanning = false; /// <summary> /// Indicates if a pan gesture is being performed /// </summary> public static bool isPanning { get { return _isPanning; } } static bool _isSwiping = false; /// <summary> /// Indicates if a swipe gesture is being performed /// </summary> public static bool isSwiping { get { return _isSwiping; } } static bool _isPressing = false; /// <summary> /// Indicates if a pressing gesture is being performed /// </summary> public static bool isPressing { get { return _isPressing; } } static bool _isTapping = false; /// <summary> /// Indicates if a tapping gesture is being performed /// </summary> public static bool isTapping { get { return _isTapping; } } static List<OTTouchFinger> fingers = new List<OTTouchFinger>(); static List<OTTouchGesture> gestures = new List<OTTouchGesture>(); static List<int> fingerChecks = new List<int>(); static void GetFingers() { if (OT.mobile) { fingerChecks.Clear(); int i; for (i=0; i<Input.touches.Length; i++) fingerChecks.Add(Input.touches[i].fingerId); // remove fingers that have gone i=0; while (i<fingers.Count) { if (!fingerChecks.Contains(fingers[i].fingerId)) { OTTouchFinger finger = fingers[i]; OTTouchFinger.lookup.Remove(finger.fingerId); if (finger.gesture!=null) finger.gesture.RemoveFinger(finger); fingers.RemoveAt(i); } else i++; } // update and add new fingers for (i=0; i<Input.touches.Length; i++) { OTTouchFinger finger = OTTouchFinger.Lookup(Input.touches[i]); if (finger==null) { fingers.Add(new OTTouchFinger(Input.touches[i])); gestures.Add(new OTTouchGesture(fingers[fingers.Count-1])); } else finger.Assign(Input.touches[i]); } } for (int i=0; i<fingers.Count; i++) fingers[i].Update(); } public static void Update() { if (active) { GetFingers(); // check the current gestures int i=0; while (i<gestures.Count) { gestures[i].Update(); switch(gestures[i].phase) { case OTTouchGesture.Phase.Began: gestures[i].Begin(); if (onGestureBegan!=null) onGestureBegan(gestures[i]); gestures[i].phase = OTTouchGesture.Phase.Running; i++; break; case OTTouchGesture.Phase.Running: if (onGestureRunning!=null) onGestureRunning(gestures[i]); i++; break; case OTTouchGesture.Phase.Ended: if (onGestureEnded!=null) onGestureEnded(gestures[i]); gestures.RemoveAt(i); break; } } } } } public class OTTouchGesture { public enum Type { Tap, Press, Swipe, Pan, Pinch, Rotate }; public enum Phase { Began, Running, Ended }; public Type type; public Phase phase = Phase.Began; public OTObject target; public float duration = 0; List<OTTouchFinger> startFingers = new List<OTTouchFinger>(); List<OTTouchFinger> fingers = new List<OTTouchFinger>(); public OTTouchGesture(OTTouchFinger finger) { type = Type.Press; fingers.Add(finger); finger.gesture = this; } public void Begin() { startFingers.Clear(); for (int i=0; i<fingers.Count; i++) startFingers.Add(fingers[i].Clone()); } public void RemoveFinger(OTTouchFinger finger) { if (fingers.Contains(finger)) { fingers.Remove(finger); finger.gesture = null; } } public void AddFinger(OTTouchFinger finger) { if (!fingers.Contains(finger)) { fingers.Add(finger); finger.gesture = this; } } public void Update() { if (fingers.Count==0) phase = Phase.Ended; if (phase == Phase.Running) duration += Time.deltaTime; } } public class OTTouchFinger { public int fingerId; Vector2 position = Vector2.zero; Vector2 deltaPosition = Vector2.zero; float deltaTime = 0; int tapCount = 0; TouchPhase phase = TouchPhase.Stationary; public OTTouchGesture gesture = null; public float time = 0; static public Dictionary<int, OTTouchFinger> lookup = new Dictionary<int, OTTouchFinger>(); public static OTTouchFinger Lookup(Touch touch) { if (lookup.ContainsKey(touch.fingerId)) return lookup[touch.fingerId]; else return null; } public OTTouchFinger Clone() { return new OTTouchFinger(this); } public void Assign(Touch touch) { fingerId = touch.fingerId; position = touch.position; deltaPosition = touch.deltaPosition; deltaTime = touch.deltaTime; tapCount = touch.tapCount; phase = touch.phase; } public void Assign(OTTouchFinger finger) { fingerId = finger.fingerId; position = finger.position; deltaPosition = finger.deltaPosition; deltaTime = finger.deltaTime; tapCount = finger.tapCount; phase = finger.phase; } public OTTouchFinger(int id, Vector2 position) { fingerId = id; this.position = position; lookup.Add(id,this); } public OTTouchFinger(Touch touch) { Assign(touch); lookup.Add(touch.fingerId, this); } public OTTouchFinger(OTTouchFinger finger) { Assign(finger); } public void Update() { time += Time.deltaTime; } }
// // Copyright (C) Microsoft. All rights reserved. // using System; using System.IO; using System.Reflection; using System.ComponentModel; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Management.Automation; using System.Management.Automation.Provider; using System.Xml; using System.Collections; using System.Collections.Generic; using System.Management.Automation.Runspaces; using System.Diagnostics.CodeAnalysis; using Dbg = System.Management.Automation; namespace Microsoft.WSMan.Management { #region Base class for cmdlets taking credential, authentication, certificatethumbprint /// <summary> /// Common base class for all WSMan cmdlets that /// take Authentication, CertificateThumbprint and Credential parameters /// </summary> public class AuthenticatingWSManCommand : PSCmdlet { /// <summary> /// The following is the definition of the input parameter "Credential". /// Specifies a user account that has permission to perform this action. The /// default is the current user. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] [Credential] [Alias("cred", "c")] public virtual PSCredential Credential { get { return credential; } set { credential = value; ValidateSpecifiedAuthentication(); } } private PSCredential credential; /// <summary> /// The following is the definition of the input parameter "Authentication". /// This parameter takes a set of authentication methods the user can select /// from. The available method are an enum called Authentication in the /// System.Management.Automation.Runspaces namespace. The available options /// should be as follows: /// - Default : Use the default authentication (ad defined by the underlying /// protocol) for establishing a remote connection. /// - Negotiate /// - Kerberos /// - Basic: Use basic authentication for establishing a remote connection. /// -CredSSP: Use CredSSP authentication for establishing a remote connection /// which will enable the user to perform credential delegation. (i.e. second /// hop) /// </summary> [Parameter] [ValidateNotNullOrEmpty] [Alias("auth", "am")] public virtual AuthenticationMechanism Authentication { get { return authentication; } set { authentication = value; ValidateSpecifiedAuthentication(); } } private AuthenticationMechanism authentication = AuthenticationMechanism.Default; /// <summary> /// Specifies the certificate thumbprint to be used to impersonate the user on the /// remote machine. /// </summary> [Parameter] [ValidateNotNullOrEmpty] public virtual string CertificateThumbprint { get { return thumbPrint; } set { thumbPrint = value; ValidateSpecifiedAuthentication(); } } private string thumbPrint = null; internal void ValidateSpecifiedAuthentication() { WSManHelper.ValidateSpecifiedAuthentication( this.Authentication, this.Credential, this.CertificateThumbprint); } } #endregion #region Connect-WsMan /// <summary> /// connect wsman cmdlet /// </summary> [Cmdlet(VerbsCommunications.Connect, "WSMan", DefaultParameterSetName = "ComputerName", HelpUri = "http://go.microsoft.com/fwlink/?LinkId=141437")] public class ConnectWSManCommand : AuthenticatingWSManCommand { #region Parameters /// <summary> /// The following is the definition of the input parameter "ApplicationName". /// ApplicationName identifies the remote endpoint. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [ValidateNotNullOrEmpty] public String ApplicationName { get { return applicationname; } set { applicationname = value; } } private String applicationname = null; /// <summary> /// The following is the definition of the input parameter "ComputerName". /// Executes the management operation on the specified computer(s). The default /// is the local computer. Type the fully qualified domain name, NETBIOS name or /// IP address to indicate the remote host(s) /// </summary> [Parameter(ParameterSetName = "ComputerName", Position = 0)] [Alias("cn")] public String ComputerName { get { return computername; } set { computername = value; if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.CurrentCultureIgnoreCase))) { computername = "localhost"; } } } private String computername = null; /// <summary> /// The following is the definition of the input parameter "ConnectionURI". /// Specifies the transport, server, port, and ApplicationName of the new /// runspace. The format of this string is: /// transport://server:port/ApplicationName. /// </summary> [Parameter(ParameterSetName = "URI")] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] public Uri ConnectionURI { get { return connectionuri; } set { connectionuri = value; } } private Uri connectionuri; /// <summary> /// The following is the definition of the input parameter "OptionSet". /// OptionSet is a hash table and is used to pass a set of switches to the /// service to modify or refine the nature of the request. /// </summary> [Parameter] [ValidateNotNullOrEmpty] [Alias("os")] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public Hashtable OptionSet { get { return optionset; } set { optionset = value; } } private Hashtable optionset; /// <summary> /// The following is the definition of the input parameter "Port". /// Specifies the port to be used when connecting to the ws management service. /// </summary> [Parameter] [ValidateNotNullOrEmpty] [Parameter(ParameterSetName = "ComputerName")] [ValidateRange(1, Int32.MaxValue)] public Int32 Port { get { return port; } set { port = value; } } private Int32 port = 0; /// <summary> /// The following is the definition of the input parameter "SessionOption". /// Defines a set of extended options for the WSMan session. This hashtable can /// be created using New-WSManSessionOption /// </summary> [Parameter] [ValidateNotNullOrEmpty] [Alias("so")] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public SessionOption SessionOption { get { return sessionoption; } set { sessionoption = value; } } private SessionOption sessionoption; /// <summary> /// The following is the definition of the input parameter "UseSSL". /// Uses the Secure Sockets Layer (SSL) protocol to establish a connnection to /// the remote computer. If SSL is not available on the port specified by the /// Port parameter, the command fails. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")] public SwitchParameter UseSSL { get { return usessl; } set { usessl = value; } } private SwitchParameter usessl; #endregion /// <summary> /// BeginProcessing method. /// </summary> protected override void BeginProcessing() { WSManHelper helper = new WSManHelper(this); if (connectionuri != null) { try { //always in the format http://server:port/applicationname string[] constrsplit = connectionuri.OriginalString.Split(new string[] { ":" + port + "/" + applicationname }, StringSplitOptions.None); string[] constrsplit1 = constrsplit[0].Split(new string[] { "//" }, StringSplitOptions.None); computername = constrsplit1[1].Trim(); } catch (IndexOutOfRangeException) { helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); } } string crtComputerName = computername; if (crtComputerName == null) { crtComputerName = "localhost"; } if (this.SessionState.Path.CurrentProviderLocation(WSManStringLiterals.rootpath).Path.StartsWith(this.SessionState.Drive.Current.Name + ":" + WSManStringLiterals.DefaultPathSeparator + crtComputerName, StringComparison.CurrentCultureIgnoreCase)) { helper.AssertError(helper.GetResourceMsgFromResourcetext("ConnectFailure"), false, computername); } helper.CreateWsManConnection(ParameterSetName, connectionuri, port, computername, applicationname, usessl.IsPresent, Authentication, sessionoption, Credential, CertificateThumbprint); }//End BeginProcessing() }//end class #endregion # region Disconnect-WSMAN /// <summary> /// The following is the definition of the input parameter "ComputerName". /// Executes the management operation on the specified computer(s). The default /// is the local computer. Type the fully qualified domain name, NETBIOS name or /// IP address to indicate the remote host(s) /// </summary> [Cmdlet(VerbsCommunications.Disconnect, "WSMan", HelpUri = "http://go.microsoft.com/fwlink/?LinkId=141439")] public class DisconnectWSManCommand : PSCmdlet, IDisposable { /// <summary> /// The following is the definition of the input parameter "ComputerName". /// Executes the management operation on the specified computer(s). The default /// is the local computer. Type the fully qualified domain name, NETBIOS name or /// IP address to indicate the remote host(s) /// </summary> [Parameter(Position = 0)] public String ComputerName { get { return computername; } set { computername = value; if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.CurrentCultureIgnoreCase))) { computername = "localhost"; } } } private String computername = null; #region IDisposable Members /// <summary> /// public dispose method /// </summary> public void Dispose() { //CleanUp(); GC.SuppressFinalize(this); } /// <summary> /// public dispose method /// </summary> public void Dispose(object session) { session = null; this.Dispose(); } #endregion IDisposable Members /// <summary> /// BeginProcessing method. /// </summary> protected override void BeginProcessing() { WSManHelper helper = new WSManHelper(this); if (computername == null) { computername = "localhost"; } if (this.SessionState.Path.CurrentProviderLocation(WSManStringLiterals.rootpath).Path.StartsWith(WSManStringLiterals.rootpath + ":" + WSManStringLiterals.DefaultPathSeparator + computername, StringComparison.CurrentCultureIgnoreCase)) { helper.AssertError(helper.GetResourceMsgFromResourcetext("DisconnectFailure"), false, computername); } if (computername.Equals("localhost", StringComparison.CurrentCultureIgnoreCase)) { helper.AssertError(helper.GetResourceMsgFromResourcetext("LocalHost"), false, computername); } object _ws = helper.RemoveFromDictionary(computername); if (_ws != null) { Dispose(_ws); } else { helper.AssertError(helper.GetResourceMsgFromResourcetext("InvalidComputerName"), false, computername); } }//End BeginProcessing() }//End Class #endregion Disconnect-WSMAN }
// Copyright (c) 2010-2013 SharpDoc - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using Mono.Cecil; using SharpDoc.Logging; using SharpDoc.Model; namespace SharpDoc { /// <summary> /// Mono Cecil implementation of <see cref="IAssemblyManager"/>. /// </summary> internal class MonoCecilAssemblyManager : BaseAssemblyResolver, IAssemblyManager { /// <summary> /// Initializes a new instance of the <see cref="MonoCecilAssemblyManager"/> class. /// </summary> public MonoCecilAssemblyManager() { AssemblySources = new List<NAssemblySource>(); AssemblyReferences = new List<AssemblyDefinition>(); } private List<AssemblyDefinition> AssemblyReferences { get; set; } private List<NAssemblySource> AssemblySources { get; set; } /// <summary> /// Loads all assembly sources/xml doc and references /// </summary> public List<NAssemblySource> Load(Config config) { // Preload references foreach (var assemblyRef in config.References) { if (!File.Exists(assemblyRef)) { Logger.Error("Assembly reference file [{0}] not found", assemblyRef); } else { AssemblyReferences.Add(AssemblyDefinition.ReadAssembly(assemblyRef, new ReaderParameters(ReadingMode.Deferred))); } } var configPath = Path.GetDirectoryName(Path.GetFullPath(config.FilePath)); configPath = configPath ?? Environment.CurrentDirectory; // Load all sources foreach (var source in config.Sources) { // Setup full path if (!string.IsNullOrEmpty(source.AssemblyPath)) source.AssemblyPath = Path.Combine(configPath, source.AssemblyPath); if (!string.IsNullOrEmpty(source.DocumentationPath)) source.DocumentationPath = Path.Combine(configPath, source.DocumentationPath); source.MergeGroup = source.MergeGroup ?? "default"; Load(source); } var finalSources = new List<NAssemblySource>(); // Check that all source assemblies have valid Xml associated with it foreach (var assemblySource in AssemblySources.Where(node => node.Assembly != null)) { int countXmlDocFound = 0; NDocumentApi docFound = null; string assemblyName = ((AssemblyDefinition) assemblySource.Assembly).Name.Name; var docSources = new List<NAssemblySource>(); if (assemblySource.Document != null) docSources.Add(assemblySource); docSources.AddRange( AssemblySources.Where(node => node.Assembly == null) ); foreach (var doc in docSources) { var node = doc.Document.Document.SelectSingleNode("/doc/assembly/name"); if (assemblyName == node.InnerText.Trim()) { docFound = doc.Document; countXmlDocFound++; } } if (countXmlDocFound == 0) Logger.Fatal("Unable to find documentation for assembly [{0}]", assemblyName); else if (countXmlDocFound > 1) Logger.Fatal("Cannot load from multiple ([{0}]) documentation sources for assembly [{1}]", countXmlDocFound, assemblyName); assemblySource.Document = docFound; finalSources.Add(assemblySource); } return finalSources; } private HashSet<string> searchPaths = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase); private void Load(ConfigSource configSource) { NAssemblySource assemblySource = null; if (configSource.AssemblyPath != null) { // Check Parameters if (!File.Exists(configSource.AssemblyPath)) { Logger.Error("Assembly file [{0}] not found", configSource.AssemblyPath); return; } var extension = Path.GetExtension(configSource.AssemblyPath); if (extension != null && (extension.ToLower() == ".dll" || extension.ToLower() == ".exe")) { assemblySource = LoadAssembly(configSource.AssemblyPath); assemblySource.MergeGroup = configSource.MergeGroup; AssemblySources.Add(assemblySource); } else { Logger.Fatal("Invalid Assembly source [{0}]. Must be either an Assembly", configSource.AssemblyPath); } } if (configSource.DocumentationPath != null) { if (!File.Exists(configSource.DocumentationPath)) { Logger.Error("Documentation file [{0}] not found", configSource.DocumentationPath); return; } var extension = Path.GetExtension(configSource.DocumentationPath); if (extension != null && extension.ToLower() == ".xml") { if (assemblySource == null) { assemblySource = new NAssemblySource(); AssemblySources.Add(assemblySource); } assemblySource.Document = LoadAssemblyDocumentation(configSource.DocumentationPath); } else { Logger.Fatal("Invalid Assembly source [{0}]. Must be either a Xml comment file", configSource.DocumentationPath); } } } private NAssemblySource LoadAssembly(string source) { var dirPath = Path.GetDirectoryName(source); if (!searchPaths.Contains(dirPath)) { searchPaths.Add(dirPath); AddSearchDirectory(dirPath); } var parameters = new ReaderParameters(ReadingMode.Immediate) { AssemblyResolver = this }; var assemblyDefinition = AssemblyDefinition.ReadAssembly(source, parameters); var assemblySource = new NAssemblySource(assemblyDefinition) {Filename = source}; return assemblySource; } private NDocumentApi LoadAssemblyDocumentation(string source) { var xmlDoc = NDocumentApi.Load(source); var node = xmlDoc.Document.SelectSingleNode("/doc/assembly/name"); if (node == null) Logger.Fatal("Not valid xml documentation for source [{0}]", source); return xmlDoc; } public override AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters) { foreach (var assemblyRef in AssemblyReferences) { if (assemblyRef.FullName == name.Name) return assemblyRef; } return base.Resolve(name, parameters); } } }
// 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 ShuffleSByte() { var test = new SimpleBinaryOpTest__ShuffleSByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.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 (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__ShuffleSByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(SByte[] inArray1, SByte[] inArray2, SByte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<SByte> _fld1; public Vector256<SByte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__ShuffleSByte testClass) { var result = Avx2.Shuffle(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__ShuffleSByte testClass) { fixed (Vector256<SByte>* pFld1 = &_fld1) fixed (Vector256<SByte>* pFld2 = &_fld2) { var result = Avx2.Shuffle( Avx.LoadVector256((SByte*)(pFld1)), Avx.LoadVector256((SByte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector256<SByte> _clsVar1; private static Vector256<SByte> _clsVar2; private Vector256<SByte> _fld1; private Vector256<SByte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__ShuffleSByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); } public SimpleBinaryOpTest__ShuffleSByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, _data2, new SByte[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.Shuffle( Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.Shuffle( Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.Shuffle( Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Shuffle), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Shuffle), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) }) .Invoke(null, new object[] { Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Shuffle), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.Shuffle( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<SByte>* pClsVar1 = &_clsVar1) fixed (Vector256<SByte>* pClsVar2 = &_clsVar2) { var result = Avx2.Shuffle( Avx.LoadVector256((SByte*)(pClsVar1)), Avx.LoadVector256((SByte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr); var result = Avx2.Shuffle(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)); var result = Avx2.Shuffle(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)); var result = Avx2.Shuffle(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__ShuffleSByte(); var result = Avx2.Shuffle(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__ShuffleSByte(); fixed (Vector256<SByte>* pFld1 = &test._fld1) fixed (Vector256<SByte>* pFld2 = &test._fld2) { var result = Avx2.Shuffle( Avx.LoadVector256((SByte*)(pFld1)), Avx.LoadVector256((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.Shuffle(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<SByte>* pFld1 = &_fld1) fixed (Vector256<SByte>* pFld2 = &_fld2) { var result = Avx2.Shuffle( Avx.LoadVector256((SByte*)(pFld1)), Avx.LoadVector256((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.Shuffle(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx2.Shuffle( Avx.LoadVector256((SByte*)(&test._fld1)), Avx.LoadVector256((SByte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<SByte> op1, Vector256<SByte> op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != ((right[0] < 0) ? 0 : left[right[0] & 0x0F])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (i < 16 ? (right[i] < 0 ? 0 : left[right[i] & 0x0F]) : (right[i] < 0 ? 0 : left[(right[i] & 0x0F) + 16]))) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Shuffle)}<SByte>(Vector256<SByte>, Vector256<SByte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
#region Header // Revit API .NET Labs // // Copyright (C) 2007-2021 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software // for any purpose and without fee is hereby granted, provided // that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. #endregion // Header #region Namespaces using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using Autodesk.Revit.ApplicationServices; using Autodesk.Revit.Attributes; using Autodesk.Revit.DB; using Autodesk.Revit.UI; #endregion // Namespaces namespace XtraCs { #region Lab3_1_StandardFamiliesAndTypes /// <summary> /// List all loaded standard families and types. /// As a result of the issues explained below, we implemented /// the LabUtils utility methods FamilyCategory and GetFamilies. /// <include file='../doc/labs.xml' path='labs/lab[@name="3-1"]/*' /> /// </summary> [Transaction( TransactionMode.ReadOnly )] public class Lab3_1_StandardFamiliesAndTypes : IExternalCommand { public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements ) { UIApplication app = commandData.Application; Document doc = app.ActiveUIDocument.Document; List<string> a = new List<string>(); FilteredElementCollector families; #region 3.1.a Retrieve and iterate over all Family objects in document: // // retrieve all family elements in current document: // families = new FilteredElementCollector( doc ); families.OfClass( typeof( Family ) ); foreach( Family f in families ) { // Get its category name; notice that the Category property is not // implemented for the Family class; use FamilyCategory instead; // notice that that is also not always implemented; in that case, // use the workaround demonstrated below, looking at the contained // family symbols' category: a.Add( string.Format( "Name={0}; Category={1}; FamilyCategory={2}", f.Name, ( ( null == f.Category ) ? "?" : f.Category.Name ), ( ( null == f.FamilyCategory ) ? "?" : f.FamilyCategory.Name ) ) ); } #endregion // 3.1.a string msg = "{0} standard familie{1} are loaded in this model{2}"; LabUtils.InfoMsg( msg, a ); // Loop through the collection of families, and now look at // the child symbols (types) as well. These symbols can be // used to determine the family category. foreach( Family f in families ) { string catName; bool first = true; // Loop all contained symbols (types): //foreach( FamilySymbol s in f.Symbols ) // 2014 foreach( ElementId id in f.GetFamilySymbolIds() ) // 2015 { FamilySymbol s = doc.GetElement( id ) as FamilySymbol; // you can determine the family category from its first symbol. if( first ) { first = false; #region 3.1.b Retrieve category name of first family symbol: catName = s.Category.Name; #endregion // 3.1.b msg = "Family: Name=" + f.Name + "; Id=" + f.Id.IntegerValue.ToString() + "; Category=" + catName + "\r\nContains Types:"; } msg += "\r\n " + s.Name + "; Id=" + s.Id.IntegerValue.ToString(); } // Show the symbols for this family and allow user to proceed // to the next family (OK) or cancel (Cancel) msg += "\r\nContinue?"; if( !LabUtils.QuestionMsg( msg ) ) { break; } } // // return all families whose name contains the substring "Round Duct": // IEnumerable<Family> round_duct_families = LabUtils.GetFamilies( doc, "Round Duct", true ); int n = round_duct_families.Count(); return Result.Failed; } } #endregion // Lab3_1_StandardFamiliesAndTypes #region Lab3_2_LoadStandardFamilies /// <summary> /// Load an entire family or a specific type from a family. /// <include file='../doc/labs.xml' path='labs/lab[@name="3-2"]/*' /> /// </summary> [Transaction( TransactionMode.Manual )] public class Lab3_2_LoadStandardFamilies : IExternalCommand { public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements ) { UIApplication app = commandData.Application; Document doc = app.ActiveUIDocument.Document; bool rc; using( Transaction t = new Transaction( doc ) ) { t.Start("Load Family"); #region 3.2.a Load an entire RFA family file: // Load a whole Family // // Example for a family WITH TXT file: rc = doc.LoadFamily( LabConstants.WholeFamilyFileToLoad1 ); #endregion // 3.2.a if( rc ) { LabUtils.InfoMsg( "Successfully loaded family " + LabConstants.WholeFamilyFileToLoad1 + "." ); } else { LabUtils.ErrorMsg( "ERROR loading family " + LabConstants.WholeFamilyFileToLoad1 + "." ); } // Example for a family WITHOUT TXT file: rc = doc.LoadFamily( LabConstants.WholeFamilyFileToLoad2 ); if( rc ) { LabUtils.InfoMsg( "Successfully loaded family " + LabConstants.WholeFamilyFileToLoad2 + "." ); } else { LabUtils.ErrorMsg( "ERROR loading family " + LabConstants.WholeFamilyFileToLoad2 + "." ); } #region 3.2.b Load an individual type from a RFA family file: // Load only a specific symbol (type): rc = doc.LoadFamilySymbol( LabConstants.FamilyFileToLoadSingleSymbol, LabConstants.SymbolName ); #endregion // 3.2.b if( rc ) { LabUtils.InfoMsg( "Successfully loaded family symbol " + LabConstants.FamilyFileToLoadSingleSymbol + " : " + LabConstants.SymbolName + "." ); } else { LabUtils.ErrorMsg( "ERROR loading family symbol " + LabConstants.FamilyFileToLoadSingleSymbol + " : " + LabConstants.SymbolName + "." ); } t.Commit(); } return Result.Succeeded; } } #endregion // Lab3_2_LoadStandardFamilies #region Lab3_3_DetermineInstanceTypeAndFamily /// <summary> /// For a selected family instance in the model, determine its type and family. /// <include file='../doc/labs.xml' path='labs/lab[@name="3-3"]/*' /> /// </summary> [Transaction( TransactionMode.ReadOnly )] public class Lab3_3_DetermineInstanceTypeAndFamily : IExternalCommand { public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements ) { UIApplication app = commandData.Application; UIDocument uidoc = app.ActiveUIDocument; Document doc = uidoc.Document; // retrieve all FamilySymbol objects of "Windows" category: BuiltInCategory bic = BuiltInCategory.OST_Windows; FilteredElementCollector symbols = LabUtils.GetFamilySymbols( doc, bic ); List<string> a = new List<string>(); foreach( FamilySymbol s in symbols ) { Family fam = s.Family; a.Add( s.Name + ", Id=" + s.Id.IntegerValue.ToString() + "; Family name=" + fam.Name + ", Family Id=" + fam.Id.IntegerValue.ToString() ); } LabUtils.InfoMsg( "{0} windows family symbol{1} loaded in the model{1}", a ); // loop through the selection set and check for // standard family instances of "Windows" category: int iBic = (int) bic; string msg, content; ICollection<ElementId> ids = uidoc.Selection.GetElementIds(); foreach( ElementId id in ids ) { Element e = doc.GetElement( id ); if( e is FamilyInstance && null != e.Category && e.Category.Id.IntegerValue.Equals( iBic ) ) { msg = "Selected window Id=" + e.Id.IntegerValue.ToString(); FamilyInstance inst = e as FamilyInstance; #region 3.3 Retrieve the type of the family instance, and the family of the type: FamilySymbol fs = inst.Symbol; Family f = fs.Family; #endregion // 3.3 content = "FamilySymbol = " + fs.Name + "; Id=" + fs.Id.IntegerValue.ToString(); content += "\r\n Family = " + f.Name + "; Id=" + f.Id.IntegerValue.ToString(); LabUtils.InfoMsg( msg, content ); } } return Result.Succeeded; } } #endregion // Lab3_3_DetermineInstanceTypeAndFamily #region Lab3_4_ChangeSelectedInstanceType /// <summary> /// Form-based utility to change the type or symbol of a selected standard family instance. /// <include file='../doc/labs.xml' path='labs/lab[@name="3-4"]/*' /> /// </summary> [Transaction( TransactionMode.Manual )] public class Lab3_4_ChangeSelectedInstanceType : IExternalCommand { public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements ) { UIApplication app = commandData.Application; UIDocument uidoc = app.ActiveUIDocument; Document doc = uidoc.Document; FamilyInstance inst = LabUtils.GetSingleSelectedElementOrPrompt( uidoc, typeof( FamilyInstance ) ) as FamilyInstance; if( null == inst ) { LabUtils.ErrorMsg( "Selected element is not a " + "standard family instance." ); return Result.Cancelled; } // determine selected instance category: Category instCat = inst.Category; Dictionary<string, List<FamilySymbol>> mapFamilyToSymbols = new Dictionary<string, List<FamilySymbol>>(); { WaitCursor waitCursor = new WaitCursor(); // Collect all types applicable to this category and sort them into // a dictionary mapping the family name to a list of its types. // // We create a collection of all loaded families for this category // and for each one, the list of all loaded types (symbols). // // There are many ways how to store the matching objects, but we choose // whatever is most suitable for the relevant UI. We could use Revit's // generic Map class, but it is probably more efficient to use the .NET // strongly-typed Dictionary with // KEY = Family name (String) // VALUE = list of corresponding FamilySymbol objects // // find all corresponding families and types: FilteredElementCollector families = new FilteredElementCollector( doc ); families.OfClass( typeof( Family ) ); foreach( Family f in families ) { bool categoryMatches = false; ISet<ElementId> ids = f.GetFamilySymbolIds(); // 2015 // we cannot trust f.Category or // f.FamilyCategory, so grab the category // from first family symbol instead: //foreach( FamilySymbol sym in f.Symbols ) // 2014 foreach( ElementId id in ids ) // 2015 { Element symbol = doc.GetElement( id ); categoryMatches = symbol.Category.Id.Equals( instCat.Id ); break; } if( categoryMatches ) { List<FamilySymbol> symbols = new List<FamilySymbol>(); //foreach( FamilySymbol sym in f.Symbols ) // 2014 foreach( ElementId id in ids ) // 2015 { FamilySymbol symbol = doc.GetElement( id ) as FamilySymbol; symbols.Add( symbol ); } mapFamilyToSymbols.Add( f.Name, symbols ); } } } // display the form allowing the user to select // a family and a type, and assign this type // to the instance. Lab3_4_Form form = new Lab3_4_Form( mapFamilyToSymbols ); if( System.Windows.Forms.DialogResult.OK == form.ShowDialog() ) { using( Transaction t = new Transaction( doc ) ) { t.Start( "Change Selected Instance Type" ); inst.Symbol = form.cmbType.SelectedItem as FamilySymbol; t.Commit(); } LabUtils.InfoMsg( "Successfully changed family : type to " + form.cmbFamily.Text + " : " + form.cmbType.Text ); } return Result.Succeeded; } } #endregion // Lab3_4_ChangeSelectedInstanceType #region Lab3_5_WallAndFloorTypes /// <summary> /// Access and modify system family type, similarly /// to the standard families looked at above: /// /// List all wall and floor types and /// change the type of selected walls and floors. /// <include file='../doc/labs.xml' path='labs/lab[@name="3-5"]/*' /> /// </summary> [Transaction( TransactionMode.Manual )] public class Lab3_5_WallAndFloorTypes : IExternalCommand { public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements ) { UIApplication app = commandData.Application; UIDocument uidoc = app.ActiveUIDocument; Document doc = uidoc.Document; // Find all wall types and their system families (or kinds): WallType newWallType = null; string msg = "All wall types and families in the model:"; string content = string.Empty; FilteredElementCollector wallTypes = new FilteredElementCollector( doc ) .OfClass( typeof( WallType ) ); foreach( WallType wt in wallTypes ) { content += "\nType=" + wt.Name + " Family=" + wt.Kind.ToString(); newWallType = wt; } content += "\n\nStored WallType " + newWallType.Name + " (Id=" + newWallType.Id.IntegerValue.ToString() + ") for later use."; LabUtils.InfoMsg( msg, content ); // Find all floor types: FloorType newFloorType = null; msg = "All floor types in the model:"; content = string.Empty; //foreach( FloorType ft in doc.FloorTypes ) // 2014 FilteredElementCollector floorTypes // 2015 = new FilteredElementCollector( doc ) .OfClass( typeof( FloorType ) ); foreach( FloorType ft in floorTypes ) // 2015 { content += "\nType=" + ft.Name + ", Id=" + ft.Id.IntegerValue.ToString(); // In 9.0, the "Foundation Slab" system family from "Structural // Foundations" category ALSO contains FloorType class instances. // Be careful to exclude those as choices for standard floor types. Parameter p = ft.get_Parameter( BuiltInParameter.SYMBOL_FAMILY_NAME_PARAM ); string famName = null == p ? "?" : p.AsString(); Category cat = ft.Category; content += ", Family=" + famName + ", Category=" + cat.Name; // store for the new floor type only if it has the proper Floors category: if( cat.Id.Equals( (int) BuiltInCategory.OST_Floors ) ) { newFloorType = ft; } } content += ( null == newFloorType ) ? "\n\nNo floor type found." : "\n\nStored FloorType " + newFloorType.Name + " (Id=" + newFloorType.Id.IntegerValue.ToString() + ") for later use"; LabUtils.InfoMsg( msg, content ); // Change the type for selected walls and floors: using( Transaction t = new Transaction( doc ) ) { t.Start( "Change Type of Walls and Floors" ); msg = "{0} {1}: Id={2}" + "\r\n changed from old type={3}; Id={4}" + " to new type={5}; Id={6}."; //ElementSet sel = uidoc.Selection.Elements; // 2014 ICollection<ElementId> ids = uidoc.Selection.GetElementIds(); // 2015 int iWall = 0; int iFloor = 0; foreach( ElementId id in ids ) { Element e = doc.GetElement( id ); if( e is Wall ) { ++iWall; Wall wall = e as Wall; WallType oldWallType = wall.WallType; // change wall type and report the old/new values wall.WallType = newWallType; LabUtils.InfoMsg( string.Format( msg, "Wall", iWall, wall.Id.IntegerValue, oldWallType.Name, oldWallType.Id.IntegerValue, wall.WallType.Name, wall.WallType.Id.IntegerValue ) ); } else if( null != newFloorType && e is Floor ) { ++iFloor; Floor f = e as Floor; FloorType oldFloorType = f.FloorType; f.FloorType = newFloorType; LabUtils.InfoMsg( string.Format( msg, "Floor", iFloor, f.Id.IntegerValue, oldFloorType.Name, oldFloorType.Id.IntegerValue, f.FloorType.Name, f.FloorType.Id.IntegerValue ) ); } } t.Commit(); } return Result.Succeeded; } } #endregion // Lab3_5_WallAndFloorTypes #region Lab3_6_DuplicateWallType /// <summary> /// Create a new family symbol or type by calling Duplicate() /// on an existing one and then modifying its parameters. /// </summary> [Transaction( TransactionMode.Manual )] public class Lab3_6_DuplicateWallType : IExternalCommand { public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements ) { UIApplication app = commandData.Application; UIDocument uidoc = app.ActiveUIDocument; Document doc = uidoc.Document; //ElementSet a = uidoc.Selection.Elements; // 2014 ICollection<ElementId> ids = uidoc.Selection.GetElementIds(); // 2015 const string newWallTypeName = "NewWallType_with_Width_doubled"; using( Transaction t = new Transaction( doc ) ) { t.Start( "Duplicate Wall Type" ); foreach( ElementId id in ids ) { Wall wall = doc.GetElement( id ) as Wall; if( null != wall ) { WallType wallType = wall.WallType; WallType newWallType = wallType.Duplicate( newWallTypeName ) as WallType; //CompoundStructureLayerArray layers = newWallType.CompoundStructure.Layers; // 2011 IList<CompoundStructureLayer> layers = newWallType.GetCompoundStructure().GetLayers(); // 2012 foreach( CompoundStructureLayer layer in layers ) { // double each layer thickness: //layer.Thickness *= 2.0; // 2011 layer.Width *= 2.0; // 2012 } // assign the new wall type back to the wall: wall.WallType = newWallType; // only process the first wall, if one was selected: break; } } t.Commit(); } return Result.Succeeded; #region Assign colour #if ASSIGN_COLOUR ElementSet elemset = doc.Selection.Elements; foreach( Element e in elemset ) { FamilyInstance inst = e as FamilyInstance; // get the symbol and duplicate it: FamilySymbol dupSym = inst.Symbol.Duplicate( "D1" ) as FamilySymbol; // access the material: ElementId matId = dupSym.get_Parameter( "Material" ).AsElementId(); Material mat = doc.GetElement( ref matId ) as Autodesk.Revit.Elements.Material; // change the color of this material: mat.Color = new Color( 255, 0, 0 ); // assign the new symbol to the instance: inst.Symbol = dupSym; #endif // ASSIGN_COLOUR #endregion // Assign colour } } #endregion // Lab3_6_DuplicateWallType #region Lab3_7_DeleteFamilyType /// <summary> /// Delete a specific individual type from a family. /// Hard-coded to a column type named "475 x 610mm". /// </summary> [Transaction( TransactionMode.Manual )] public class Lab3_7_DeleteFamilyType : IExternalCommand { public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements ) { UIApplication app = commandData.Application; Document doc = app.ActiveUIDocument.Document; FilteredElementCollector collector = LabUtils.GetFamilySymbols( doc, BuiltInCategory.OST_Columns ); #region Test explicit LINQ statement and cast #if USE_EXPLICIT_LINQ_STATEMENT var column_types = from element in collector where element.Name.Equals( "475 x 610mm" ) select element; FamilySymbol symbol = column_types .Cast<FamilySymbol>() .First<FamilySymbol>(); #endif // USE_EXPLICIT_LINQ_STATEMENT #if CAST_TO_FAMILY_SYMBOL FamilySymbol symbol = collector.First<Element>( e => e.Name.Equals( "475 x 610mm" ) ) as FamilySymbol; #endif // CAST_TO_FAMILY_SYMBOL #endregion // Test explicit LINQ statement and cast Element symbol = collector.First<Element>( e => e.Name.Equals( "475 x 610mm" ) ); using( Transaction t = new Transaction( doc ) ) { t.Start( "Delete Family Type" ); //doc.Delete( symbol ); // 2013 doc.Delete( symbol.Id ); // 2014 t.Commit(); } return Result.Succeeded; } } #endregion // Lab3_7_DeleteFamilyType }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR.Client; using System.Collections.Concurrent; using System.Net; namespace SignalRClient { public class Connection { private Uri _uri; public Uri Uri { get { return _uri; } set { _uri = value; } } private string _hubName; public string HubName { get { return _hubName; } set { _hubName = value; } } public HubConnection _hubConnection; public IHubProxy _commandHub; public ConcurrentDictionary<string, IDisposable> EventHandler = new ConcurrentDictionary<string, IDisposable>(); public ConcurrentDictionary<string, ConcurrentQueue<string>> EventQueue = new ConcurrentDictionary<string, ConcurrentQueue<string>>(); private void EnQueue(string eventName, string message) { var fReturn = false; Debug.WriteLine("{0}: EnQueue message '{1}'.", eventName, message); ConcurrentQueue<string> EnQueue; fReturn = EventQueue.TryGetValue(eventName, out EnQueue); if (fReturn) { EnQueue.Enqueue(message); } } public string TryDequeue(string eventName) { return Dequeue(eventName, 0); } public string Dequeue(string eventName) { return Dequeue(eventName, -1); } public string Dequeue(string eventName, int dwMillisecondsTotalWaitTime) { return Dequeue(eventName, dwMillisecondsTotalWaitTime, 100); } public string Dequeue(string eventName, int dwMillisecondsTotalWaitTime, int dwMilliSecondsWaitIntervall) { var fReturn = false; string message = string.Empty; IDisposable eventHandler; fReturn = EventHandler.TryGetValue(eventName, out eventHandler); if (!fReturn) { return null; } ConcurrentQueue<string> eventQueue; fReturn = EventQueue.TryGetValue(eventName, out eventQueue); if (!fReturn) { return null; } fReturn = eventQueue.TryDequeue(out message); if (fReturn || 0 == dwMillisecondsTotalWaitTime) { return fReturn ? message : null; } if ((dwMilliSecondsWaitIntervall > dwMillisecondsTotalWaitTime) && (-1 != dwMillisecondsTotalWaitTime)) { dwMilliSecondsWaitIntervall = dwMillisecondsTotalWaitTime; } var fInfiniteWaitTime = -1 == dwMillisecondsTotalWaitTime ? true : false; var datNow = DateTimeOffset.UtcNow; do { System.Threading.Thread.Sleep(dwMilliSecondsWaitIntervall); fReturn = eventQueue.TryDequeue(out message); if (fReturn) { break; } } while (fInfiniteWaitTime || dwMillisecondsTotalWaitTime > (DateTimeOffset.UtcNow - datNow).TotalMilliseconds); return fReturn ? message : null; } public List<string> DequeueAll(string eventName) { var fReturn = false; var message = string.Empty; var messages = new List<string>(); while(true) { message = TryDequeue(eventName); if (null != message) { messages.Add(message); continue; } break; } return messages; } async public Task<bool> Start(string eventName) { var fReturn = false; if (null == _commandHub) { throw new ArgumentException("_commandHub"); } fReturn = EventHandler.TryAdd(eventName, null); if (!fReturn) { Debug.WriteLine(string.Format("{0}: Adding EventHandler FAILED. [{1}]", eventName, EventHandler.Count)); return fReturn; } ConcurrentQueue<string> queue = null; fReturn = EventQueue.TryGetValue(eventName, out queue); if(!fReturn) { queue = new ConcurrentQueue<string>(); fReturn = EventQueue.TryAdd(eventName, queue); if (!fReturn) { Debug.WriteLine(string.Format("{0}: Adding EventQueue FAILED. [{1}]", eventName, EventQueue.Count)); return fReturn; } } IDisposable eventHandler; eventHandler = _commandHub.On(eventName, m => { this.EnQueue(eventName, m); }); if (null == eventHandler) { Debug.WriteLine(string.Format("{0}: Adding EventHandler FAILED. [{1}]", eventName, EventHandler.Count)); fReturn = Stop(eventName); fReturn = false; return fReturn; } fReturn = EventHandler.TryUpdate(eventName, eventHandler, null); if (!fReturn) { Debug.WriteLine(string.Format("{0}: Updating EventHandler FAILED. [{1}]", eventName, EventHandler.Count)); fReturn = this.Stop(eventName); fReturn = false; return fReturn; } Debug.WriteLine(string.Format("{0}: Starting _hubConnection ... [{1}]", eventName, EventHandler.Count)); await _hubConnection.Start(); fReturn = true; return fReturn; } public void Stop() { foreach (var eventHandler in EventHandler) { Stop(eventHandler.Key.ToString()); } } public bool Stop(string eventName) { IDisposable eventHandler; var fReturn = false; fReturn = EventHandler.TryRemove(eventName, out eventHandler); if (!fReturn || (null == eventHandler)) { return fReturn; } eventHandler.Dispose(); if (0 >= EventHandler.Count) { _hubConnection.Stop(); } return fReturn; } public Connection() { _Connection(_uri, _hubName, CredentialCache.DefaultNetworkCredentials); } public Connection(Uri uri, string hubName) { _Connection(uri, hubName, CredentialCache.DefaultNetworkCredentials); } public Connection(Uri uri, string hubName, ICredentials Credentials) { _Connection(uri, hubName, Credentials); } public Connection(Uri uri, string hubName, string Username, string Password) { var cred = new NetworkCredential(Username, Password); _Connection(uri, hubName, cred); } private void _Connection(Uri uri, string hubName, ICredentials Credentials) { _uri = uri; if (null == uri) { throw new ArgumentNullException("uri"); } _hubName = hubName; if (string.IsNullOrWhiteSpace(hubName)) { throw new ArgumentNullException("hubName"); } if (null == Credentials) { throw new ArgumentNullException("Credentials"); } _hubConnection = new HubConnection(_uri.AbsoluteUri); _hubConnection.Credentials = CredentialCache.DefaultNetworkCredentials; _commandHub = _hubConnection.CreateHubProxy(_hubName); } ~Connection() { this.Stop(); _hubConnection.Dispose(); } } }
// MIT License // // Copyright (c) 2009-2017 Luca Piccioni // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // This file is automatically generated #pragma warning disable 649, 1572, 1573 // ReSharper disable RedundantUsingDirective using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; using Khronos; // ReSharper disable CheckNamespace // ReSharper disable InconsistentNaming // ReSharper disable JoinDeclarationAndInitializer namespace OpenGL { public partial class Glx { /// <summary> /// [GLX] Value of GLX_DEVICE_ID_NV symbol. /// </summary> [RequiredByFeature("GLX_NV_video_capture")] public const int DEVICE_ID_NV = 0x20CD; /// <summary> /// [GLX] Value of GLX_UNIQUE_ID_NV symbol. /// </summary> [RequiredByFeature("GLX_NV_video_capture")] public const int UNIQUE_ID_NV = 0x20CE; /// <summary> /// [GLX] Value of GLX_NUM_VIDEO_CAPTURE_SLOTS_NV symbol. /// </summary> [RequiredByFeature("GLX_NV_video_capture")] public const int NUM_VIDEO_CAPTURE_SLOTS_NV = 0x20CF; /// <summary> /// [GLX] glXBindVideoCaptureDeviceNV: Binding for glXBindVideoCaptureDeviceNV. /// </summary> /// <param name="dpy"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="video_capture_slot"> /// A <see cref="T:uint"/>. /// </param> /// <param name="device"> /// A <see cref="T:IntPtr"/>. /// </param> [RequiredByFeature("GLX_NV_video_capture")] public static int BindVideoCaptureDeviceNV(IntPtr dpy, uint video_capture_slot, IntPtr device) { int retValue; Debug.Assert(Delegates.pglXBindVideoCaptureDeviceNV != null, "pglXBindVideoCaptureDeviceNV not implemented"); retValue = Delegates.pglXBindVideoCaptureDeviceNV(dpy, video_capture_slot, device); LogCommand("glXBindVideoCaptureDeviceNV", retValue, dpy, video_capture_slot, device ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [GLX] glXEnumerateVideoCaptureDevicesNV: Binding for glXEnumerateVideoCaptureDevicesNV. /// </summary> /// <param name="dpy"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="screen"> /// A <see cref="T:int"/>. /// </param> /// <param name="nelements"> /// A <see cref="T:int[]"/>. /// </param> [RequiredByFeature("GLX_NV_video_capture")] public static IntPtr EnumerateVideoCaptureDevicesNV(IntPtr dpy, int screen, int[] nelements) { IntPtr retValue; unsafe { fixed (int* p_nelements = nelements) { Debug.Assert(Delegates.pglXEnumerateVideoCaptureDevicesNV != null, "pglXEnumerateVideoCaptureDevicesNV not implemented"); retValue = Delegates.pglXEnumerateVideoCaptureDevicesNV(dpy, screen, p_nelements); LogCommand("glXEnumerateVideoCaptureDevicesNV", retValue, dpy, screen, nelements ); } } DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [GLX] glXLockVideoCaptureDeviceNV: Binding for glXLockVideoCaptureDeviceNV. /// </summary> /// <param name="dpy"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="device"> /// A <see cref="T:IntPtr"/>. /// </param> [RequiredByFeature("GLX_NV_video_capture")] public static void LockVideoCaptureDeviceNV(IntPtr dpy, IntPtr device) { Debug.Assert(Delegates.pglXLockVideoCaptureDeviceNV != null, "pglXLockVideoCaptureDeviceNV not implemented"); Delegates.pglXLockVideoCaptureDeviceNV(dpy, device); LogCommand("glXLockVideoCaptureDeviceNV", null, dpy, device ); DebugCheckErrors(null); } /// <summary> /// [GLX] glXQueryVideoCaptureDeviceNV: Binding for glXQueryVideoCaptureDeviceNV. /// </summary> /// <param name="dpy"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="device"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="attribute"> /// A <see cref="T:int"/>. /// </param> /// <param name="value"> /// A <see cref="T:int[]"/>. /// </param> [RequiredByFeature("GLX_NV_video_capture")] public static int QueryVideoCaptureDeviceNV(IntPtr dpy, IntPtr device, int attribute, int[] value) { int retValue; unsafe { fixed (int* p_value = value) { Debug.Assert(Delegates.pglXQueryVideoCaptureDeviceNV != null, "pglXQueryVideoCaptureDeviceNV not implemented"); retValue = Delegates.pglXQueryVideoCaptureDeviceNV(dpy, device, attribute, p_value); LogCommand("glXQueryVideoCaptureDeviceNV", retValue, dpy, device, attribute, value ); } } DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [GLX] glXReleaseVideoCaptureDeviceNV: Binding for glXReleaseVideoCaptureDeviceNV. /// </summary> /// <param name="dpy"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="device"> /// A <see cref="T:IntPtr"/>. /// </param> [RequiredByFeature("GLX_NV_video_capture")] public static void ReleaseVideoCaptureDeviceNV(IntPtr dpy, IntPtr device) { Debug.Assert(Delegates.pglXReleaseVideoCaptureDeviceNV != null, "pglXReleaseVideoCaptureDeviceNV not implemented"); Delegates.pglXReleaseVideoCaptureDeviceNV(dpy, device); LogCommand("glXReleaseVideoCaptureDeviceNV", null, dpy, device ); DebugCheckErrors(null); } internal static unsafe partial class Delegates { [RequiredByFeature("GLX_NV_video_capture")] [SuppressUnmanagedCodeSecurity] internal delegate int glXBindVideoCaptureDeviceNV(IntPtr dpy, uint video_capture_slot, IntPtr device); [RequiredByFeature("GLX_NV_video_capture")] internal static glXBindVideoCaptureDeviceNV pglXBindVideoCaptureDeviceNV; [RequiredByFeature("GLX_NV_video_capture")] [SuppressUnmanagedCodeSecurity] internal delegate IntPtr glXEnumerateVideoCaptureDevicesNV(IntPtr dpy, int screen, int* nelements); [RequiredByFeature("GLX_NV_video_capture")] internal static glXEnumerateVideoCaptureDevicesNV pglXEnumerateVideoCaptureDevicesNV; [RequiredByFeature("GLX_NV_video_capture")] [SuppressUnmanagedCodeSecurity] internal delegate void glXLockVideoCaptureDeviceNV(IntPtr dpy, IntPtr device); [RequiredByFeature("GLX_NV_video_capture")] internal static glXLockVideoCaptureDeviceNV pglXLockVideoCaptureDeviceNV; [RequiredByFeature("GLX_NV_video_capture")] [SuppressUnmanagedCodeSecurity] internal delegate int glXQueryVideoCaptureDeviceNV(IntPtr dpy, IntPtr device, int attribute, int* value); [RequiredByFeature("GLX_NV_video_capture")] internal static glXQueryVideoCaptureDeviceNV pglXQueryVideoCaptureDeviceNV; [RequiredByFeature("GLX_NV_video_capture")] [SuppressUnmanagedCodeSecurity] internal delegate void glXReleaseVideoCaptureDeviceNV(IntPtr dpy, IntPtr device); [RequiredByFeature("GLX_NV_video_capture")] internal static glXReleaseVideoCaptureDeviceNV pglXReleaseVideoCaptureDeviceNV; } } }
//////////////////////////////////////////////////////////////////////////////// // The MIT License (MIT) // // Copyright (c) 2021 Tim Stair // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //////////////////////////////////////////////////////////////////////////////// using System; using System.Drawing; using System.Linq; using System.Windows.Forms; namespace Support.UI { public class QueryPanelDialog : QueryPanel { private Form m_zForm; private int m_nMaxDesiredHeight = -1; private string m_sButtonPressed = string.Empty; public Form Form => m_zForm; /// <summary> /// Constructor /// </summary> /// <param name="sTitle">Title of the dialog</param> /// <param name="nWidth">Width of the dialog</param> /// <param name="bTabbed">Whether the panel should be tabbed</param> public QueryPanelDialog(string sTitle, int nWidth, bool bTabbed) : base(null, bTabbed) { InitForm(sTitle, nWidth, null, null); X_LABEL_SIZE = (int)((float)m_zPanel.Width * 0.25); } /// <summary> /// Constructor /// </summary> /// <param name="sTitle">Title of the dialog</param> /// <param name="nWidth">Width of the dialog</param> /// <param name="nLabelWidth">Width of labels</param> /// <param name="bTabbed">Flag indicating whether this should support tabs</param> public QueryPanelDialog(string sTitle, int nWidth, int nLabelWidth, bool bTabbed) : base(null, nLabelWidth, bTabbed) { InitForm(sTitle, nWidth, null, null); if (0 < nLabelWidth && nLabelWidth < m_zPanel.Width) { X_LABEL_SIZE = nLabelWidth; } } /// <summary> /// Constructor /// </summary> /// <param name="sTitle">Title of the dialog</param> /// <param name="nWidth">Width of the dialog</param> /// <param name="nLabelWidth">Width of labels</param> /// <param name="bTabbed">Flag indicating whether this should support tabs</param> /// <param name="arrayButtons">Array of button names to support</param> public QueryPanelDialog(string sTitle, int nWidth, int nLabelWidth, bool bTabbed, string[] arrayButtons) : base(null, nLabelWidth, bTabbed) { InitForm(sTitle, nWidth, arrayButtons, null); if (0 < nLabelWidth && nLabelWidth < m_zPanel.Width) { X_LABEL_SIZE = nLabelWidth; } } /// <summary> /// Constructor /// </summary> /// <param name="sTitle">Title of the dialog</param> /// <param name="nWidth">Width of the dialog</param> /// <param name="nLabelWidth">Width of labels</param> /// <param name="bTabbed">Flag indicating whether this should support tabs</param> /// <param name="arrayButtons">Array of button names to support</param> /// <param name="arrayHandlers">The handlers to associated with the buttons (order match with buttons, null is allowed for an event handler)</param> public QueryPanelDialog(string sTitle, int nWidth, int nLabelWidth, bool bTabbed, string[] arrayButtons, EventHandler[] arrayHandlers) : base(null, nLabelWidth, bTabbed) { InitForm(sTitle, nWidth, arrayButtons, arrayHandlers); if (0 < nLabelWidth && nLabelWidth < m_zPanel.Width) { X_LABEL_SIZE = nLabelWidth; } } /// <summary> /// Initializes the form associated with this QueryDialog /// </summary> /// <param name="sTitle">Title of the dialog</param> /// <param name="nWidth">Width of the dialog</param> /// <param name="arrayButtons">The names of the buttons to put on the dialog</param> /// <param name="arrayHandlers">event handlers for the buttons</param> private void InitForm(string sTitle, int nWidth, string[] arrayButtons, EventHandler[] arrayHandlers) { m_zForm = new Form { Size = new Size(nWidth, 300) }; Button btnDefault = null; // used to set the proper height of the internal panel // setup the buttons if (null == arrayButtons) { var btnCancel = new Button(); var btnOk = new Button(); btnOk.Click += btnOk_Click; btnCancel.Click += btnCancel_Click; btnOk.TabIndex = 65001; btnCancel.TabIndex = 65002; btnCancel.Text = "Cancel"; btnOk.Text = "OK"; btnCancel.Location = new Point((m_zForm.ClientSize.Width - (3 * X_CONTROL_BUFFER)) - btnCancel.Size.Width, (m_zForm.ClientSize.Height - Y_CONTROL_BUFFER) - btnCancel.Size.Height); btnOk.Location = new Point((btnCancel.Location.X - X_CONTROL_BUFFER) - btnOk.Size.Width, btnCancel.Location.Y); btnOk.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; btnCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; m_zForm.AcceptButton = btnOk; m_zForm.CancelButton = btnCancel; m_zForm.Controls.Add(btnOk); m_zForm.Controls.Add(btnCancel); btnDefault = btnCancel; } else { Button btnPrevious = null; for (int nIdx = arrayButtons.Length - 1; nIdx > -1; nIdx--) { btnDefault = new Button(); var bHandlerSet = false; if (arrayHandlers?[nIdx] != null) { btnDefault.Click += arrayHandlers[nIdx]; bHandlerSet = true; } if (!bHandlerSet) { btnDefault.Click += btnGeneric_Click; } btnDefault.TabIndex = 65000 + nIdx; btnDefault.Text = arrayButtons[nIdx]; btnDefault.Location = null == btnPrevious ? new Point((m_zForm.ClientSize.Width - (3 * X_CONTROL_BUFFER)) - btnDefault.Size.Width, (m_zForm.ClientSize.Height - Y_CONTROL_BUFFER) - btnDefault.Size.Height) : new Point((btnPrevious.Location.X - X_CONTROL_BUFFER) - btnDefault.Size.Width, btnPrevious.Location.Y); btnDefault.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; m_zForm.Controls.Add(btnDefault); btnPrevious = btnDefault; } } // setup the form m_zForm.FormBorderStyle = FormBorderStyle.FixedSingle; m_zForm.MaximizeBox = false; m_zForm.MinimizeBox = false; m_zForm.Name = "QueryDialog"; m_zForm.ShowInTaskbar = false; m_zForm.SizeGripStyle = SizeGripStyle.Hide; m_zForm.StartPosition = FormStartPosition.CenterParent; m_zForm.Text = sTitle; m_zForm.Load += QueryDialog_Load; // setup the panel to contain the controls m_zPanel.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right; if (null != btnDefault) { m_zPanel.Size = new Size(m_zForm.ClientSize.Width, m_zForm.ClientSize.Height - (btnDefault.Size.Height + (2*Y_CONTROL_BUFFER))); } m_zPanel.AutoScroll = true; m_zPanel.Resize += m_zPanel_Resize; m_zForm.Controls.Add(m_zPanel); } void m_zPanel_Resize(object sender, EventArgs e) { SetupScrollState(m_zPanel); } /// <summary> /// Sets the title text of the dialog. /// </summary> /// <param name="sTitle"></param> public void SetTitleText(string sTitle) { m_zForm.Text = sTitle; } /// <summary> /// Flags the dialog to be shown in the task bar. /// </summary> /// <param name="bShow"></param> public void ShowInTaskBar(bool bShow) { m_zForm.ShowInTaskbar = bShow; } /// <summary> /// Allows the form to be resized. This should be used after all of the controls have been added to set the minimum size. /// </summary> public void AllowResize() { m_zForm.MaximizeBox = true; m_zForm.FormBorderStyle = FormBorderStyle.Sizable; } /// <summary> /// Sets the icon for the form /// </summary> /// <param name="zIcon">The icon to use for the dialog. If null is specified the icon is hidden.</param> public void SetIcon(Icon zIcon) { if (null == zIcon) { m_zForm.ShowIcon = false; } else { m_zForm.Icon = zIcon; } } /// <summary> /// Shows the dialog (much like the Form.ShowDialog method) /// </summary> /// <param name="zParentForm"></param> /// <returns></returns> public DialogResult ShowDialog(IWin32Window zParentForm) { return m_zForm.ShowDialog(zParentForm); } /// <summary> /// Returns the string on the button pressed on exit. /// </summary> /// <returns></returns> public string GetButtonPressedString() { return m_sButtonPressed; } #region Events /// <summary> /// Handles generic button presses (for those on the bottom of the dialog) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnGeneric_Click(object sender, EventArgs e) { m_zForm.DialogResult = DialogResult.OK; m_sButtonPressed = ((Button)sender).Text; m_zForm.Close(); } /// <summary> /// Handles the Ok button press. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnOk_Click(object sender, EventArgs e) { m_zForm.DialogResult = DialogResult.OK; m_sButtonPressed = m_zForm.DialogResult.ToString(); } /// <summary> /// Handles the Cancel button press. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnCancel_Click(object sender, EventArgs e) { m_zForm.DialogResult = DialogResult.Cancel; m_sButtonPressed = m_zForm.DialogResult.ToString(); } /// <summary> /// Sets the max desired height for the dialog. /// </summary> /// <param name="nMaxHeight"></param> public void SetMaxHeight(int nMaxHeight) { m_nMaxDesiredHeight = nMaxHeight; } /// <summary> /// The dialog load event /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void QueryDialog_Load(object sender, EventArgs e) { if (null == m_zTabControl) { int nHeight = GetYPosition() + m_nButtonHeight + (Y_CONTROL_BUFFER * 2); if (m_nMaxDesiredHeight > 0) { if (nHeight > m_nMaxDesiredHeight) { nHeight = m_nMaxDesiredHeight; } } m_zForm.ClientSize = new Size(m_zForm.ClientSize.Width, nHeight); } else { var nLargestHeight = -1; foreach(var zPage in m_zTabControl.TabPages.OfType<TabPage>()) { if(nLargestHeight < (int)zPage.Tag) { nLargestHeight = (int)zPage.Tag; } } if (nLargestHeight > 0) { if (m_nMaxDesiredHeight > 0) { nLargestHeight = Math.Min(m_nMaxDesiredHeight, nLargestHeight); } // hard coded extra vertical space m_zForm.ClientSize = new Size(m_zForm.ClientSize.Width, nLargestHeight + 60); } } // add the panel controls after the client size has been set (adding them before displayed an odd issue with control anchor/size) FinalizeControls(); if (0 < m_zPanel.Controls.Count) { m_zPanel.SelectNextControl(m_zPanel.Controls[m_zPanel.Controls.Count - 1], true, true, true, true); } } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Edubase.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim 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.Reflection; using OpenMetaverse; using OpenMetaverse.Imaging; using Aurora.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Services.Interfaces; namespace OpenSim.Region.ClientStack.LindenUDP { /// <summary> /// Stores information about a current texture download and a reference to the texture asset /// </summary> public class J2KImage { private const int IMAGE_PACKET_SIZE = 1000; private const int FIRST_PACKET_SIZE = 600; private readonly LLImageManager m_imageManager; public UUID AgentID; public IAssetService AssetService; public sbyte DiscardLevel; public bool HasAsset; public IInventoryAccessModule InventoryAccessModule; public bool IsDecoded; public IJ2KDecoder J2KDecoder; public uint LastSequence; public OpenJPEG.J2KLayerInfo[] Layers; public float Priority; public uint StartPacket; public UUID TextureID; private byte[] m_asset; private bool m_assetRequested; private uint m_currentPacket; private bool m_decodeRequested; private bool m_sentInfo; private uint m_stopPacket; public J2KImage(LLImageManager imageManager) { m_imageManager = imageManager; } public void Dispose() { m_asset = null; } /// <summary> /// Sends packets for this texture to a client until packetsToSend is /// hit or the transfer completes /// </summary> /// <param name = "client">Reference to the client that the packets are destined for</param> /// <param name = "packetsToSend">Maximum number of packets to send during this call</param> /// <param name = "packetsSent">Number of packets sent during this call</param> /// <returns>True if the transfer completes at the current discard level, otherwise false</returns> public bool SendPackets(LLClientView client, int packetsToSend, out int packetsSent) { packetsSent = 0; if (m_currentPacket <= m_stopPacket) { bool sendMore = true; if (!m_sentInfo || (m_currentPacket == 0)) { sendMore = !SendFirstPacket(client); m_sentInfo = true; ++m_currentPacket; ++packetsSent; } if (m_currentPacket < 2) { m_currentPacket = 2; } while (sendMore && packetsSent < packetsToSend && m_currentPacket <= m_stopPacket) { sendMore = SendPacket(client); ++m_currentPacket; ++packetsSent; } } return (m_currentPacket > m_stopPacket); } public void RunUpdate() { //This is where we decide what we need to update //and assign the real discardLevel and packetNumber //assuming of course that the connected client might be bonkers if (!HasAsset) { if (!m_assetRequested) { m_assetRequested = true; AssetService.Get(TextureID.ToString(), this, AssetReceived); } } else { if (!IsDecoded) { //We need to decode the requested image first if (!m_decodeRequested) { //Request decode m_decodeRequested = true; // Do we have a jpeg decoder? if (J2KDecoder != null) { if (m_asset == null) { J2KDecodedCallback(TextureID, new OpenJPEG.J2KLayerInfo[0]); } else { // Send it off to the jpeg decoder J2KDecoder.BeginDecode(TextureID, m_asset, J2KDecodedCallback); } } else { J2KDecodedCallback(TextureID, new OpenJPEG.J2KLayerInfo[0]); } } } else { // Check for missing image asset data if (m_asset == null) { MainConsole.Instance.Warn( "[J2KIMAGE]: RunUpdate() called with missing asset data (no missing image texture?). Canceling texture transfer"); m_currentPacket = m_stopPacket; return; } if (DiscardLevel >= 0 || m_stopPacket == 0) { // This shouldn't happen, but if it does, we really can't proceed if (Layers == null) { MainConsole.Instance.Warn("[J2KIMAGE]: RunUpdate() called with missing Layers. Canceling texture transfer"); m_currentPacket = m_stopPacket; return; } int maxDiscardLevel = Math.Max(0, Layers.Length - 1); // Treat initial texture downloads with a DiscardLevel of -1 a request for the highest DiscardLevel if (DiscardLevel < 0 && m_stopPacket == 0) DiscardLevel = (sbyte) maxDiscardLevel; // Clamp at the highest discard level DiscardLevel = (sbyte) Math.Min(DiscardLevel, maxDiscardLevel); //Calculate the m_stopPacket if (Layers.Length > 0) { m_stopPacket = (uint) GetPacketForBytePosition(Layers[(Layers.Length - 1) - DiscardLevel].End); //I don't know why, but the viewer seems to expect the final packet if the file //is just one packet bigger. if (TexturePacketCount() == m_stopPacket + 1) { m_stopPacket = TexturePacketCount(); } } else { m_stopPacket = TexturePacketCount(); } m_currentPacket = StartPacket; } } } } private bool SendFirstPacket(LLClientView client) { if (client == null) return false; if (m_asset == null) { MainConsole.Instance.Warn("[J2KIMAGE]: Sending ImageNotInDatabase for texture " + TextureID); client.SendImageNotFound(TextureID); return true; } if (m_asset.Length <= FIRST_PACKET_SIZE) { // We have less then one packet's worth of data client.SendImageFirstPart(1, TextureID, (uint) m_asset.Length, m_asset, 2); m_stopPacket = 0; return true; } // This is going to be a multi-packet texture download byte[] firstImageData = new byte[FIRST_PACKET_SIZE]; try { Buffer.BlockCopy(m_asset, 0, firstImageData, 0, FIRST_PACKET_SIZE); } catch (Exception) { MainConsole.Instance.ErrorFormat( "[J2KIMAGE]: Texture block copy for the first packet failed. textureid={0}, assetlength={1}", TextureID, m_asset.Length); return true; } client.SendImageFirstPart(TexturePacketCount(), TextureID, (uint) m_asset.Length, firstImageData, (byte) ImageCodec.J2C); return false; } private bool SendPacket(LLClientView client) { if (client == null || m_asset == null) return false; bool complete = false; int imagePacketSize = ((int) m_currentPacket == (TexturePacketCount())) ? LastPacketSize() : IMAGE_PACKET_SIZE; try { if ((CurrentBytePosition() + IMAGE_PACKET_SIZE) > m_asset.Length) { imagePacketSize = LastPacketSize(); complete = true; if ((CurrentBytePosition() + imagePacketSize) > m_asset.Length) { imagePacketSize = m_asset.Length - CurrentBytePosition(); complete = true; } } // It's concievable that the client might request packet one // from a one packet image, which is really packet 0, // which would leave us with a negative imagePacketSize.. if (imagePacketSize > 0) { byte[] imageData = new byte[imagePacketSize]; int currentPosition = CurrentBytePosition(); try { Buffer.BlockCopy(m_asset, currentPosition, imageData, 0, imagePacketSize); } catch (Exception e) { MainConsole.Instance.ErrorFormat( "[J2KIMAGE]: Texture block copy for the first packet failed. textureid={0}, assetlength={1}, currentposition={2}, imagepacketsize={3}, exception={4}", TextureID, m_asset.Length, currentPosition, imagePacketSize, e.Message); return false; } //Send the packet client.SendImageNextPart((ushort) (m_currentPacket - 1), TextureID, imageData); } return !complete; } catch (Exception) { return false; } } private ushort TexturePacketCount() { if (!IsDecoded) return 0; if (m_asset == null) return 0; if (m_asset.Length <= FIRST_PACKET_SIZE) return 1; return (ushort) (((m_asset.Length - FIRST_PACKET_SIZE + IMAGE_PACKET_SIZE - 1)/IMAGE_PACKET_SIZE) + 1); } private int GetPacketForBytePosition(int bytePosition) { return ((bytePosition - FIRST_PACKET_SIZE + IMAGE_PACKET_SIZE - 1)/IMAGE_PACKET_SIZE) + 1; } private int LastPacketSize() { if (m_currentPacket == 1) return m_asset.Length; int lastsize = (m_asset.Length - FIRST_PACKET_SIZE)%IMAGE_PACKET_SIZE; //If the last packet size is zero, it's really cImagePacketSize, it sits on the boundary if (lastsize == 0) { lastsize = IMAGE_PACKET_SIZE; } return lastsize; } private int CurrentBytePosition() { if (m_currentPacket == 0) return 0; if (m_currentPacket == 1) return FIRST_PACKET_SIZE; int result = FIRST_PACKET_SIZE + ((int) m_currentPacket - 2)*IMAGE_PACKET_SIZE; if (result < 0) { result = FIRST_PACKET_SIZE; } return result; } private void J2KDecodedCallback(UUID AssetId, OpenJPEG.J2KLayerInfo[] layers) { Layers = layers; IsDecoded = true; RunUpdate(); } private void AssetDataCallback(UUID AssetID, AssetBase asset) { HasAsset = true; if (asset == null || asset.Data == null || asset.Type == (int)AssetType.Mesh) { if (m_imageManager.MissingImage != null) { m_asset = m_imageManager.MissingImage.Data; } else { m_asset = null; IsDecoded = true; } } else { m_asset = asset.Data; asset = null; } RunUpdate(); } private void AssetReceived(string id, Object sender, AssetBase asset) { UUID assetID = UUID.Zero; if (asset != null) assetID = asset.ID; else if ((InventoryAccessModule != null) && (sender != InventoryAccessModule)) { // Unfortunately we need this here, there's no other way. // This is due to the fact that textures opened directly from the agent's inventory // don't have any distinguishing feature. As such, in order to serve those when the // foreign user is visiting, we need to try again after the first fail to the local // asset service. string assetServerURL = string.Empty; if (InventoryAccessModule.IsForeignUser(AgentID, out assetServerURL)) { MainConsole.Instance.DebugFormat( "[J2KIMAGE]: texture {0} not found in local asset storage. Trying user's storage.", id); AssetService.Get(assetServerURL + "/" + id, InventoryAccessModule, AssetReceived); return; } } AssetDataCallback(assetID, asset); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Net.Http; using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http3; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure { internal sealed partial class KestrelTrace : ILogger { private readonly ILogger _generalLogger; private readonly ILogger _badRequestsLogger; private readonly ILogger _connectionsLogger; private readonly ILogger _http2Logger; private readonly ILogger _http3Logger; public KestrelTrace(ILoggerFactory loggerFactory) { _generalLogger = loggerFactory.CreateLogger("Microsoft.AspNetCore.Server.Kestrel"); _badRequestsLogger = loggerFactory.CreateLogger("Microsoft.AspNetCore.Server.Kestrel.BadRequests"); _connectionsLogger = loggerFactory.CreateLogger("Microsoft.AspNetCore.Server.Kestrel.Connections"); _http2Logger = loggerFactory.CreateLogger("Microsoft.AspNetCore.Server.Kestrel.Http2"); _http3Logger = loggerFactory.CreateLogger("Microsoft.AspNetCore.Server.Kestrel.Http3"); } [LoggerMessage(39, LogLevel.Debug, @"Connection id ""{ConnectionId}"" accepted.", EventName = "ConnectionAccepted")] private static partial void ConnectionAccepted(ILogger logger, string connectionId); public void ConnectionAccepted(string connectionId) { ConnectionAccepted(_connectionsLogger, connectionId); } [LoggerMessage(1, LogLevel.Debug, @"Connection id ""{ConnectionId}"" started.", EventName = "ConnectionStart")] private static partial void ConnectionStart(ILogger logger, string connectionId); public void ConnectionStart(string connectionId) { ConnectionStart(_connectionsLogger, connectionId); } [LoggerMessage(2, LogLevel.Debug, @"Connection id ""{ConnectionId}"" stopped.", EventName = "ConnectionStop")] private static partial void ConnectionStop(ILogger logger, string connectionId); public void ConnectionStop(string connectionId) { ConnectionStop(_connectionsLogger, connectionId); } [LoggerMessage(4, LogLevel.Debug, @"Connection id ""{ConnectionId}"" paused.", EventName = "ConnectionPause")] private static partial void ConnectionPause(ILogger logger, string connectionId); public void ConnectionPause(string connectionId) { ConnectionPause(_connectionsLogger, connectionId); } [LoggerMessage(5, LogLevel.Debug, @"Connection id ""{ConnectionId}"" resumed.", EventName = "ConnectionResume")] private static partial void ConnectionResume(ILogger logger, string connectionId); public void ConnectionResume(string connectionId) { ConnectionResume(_connectionsLogger, connectionId); } [LoggerMessage(9, LogLevel.Debug, @"Connection id ""{ConnectionId}"" completed keep alive response.", EventName = "ConnectionKeepAlive")] private static partial void ConnectionKeepAlive(ILogger logger, string connectionId); public void ConnectionKeepAlive(string connectionId) { ConnectionKeepAlive(_connectionsLogger, connectionId); } [LoggerMessage(24, LogLevel.Warning, @"Connection id ""{ConnectionId}"" rejected because the maximum number of concurrent connections has been reached.", EventName = "ConnectionRejected")] private static partial void ConnectionRejected(ILogger logger, string connectionId); public void ConnectionRejected(string connectionId) { ConnectionRejected(_connectionsLogger, connectionId); } [LoggerMessage(10, LogLevel.Debug, @"Connection id ""{ConnectionId}"" disconnecting.", EventName = "ConnectionDisconnect")] private static partial void ConnectionDisconnect(ILogger logger, string connectionId); public void ConnectionDisconnect(string connectionId) { ConnectionDisconnect(_connectionsLogger, connectionId); } [LoggerMessage(13, LogLevel.Error, @"Connection id ""{ConnectionId}"", Request id ""{TraceIdentifier}"": An unhandled exception was thrown by the application.", EventName = "ApplicationError")] private static partial void ApplicationError(ILogger logger, string connectionId, string traceIdentifier, Exception ex); public void ApplicationError(string connectionId, string traceIdentifier, Exception ex) { ApplicationError(_generalLogger, connectionId, traceIdentifier, ex); } [LoggerMessage(18, LogLevel.Debug, @"Connection id ""{ConnectionId}"" write of ""{count}"" body bytes to non-body HEAD response.", EventName = "ConnectionHeadResponseBodyWrite")] private static partial void ConnectionHeadResponseBodyWrite(ILogger logger, string connectionId, long count); public void ConnectionHeadResponseBodyWrite(string connectionId, long count) { ConnectionHeadResponseBodyWrite(_generalLogger, connectionId, count); } [LoggerMessage(16, LogLevel.Debug, "Some connections failed to close gracefully during server shutdown.", EventName = "NotAllConnectionsClosedGracefully")] private static partial void NotAllConnectionsClosedGracefully(ILogger logger); public void NotAllConnectionsClosedGracefully() { NotAllConnectionsClosedGracefully(_connectionsLogger); } [LoggerMessage(17, LogLevel.Debug, @"Connection id ""{ConnectionId}"" bad request data: ""{message}""", EventName = "ConnectionBadRequest")] private static partial void ConnectionBadRequest(ILogger logger, string connectionId, string message, Microsoft.AspNetCore.Http.BadHttpRequestException ex); public void ConnectionBadRequest(string connectionId, Microsoft.AspNetCore.Http.BadHttpRequestException ex) { ConnectionBadRequest(_badRequestsLogger, connectionId, ex.Message, ex); } [LoggerMessage(20, LogLevel.Debug, @"Connection id ""{ConnectionId}"" request processing ended abnormally.", EventName = "RequestProcessingError")] private static partial void RequestProcessingError(ILogger logger, string connectionId, Exception ex); public void RequestProcessingError(string connectionId, Exception ex) { RequestProcessingError(_badRequestsLogger, connectionId, ex); } [LoggerMessage(21, LogLevel.Debug, "Some connections failed to abort during server shutdown.", EventName = "NotAllConnectionsAborted")] private static partial void NotAllConnectionsAborted(ILogger logger); public void NotAllConnectionsAborted() { NotAllConnectionsAborted(_connectionsLogger); } [LoggerMessage(22, LogLevel.Warning, @"As of ""{now}"", the heartbeat has been running for ""{heartbeatDuration}"" which is longer than ""{interval}"". This could be caused by thread pool starvation.", EventName = "HeartbeatSlow")] private static partial void HeartbeatSlow(ILogger logger, DateTimeOffset now, TimeSpan heartbeatDuration, TimeSpan interval); public void HeartbeatSlow(TimeSpan heartbeatDuration, TimeSpan interval, DateTimeOffset now) { // while the heartbeat does loop over connections, this log is usually an indicator of threadpool starvation HeartbeatSlow(_generalLogger, now, heartbeatDuration, interval); } [LoggerMessage(23, LogLevel.Critical, @"Connection id ""{ConnectionId}"" application never completed.", EventName = "ApplicationNeverCompleted")] private static partial void ApplicationNeverCompleted(ILogger logger, string connectionId); public void ApplicationNeverCompleted(string connectionId) { ApplicationNeverCompleted(_generalLogger, connectionId); } [LoggerMessage(25, LogLevel.Debug, @"Connection id ""{ConnectionId}"", Request id ""{TraceIdentifier}"": started reading request body.", EventName = "RequestBodyStart", SkipEnabledCheck = true)] private static partial void RequestBodyStart(ILogger logger, string connectionId, string traceIdentifier); public void RequestBodyStart(string connectionId, string traceIdentifier) { RequestBodyStart(_generalLogger, connectionId, traceIdentifier); } [LoggerMessage(26, LogLevel.Debug, @"Connection id ""{ConnectionId}"", Request id ""{TraceIdentifier}"": done reading request body.", EventName = "RequestBodyDone", SkipEnabledCheck = true)] private static partial void RequestBodyDone(ILogger logger, string connectionId, string traceIdentifier); public void RequestBodyDone(string connectionId, string traceIdentifier) { RequestBodyDone(_generalLogger, connectionId, traceIdentifier); } [LoggerMessage(27, LogLevel.Debug, @"Connection id ""{ConnectionId}"", Request id ""{TraceIdentifier}"": the request timed out because it was not sent by the client at a minimum of {Rate} bytes/second.", EventName = "RequestBodyMinimumDataRateNotSatisfied")] private static partial void RequestBodyMinimumDataRateNotSatisfied(ILogger logger, string connectionId, string? traceIdentifier, double rate); public void RequestBodyMinimumDataRateNotSatisfied(string connectionId, string? traceIdentifier, double rate) { RequestBodyMinimumDataRateNotSatisfied(_badRequestsLogger, connectionId, traceIdentifier, rate); } [LoggerMessage(32, LogLevel.Information, @"Connection id ""{ConnectionId}"", Request id ""{TraceIdentifier}"": the application completed without reading the entire request body.", EventName = "RequestBodyNotEntirelyRead")] private static partial void RequestBodyNotEntirelyRead(ILogger logger, string connectionId, string traceIdentifier); public void RequestBodyNotEntirelyRead(string connectionId, string traceIdentifier) { RequestBodyNotEntirelyRead(_generalLogger, connectionId, traceIdentifier); } [LoggerMessage(33, LogLevel.Information, @"Connection id ""{ConnectionId}"", Request id ""{TraceIdentifier}"": automatic draining of the request body timed out after taking over 5 seconds.", EventName = "RequestBodyDrainTimedOut")] private static partial void RequestBodyDrainTimedOut(ILogger logger, string connectionId, string traceIdentifier); public void RequestBodyDrainTimedOut(string connectionId, string traceIdentifier) { RequestBodyDrainTimedOut(_generalLogger, connectionId, traceIdentifier); } [LoggerMessage(28, LogLevel.Debug, @"Connection id ""{ConnectionId}"", Request id ""{TraceIdentifier}"": the connection was closed because the response was not read by the client at the specified minimum data rate.", EventName = "ResponseMinimumDataRateNotSatisfied")] private static partial void ResponseMinimumDataRateNotSatisfied(ILogger logger, string connectionId, string? traceIdentifier); public void ResponseMinimumDataRateNotSatisfied(string connectionId, string? traceIdentifier) { ResponseMinimumDataRateNotSatisfied(_badRequestsLogger, connectionId, traceIdentifier); } [LoggerMessage(34, LogLevel.Information, @"Connection id ""{ConnectionId}"", Request id ""{TraceIdentifier}"": the application aborted the connection.", EventName = "ApplicationAbortedConnection")] private static partial void ApplicationAbortedConnection(ILogger logger, string connectionId, string traceIdentifier); public void ApplicationAbortedConnection(string connectionId, string traceIdentifier) { ApplicationAbortedConnection(_connectionsLogger, connectionId, traceIdentifier); } [LoggerMessage(29, LogLevel.Debug, @"Connection id ""{ConnectionId}"": HTTP/2 connection error.", EventName = "Http2ConnectionError")] private static partial void Http2ConnectionError(ILogger logger, string connectionId, Http2ConnectionErrorException ex); public void Http2ConnectionError(string connectionId, Http2ConnectionErrorException ex) { Http2ConnectionError(_http2Logger, connectionId, ex); } [LoggerMessage(36, LogLevel.Debug, @"Connection id ""{ConnectionId}"" is closing.", EventName = "Http2ConnectionClosing")] private static partial void Http2ConnectionClosing(ILogger logger, string connectionId); public void Http2ConnectionClosing(string connectionId) { Http2ConnectionClosing(_http2Logger, connectionId); } [LoggerMessage(48, LogLevel.Debug, @"Connection id ""{ConnectionId}"" is closed. The last processed stream ID was {HighestOpenedStreamId}.", EventName = "Http2ConnectionClosed")] private static partial void Http2ConnectionClosed(ILogger logger, string connectionId, int highestOpenedStreamId); public void Http2ConnectionClosed(string connectionId, int highestOpenedStreamId) { Http2ConnectionClosed(_http2Logger, connectionId, highestOpenedStreamId); } [LoggerMessage(30, LogLevel.Debug, @"Connection id ""{ConnectionId}"": HTTP/2 stream error.", EventName = "Http2StreamError")] private static partial void Http2StreamError(ILogger logger, string connectionId, Http2StreamErrorException ex); public void Http2StreamError(string connectionId, Http2StreamErrorException ex) { Http2StreamError(_http2Logger, connectionId, ex); } [LoggerMessage(35, LogLevel.Debug, @"Trace id ""{TraceIdentifier}"": HTTP/2 stream error ""{error}"". A Reset is being sent to the stream.", EventName = "Http2StreamResetAbort")] private static partial void Http2StreamResetAbort(ILogger logger, string traceIdentifier, Http2ErrorCode error, ConnectionAbortedException abortReason); public void Http2StreamResetAbort(string traceIdentifier, Http2ErrorCode error, ConnectionAbortedException abortReason) { Http2StreamResetAbort(_http2Logger, traceIdentifier, error, abortReason); } [LoggerMessage(31, LogLevel.Debug, @"Connection id ""{ConnectionId}"": HPACK decoding error while decoding headers for stream ID {StreamId}.", EventName = "HPackDecodingError")] private static partial void HPackDecodingError(ILogger logger, string connectionId, int streamId, Exception ex); public void HPackDecodingError(string connectionId, int streamId, Exception ex) { HPackDecodingError(_http2Logger, connectionId, streamId, ex); } [LoggerMessage(38, LogLevel.Information, @"Connection id ""{ConnectionId}"": HPACK encoding error while encoding headers for stream ID {StreamId}.", EventName = "HPackEncodingError")] private static partial void HPackEncodingError(ILogger logger, string connectionId, int streamId, Exception ex); public void HPackEncodingError(string connectionId, int streamId, Exception ex) { HPackEncodingError(_http2Logger, connectionId, streamId, ex); } [LoggerMessage(37, LogLevel.Trace, @"Connection id ""{ConnectionId}"" received {type} frame for stream ID {id} with length {length} and flags {flags}.", EventName = "Http2FrameReceived", SkipEnabledCheck = true)] private static partial void Http2FrameReceived(ILogger logger, string connectionId, Http2FrameType type, int id, int length, object flags); public void Http2FrameReceived(string connectionId, Http2Frame frame) { if (_http2Logger.IsEnabled(LogLevel.Trace)) { Http2FrameReceived(_http2Logger, connectionId, frame.Type, frame.StreamId, frame.PayloadLength, frame.ShowFlags()); } } [LoggerMessage(49, LogLevel.Trace, @"Connection id ""{ConnectionId}"" sending {type} frame for stream ID {id} with length {length} and flags {flags}.", EventName = "Http2FrameSending", SkipEnabledCheck = true)] private static partial void Http2FrameSending(ILogger logger, string connectionId, Http2FrameType type, int id, int length, object flags); public void Http2FrameSending(string connectionId, Http2Frame frame) { if (_http2Logger.IsEnabled(LogLevel.Trace)) { Http2FrameSending(_http2Logger, connectionId, frame.Type, frame.StreamId, frame.PayloadLength, frame.ShowFlags()); } } [LoggerMessage(40, LogLevel.Debug, @"Connection id ""{ConnectionId}"" reached the maximum number of concurrent HTTP/2 streams allowed.", EventName = "Http2MaxConcurrentStreamsReached")] private static partial void Http2MaxConcurrentStreamsReached(ILogger logger, string connectionId); public void Http2MaxConcurrentStreamsReached(string connectionId) { Http2MaxConcurrentStreamsReached(_http2Logger, connectionId); } [LoggerMessage(41, LogLevel.Warning, "One or more of the following response headers have been removed because they are invalid for HTTP/2 and HTTP/3 responses: 'Connection', 'Transfer-Encoding', 'Keep-Alive', 'Upgrade' and 'Proxy-Connection'.", EventName = "InvalidResponseHeaderRemoved")] private static partial void InvalidResponseHeaderRemoved(ILogger logger); public void InvalidResponseHeaderRemoved() { InvalidResponseHeaderRemoved(_generalLogger); } [LoggerMessage(42, LogLevel.Debug, @"Connection id ""{ConnectionId}"": HTTP/3 connection error.", EventName = "Http3ConnectionError")] private static partial void Http3ConnectionError(ILogger logger, string connectionId, Http3ConnectionErrorException ex); public void Http3ConnectionError(string connectionId, Http3ConnectionErrorException ex) { Http3ConnectionError(_http3Logger, connectionId, ex); } [LoggerMessage(43, LogLevel.Debug, @"Connection id ""{ConnectionId}"" is closing.", EventName = "Http3ConnectionClosing")] private static partial void Http3ConnectionClosing(ILogger logger, string connectionId); public void Http3ConnectionClosing(string connectionId) { Http3ConnectionClosing(_http3Logger, connectionId); } [LoggerMessage(44, LogLevel.Debug, @"Connection id ""{ConnectionId}"" is closed. The last processed stream ID was {HighestOpenedStreamId}.", EventName = "Http3ConnectionClosed")] private static partial void Http3ConnectionClosed(ILogger logger, string connectionId, long? highestOpenedStreamId); public void Http3ConnectionClosed(string connectionId, long? highestOpenedStreamId) { Http3ConnectionClosed(_http3Logger, connectionId, highestOpenedStreamId); } [LoggerMessage(45, LogLevel.Debug, @"Trace id ""{TraceIdentifier}"": HTTP/3 stream error ""{error}"". An abort is being sent to the stream.", EventName = "Http3StreamAbort", SkipEnabledCheck = true)] private static partial void Http3StreamAbort(ILogger logger, string traceIdentifier, string error, ConnectionAbortedException abortReason); public void Http3StreamAbort(string traceIdentifier, Http3ErrorCode error, ConnectionAbortedException abortReason) { if (_http3Logger.IsEnabled(LogLevel.Debug)) { Http3StreamAbort(_http3Logger, traceIdentifier, Http3Formatting.ToFormattedErrorCode(error), abortReason); } } [LoggerMessage(46, LogLevel.Trace, @"Connection id ""{ConnectionId}"" received {type} frame for stream ID {id} with length {length}.", EventName = "Http3FrameReceived", SkipEnabledCheck = true)] private static partial void Http3FrameReceived(ILogger logger, string connectionId, string type, long id, long length); public void Http3FrameReceived(string connectionId, long streamId, Http3RawFrame frame) { if (_http3Logger.IsEnabled(LogLevel.Trace)) { Http3FrameReceived(_http3Logger, connectionId, Http3Formatting.ToFormattedType(frame.Type), streamId, frame.Length); } } [LoggerMessage(47, LogLevel.Trace, @"Connection id ""{ConnectionId}"" sending {type} frame for stream ID {id} with length {length}.", EventName = "Http3FrameSending", SkipEnabledCheck = true)] private static partial void Http3FrameSending(ILogger logger, string connectionId, string type, long id, long length); public void Http3FrameSending(string connectionId, long streamId, Http3RawFrame frame) { if (_http3Logger.IsEnabled(LogLevel.Trace)) { Http3FrameSending(_http3Logger, connectionId, Http3Formatting.ToFormattedType(frame.Type), streamId, frame.Length); } } [LoggerMessage(50, LogLevel.Debug, @"Connection id ""{ConnectionId}"": Unexpected error when initializing outbound control stream.", EventName = "Http3OutboundControlStreamError")] private static partial void Http3OutboundControlStreamError(ILogger logger, string connectionId, Exception ex); public void Http3OutboundControlStreamError(string connectionId, Exception ex) { Http3OutboundControlStreamError(_http3Logger, connectionId, ex); } [LoggerMessage(51, LogLevel.Debug, @"Connection id ""{ConnectionId}"": QPACK decoding error while decoding headers for stream ID {StreamId}.", EventName = "QPackDecodingError")] private static partial void QPackDecodingError(ILogger logger, string connectionId, long streamId, Exception ex); public void QPackDecodingError(string connectionId, long streamId, Exception ex) { QPackDecodingError(_http3Logger, connectionId, streamId, ex); } [LoggerMessage(52, LogLevel.Information, @"Connection id ""{ConnectionId}"": QPACK encoding error while encoding headers for stream ID {StreamId}.", EventName = "QPackEncodingError")] private static partial void QPackEncodingError(ILogger logger, string connectionId, long streamId, Exception ex); public void QPackEncodingError(string connectionId, long streamId, Exception ex) { QPackEncodingError(_http3Logger, connectionId, streamId, ex); } [LoggerMessage(53, LogLevel.Debug, @"Connection id ""{ConnectionId}"": GOAWAY stream ID {GoAwayStreamId}.", EventName = "Http3GoAwayHighestOpenedStreamId")] private static partial void Http3GoAwayStreamId(ILogger logger, string connectionId, long goAwayStreamId); public void Http3GoAwayStreamId(string connectionId, long goAwayStreamId) { Http3GoAwayStreamId(_http3Logger, connectionId, goAwayStreamId); } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) => _generalLogger.Log(logLevel, eventId, state, exception, formatter); public bool IsEnabled(LogLevel logLevel) => _generalLogger.IsEnabled(logLevel); public IDisposable BeginScope<TState>(TState state) => _generalLogger.BeginScope(state); } }
//--------------------------------------------------------------------- // <copyright file="RequestDescription.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <summary> // Provides a description of the request a client has submitted. // </summary> // // @owner [....] //--------------------------------------------------------------------- namespace System.Data.Services { #region Namespaces. using System; using System.Collections; using System.Collections.Generic; using System.Data.Services.Providers; using System.Diagnostics; using System.Linq; #endregion Namespaces. /// <summary> /// Query Counting Option /// </summary> internal enum RequestQueryCountOption { /// <summary>Do not count the result set</summary> None, /// <summary>Count and return value inline (together with data)</summary> Inline, /// <summary>Count and return value only (as integer)</summary> ValueOnly } /// <summary> /// Use this class to describe the data request a client has /// submitted to the service. /// </summary> [DebuggerDisplay("RequestDescription={TargetSource} '{ContainerName}' -> {TargetKind} '{TargetResourceType}'")] internal class RequestDescription { /// <summary> /// The default response version of the data service. If no version is set for a particular response /// The DataService will respond with this version (1.0) /// </summary> internal static readonly Version DataServiceDefaultResponseVersion = new Version(1, 0); #region Private fields. /// <summary> /// Default set of known data service versions, currently 1.0 and 2.0 /// </summary> private static readonly Version[] KnownDataServiceVersions = new Version[] { new Version(1, 0), new Version(2, 0) }; /// <summary>The name of the container for results.</summary> private readonly string containerName; /// <summary>Root of the projection and expansion tree.</summary> /// <remarks>If this is null - no projections or expansions were part of the request.</remarks> private readonly RootProjectionNode rootProjectionNode; /// <summary>The MIME type for the requested resource, if specified.</summary> private readonly string mimeType; /// <summary>URI for the result (without the query component).</summary> private readonly Uri resultUri; /// <summary>SegmentInfo containing information about every segment in the uri</summary> private readonly SegmentInfo[] segmentInfos; /// <summary>Whether the container name should be used to name the result.</summary> private readonly bool usesContainerName; /// <summary>Query count option, whether to count the result set or not, and how</summary> private RequestQueryCountOption countOption; /// <summary>The value of the row count</summary> private long countValue; /// <summary>The minimum client version requirement</summary> private Version requireMinimumVersion; /// <summary>The server response version</summary> private Version responseVersion; /// <summary> /// Max version of features used in the request. We need to distinguish between feature versions and response version since /// some new features (e.g. Server Projections) do not cause response version to be raised. /// </summary> private Version maxFeatureVersion; #endregion Private fields. /// <summary> /// Initializes a new RequestDescription for a query specified by the /// request Uri. /// </summary> /// <param name="targetKind">The kind of target for the request.</param> /// <param name="targetSource">The source for this target.</param> /// <param name="resultUri">URI to the results requested (with no query component).</param> internal RequestDescription(RequestTargetKind targetKind, RequestTargetSource targetSource, Uri resultUri) { WebUtil.DebugEnumIsDefined(targetKind); Debug.Assert(resultUri != null, "resultUri != null"); Debug.Assert(resultUri.IsAbsoluteUri, "resultUri.IsAbsoluteUri(" + resultUri + ")"); SegmentInfo segment = new SegmentInfo(); segment.TargetKind = targetKind; segment.TargetSource = targetSource; segment.SingleResult = true; this.segmentInfos = new SegmentInfo[] { segment }; this.resultUri = resultUri; this.requireMinimumVersion = new Version(1, 0); this.responseVersion = DataServiceDefaultResponseVersion; this.maxFeatureVersion = new Version(1, 0); } /// <summary> /// Initializes a new RequestDescription for a query specified by the /// request Uri. /// </summary> /// <param name="segmentInfos">list containing information about each segment of the request uri</param> /// <param name="containerName">Name of the container source.</param> /// <param name="usesContainerName">Whether the container name should be used to name the result.</param> /// <param name="mimeType">The MIME type for the requested resource, if specified.</param> /// <param name="resultUri">URI to the results requested (with no query component).</param> internal RequestDescription( SegmentInfo[] segmentInfos, string containerName, bool usesContainerName, string mimeType, Uri resultUri) { Debug.Assert(segmentInfos != null && segmentInfos.Length != 0, "segmentInfos != null && segmentInfos.Length != 0"); Debug.Assert(resultUri != null, "resultUri != null"); Debug.Assert(resultUri.IsAbsoluteUri, "resultUri.IsAbsoluteUri(" + resultUri + ")"); this.segmentInfos = segmentInfos; this.containerName = containerName; this.usesContainerName = usesContainerName; this.mimeType = mimeType; this.resultUri = resultUri; this.requireMinimumVersion = new Version(1, 0); this.responseVersion = DataServiceDefaultResponseVersion; this.maxFeatureVersion = new Version(1, 0); } /// <summary>Initializes a new RequestDescription based on an existing one.</summary> /// <param name="other">Other description to base new description on.</param> /// <param name="queryResults">Query results for new request description.</param> /// <param name="rootProjectionNode">Projection segment describing the projections on the top level of the query.</param> internal RequestDescription( RequestDescription other, IEnumerable queryResults, RootProjectionNode rootProjectionNode) { Debug.Assert( queryResults == null || other.SegmentInfos != null, "queryResults == null || other.SegmentInfos != null -- otherwise there isn't a segment in which to replace the query."); Debug.Assert( rootProjectionNode == null || queryResults != null, "rootProjectionNode == null || queryResults != null -- otherwise there isn't a query to execute and expand"); this.containerName = other.containerName; this.mimeType = other.mimeType; this.usesContainerName = other.usesContainerName; this.resultUri = other.resultUri; this.segmentInfos = other.SegmentInfos; this.rootProjectionNode = rootProjectionNode; this.countOption = other.countOption; this.SkipTokenExpressionCount = other.SkipTokenExpressionCount; this.SkipTokenProperties = other.SkipTokenProperties; this.countValue = other.countValue; this.requireMinimumVersion = other.requireMinimumVersion; this.responseVersion = other.responseVersion; this.maxFeatureVersion = other.maxFeatureVersion; if (queryResults == null) { this.segmentInfos = other.SegmentInfos; } else { int lastSegmentIndex = other.SegmentInfos.Length - 1; SegmentInfo lastSegmentInfo = other.SegmentInfos[lastSegmentIndex]; lastSegmentInfo.RequestEnumerable = queryResults; } } /// <summary>The name of the container for results.</summary> internal string ContainerName { [DebuggerStepThrough] get { return this.containerName; } } /// <summary>Root of the projection and expansion tree.</summary> internal RootProjectionNode RootProjectionNode { [DebuggerStepThrough] get { return this.rootProjectionNode; } } /// <summary>URI for the result (without the query component).</summary> internal Uri ResultUri { [DebuggerStepThrough] get { return this.resultUri; } } /// <summary>Returns the list containing the information about each segment that make up the request uri</summary> internal SegmentInfo[] SegmentInfos { [DebuggerStepThrough] get { return this.segmentInfos; } } /// <summary>The base query for the request, before client-specified composition.</summary> internal IEnumerable RequestEnumerable { get { return this.LastSegmentInfo.RequestEnumerable; } } /// <summary>Whether the result of this request is a single element.</summary> internal bool IsSingleResult { get { return this.LastSegmentInfo.SingleResult; } } /// <summary>The MIME type for the requested resource, if specified.</summary> internal string MimeType { [DebuggerStepThrough] get { return this.mimeType; } } /// <summary>The kind of target being requested.</summary> internal RequestTargetKind TargetKind { get { return this.LastSegmentInfo.TargetKind; } } /// <summary>The type of resource targetted by this request.</summary> internal ResourceType TargetResourceType { get { return this.LastSegmentInfo.TargetResourceType; } } /// <summary>The type of source for the request target.</summary> internal RequestTargetSource TargetSource { get { return this.LastSegmentInfo.TargetSource; } } /// <summary> /// Returns the resource property on which this query is targeted /// </summary> internal ResourceProperty Property { get { return this.LastSegmentInfo.ProjectedProperty; } } /// <summary>Whether the container name should be used to name the result.</summary> internal bool UsesContainerName { [DebuggerStepThrough] get { return this.usesContainerName; } } /// <summary>Returns the last segment</summary> internal SegmentInfo LastSegmentInfo { get { return this.segmentInfos[this.segmentInfos.Length - 1]; } } /// <summary>Returns true if the request description refers to a link uri. Otherwise returns false.</summary> internal bool LinkUri { get { return (this.segmentInfos.Length >= 3 && this.segmentInfos[this.segmentInfos.Length - 2].TargetKind == RequestTargetKind.Link); } } /// <summary>Returns the request's counting options</summary> internal RequestQueryCountOption CountOption { get { return this.countOption; } set { this.countOption = value; } } /// <summary>Number of expressions in the $skiptoken for top level expression</summary> internal int SkipTokenExpressionCount { get; set; } /// <summary>Collection of properties in the $skiptoken for top level expression</summary> internal ICollection<ResourceProperty> SkipTokenProperties { get; set; } /// <summary>Returns the value of the row count</summary> internal long CountValue { get { return this.countValue; } set { this.countValue = value; } } /// <summary>The minimum client version requirement</summary> internal Version RequireMinimumVersion { get { return this.requireMinimumVersion; } } /// <summary>The server response version</summary> internal Version ResponseVersion { get { return this.responseVersion; } } /// <summary>Max version of features used in the user's request</summary> internal Version MaxFeatureVersion { get { return this.maxFeatureVersion; } } /// <summary> /// Is the request for an IEnumerable&lt;T&gt; returning service operation. /// </summary> internal bool IsRequestForEnumServiceOperation { get { return this.TargetSource == RequestTargetSource.ServiceOperation && this.SegmentInfos[0].Operation.ResultKind == ServiceOperationResultKind.Enumeration; } } /// <summary> /// Get the single result from the given segment info /// </summary> /// <param name="segmentInfo">segmentInfo which contains the request query</param> /// <returns>query result as returned by the IQueryable query</returns> internal static IEnumerator GetSingleResultFromEnumerable(SegmentInfo segmentInfo) { IEnumerator queryResults = WebUtil.GetRequestEnumerator(segmentInfo.RequestEnumerable); bool shouldDispose = true; try { WebUtil.CheckResourceExists(queryResults.MoveNext(), segmentInfo.Identifier); CheckQueryResult(queryResults.Current, segmentInfo); shouldDispose = false; return queryResults; } finally { // Dispose the Enumerator in case of error if (shouldDispose) { WebUtil.Dispose(queryResults); } } } /// <summary> /// Checks query result. /// </summary> /// <param name="result">Query result to be checked.</param> /// <param name="segmentInfo">Segment details for the <paramref name="result"/>.</param> internal static void CheckQueryResult(object result, SegmentInfo segmentInfo) { // e.g. /Customers(4) - if there is a direct reference to an entity, it should not be null. // e.g. $value also must not be null, since you are dereferencing the values // Any other case, having null is fine if (segmentInfo.IsDirectReference && result == null) { throw DataServiceException.CreateResourceNotFound(segmentInfo.Identifier); } IEnumerable enumerable; if (segmentInfo.TargetKind == RequestTargetKind.OpenProperty && WebUtil.IsElementIEnumerable(result, out enumerable)) { throw DataServiceException.CreateSyntaxError( Strings.InvalidUri_OpenPropertiesCannotBeCollection(segmentInfo.Identifier)); } } /// <summary> /// Create a new request description from the given request description and new entity as the result. /// </summary> /// <param name="description">Existing request description.</param> /// <param name="entity">entity that needs to be the result of the new request.</param> /// <param name="container">container to which the entity belongs to.</param> /// <returns>a new instance of request description containing information about the given entity.</returns> internal static RequestDescription CreateSingleResultRequestDescription( RequestDescription description, object entity, ResourceSetWrapper container) { // Create a new request description for the results that will be returned. SegmentInfo segmentInfo = new SegmentInfo(); segmentInfo.RequestEnumerable = new object[] { entity }; segmentInfo.TargetKind = description.TargetKind; segmentInfo.TargetSource = description.TargetSource; segmentInfo.SingleResult = true; segmentInfo.ProjectedProperty = description.Property; segmentInfo.TargetResourceType = container != null ? container.ResourceType : null; segmentInfo.TargetContainer = container; segmentInfo.Identifier = description.LastSegmentInfo.Identifier; #if DEBUG segmentInfo.AssertValid(); #endif SegmentInfo[] segmentInfos = description.SegmentInfos; segmentInfos[segmentInfos.Length - 1] = segmentInfo; RequestDescription resultDescription = new RequestDescription( segmentInfos, container != null ? container.Name : null, description.UsesContainerName, description.MimeType, description.ResultUri); resultDescription.requireMinimumVersion = description.RequireMinimumVersion; resultDescription.responseVersion = description.ResponseVersion; resultDescription.maxFeatureVersion = description.MaxFeatureVersion; return resultDescription; } /// <summary> /// Checks whether etag headers are allowed (both request and response) for this request. /// ETag request headers are mainly If-Match and If-None-Match headers /// ETag response header is written only when its valid to specify one of the above mentioned request headers. /// </summary> /// <param name="description">description about the request uri.</param> /// <returns>true if If-Match or If-None-Match are allowed request headers for this request, otherwise false.</returns> internal static bool IsETagHeaderAllowed(RequestDescription description) { // IfMatch and IfNone match request headers are allowed and etag response header must be written // only when the request targets a single resource, which does not have $count and $links segment and there are no $expands query option specified. return description.IsSingleResult && description.CountOption != RequestQueryCountOption.ValueOnly && (description.RootProjectionNode == null || !description.RootProjectionNode.ExpansionsSpecified) && !description.LinkUri; } /// <summary> /// Verify that the request version is a version we know. /// </summary> /// <param name="requestVersion">request version from the header</param> /// <returns>returns true if the request version is known</returns> internal static bool IsKnownRequestVersion(Version requestVersion) { return KnownDataServiceVersions.Contains(requestVersion); } /// <summary> /// Raise the feature version if the target container contains any type with FF mapped properties that is KeepInContent=false. /// </summary> /// <param name="service">service instance</param> /// <returns>This RequestDescription instance</returns> internal RequestDescription UpdateAndCheckEpmFeatureVersion(IDataService service) { Debug.Assert(this.LastSegmentInfo != null, "this.LastSegmentInfo != null"); if (this.LinkUri) { // For $link operations we raise the feature version if either side of $link points to a set that // is not V1 compatible. ResourceSetWrapper leftSet; ResourceSetWrapper rightSet; this.GetLinkedResourceSets(out leftSet, out rightSet); Debug.Assert(leftSet != null, "leftSet != null"); Debug.Assert(rightSet != null, "rightSet != null"); this.UpdateAndCheckEpmFeatureVersion(leftSet, service); this.UpdateAndCheckEpmFeatureVersion(rightSet, service); } else { // The last segment might not be a resource. Trace backward to find the target entity resource. int resourceIndex = this.GetIndexOfTargetEntityResource(); // Not every request has a target resource. Service Operations for example can return just primitives. if (resourceIndex != -1) { ResourceSetWrapper resourceSet = this.SegmentInfos[resourceIndex].TargetContainer; Debug.Assert(resourceSet != null, "resourceSet != null"); this.UpdateAndCheckEpmFeatureVersion(resourceSet, service); } } return this; } /// <summary> /// Raise the feature version if the given set contains any type with FF mapped properties that is KeepInContent=false. /// </summary> /// <param name="resourceSet">Resource set to test</param> /// <param name="service">service instance</param> /// <returns>This RequestDescription instance</returns> internal RequestDescription UpdateAndCheckEpmFeatureVersion(ResourceSetWrapper resourceSet, IDataService service) { Debug.Assert(resourceSet != null, "resourceSet != null"); Debug.Assert(service != null, "provider != null"); // For feature version we only look at the SET, and bump the version if it's not V1 compatible. We do this even if the // target kind is not Resource. So we could have request and response DSV be 1.0 while feature version be 2.0. if (!resourceSet.EpmIsV1Compatible(service.Provider)) { this.RaiseFeatureVersion(2, 0, service.Configuration); } return this; } /// <summary>Updates the response version based on response format and the target resource type</summary> /// <param name="acceptTypesText">text for Accepts header content required to infere response format</param> /// <param name="provider">data service provider instance</param> /// <returns>The instance for which the update of response version happens</returns> internal RequestDescription UpdateEpmResponseVersion(string acceptTypesText, DataServiceProviderWrapper provider) { return this.UpdateEpmResponseVersion(acceptTypesText, this.LastSegmentInfo.TargetContainer, provider); } /// <summary>Updates the response version based on response format and given resource type</summary> /// <param name="acceptTypesText">text for Accepts header content required to infere response format</param> /// <param name="resourceSet">resourceSet to check for friendly feeds presence</param> /// <param name="provider">data service provider instance</param> /// <returns>The instance for which the update of response version happens</returns> internal RequestDescription UpdateEpmResponseVersion(string acceptTypesText, ResourceSetWrapper resourceSet, DataServiceProviderWrapper provider) { Debug.Assert(provider != null, "provider != null"); // Response will be 2.0 if any of the property in the types contained in the resource set has KeepInContent false if (this.TargetKind == RequestTargetKind.Resource) { Debug.Assert(resourceSet != null, "Must have valid resource set"); if (!resourceSet.EpmIsV1Compatible(provider) && !this.LinkUri) { // Friendly feeds must only bump the response version for Atom responses if (WebUtil.IsAtomMimeType(acceptTypesText)) { this.RaiseResponseVersion(2, 0); } } } return this; } /// <summary> /// Returns the last segment info whose target request kind is resource /// </summary> /// <returns>The index of the parent resource</returns> internal int GetIndexOfTargetEntityResource() { Debug.Assert(this.segmentInfos.Length >= 1, "this.segmentInfos.Length >= 1"); int result = -1; if (this.LinkUri || this.CountOption == RequestQueryCountOption.ValueOnly) { return this.SegmentInfos.Length - 1; } for (int j = this.SegmentInfos.Length - 1; j >= 0; j--) { if (this.segmentInfos[j].TargetKind == RequestTargetKind.Resource || this.segmentInfos[j].HasKeyValues) { result = j; break; } } return result; } /// <summary> /// Raise the minimum client version requirement for this request /// </summary> /// <param name="major">The major segment of the version</param> /// <param name="minor">The minor segment of the version</param> internal void RaiseMinimumVersionRequirement(int major, int minor) { this.requireMinimumVersion = RaiseVersion(this.requireMinimumVersion, major, minor); // Each time we bump the request version we need to bump the max feature version as well. // Note that sometimes we need to bump max feature version even if request version is not raised. this.maxFeatureVersion = RaiseVersion(this.maxFeatureVersion, major, minor); } /// <summary> /// Raise the response version for this request /// </summary> /// <param name="major">The major segment of the version</param> /// <param name="minor">The minor segment of the version</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811", Justification = "Will be used for other 2.0 server features")] internal void RaiseResponseVersion(int major, int minor) { this.responseVersion = RaiseVersion(this.responseVersion, major, minor); // Each time we bump the response version we need to bump the max feature version as well. // Note that sometimes we need to bump max feature version even if response version is not raised. this.maxFeatureVersion = RaiseVersion(this.maxFeatureVersion, major, minor); } /// <summary> /// Raise the version for features used in the user's request /// </summary> /// <param name="major">The major segment of the version</param> /// <param name="minor">The minor segment of the version</param> /// <param name="config">Data service configuration instance to validate the feature version.</param> internal void RaiseFeatureVersion(int major, int minor, DataServiceConfiguration config) { this.maxFeatureVersion = RaiseVersion(this.maxFeatureVersion, major, minor); config.ValidateMaxProtocolVersion(this); } /// <summary> /// If necessary raises version to the version requested by the user. /// </summary> /// <param name="versionToRaise">Version to raise.</param> /// <param name="major">The major segment of the new version</param> /// <param name="minor">The minor segment of the new version</param> /// <returns>New version if the requested version is greater than the existing version.</returns> private static Version RaiseVersion(Version versionToRaise, int major, int minor) { if (major > versionToRaise.Major || (major == versionToRaise.Major && minor > versionToRaise.Minor)) { versionToRaise = new Version(major, minor); } return versionToRaise; } /// <summary> /// Returns the resource sets on the left and right hand sides of $link. /// </summary> /// <param name="leftSet">Resource set to the left of $link.</param> /// <param name="rightSet">Resource set to the right of $link.</param> private void GetLinkedResourceSets(out ResourceSetWrapper leftSet, out ResourceSetWrapper rightSet) { Debug.Assert(this.LinkUri, "GetLinkedResourceSets should only be called if this is a $link request."); int idx = 0; for (; idx < this.segmentInfos.Length; idx++) { if (this.segmentInfos[idx].TargetKind == RequestTargetKind.Link) { break; } } Debug.Assert(idx > 0 && idx < this.segmentInfos.Length - 1, "idx > 0 && idx < this.segmentInfos.Length - 1"); leftSet = this.segmentInfos[idx - 1].TargetContainer; rightSet = this.segmentInfos[idx + 1].TargetContainer; } } }
using System.Collections.Generic; using System.Xml; using Google.GData.Client; namespace Google.GData.Extensions { /// <summary> /// base class to implement extensions holding extensions /// TODO: at one point think about using this as the base for atom:base /// as there is some utility overlap between the 2 of them /// </summary> public class SimpleContainer : ExtensionBase, IExtensionContainer { private ExtensionList extensionFactories; private ExtensionList extensions; /// <summary> /// constructor /// </summary> /// <param name="name">the xml name</param> /// <param name="prefix">the xml prefix</param> /// <param name="ns">the xml namespace</param> protected SimpleContainer(string name, string prefix, string ns) : base(name, prefix, ns) { } /// <summary>the list of extensions for this container /// the elements in that list MUST implement IExtensionElementFactory /// and IExtensionElement</summary> /// <returns> </returns> public ExtensionList ExtensionElements { get { if (extensions == null) { extensions = new ExtensionList(this); } return extensions; } } /// <summary> /// Finds a specific ExtensionElement based on its local name /// and its namespace. If namespace is NULL, the first one where /// the localname matches is found. If there are extensionelements that do /// not implrment ExtensionElementFactory, they will not be taken into account /// </summary> /// <param name="localName">the xml local name of the element to find</param> /// <param name="ns">the namespace of the elementToPersist</param> /// <returns>Object</returns> public IExtensionElementFactory FindExtension(string localName, string ns) { return Utilities.FindExtension(ExtensionElements, localName, ns); } /// <summary> /// all extension elements that match a namespace/localname /// given will be removed and the new one will be inserted /// </summary> /// <param name="localName">the local name to find</param> /// <param name="ns">the namespace to match, if null, ns is ignored</param> /// <param name="obj">the new element to put in</param> public void ReplaceExtension(string localName, string ns, IExtensionElementFactory obj) { DeleteExtensions(localName, ns); ExtensionElements.Add(obj); } /// <summary> /// Finds all ExtensionElement based on its local name /// and its namespace. If namespace is NULL, all where /// the localname matches is found. If there are extensionelements that do /// not implrment ExtensionElementFactory, they will not be taken into account /// Primary use of this is to find XML nodes /// </summary> /// <param name="localName">the xml local name of the element to find</param> /// <param name="ns">the namespace of the element to find</param> /// <returns>none</returns> public ExtensionList FindExtensions(string localName, string ns) { return Utilities.FindExtensions(ExtensionElements, localName, ns, new ExtensionList(this)); } /// <summary> /// Deletes all Extensions from the Extension list that match /// a localName and a Namespace. /// </summary> /// <param name="localName">the local name to find</param> /// <param name="ns">the namespace to match, if null, ns is ignored</param> /// <returns>int - the number of deleted extensions</returns> public int DeleteExtensions(string localName, string ns) { // Find them first ExtensionList arr = FindExtensions(localName, ns); foreach (IExtensionElementFactory ob in arr) { extensions.Remove(ob); } return arr.Count; } /// <summary>the list of extensions for this container /// the elements in that list MUST implement IExtensionElementFactory /// and IExtensionElement</summary> /// <returns> </returns> public ExtensionList ExtensionFactories { get { if (extensionFactories == null) { extensionFactories = new ExtensionList(this); } return extensionFactories; } } /// <summary> /// all extension element factories that match a namespace/localname /// given will be removed and the new one will be inserted /// </summary> /// <param name="localName">the local name to find</param> /// <param name="ns">the namespace to match, if null, ns is ignored</param> /// <param name="obj">the new element to put in</param> public void ReplaceFactory(string localName, string ns, IExtensionElementFactory obj) { ExtensionList arr = Utilities.FindExtensions(ExtensionFactories, localName, ns, new ExtensionList(this)); foreach (IExtensionElementFactory ob in arr) { ExtensionFactories.Remove(ob); } ExtensionFactories.Add(obj); } /// <summary> /// Finds all ExtensionElement based on its local name /// and its namespace. If namespace is NULL, all where /// the localname matches is found. If there are extensionelements that do /// not implement ExtensionElementFactory, they will not be taken into account /// Primary use of this is to find XML nodes /// </summary> /// <param name="localName">the xml local name of the element to find</param> /// <param name="ns">the namespace of the element to find</param> /// <returns>none</returns> public List<T> FindExtensions<T>(string localName, string ns) where T : IExtensionElementFactory { return Utilities.FindExtensions<T>(ExtensionElements, localName, ns); } /// <summary>Parses an xml node to create a Who object.</summary> /// <param name="node">the node to work on, can be NULL</param> /// <param name="parser">the xml parser to use if we need to dive deeper</param> /// <returns>the created SimpleElement object</returns> public override IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser) { Tracing.TraceCall("for: " + XmlName); if (node != null) { object localname = node.LocalName; if (!localname.Equals(XmlName) || !node.NamespaceURI.Equals(XmlNameSpace)) { return null; } } SimpleContainer sc = null; // create a new container sc = MemberwiseClone() as SimpleContainer; sc.InitInstance(this); sc.ProcessAttributes(node); sc.ProcessChildNodes(node, parser); return sc; } /// <summary> /// need so setup the namespace based on the version information /// </summary> protected override void VersionInfoChanged() { base.VersionInfoChanged(); VersionInfo.ImprintVersion(extensions); VersionInfo.ImprintVersion(extensionFactories); } /// <summary> /// used to copy the unknown childnodes for later saving /// </summary> /// <param name="node">the node to process</param> /// <param name="parser">the feed parser to pass down if need be</param> public override void ProcessChildNodes(XmlNode node, AtomFeedParser parser) { if (node != null && node.HasChildNodes) { XmlNode childNode = node.FirstChild; while (childNode != null) { bool fProcessed = false; if (childNode is XmlElement) { foreach (IExtensionElementFactory f in ExtensionFactories) { if (string.Compare(childNode.NamespaceURI, f.XmlNameSpace) == 0) { if (string.Compare(childNode.LocalName, f.XmlName) == 0) { Tracing.TraceMsg("Added extension to SimpleContainer for: " + f.XmlName); ExtensionElements.Add(f.CreateInstance(childNode, parser)); fProcessed = true; break; } } } } if (!fProcessed) { ChildNodes.Add(childNode); } childNode = childNode.NextSibling; } } } /// <summary> /// saves out the inner xml, so all of our subelements /// gets called from Save, whcih takes care of saving attributes /// </summary> /// <param name="writer"></param> public override void SaveInnerXml(XmlWriter writer) { if (extensions != null) { foreach (IExtensionElementFactory e in ExtensionElements) { e.Save(writer); } } } protected void SetStringValue<T>(string value, string elementName, string ns) where T : SimpleElement, new() { T v = null; if (!string.IsNullOrEmpty(value)) { v = new T(); v.Value = value; } ReplaceExtension(elementName, ns, v); } protected string GetStringValue<T>(string elementName, string ns) where T : SimpleElement { T e = FindExtension(elementName, ns) as T; if (e != null) { return e.Value; } return null; } } }
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 CloudFoundryWeb.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.Globalization; using System.Runtime.CompilerServices; namespace System { // TimeSpan represents a duration of time. A TimeSpan can be negative // or positive. // // TimeSpan is internally represented as a number of milliseconds. While // this maps well into units of time such as hours and days, any // periods longer than that aren't representable in a nice fashion. // For instance, a month can be between 28 and 31 days, while a year // can contain 365 or 364 days. A decade can have between 1 and 3 leapyears, // depending on when you map the TimeSpan into the calendar. This is why // we do not provide Years() or Months(). // // Note: System.TimeSpan needs to interop with the WinRT structure // type Windows::Foundation:TimeSpan. These types are currently binary-compatible in // memory so no custom marshalling is required. If at any point the implementation // details of this type should change, or new fields added, we need to remember to add // an appropriate custom ILMarshaler to keep WInRT interop scenarios enabled. // [Serializable] public readonly struct TimeSpan : IComparable, IComparable<TimeSpan>, IEquatable<TimeSpan>, IFormattable, ISpanFormattable { public const long TicksPerMillisecond = 10000; public const long TicksPerSecond = TicksPerMillisecond * 1000; // 10,000,000 public const long TicksPerMinute = TicksPerSecond * 60; // 600,000,000 public const long TicksPerHour = TicksPerMinute * 60; // 36,000,000,000 public const long TicksPerDay = TicksPerHour * 24; // 864,000,000,000 internal const long MaxSeconds = long.MaxValue / TicksPerSecond; internal const long MinSeconds = long.MinValue / TicksPerSecond; internal const long MaxMilliSeconds = long.MaxValue / TicksPerMillisecond; internal const long MinMilliSeconds = long.MinValue / TicksPerMillisecond; internal const long TicksPerTenthSecond = TicksPerMillisecond * 100; public static readonly TimeSpan Zero = new TimeSpan(0); public static readonly TimeSpan MaxValue = new TimeSpan(long.MaxValue); public static readonly TimeSpan MinValue = new TimeSpan(long.MinValue); // internal so that DateTime doesn't have to call an extra get // method for some arithmetic operations. internal readonly long _ticks; // Do not rename (binary serialization) public TimeSpan(long ticks) { this._ticks = ticks; } public TimeSpan(int hours, int minutes, int seconds) { _ticks = TimeToTicks(hours, minutes, seconds); } public TimeSpan(int days, int hours, int minutes, int seconds) : this(days, hours, minutes, seconds, 0) { } public TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds) { long totalMilliSeconds = ((long)days * 3600 * 24 + (long)hours * 3600 + (long)minutes * 60 + seconds) * 1000 + milliseconds; if (totalMilliSeconds > MaxMilliSeconds || totalMilliSeconds < MinMilliSeconds) throw new ArgumentOutOfRangeException(null, SR.Overflow_TimeSpanTooLong); _ticks = (long)totalMilliSeconds * TicksPerMillisecond; } public long Ticks => _ticks; public int Days => (int)(_ticks / TicksPerDay); public int Hours => (int)((_ticks / TicksPerHour) % 24); public int Milliseconds => (int)((_ticks / TicksPerMillisecond) % 1000); public int Minutes => (int)((_ticks / TicksPerMinute) % 60); public int Seconds => (int)((_ticks / TicksPerSecond) % 60); public double TotalDays => ((double)_ticks) / TicksPerDay; public double TotalHours => (double)_ticks / TicksPerHour; public double TotalMilliseconds { get { double temp = (double)_ticks / TicksPerMillisecond; if (temp > MaxMilliSeconds) return (double)MaxMilliSeconds; if (temp < MinMilliSeconds) return (double)MinMilliSeconds; return temp; } } public double TotalMinutes => (double)_ticks / TicksPerMinute; public double TotalSeconds => (double)_ticks / TicksPerSecond; public TimeSpan Add(TimeSpan ts) { long result = _ticks + ts._ticks; // Overflow if signs of operands was identical and result's // sign was opposite. // >> 63 gives the sign bit (either 64 1's or 64 0's). if ((_ticks >> 63 == ts._ticks >> 63) && (_ticks >> 63 != result >> 63)) throw new OverflowException(SR.Overflow_TimeSpanTooLong); return new TimeSpan(result); } // Compares two TimeSpan values, returning an integer that indicates their // relationship. // public static int Compare(TimeSpan t1, TimeSpan t2) { if (t1._ticks > t2._ticks) return 1; if (t1._ticks < t2._ticks) return -1; return 0; } // Returns a value less than zero if this object public int CompareTo(object? value) { if (value == null) return 1; if (!(value is TimeSpan)) throw new ArgumentException(SR.Arg_MustBeTimeSpan); long t = ((TimeSpan)value)._ticks; if (_ticks > t) return 1; if (_ticks < t) return -1; return 0; } public int CompareTo(TimeSpan value) { long t = value._ticks; if (_ticks > t) return 1; if (_ticks < t) return -1; return 0; } public static TimeSpan FromDays(double value) { return Interval(value, TicksPerDay); } public TimeSpan Duration() { if (Ticks == TimeSpan.MinValue.Ticks) throw new OverflowException(SR.Overflow_Duration); return new TimeSpan(_ticks >= 0 ? _ticks : -_ticks); } public override bool Equals(object? value) { if (value is TimeSpan) { return _ticks == ((TimeSpan)value)._ticks; } return false; } public bool Equals(TimeSpan obj) { return _ticks == obj._ticks; } public static bool Equals(TimeSpan t1, TimeSpan t2) { return t1._ticks == t2._ticks; } public override int GetHashCode() { return (int)_ticks ^ (int)(_ticks >> 32); } public static TimeSpan FromHours(double value) { return Interval(value, TicksPerHour); } private static TimeSpan Interval(double value, double scale) { if (double.IsNaN(value)) throw new ArgumentException(SR.Arg_CannotBeNaN); double ticks = value * scale; if ((ticks > long.MaxValue) || (ticks < long.MinValue)) throw new OverflowException(SR.Overflow_TimeSpanTooLong); return new TimeSpan((long)ticks); } public static TimeSpan FromMilliseconds(double value) { return Interval(value, TicksPerMillisecond); } public static TimeSpan FromMinutes(double value) { return Interval(value, TicksPerMinute); } public TimeSpan Negate() { if (Ticks == TimeSpan.MinValue.Ticks) throw new OverflowException(SR.Overflow_NegateTwosCompNum); return new TimeSpan(-_ticks); } public static TimeSpan FromSeconds(double value) { return Interval(value, TicksPerSecond); } public TimeSpan Subtract(TimeSpan ts) { long result = _ticks - ts._ticks; // Overflow if signs of operands was different and result's // sign was opposite from the first argument's sign. // >> 63 gives the sign bit (either 64 1's or 64 0's). if ((_ticks >> 63 != ts._ticks >> 63) && (_ticks >> 63 != result >> 63)) throw new OverflowException(SR.Overflow_TimeSpanTooLong); return new TimeSpan(result); } public TimeSpan Multiply(double factor) => this * factor; public TimeSpan Divide(double divisor) => this / divisor; public double Divide(TimeSpan ts) => this / ts; public static TimeSpan FromTicks(long value) { return new TimeSpan(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static long TimeToTicks(int hour, int minute, int second) { // totalSeconds is bounded by 2^31 * 2^12 + 2^31 * 2^8 + 2^31, // which is less than 2^44, meaning we won't overflow totalSeconds. long totalSeconds = (long)hour * 3600 + (long)minute * 60 + (long)second; if (totalSeconds > MaxSeconds || totalSeconds < MinSeconds) ThrowHelper.ThrowArgumentOutOfRange_TimeSpanTooLong(); return totalSeconds * TicksPerSecond; } // See System.Globalization.TimeSpanParse and System.Globalization.TimeSpanFormat #region ParseAndFormat private static void ValidateStyles(TimeSpanStyles style, string parameterName) { if (style != TimeSpanStyles.None && style != TimeSpanStyles.AssumeNegative) throw new ArgumentException(SR.Argument_InvalidTimeSpanStyles, parameterName); } public static TimeSpan Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); /* Constructs a TimeSpan from a string. Leading and trailing white space characters are allowed. */ return TimeSpanParse.Parse(s, null); } public static TimeSpan Parse(string input, IFormatProvider? formatProvider) { if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); return TimeSpanParse.Parse(input, formatProvider); } public static TimeSpan Parse(ReadOnlySpan<char> input, IFormatProvider? formatProvider = null) { return TimeSpanParse.Parse(input, formatProvider); } public static TimeSpan ParseExact(string input, string format, IFormatProvider? formatProvider) { if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); if (format == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); return TimeSpanParse.ParseExact(input, format, formatProvider, TimeSpanStyles.None); } public static TimeSpan ParseExact(string input, string[] formats, IFormatProvider? formatProvider) { if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None); } public static TimeSpan ParseExact(string input, string format, IFormatProvider? formatProvider, TimeSpanStyles styles) { ValidateStyles(styles, nameof(styles)); if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); if (format == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); return TimeSpanParse.ParseExact(input, format, formatProvider, styles); } public static TimeSpan ParseExact(ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider? formatProvider, TimeSpanStyles styles = TimeSpanStyles.None) { ValidateStyles(styles, nameof(styles)); return TimeSpanParse.ParseExact(input, format, formatProvider, styles); } public static TimeSpan ParseExact(string input, string[] formats, IFormatProvider? formatProvider, TimeSpanStyles styles) { ValidateStyles(styles, nameof(styles)); if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, styles); } public static TimeSpan ParseExact(ReadOnlySpan<char> input, string[] formats, IFormatProvider? formatProvider, TimeSpanStyles styles = TimeSpanStyles.None) { ValidateStyles(styles, nameof(styles)); return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, styles); } public static bool TryParse(string? s, out TimeSpan result) { if (s == null) { result = default; return false; } return TimeSpanParse.TryParse(s, null, out result); } public static bool TryParse(ReadOnlySpan<char> s, out TimeSpan result) { return TimeSpanParse.TryParse(s, null, out result); } public static bool TryParse(string? input, IFormatProvider? formatProvider, out TimeSpan result) { if (input == null) { result = default; return false; } return TimeSpanParse.TryParse(input, formatProvider, out result); } public static bool TryParse(ReadOnlySpan<char> input, IFormatProvider? formatProvider, out TimeSpan result) { return TimeSpanParse.TryParse(input, formatProvider, out result); } public static bool TryParseExact(string? input, string format, IFormatProvider? formatProvider, out TimeSpan result) { if (input == null || format == null) { result = default; return false; } return TimeSpanParse.TryParseExact(input, format, formatProvider, TimeSpanStyles.None, out result); } public static bool TryParseExact(ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider? formatProvider, out TimeSpan result) { return TimeSpanParse.TryParseExact(input, format, formatProvider, TimeSpanStyles.None, out result); } public static bool TryParseExact(string? input, string[] formats, IFormatProvider? formatProvider, out TimeSpan result) { if (input == null) { result = default; return false; } return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None, out result); } public static bool TryParseExact(ReadOnlySpan<char> input, string[] formats, IFormatProvider? formatProvider, out TimeSpan result) { return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None, out result); } public static bool TryParseExact(string? input, string format, IFormatProvider? formatProvider, TimeSpanStyles styles, out TimeSpan result) { ValidateStyles(styles, nameof(styles)); if (input == null || format == null) { result = default; return false; } return TimeSpanParse.TryParseExact(input, format, formatProvider, styles, out result); } public static bool TryParseExact(ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider? formatProvider, TimeSpanStyles styles, out TimeSpan result) { ValidateStyles(styles, nameof(styles)); return TimeSpanParse.TryParseExact(input, format, formatProvider, styles, out result); } public static bool TryParseExact(string? input, string[] formats, IFormatProvider? formatProvider, TimeSpanStyles styles, out TimeSpan result) { ValidateStyles(styles, nameof(styles)); if (input == null) { result = default; return false; } return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, styles, out result); } public static bool TryParseExact(ReadOnlySpan<char> input, string[] formats, IFormatProvider? formatProvider, TimeSpanStyles styles, out TimeSpan result) { ValidateStyles(styles, nameof(styles)); return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, styles, out result); } public override string ToString() { return TimeSpanFormat.FormatC(this); } public string ToString(string? format) { return TimeSpanFormat.Format(this, format, null); } public string ToString(string? format, IFormatProvider? formatProvider) { return TimeSpanFormat.Format(this, format, formatProvider); } public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider? formatProvider = null) { return TimeSpanFormat.TryFormat(this, destination, out charsWritten, format, formatProvider); } #endregion public static TimeSpan operator -(TimeSpan t) { if (t._ticks == TimeSpan.MinValue._ticks) throw new OverflowException(SR.Overflow_NegateTwosCompNum); return new TimeSpan(-t._ticks); } public static TimeSpan operator -(TimeSpan t1, TimeSpan t2) => t1.Subtract(t2); public static TimeSpan operator +(TimeSpan t) => t; public static TimeSpan operator +(TimeSpan t1, TimeSpan t2) => t1.Add(t2); public static TimeSpan operator *(TimeSpan timeSpan, double factor) { if (double.IsNaN(factor)) { throw new ArgumentException(SR.Arg_CannotBeNaN, nameof(factor)); } // Rounding to the nearest tick is as close to the result we would have with unlimited // precision as possible, and so likely to have the least potential to surprise. double ticks = Math.Round(timeSpan.Ticks * factor); if (ticks > long.MaxValue || ticks < long.MinValue) { throw new OverflowException(SR.Overflow_TimeSpanTooLong); } return FromTicks((long)ticks); } public static TimeSpan operator *(double factor, TimeSpan timeSpan) => timeSpan * factor; public static TimeSpan operator /(TimeSpan timeSpan, double divisor) { if (double.IsNaN(divisor)) { throw new ArgumentException(SR.Arg_CannotBeNaN, nameof(divisor)); } double ticks = Math.Round(timeSpan.Ticks / divisor); if (ticks > long.MaxValue || ticks < long.MinValue || double.IsNaN(ticks)) { throw new OverflowException(SR.Overflow_TimeSpanTooLong); } return FromTicks((long)ticks); } // Using floating-point arithmetic directly means that infinities can be returned, which is reasonable // if we consider TimeSpan.FromHours(1) / TimeSpan.Zero asks how many zero-second intervals there are in // an hour for which infinity is the mathematic correct answer. Having TimeSpan.Zero / TimeSpan.Zero return NaN // is perhaps less useful, but no less useful than an exception. public static double operator /(TimeSpan t1, TimeSpan t2) => t1.Ticks / (double)t2.Ticks; public static bool operator ==(TimeSpan t1, TimeSpan t2) => t1._ticks == t2._ticks; public static bool operator !=(TimeSpan t1, TimeSpan t2) => t1._ticks != t2._ticks; public static bool operator <(TimeSpan t1, TimeSpan t2) => t1._ticks < t2._ticks; public static bool operator <=(TimeSpan t1, TimeSpan t2) => t1._ticks <= t2._ticks; public static bool operator >(TimeSpan t1, TimeSpan t2) => t1._ticks > t2._ticks; public static bool operator >=(TimeSpan t1, TimeSpan t2) => t1._ticks >= t2._ticks; } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/devtools/clouderrorreporting/v1beta1/error_group_service.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Cloud.ErrorReporting.V1Beta1 { /// <summary>Holder for reflection information generated from google/devtools/clouderrorreporting/v1beta1/error_group_service.proto</summary> public static partial class ErrorGroupServiceReflection { #region Descriptor /// <summary>File descriptor for google/devtools/clouderrorreporting/v1beta1/error_group_service.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ErrorGroupServiceReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CkVnb29nbGUvZGV2dG9vbHMvY2xvdWRlcnJvcnJlcG9ydGluZy92MWJldGEx", "L2Vycm9yX2dyb3VwX3NlcnZpY2UucHJvdG8SK2dvb2dsZS5kZXZ0b29scy5j", "bG91ZGVycm9ycmVwb3J0aW5nLnYxYmV0YTEaHGdvb2dsZS9hcGkvYW5ub3Rh", "dGlvbnMucHJvdG8aOGdvb2dsZS9kZXZ0b29scy9jbG91ZGVycm9ycmVwb3J0", "aW5nL3YxYmV0YTEvY29tbW9uLnByb3RvIiUKD0dldEdyb3VwUmVxdWVzdBIS", "Cgpncm91cF9uYW1lGAEgASgJIlwKElVwZGF0ZUdyb3VwUmVxdWVzdBJGCgVn", "cm91cBgBIAEoCzI3Lmdvb2dsZS5kZXZ0b29scy5jbG91ZGVycm9ycmVwb3J0", "aW5nLnYxYmV0YTEuRXJyb3JHcm91cDKOAwoRRXJyb3JHcm91cFNlcnZpY2US", "tAEKCEdldEdyb3VwEjwuZ29vZ2xlLmRldnRvb2xzLmNsb3VkZXJyb3JyZXBv", "cnRpbmcudjFiZXRhMS5HZXRHcm91cFJlcXVlc3QaNy5nb29nbGUuZGV2dG9v", "bHMuY2xvdWRlcnJvcnJlcG9ydGluZy52MWJldGExLkVycm9yR3JvdXAiMYLT", "5JMCKxIpL3YxYmV0YTEve2dyb3VwX25hbWU9cHJvamVjdHMvKi9ncm91cHMv", "Kn0SwQEKC1VwZGF0ZUdyb3VwEj8uZ29vZ2xlLmRldnRvb2xzLmNsb3VkZXJy", "b3JyZXBvcnRpbmcudjFiZXRhMS5VcGRhdGVHcm91cFJlcXVlc3QaNy5nb29n", "bGUuZGV2dG9vbHMuY2xvdWRlcnJvcnJlcG9ydGluZy52MWJldGExLkVycm9y", "R3JvdXAiOILT5JMCMhopL3YxYmV0YTEve2dyb3VwLm5hbWU9cHJvamVjdHMv", "Ki9ncm91cHMvKn06BWdyb3VwQtEBCi9jb20uZ29vZ2xlLmRldnRvb2xzLmNs", "b3VkZXJyb3JyZXBvcnRpbmcudjFiZXRhMUIWRXJyb3JHcm91cFNlcnZpY2VQ", "cm90b1ABWl5nb29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlz", "L2RldnRvb2xzL2Nsb3VkZXJyb3JyZXBvcnRpbmcvdjFiZXRhMTtjbG91ZGVy", "cm9ycmVwb3J0aW5nqgIjR29vZ2xlLkNsb3VkLkVycm9yUmVwb3J0aW5nLlYx", "QmV0YTFiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Cloud.ErrorReporting.V1Beta1.CommonReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.ErrorReporting.V1Beta1.GetGroupRequest), global::Google.Cloud.ErrorReporting.V1Beta1.GetGroupRequest.Parser, new[]{ "GroupName" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.ErrorReporting.V1Beta1.UpdateGroupRequest), global::Google.Cloud.ErrorReporting.V1Beta1.UpdateGroupRequest.Parser, new[]{ "Group" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// A request to return an individual group. /// </summary> public sealed partial class GetGroupRequest : pb::IMessage<GetGroupRequest> { private static readonly pb::MessageParser<GetGroupRequest> _parser = new pb::MessageParser<GetGroupRequest>(() => new GetGroupRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GetGroupRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.ErrorReporting.V1Beta1.ErrorGroupServiceReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetGroupRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetGroupRequest(GetGroupRequest other) : this() { groupName_ = other.groupName_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetGroupRequest Clone() { return new GetGroupRequest(this); } /// <summary>Field number for the "group_name" field.</summary> public const int GroupNameFieldNumber = 1; private string groupName_ = ""; /// <summary> /// [Required] The group resource name. Written as /// &lt;code>projects/&lt;var>projectID&lt;/var>/groups/&lt;var>group_name&lt;/var>&lt;/code>. /// Call /// &lt;a href="/error-reporting/reference/rest/v1beta1/projects.groupStats/list"> /// &lt;code>groupStats.list&lt;/code>&lt;/a> to return a list of groups belonging to /// this project. /// /// Example: &lt;code>projects/my-project-123/groups/my-group&lt;/code> /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string GroupName { get { return groupName_; } set { groupName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GetGroupRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GetGroupRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (GroupName != other.GroupName) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (GroupName.Length != 0) hash ^= GroupName.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (GroupName.Length != 0) { output.WriteRawTag(10); output.WriteString(GroupName); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (GroupName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(GroupName); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GetGroupRequest other) { if (other == null) { return; } if (other.GroupName.Length != 0) { GroupName = other.GroupName; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { GroupName = input.ReadString(); break; } } } } } /// <summary> /// A request to replace the existing data for the given group. /// </summary> public sealed partial class UpdateGroupRequest : pb::IMessage<UpdateGroupRequest> { private static readonly pb::MessageParser<UpdateGroupRequest> _parser = new pb::MessageParser<UpdateGroupRequest>(() => new UpdateGroupRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<UpdateGroupRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.ErrorReporting.V1Beta1.ErrorGroupServiceReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UpdateGroupRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UpdateGroupRequest(UpdateGroupRequest other) : this() { Group = other.group_ != null ? other.Group.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UpdateGroupRequest Clone() { return new UpdateGroupRequest(this); } /// <summary>Field number for the "group" field.</summary> public const int GroupFieldNumber = 1; private global::Google.Cloud.ErrorReporting.V1Beta1.ErrorGroup group_; /// <summary> /// [Required] The group which replaces the resource on the server. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.ErrorReporting.V1Beta1.ErrorGroup Group { get { return group_; } set { group_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as UpdateGroupRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(UpdateGroupRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Group, other.Group)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (group_ != null) hash ^= Group.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (group_ != null) { output.WriteRawTag(10); output.WriteMessage(Group); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (group_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Group); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(UpdateGroupRequest other) { if (other == null) { return; } if (other.group_ != null) { if (group_ == null) { group_ = new global::Google.Cloud.ErrorReporting.V1Beta1.ErrorGroup(); } Group.MergeFrom(other.Group); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (group_ == null) { group_ = new global::Google.Cloud.ErrorReporting.V1Beta1.ErrorGroup(); } input.ReadMessage(group_); break; } } } } } #endregion } #endregion Designer generated code